diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 4d82b771cf..8049a412bc 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -99,7 +99,7 @@ How to read this: | **Metro Transit** (Metropolitan Council) | Transit layer live vehicles, Minneapolis–St Paul | Metro Transit / Metropolitan Council open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Metro Transit / Metropolitan Council (courtesy text) | | **OVapi / Stichting OpenGeo** | Transit layer live vehicles, Netherlands | OVapi / Stichting OpenGeo open realtime vehicle data, used for the live view; published for developer use and not against their use. The client sends a User-Agent and conditional requests. | Attribution to OVapi / Stichting OpenGeo (courtesy text) | | **Entur** (api.entur.io) | Transit layer live vehicles, Norway | Entur open realtime vehicle data, used for the live view; published for developer use and not against their use. The client sends the `ET-Client-Name` identifying header. | Attribution to Entur (courtesy text) | -| **TransLink** (Queensland Government) | Transit layer live vehicles, South East Queensland | TransLink / Queensland Government open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to TransLink / Queensland Government (courtesy text) | +| **TransLink** (Queensland Government) | Transit layer live vehicles, South East Queensland and Cairns | TransLink / Queensland Government open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Translink, Department of Transport and Main Roads (courtesy text) | | **HSL** (realtime.hsl.fi) | Transit layer live vehicles, Helsinki | HSL (Helsinki Region Transport) open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to HSL (Helsinki Region Transport) (courtesy text) | | **TTC** (bustime.ttc.ca) | Transit layer live vehicles, Toronto — surface vehicles (buses and streetcars) only | Toronto Transit Commission BusTime open realtime vehicle data, published through City of Toronto Open Data and used for the live view. The subway publishes no vehicle positions, so Lines 1/2/4 are absent rather than inferred. | Attribution to Toronto Transit Commission — City of Toronto Open Data, under the Open Government Licence – Toronto | | **MiWay** (miapp.ca) | Transit layer live vehicles, Mississauga ON | MiWay open realtime vehicle data, published by the City of Mississauga under its Open Data Terms of Use, used for the live view. The licence is revocable and asks that the Terms of Use link travel with the data. | Attribution to MiWay — City of Mississauga Open Data, linked to the Terms of Use | @@ -272,7 +272,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei - **Houston TranStar cameras.** Keyless. The camera list is the public `traffic.houstontranstar.org/data/layers/cctvSnapshots_json.js` catalog (~1,000 cameras across Greater Houston); frames are stills at `www.houstontranstar.org/snapshots/cctv/.jpg`, synthesized from a validated numeric id rather than taken from the payload, and only that host is registered. Cameras whose catalog id is `0` (a different, non-snapshot class) and cameras outside Greater Houston are dropped. TranStar's `dir` field is the side of the freeway the camera sits on, not the way it faces: TranStar's own map shows it as "Traffic closest to the camera is traveling …" (South → eastbound, North → westbound, West → southbound, East → northbound). That travel direction (90°, 270°, 180°, 0°) seeds the heading as a low-confidence prior with the low-confidence pose; `None` or an unknown value uses the shared id-hash fallback at low confidence. Headings are corrected with the in-app calibration gizmo. Off by default. TranStar's [Content Usage terms](https://traffic.houstontranstar.org/disclaimer.aspx) prohibit copying or distributing the site's information, and external framing or linking to specific images, without TxDOT's prior written permission; its FAQ grants permission-free use only for the RSS feeds. This project does not hold that permission for downstream installations, so the pack loads only when an operator who holds TxDOT's written permission sets `CCTV_HOUSTON_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to TranStar. Once enabled, it loads the 250 cameras nearest downtown, Uptown, the Medical Center, IAH and Galveston; `CCTV_HOUSTON_MAX_SOURCES` (8–400) changes the cap. Snapshots update about every 3 minutes, which is also the ambient still cadence. Frames are fetched from TranStar and relayed to the browser on demand, buffered only transiently per request, sent with `Cache-Control: no-store`, and not archived. - **Autostrada del Brennero (A22) webcams.** Keyless. The camera list is one request to the Open Data Hub tourism API (`tourism.api.opendatahub.com/v1/WebcamInfo?source=a22`), run by NOI Techpark in South Tyrol, which republishes Autobrennero's own list of 13 motorway webcams with coordinates and kilometre markers. Frames are the operator's stills on `www.autobrennero.it/WebCamImg/km.jpg`, refreshed about once a minute, and only the exact image for each camera's kilometre is registered. The feed names no bearing, so headings use the id-hash fallback at low confidence. The road climbs from about 20 m in the Po valley to about 1,370 m at the Brenner Pass, so each camera's ground elevation comes from a per-kilometre table sampled from the Copernicus GLO-90 DEM (via Open-Meteo's elevation API); a camera not in the table uses a 200 m prior. The Open Data Hub tags every record CC0 (`ClosedData: false`, Autobrennero as licence holder), but that tag is the aggregator's metadata and Autobrennero publishes no terms of its own for the images, so they are credited to the operator as a courtesy and are not redistributed. Frames are fetched at request time and never stored. Disable with `CCTV_A22_ENABLED=0`. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. -- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All fifty-two registered feeds, covering forty-nine regions, are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington, YRT and Rio’s SMTR publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. +- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All fifty-three registered feeds, covering fifty regions, are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington, YRT and Rio’s SMTR publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. TransLink needs no table: its route keys carry a GTFS version suffix (`200-4`) and Cairns puts a `C` before its bus numbers (`C123-33`), so both are stripped by rule to the number on the vehicle. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. - **Rail (GTFS-Realtime trains).** Each feed in `src/data/railFeeds.js` records its licence, its credit and the passage of its terms the decision rests on, and a feed is switched on only when those terms were read and cover this use, or, for those that publish no licence at all, on the basis its entry records. Such a basis is never a licence, and the credit does not present it as one: its label says there is no licence ("No licence published", "No licence stated") or names the publication the use rests on. Five enabled feeds publish no licence for their train positions. MARC is used on what its publication says (open publication with a no-endorsement disclaimer), and METRO light rail on the same basis as the Transit layer's Metro Transit feed. Tri-Rail and Charlotte's LYNX are used without a published licence by project owner decision of 2026-11-10. The fifth is Irish Rail, whose train positions publish no licence while its NTA timetable is CC BY 4.0. The registry lists 30 feeds, all switched on, and every one is keyless: its realtime feed and its static timetable are published for anyone to fetch, so no feed needs a key, an account or a registration, and the server holds no rail credential. No rail request carries a credential of the deployer's; one feed's published URL includes a fixed public value its publisher prints for everyone (Bordeaux's `apiKey`). `/api/rail/feeds` lists the offered feeds, `/api/rail/trains/` returns one feed's train snapshot, `/api/rail/updates/` its trip updates, and `/api/rail/paths/` and `/api/rail/schedule/` its path and schedule packs, when built. The proxy requests only registered feeds and reuses the Transit proxy's request policy (a short snapshot cache with single-flight refresh, serve-stale, admission limits, the failure cooldown ladder, redirects followed hop by hop only on the feed's own https origin, and an 8 MiB body cap unless a feed sets its own, at most 64 MiB). Many operators publish trains in the same feed as their buses, so each feed has a classifier: the proxy keeps only vehicles it recognises as trains, tags each with a category (`transit`, `local`, `regional`, `national` or `international`) and a mode (`rail`, `metro` or `tram`), and drops everything else server-side, counted in the snapshot as `dropped`; the browser never receives a bus. Every train shown is live, where its operator last reported it: 29 feeds publish live GPS positions (SJ Nord's through SIRI VM), and Irish Rail reports the station or timing point a train last passed. No train is placed or moved from a timetable; a feed whose live positions fail shows as unavailable, and its trains age out as any quiet train does. 22 feeds register trip updates, polled while one of their trains is selected and that feed's schedule pack is loaded. 28 feeds work out of the box. Packs are an opt-in extra for live trains: nothing is downloaded when the app starts, and `node scripts/build-rail-paths.mjs --feed ` (repeatable) or `--all` downloads a feed's static GTFS (29 of the 30 have one) and writes a path pack (the operator's track shapes) and a schedule pack (the stop times for a window of days) to `.cache/rail-paths/` (or to `RAIL_PATHS_DIR` when set, the directory the server then serves). With them, a live train is drawn on its operator's route line and its card names its stops, its next stop and, from the trip updates, their delays. Renfe long and medium distance and KTMB, whose vehicles name no route, are classified from their pack's routes, so `/api/rail/feeds` lists them only once that pack is built. Lines are the operator's own shapes as published: nothing is routed or redrawn from other map data, and no line is drawn where an operator publishes no shape. **Share-alike sources bind the deployer.** A pack built from a ShareAlike or ODbL source is a derived database of it, so a deployer who serves it publicly makes it subject to the same licence and must offer it under that licence with the attribution kept. That covers the Montpellier packs (ODbL). For the ODbL datasets of France's national access point, its special conditions also require that "Les bases de données ainsi repartagées doivent être publiées sur le Point d'accès national transport.data.gouv.fr, dans le format d'origine" ([Licence ODbL](https://doc.transport.data.gouv.fr/le-point-d-acces-national/cadre-juridique/conditions-dutilisation-des-donnees/licence-odbl), read 2026-11-10): a deployer who serves the Montpellier packs publicly takes on republishing that derived data there, as GTFS. The build downloads each static GTFS itself, over https and with no credential. A feed's `staticRouteTypes` lists the route types it keeps when its classifier accepts every route of a mode-specific feed. A frequency-based trip becomes one run per departure on its template's stops and run times. Packs are build output, not part of the repository, and cover a fixed window of days, so they are rebuilt before it ends, and more often where an operator republishes more often. A build in which any feed fails exits with code 2, the other feeds still built. A stop the GTFS gives no coordinates, which some feeds write as (0, 0), is left out of the run, so no line is ever drawn to it and no stop is placed by guesswork. Where several loaded feeds carry the same train, it is drawn once. Copies are matched by train number within 100 km, or, for a short line name (S1, RB 1, U6), on the same line in the same category within 15 km. A train number is three or more digits, or a shorter number after a long-distance product (EC, ECE, EN, ICE, NJ, RJ, RJX, TGV; not IC, where a short number names a line); a trip id that is an operator prefix and a number, or a headsign that is a bare number, is read too. The copy drawn is scored by its position source (live GPS, then station reports), then by its line (on its operator's shape, then without one), and stays drawn until another scores strictly higher. No train is ever placed in Ukraine, a safety rule: the build leaves out every run with a stop there, a stop whose id names Ukraine or whose position is inside its recognised borders (either is enough: an id naming another country does not keep a stop inside them), and the proxy drops every live position inside those borders (`src/data/railNoPositions.js`). Trains use the Transit layer's delayed playback between reports and move along their line in the path pack where there is one, else in straight lines. No train position is archived to disk, there is no proxy history, and nothing is collected in the background. Operator credits appear when that feed's trains are shown and do not imply endorsement. - **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query. diff --git a/README.md b/README.md index ea347a7399..dce218cccb 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ We've got a plurality of sensor systems watching the planet right now. Satellite - **📡 Contacts:** A 250 km roster of everything near your target — step through live aircraft and drop into any cockpit. - **🎯 Click-to-track anything:** Camera locks on, draws a fading trail, surfaces full metadata — and a tracked fire or vessel hands you off to the nearest live camera in one click. - **🖊️ Voice whiteboard:** Speak annotations onto the world — real boundary polygons, marks, and routes. -- **🛫 3D fleet:** 122 procedural models drawn life size by type — airliners, business jets, helicopters, drones, ships, buses, trams and trains — and every contact swaps from glyph to 3D model as you close in. +- **🛫 3D fleet:** 122 procedural models drawn life size by type — airliners, business jets, helicopters, drones, ships, buses, trams and trains — and every contact within 3 km of the camera swaps from glyph to its 3D model. - **🎨 Reskin reality:** GLSL sensor looks over the normal globe — CRT, NVG, FLIR/thermal, Noir. - **🟩 Detection overlay:** Screen-space bounding boxes and IDs on everything in view. - **🎖️ Military HUD:** Tactical heads-up display with intelligence-style telemetry. @@ -452,7 +452,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of | 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 | | 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer with full-screen **EXPAND**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key | | 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 | -| 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, Rio de Janeiro (buses and BRT), Szczecin, Lisbon (Carris Metropolitana and the city’s Carris), Prague, Warsaw, Kraków, Poznań, Gdańsk, Rzeszów, Vilnius, Bucharest, Cluj-Napoca, Iași, Rome, Turin, Venice (buses and waterbuses), Bordeaux, Montpellier, Rouen, Toulon, Le Havre, Tours, Málaga, Sendai, Johor Bahru, Kota Bharu, Adelaide, Atlanta, Denver, Edmonton, Halifax, Victoria, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 | +| 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, Cairns, Rio de Janeiro (buses and BRT), Szczecin, Lisbon (Carris Metropolitana and the city’s Carris), Prague, Warsaw, Kraków, Poznań, Gdańsk, Rzeszów, Vilnius, Bucharest, Cluj-Napoca, Iași, Rome, Turin, Venice (buses and waterbuses), Bordeaux, Montpellier, Rouen, Toulon, Le Havre, Tours, Málaga, Sendai, Johor Bahru, Kota Bharu, Adelaide, Atlanta, Denver, Edmonton, Halifax, Victoria, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 | | 🚆 **Rail** | Live trains across the US, Canada, Australia, Ireland, Finland, Spain, Norway, Malaysia, Japan and France, from 30 keyless operator feeds: live GPS positions from 29 of them and Irish Rail’s station reports, 28 live out of the box, and Renfe long and medium distance and KTMB once their pack is built. No train is placed from a timetable. Opt-in packs (`node scripts/build-rail-paths.mjs --feed ` or `--all`) add the operator’s own route lines, stop names, next stops and trip-update delays. Coloured by service category (urban, local, regional, national, international) with a filter chip and legend for each; trains are drawn once when several feeds carry them, and open a card per train. Buses in mixed feeds are dropped by the server | Operator GTFS-Realtime feeds (static GTFS for opt-in packs) | 🟢 | | 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 | | 🧭 **Directions** | Click A and B on the globe for a street-following drive, walk or cycle route draped on the terrain with turn-by-turn steps — then FLY the camera along it. No key, no geocoder, no mic | OSRM on FOSSGIS servers (OpenStreetMap) | 🟢 | diff --git a/changelog.d/1169-australian-transit.md b/changelog.d/1169-australian-transit.md new file mode 100644 index 0000000000..d86ef03a1a --- /dev/null +++ b/changelog.d/1169-australian-transit.md @@ -0,0 +1,5 @@ +- Transit adds TransLink Cairns, a keyless feed under CC BY 4.0. TransLink + trains, Gold Coast light rail and ferries, and Adelaide Metro trains, trams + and the SeaLink ferry, now show as their own modes instead of buses. + TransLink route labels drop the GTFS version and Cairns's `C` prefix, so a + bus reads "Route 123", not "Route C123-33" (willrenzo39, #1169). diff --git a/changelog.d/1210-installations-note-english.md b/changelog.d/1210-installations-note-english.md new file mode 100644 index 0000000000..e8fccd4add --- /dev/null +++ b/changelog.d/1210-installations-note-english.md @@ -0,0 +1,3 @@ +- Return the Mapped Installations status (site counts, Overpass retries) to the + voice analyst in English; the Layers panel, the nearby-search toast and the + awareness panel translate it where they show it (daikaginza, #1210). diff --git a/changelog.d/1699-zh-hant-generated.md b/changelog.d/1699-zh-hant-generated.md new file mode 100644 index 0000000000..81710dc300 --- /dev/null +++ b/changelog.d/1699-zh-hant-generated.md @@ -0,0 +1,4 @@ +- Generate the Traditional Chinese catalog instead of translating it: + `npm run i18n -- --zh-hant` writes `zh-Hant` from `zh-CN` with OpenCC `s2tw` + and its character corrections, and `npm test` fails, naming the key, when + `zh-Hant` is edited by hand (German, @gekh, #1699). diff --git a/changelog.d/1700-i18n-plurals-context.md b/changelog.d/1700-i18n-plurals-context.md new file mode 100644 index 0000000000..6f206ba154 --- /dev/null +++ b/changelog.d/1700-i18n-plurals-context.md @@ -0,0 +1,7 @@ +- Give counts real plural forms in every language: the wildlife count, the + Data Library list, the News time window, the GhostMaps event age and the + bridge radar range now read "1 Tag" and "7 Tage", «0,75 МОР. МИЛИ» and + «12 МОР. МИЛЬ». Street level words "the view centre" in each language's + grammar, the News heading Latest agrees with the news it heads, and FOCUS, + CONFIRMED and the course readout each have their own translation where one + word served two places (German, @gekh, #1700). diff --git a/changelog.d/1785-models-three-km-true-size.md b/changelog.d/1785-models-three-km-true-size.md new file mode 100644 index 0000000000..39faedf202 --- /dev/null +++ b/changelog.d/1785-models-three-km-true-size.md @@ -0,0 +1,5 @@ +- Aircraft, vessels, transit and rail vehicles draw as 3D models only within + 3 km of the camera, at their true size, and as icons farther away; Proximity + and All use the same distance and differ by how many models they allow. + Deselecting a plane drawn as a model no longer flashes its icon for a second + before the model returns (Sameh Khamis, @samehkhamis, #1785). diff --git a/changelog.d/1788-sprites-history-live.md b/changelog.d/1788-sprites-history-live.md new file mode 100644 index 0000000000..8c3834d7d3 --- /dev/null +++ b/changelog.d/1788-sprites-history-live.md @@ -0,0 +1,7 @@ +- Draw contacts by kind: aircraft icons share one size, helicopters turn a + three-frame rotor while airborne or moving, ADS-B ground vehicles get one + amber sprite and ground stations one mast, and vessels get hull sprites by + type plus one buoy. Going back to live keeps contacts on screen and replaces + them by id instead of emptying the map, and 1 min/s playback no longer + stalls waiting for positions. Cesium models move their parts (rotors, + propellers, gear, doors) from the optional model part state (samehkhamis, #1788). diff --git a/changelog.d/1789-multi-part-fleet-models.md b/changelog.d/1789-multi-part-fleet-models.md new file mode 100644 index 0000000000..e99f3e4efc --- /dev/null +++ b/changelog.d/1789-multi-part-fleet-models.md @@ -0,0 +1,5 @@ +- Ship the fleet models with named parts: rotors, propellers, landing gear and + doors on every aircraft, helicopter, vessel, ground vehicle and transit + model, so renderers that draw model part state can spin, pose or highlight + them. Stowed gear and closed doors are built hidden, so models look as + before without it (samehkhamis, #1789). diff --git a/changelog.d/1790-vessels-toggle-without-feed.md b/changelog.d/1790-vessels-toggle-without-feed.md new file mode 100644 index 0000000000..a92d08d73c --- /dev/null +++ b/changelog.d/1790-vessels-toggle-without-feed.md @@ -0,0 +1,3 @@ +- Let AIS vessels turn on and off again when their feed fails; the live + position load no longer passes the poll's answer to `enable()` + (samehkhamis, #1790). diff --git a/changelog.d/1792-parts-check-while-spinning.md b/changelog.d/1792-parts-check-while-spinning.md new file mode 100644 index 0000000000..504c0edf25 --- /dev/null +++ b/changelog.d/1792-parts-check-while-spinning.md @@ -0,0 +1,2 @@ +- Fix the model parts conformance check timing out while a part spins: it + waits for drawn frames instead of a settled scene (samehkhamis, #1792). diff --git a/changelog.d/1793-panel-speed-reported.md b/changelog.d/1793-panel-speed-reported.md new file mode 100644 index 0000000000..602ec70179 --- /dev/null +++ b/changelog.d/1793-panel-speed-reported.md @@ -0,0 +1,3 @@ +- Show the reported ground speed in the flights and military panels while an + aircraft's placement waits for its next report, instead of 0 m/s + (samehkhamis, #1793). diff --git a/changelog.d/1794-models-keep-paint.md b/changelog.d/1794-models-keep-paint.md new file mode 100644 index 0000000000..3a2ca1e472 --- /dev/null +++ b/changelog.d/1794-models-keep-paint.md @@ -0,0 +1,3 @@ +- Keep a tracked or emergency aircraft model's paint visible: its tint now + mixes in instead of multiplying, which drew red models black under the + cyan tracked colour (samehkhamis, #1794). diff --git a/changelog.d/1795-trail-follows-placed-aircraft.md b/changelog.d/1795-trail-follows-placed-aircraft.md new file mode 100644 index 0000000000..3e0d89cc13 --- /dev/null +++ b/changelog.d/1795-trail-follows-placed-aircraft.md @@ -0,0 +1,3 @@ +- The followed aircraft's trail runs to where the aircraft is drawn when an + application places live contacts, instead of ending far behind it, and its + head no longer drops out after the page loads (Sameh Khamis, @samehkhamis, #1795). diff --git a/changelog.d/1796-flights-feed-type.md b/changelog.d/1796-flights-feed-type.md new file mode 100644 index 0000000000..950ba0bdac --- /dev/null +++ b/changelog.d/1796-flights-feed-type.md @@ -0,0 +1,3 @@ +- Draw civil aircraft with their own class and model from the first fix when + the snapshot sends a type (`typeByIcao`), instead of as an airliner until + the type lookup returns (samehkhamis, #1796). diff --git a/changelog.d/1797-selection-keeps-colour.md b/changelog.d/1797-selection-keeps-colour.md new file mode 100644 index 0000000000..510ea9e8a3 --- /dev/null +++ b/changelog.d/1797-selection-keeps-colour.md @@ -0,0 +1,6 @@ +- Selecting or tracking a contact no longer recolours it: a tracked aircraft's + icon and 3D model keep the colours they have untracked (no cyan, or lighter + amber in Military Flights), a selected vessel or aid to navigation keeps its + type colour instead of turning white, and a tracked satellite's dot keeps + its class colour instead of turning yellow. An emergency stays red while + tracked (samehkhamis, #1797). diff --git a/changelog.d/1799-ground-types-plausible.md b/changelog.d/1799-ground-types-plausible.md new file mode 100644 index 0000000000..6767f86681 --- /dev/null +++ b/changelog.d/1799-ground-types-plausible.md @@ -0,0 +1,3 @@ +- Draw a feed's airport vehicle as a vehicle only while it drives on the + ground, and stand a ground station on the ground whatever height it reports + (samehkhamis, #1799). diff --git a/changelog.d/1800-live-aircraft-ground.md b/changelog.d/1800-live-aircraft-ground.md new file mode 100644 index 0000000000..0b50993986 --- /dev/null +++ b/changelog.d/1800-live-aircraft-ground.md @@ -0,0 +1,3 @@ +- Pass the host's live placement the ground under each aircraft (`groundM`), + where the layer already knows it, so landings can be judged above the ground + (samehkhamis, #1800). diff --git a/changelog.d/1801-logo-returns-to-start.md b/changelog.d/1801-logo-returns-to-start.md new file mode 100644 index 0000000000..a06968213c --- /dev/null +++ b/changelog.d/1801-logo-returns-to-start.md @@ -0,0 +1,4 @@ +- The title logo goes back to live at the starting view: the clock goes live + and the camera flies to where the app started (`homeView` of + `createApplicationControls`, the start view unless given) (samehkhamis, + #1801). diff --git a/changelog.d/1802-bikeshare-coverage.md b/changelog.d/1802-bikeshare-coverage.md new file mode 100644 index 0000000000..8a487c37e4 --- /dev/null +++ b/changelog.d/1802-bikeshare-coverage.md @@ -0,0 +1,3 @@ +- Bike Share marks every covered city on the globe above the height its + stations draw at; clicking a city's marker flies down into it + (samehkhamis, #1802). diff --git a/changelog.d/1803-shots-click-to-go-reorder.md b/changelog.d/1803-shots-click-to-go-reorder.md new file mode 100644 index 0000000000..427a9a5f4d --- /dev/null +++ b/changelog.d/1803-shots-click-to-go-reorder.md @@ -0,0 +1,4 @@ +- Clicking a shot row anywhere (its number, title or summary), or pressing + Enter or Space on its title, now goes to the shot, as LOAD did; the LOAD + button is gone. In its place, up and down arrows swap the shot with its + neighbour, saved with the project (Sameh Khamis, @samehkhamis, #XXXX). diff --git a/changelog.d/1804-route-steps-export.md b/changelog.d/1804-route-steps-export.md new file mode 100644 index 0000000000..1a46ffe2f1 --- /dev/null +++ b/changelog.d/1804-route-steps-export.md @@ -0,0 +1,3 @@ +- `gods-eye-view/sources/places` also exports `normalizeOsrmSteps`, so a route + proxy outside Core's dev server can serve the same turn-by-turn steps the + Directions layer asks for with `steps=1`. diff --git a/changelog.d/1806-renderer-engine-hook.md b/changelog.d/1806-renderer-engine-hook.md new file mode 100644 index 0000000000..4ef5551801 --- /dev/null +++ b/changelog.d/1806-renderer-engine-hook.md @@ -0,0 +1,3 @@ +- Renderer plugins can hand the application their own engine (`ApplicationHooks.engine`, + Cesium's is `{kind: 'cesium', viewer}`) for drawing beside the contract + (samehkhamis, #1806). diff --git a/changelog.d/1807-library-server-routing.md b/changelog.d/1807-library-server-routing.md new file mode 100644 index 0000000000..58296e4f33 --- /dev/null +++ b/changelog.d/1807-library-server-routing.md @@ -0,0 +1,9 @@ +- The Data Library's proxy is a fetch handler any server can mount + (`createLibraryHandler`, `sources/library`). A server can hide catalog + entries or route browser-direct ones through its proxy, view-bounded entries + ask it for a grid-snapped box, answers are cacheable for `cacheSeconds`, and + an application can fetch library tiles and datasets through its own cache + (`createApplicationTools({ library })`) and offer only what the server's + catalog names, nothing while it does not answer (`requireCatalog`). Tile + paths and view boxes have one spelling, and partitioned reads can be capped + per process and per request (samehkhamis, #1807). diff --git a/changelog.d/1810-library-catalog-fetch.md b/changelog.d/1810-library-catalog-fetch.md new file mode 100644 index 0000000000..4911a5632f --- /dev/null +++ b/changelog.d/1810-library-catalog-fetch.md @@ -0,0 +1,4 @@ +- An application can ask the Data Library's catalog with its own fetch + (`createApplicationTools({ library: { fetchImpl } })`), for a server that + wants the application's credentials on its library routes (samehkhamis, + #1810). diff --git a/changelog.d/1815-library-off.md b/changelog.d/1815-library-off.md new file mode 100644 index 0000000000..4eb96e1046 --- /dev/null +++ b/changelog.d/1815-library-off.md @@ -0,0 +1,3 @@ +- An application built with `createApplicationTools` can leave the Data Library + out with `library: false`: no catalog is asked and no Browse button is drawn + (samehkhamis, #1815). diff --git a/changelog.d/808-cctv-focus-nearest-point.md b/changelog.d/808-cctv-focus-nearest-point.md new file mode 100644 index 0000000000..1c9a691a12 --- /dev/null +++ b/changelog.d/808-cctv-focus-nearest-point.md @@ -0,0 +1,3 @@ +- Add a CCTV control method to select the catalog camera nearest an explicit + WGS84 point, optionally flying to it. Viewer-nearest navigation uses the same + coordinate lookup (Kevin Rajan, #808). diff --git a/changelog.d/881-imagery-cancellation.md b/changelog.d/881-imagery-cancellation.md new file mode 100644 index 0000000000..dd67a9ba48 --- /dev/null +++ b/changelog.d/881-imagery-cancellation.md @@ -0,0 +1,5 @@ +- Cancel Recent Imagery thumbnail fetches that are no longer wanted when focus, + the visible strip, pins or sources change; a day already known to have + imagery stays known. When the automatic day turns out empty, fetch the next + day again even if scrolling had cancelled it (kvnloo, #881; reviews: + quanticsoul4772, gekh). diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 44d598cac2..2852bea0ae 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -150,7 +150,8 @@ Google credentials are resolved on each request; the default uses the existing server-key precedence, and callers may supply `resolveApiKey`. `gods-eye-view/sources/places` exports portable response projections for Google -place results and OSRM route results/profile aliases. These functions own no +place results and OSRM route results/profile aliases, and the turn-by-turn +steps (`normalizeOsrmSteps`) Core's `/api/route` serves with `steps=1`. These functions own no credentials, requests, caches, environment loading, or rendering. Callers retain input validation and upstream-response acceptance. The boundary check builds this entry independently and rejects Node imports. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index bb301fd01a..f4ca7d74d0 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -408,7 +408,11 @@ ground state) and draws a contact where `place` puts it: position, height (the layer's own when none is given), course and speed. A null answer, a provider that throws, a kind it leaves out, or no provider at all keeps the layer's own motion, unchanged; following the world clock, the layers never -ask it. Transit and rail vehicles a provider places are advanced every frame +ask it. A tracked aircraft or military aircraft the provider places keeps its +trail joined to it: the trail runs up to the time read off its own reports +where the aircraft is drawn, not the layer's display delay, so it neither +stops short of the aircraft nor runs on ahead of it, and it is drawn from the +first report behind the aircraft. Transit and rail vehicles a provider places are advanced every frame in view while their placed position changes; one it holds still lets the render loop idle and is asked again each second, moving on once its placement does. A placed transit vehicle is drawn at its placed point, and a placed @@ -585,6 +589,17 @@ keyless routes use the keyless gate so they work behind a reverse proxy. Operators opt entries in with `GEV_LIBRARY_ENABLE` and remove them with `GEV_LIBRARY_DISABLE`. A static build with no server still serves every browser-direct, non-opt-in entry; proxied ones say they need the app's server. +The proxy is a fetch handler (`createLibraryHandler`, exported as +`gods-eye-view/sources/library`) that the dev server mounts behind its gates. +Another server can mount it with `listed` (hide entries: the catalog marks them +`listed: false` and Browse leaves them out) and `proxied` (route browser-direct +entries through it: the catalog marks them `fetch: "proxied"`). A routed +view-bounded entry asks for its box snapped to a power-of-two grid +(`libraryViewBox`, `?bbox=` on `/data/`); GeoParquet entries are read on the +server then. Tile, data and complete index answers carry `public, +max-age=` (`private` when keyed). `createApplicationTools` +takes `library.fetchTile` and `library.fetchData` so an application can fetch +library tiles and proxied datasets through its own cache. The Browse dialog is a `dialog[data-panel-surface]`: modal, labelled, search focused on open, Escape and backdrop dismiss and return focus to Browse, and it @@ -2215,7 +2230,7 @@ wins, with ADS-B taking a tie. GEV treats `minfuel` and `lifeguard` as prioritie Civil and military fleet billboards, 3D models and Cockpit dots turn red for emergencies and repaint when the broadcast changes. Priorities retain normal -colors; tracked map colors keep their existing selection treatment. The Cockpit +colors; tracking never recolours a contact, so a tracked emergency stays red. The Cockpit meta line names the squawk or ADS-B status (only emergencies are red), replacing COURSE ALIGNED while a status is present. @@ -2291,8 +2306,20 @@ clears nothing. A snapshot that fails clears the time and is asked again after 5 seconds; one the source drops for a newer request (an `AbortError`) is no failure, and nothing is cleared. A layer has one snapshot loading at a time: the older is aborted before a newer starts. Moving the view while vessels follow the clock asks for the new -area at the same time. Back at live the contacts are cleared and the layer -polls at once. +area at the same time. Back at live the layer polls at once and keeps the +contacts it shows until that live snapshot answers; it then stands in for every +contact. A contact it has keeps its icon and model: an aircraft eases from +where it is drawn onto its live path (unless that is farther than a jump would +be, 5 km; a placed aircraft over a recovery's time, nose along the way, and a +new answer while that ease runs eases on from where it is then), and a vessel +moves to its live fix. A contact it lacks is judged as a live poll judges any +absence, as last seen at its newest fix rather than when it was loaded: a +partial snapshot keeps only those fixed within five minutes, the tracked +aircraft stays only while its newest fix is under ten minutes old and it has +not landed, the selected vessel is held as a live refresh holds it, and the +rest go at once (no missed-poll grace); the tracked aircraft's trail goes on. A live poll already out when +the clock comes back to live is the one that takes over. A live snapshot that fails, or that brings no +vessels, clears the layer; one dropped for a newer poll clears nothing. A timeline may also declare `spanMs`: each record of a snapshot at a time then carries `fixes`, `{ atMs, lat, lon, altitudeM? }` in time order, its own track @@ -2307,6 +2334,13 @@ those it has keep their place, as their fixes put them. Paused, a time nearing the end of the fixes after the newest asks for the snapshot there. A contact is not drawn more than a minute before its first fix, as it was not there yet. Each contact keeps at most 240 fixes, at least 20 seconds apart, and the loaded snapshot times span at most 20 minutes. +Playing on with fixes, the layer asks for the next step 4 seconds of play +ahead at the clock's rate (at least a step; at 60x, 4 minutes ahead), and play +holds only a minute short of where the newest snapshot's fixes end (as far as +nine in ten of its records' fixes reach, at most the declared span; the minute +at most half of it), not at the step still loading. An aircraft keeps the fixes it holds +when the next snapshot's run reaches back over them: only the last of them, +made again from the new run, and the fixes past it are made and added. A snapshot at `atMs` describes the world as it stood then: `observedAtMs` is at or before `atMs`, no record is observed later than `atMs`, freshness and @@ -2346,12 +2380,20 @@ Scene controls own creation/deletion prompts, panel listeners, shot rows, playba and keyboard cancellation. The director supplies project reads and explicit editing/playback actions while retaining persistence, camera and layer sequencing. Shot selection updates the highlight without replacing the row, preserving -native double-click rename. Replacing rows revokes their old listeners. Disposal stops controls immediately; +native double-click rename. A click anywhere on a shot row (its number, title or +summary line), or Enter or Space on its title, goes to the shot: it is selected +and loaded (`SceneDirector.loadShot`: its look, layers and camera), so the row +has no separate LOAD button. Each row's up and down arrows swap the shot with +its neighbour (`SceneDirector.moveShot`, saved with the project and published as +`shot-moved`); they are disabled at the ends and while the scene plays, and, +like DEL, never load the shot. Shot rows show no thumbnail: a shot keeps no +picture of its view, only the scene's Stories card does. Replacing rows revokes +their old listeners. Disposal stops controls immediately; late file and failed-action completions cannot update removed presentation. The panel is titled Authoring and is laid out in four labelled steps: SCENE (picker on its own row listing every scene in the project, NEW SCENE, DELETE), -SHOTS (+ CAPTURE SHOT, UPDATE SHOT, the numbered shot list and a select/rename +SHOTS (+ CAPTURE SHOT, UPDATE SHOT, the numbered shot list and a go-to/rename hint), PREVIEW (PLAY, STOP, NEXT) and SAVE & SHARE (a row of Stories tag chips; the thumbnail preview, CAPTURE THUMBNAIL and SAVE TO STORIES on one row; then EXPORT, IMPORT, RUN LOG, then the EDIT DETAILS / SHARE SCENE row). On load the @@ -2835,6 +2877,10 @@ while `_clearLayersOutsideContextMode` switches the layer off): the user switching CCTV off inside Contacts closes the panel as anywhere else. A panel opened by hand while the layer is off stays open, and its meta line reads the catalog count, not the last active camera. +The CCTV control `focusNearestToPoint(lat, lon, options)` selects the catalog +camera nearest a WGS84 point and flies to it unless `focus: false`. No UI action +calls it yet. + ## UI disposal UI disposal releases the CCTV subscription, command-dock observer, legacy drag @@ -3178,8 +3224,8 @@ retain their specialized ownership. Browser acceptance: ## Ordinary action buttons -Scene panel actions, shot LOAD/DEL actions, the EDIT DETAILS / SHARE SCENE -bar and one-shot CCTV actions use the shared `gev-action-button` surface in +Scene panel actions, shot move-up/move-down/DEL actions, the EDIT DETAILS / +SHARE SCENE bar and one-shot CCTV actions use the shared `gev-action-button` surface in `ui/styles/action-button.css`, with default/danger variants and default/compact sizes, drawn by the scene panels view (`LayerPanelsView.vue`, `SceneShotList.vue`) and the CCTV panel. Feature @@ -3361,6 +3407,11 @@ catalogued systems). The chip stays ON. A loading or failed Bike Share city shows its own text. Leaving coverage clears the last-update time. The voice analyst gets the same English notes; both translate them through `translateStatusMessage` (`src/ui/statusText.js`). +Above its gate Bike Share also marks every covered city on the globe: a +green, white-ringed dot per registry system, 5 km up so terrain never hides +it, shown only while the layer is on and stations are not drawn. Clicking one +flies straight down into the city from 20 km, an explicit camera action like +the other camera controls (`attachShellServices({ runNavigation })`). ## Places and CCTV request bounds @@ -4821,6 +4872,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > The title and loading logos use a blue 10 px outer-eye stroke with a > translucent slate fill, while the globe-and-cage gaze travels up to 34 SVG > units toward the pointer for clearer feedback at the compact title size. +> The title logo is a button, "Back to live at the starting view": the world +> clock goes live and the camera flies to the view the app started from (the +> host's `homeView`, else its `startView`, else the whole planet), letting go +> of whatever it follows as Reset Globe does (`returnToStart()`). > - **Context, Cockpit, and Radio interaction contract:** explicit Contacts, > Space Missions, and successful Cockpit actions reveal the Context panel, while > restoration and replay preserve its prior collapsed state. Contacts uses the @@ -4896,9 +4951,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > at 45% of their normal presentation opacity to reduce visor clutter; callouts, > density, allocation, fade, and Outside tuning are unchanged and normal bracket > opacity returns on exit. AIR presentation follows the same retained 3D mode: -> Proximity uses 150/185 km and All uses 400/450 km. With 3D off, in-range -> contacts remain rotating 2D silhouettes; with 3D on, ready admitted models -> take over under the Cockpit cap of 60. Loading/capped contacts remain 2D, +> Proximity uses 150/185 km and All uses 400/450 km for the AIR silhouettes +> (`COCKPIT_AIR_*`). With 3D off, in-range contacts remain rotating 2D +> silhouettes; with 3D on, ready admitted models take over within 3 km under +> the Cockpit cap of 60. Loading/capped contacts remain 2D, > out-of-range contacts use rotation-free dots, and exit restores map treatment. > Its Radio popover exposes compact power, > transport, station, and volume controls. Cockpit Previous/Next changes the @@ -5791,7 +5847,9 @@ Shipped locales: **en** (source and fallback), **ar**, **de**, **es**, **fr**, * - **Gate.** `npm run i18n` (and `src/i18n/catalog.test.mjs` under `npm test`) extracts every message and fails on missing, empty, unused, placeholder-mismatched, still-English (plural forms included) or - wrongly-shaped plural entries. + wrongly-shaped plural entries. `zh-Hant` is generated from `zh-CN` + (`npm run i18n -- --zh-hant`: OpenCC `s2tw` through `opencc-js`, then a + fixed list of character corrections), and the gate fails when it differs. - **Not translated by design:** layer ids, share-link and hash parameters, API fields, voice tool schemas, provider names, feed data (callsigns, vessel and station names) and attribution. @@ -5849,7 +5907,7 @@ its criteria cannot be silently ignored. | Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache | | CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + King County (WA) Open Data + WSDOT (WA) Open Data + NYC DOT TMC (opt-in) + City of Toronto RESCU + Catalonia (Servei Català de Trànsit) + Iceland (Vegagerðin / IRCA) + Hong Kong Transport Department + FL511 (FL, opt-in) + Freeway Bureau, MOTC (Taiwan) + Houston TranStar (opt-in) + Autostrada del Brennero (IT, A22 stills) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | | Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | -| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | +| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (53 keyless feeds, 50 regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | | Rail 🚆 | Live operator train positions (GPS, or station reports for Irish Rail) and trip updates, trains only, with opt-in route packs built from static GTFS (30 keyless feeds, all on, 28 out of the box; `src/data/railFeeds.js`) | `src/layers/rail/` via `src/app/layers/rail.js` | `/api/rail` | 15s (poll + delayed playback) | | Bikeshare 🚲 | GBFS (Lyft + BCycle + Social Bicycles + PBSC incl. Bike Share Toronto, Bike Itaú (Brazil), Bicing (Barcelona) and seven other Spanish cities + Urban Sharing, Entur, JCDecaux (Lillestrøm, Valencia, Seville) + nextbike (AMBici)) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | | Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | @@ -6424,8 +6482,8 @@ Transit is off by default, and share links use token `j`. The movement panel ord places Transit directly after Street Traffic and before Rail. Cameras and utilities retain their own groups. The layer polls registered feeds near the camera every 15 seconds, below a 3,000 km altitude -gate. Forty-nine keyless regions are available: Boston, Austin, Minneapolis–St Paul, -Helsinki, the Netherlands, Norway, South East Queensland, Rio de Janeiro +gate. Fifty keyless regions are available: Boston, Austin, Minneapolis–St Paul, +Helsinki, the Netherlands, Norway, South East Queensland, Cairns, Rio de Janeiro (municipal buses and the Mobi-Rio BRT, two feeds), Szczecin, the Lisbon Metropolitan Area and the city of Lisbon, Prague and Central Bohemia, Warsaw, Kraków (buses and trams, two feeds), Poznań, Gdańsk, Rzeszów, Vilnius, Bucharest, Cluj-Napoca, Iași, Rome, Turin, Venice (buses and waterbuses, two feeds), Bordeaux, Montpellier, Rouen, Toulon, Le Havre, Tours, Málaga, Sendai, Johor Bahru, Kota Bharu, Adelaide, Atlanta, Denver, Edmonton, Halifax, Victoria, and nine in Ontario — Toronto (TTC surface vehicles; the subway publishes no positions), MiWay, Hamilton HSR, Durham Region, YRT/Viva, Guelph, @@ -6446,10 +6504,13 @@ a record from the bundled proxy is classified by the hints alone. Route hints read from each operator's routes.txt cover Prague's trolleybus lines and Petřín funicular, and Bucharest, Cluj-Napoca and Turin's trams, trolleybuses and metro lines (and Turin's Sassi–Superga rack tramway, typed a funicular in its -routes.txt). Le Havre's funicular is a correction, not read from routes.txt: its +routes.txt). Route-id hints also cover TransLink's rail, Gold Coast light rail +and ferries, and Adelaide Metro's trains, trams and SeaLink ferry; their other +routes stay buses by default. Le Havre's funicular is a correction, not read from routes.txt: its route hint and its correction both say funicular. Vilnius publishes no route ids in its positions, so -its trolleybuses read as buses. Retained history classifies its epochs the same -way, so a trail joins the live vehicle. +its trolleybuses read as buses. TransLink labels drop the GTFS version and +Cairns's `C` prefix (`C123-33` reads as route 123). Retained history classifies +its epochs the same way, so a trail joins the live vehicle. Retained transit history uses the same outlier quarantine as live observations and preserves the active live bracket. Rejected reports do not publish route or mode @@ -7288,7 +7349,7 @@ silently demoting every later lookup for the session. - **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder. - **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them. - **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode. -- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. +- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. The tracked satellite's dot keeps that colour too: tracking draws it larger (14 px), white-outlined and over everything, never in another colour (`_addTrackedEntity`, `src/layers/satellites/rendering.js`). - Class is also a **text field**, not just a color: `TELECOM · GPS` / `STARLINK` / `STATIONS · ISS` leads the tracked card's detail block and replaces the raw CelesTrak tag on the detection-overlay label. Because that canvas composites above the post-FX chain, the class stays readable in NVG/FLIR after the in-scene dot colors are flattened. - The satellites row in DATA LAYERS carries per-layer sub-controls (`DataLayerManager._syncRowControls`, the first consumer of the optional `getRowControls()` layer hook): one chip per class (the STARLINK chip exposes the existing `catalog` param), a swatch legend with live per-class counts, and an info line while SATCAT is stale or unavailable (`Classes may lag: SATCAT is a cached copy` / `Classes may lag: SATCAT unavailable`). Default is the sparse core catalog. The chips are stateless — each declares the params to apply and the manager owns the write — so the Space Missions capture/restore path over the same param stays authoritative. Controls stay hidden while the layer is off. An explicit CORE or DENSE choice participates in versioned local and share-link state; temporary Space Missions overrides do not. - **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet`, `sar` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead. @@ -7425,7 +7486,7 @@ silently demoting every later lookup for the session. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission. Close selected-pad views add one static 500 m-radius cyan launch-zone ring with a low-opacity translucent fill over the sampled photoreal launch-site surface. The single scene primitive is created only for the visible selected site and is otherwise dormant. It appears during Focus, sufficiently close manual zoom, and the replay countdown, but is suppressed above 120 km camera altitude, beyond 180 km direct camera-to-pad range, for unselected missions, and whenever Space Missions is inactive. Focus establishes a launch-site-centered camera transform once; subsequent manual heading and pitch changes remain centered on that site without an automated per-frame correction. Surface mission markers and labels use an additional conservative globe-limb margin before the exact ellipsoid occluder boundary, preventing near-horizon visibility from alternating between frames. -- **AIS vessels**: chevron symbology (naval cyan base, type tints), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`; a vessel's callout fades by the painted opacity of its own ambient card, so a card dropped by budget, collisions or UI chrome, or faded at the keyhole rim, leaves the callout readable), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. +- **AIS vessels**: hull sprites by vessel kind, tinted by type (see the map sprites entry below), world-space headings, MMSI-keyed reconciliation (selection survives refreshes; pinned 3 refreshes with STALE marker when absent), detection-overlay integration (`type: 'SEA'`; a vessel's callout fades by the painted opacity of its own ambient card, so a card dropped by budget, collisions or UI chrome, or faded at the keyhole rim, leaves the callout readable), contextStore registration for voice Q&A. Empty-space clicks, id-less photorealistic-tile picks, and Escape dismiss the vessel card/HUD/context and clear its trail; picks owned by another layer (including `gev-trail:*`) and raw vessel-record picks without a live MMSI key are no-ops for vessel selection. Click and key handlers detach while the layer is disabled and reinstall on enable. Selecting another vessel replaces the selection and trail, and reconciliation clears a trail if its owning vessel is evicted. - **Track trails**: server accumulates per-MMSI ring buffers (`/api/vessels/track?mmsi=`, Float32+Uint32, 64 samples, 30s/25m thinning); aircraft backfill proxies `/api/flights/track` (OAuth, own credit bucket). Military aircraft keep only their locally accumulated trails: `/api/military/track` validates the hex, then answers `503 history_unavailable` without an upstream request. - Shared `src/data/pickRegistry.js` stops the two flight layers' click handlers from fighting over the camera. @@ -8015,7 +8076,7 @@ pins and share links already supply complete boxes. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. - **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). @@ -8023,19 +8084,20 @@ pins and share links already supply complete boxes. ### 3D Aircraft + Tracking (June 2026) -- **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. +- **The TRACKED contact draws as a model exactly when the fleet would.** `_trackedModelRegimeActive` (`src/layers/flights/tracking.js`, `src/layers/military/tracking.js`) asks the fleet's own rule: the DISPLAY-rail `3D` toggle on, the camera below the fleet ceiling, and a place in the fleet pass's nearest-first cap (`_trackedModelEligible`), so selecting a contact changes neither its colour nor its form or size. Cockpit and TR-3B suppression are unchanged. While a contact is selected its FLEET model stays loaded but hidden (`_keepTrackedFleetModel`, `src/data/aircraftModelLayer.js`): it draws the contact only until the tracked model is ready, and the fleet pass keeps it placed where the icon is (admitting one if the contact was an icon when selected and comes within range). Deselecting hands the contact back in the same frame (`_handBackDeselected`): to that fleet model when it is loaded, else to the icon, so a contact drawn as a model never flashes its icon while a new fleet model loads. The tracked model loads on demand from the fleet set's bytes; on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset (the driver runs every `scene.preUpdate`, so an unbounded catch would spin load→reject at frame rate), and the load-failure budget is per-selection state cleared by `_resetTrackedSelectionState()` on deselect / re-track / cross-layer / init / destroy. The icon stays the visual throughout a failed load. - **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. Tiles still streaming is not a miss: no sample is taken, so it earns no retry backoff, and the first fleet tick after the tiles settle samples (2026-11-15); only a sample that finds no ground backs off (2 s, doubling to 30 s). WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. - **Ground-snap clock rollback recovery.** If the wall clock moves before the sampling-window start, ground snap opens a new window while retaining the normal four-samples-per-250-ms budget. Retry timestamps more than the maximum 30-second backoff ahead of the current clock are ignored. A smaller rollback can retain a bounded retry delay of up to 30 seconds. -- Commercial and military aircraft use the same high-level FLEET model regime: 2D billboards when zoomed out, optional glTF models when closer, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons. The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the tracked colour (cyan, or amber in Military Flights) and the emergency red multiply into the mesh, so its paint still shows. IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. -- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and add/keep radii as the aircraft (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is a bone-white ringed disc (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`) instead of a chevron, never rotated, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its disc but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay. +- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. +- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo. +- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before. +- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay. - **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload. - The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged. -- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only below `MODEL_ALT_CEIL_M` and only for the nearest `MODEL_MAX` in view — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design. -- **Consequence of the flip on the recorded tracked/fleet inversion:** the 150–800 km band where surrounding contacts draw as models while the SELECTED one is still a glyph is now what an operator sees WITHOUT arming anything. The inversion itself is unchanged and still deliberate (see `src/data/trackedModelRegime.js`); only its reachability changed. +- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only within 3 km of the camera and only for the nearest `MODEL_MAX` — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design. - Civilian and military 2D aircraft use the established distance scale: `3×` near the camera and a `0.5×` floor from 8,000 km outward. A standard 20 px ambient icon therefore remains about 10 px at globe altitude while retaining the @@ -8860,8 +8922,8 @@ on purpose: - **Class.** Each aircraft is classified with `aircraftClass.js` from its ADS-B emitter category (dump1090 strings: `A1` light, `A3` large, `A7` rotorcraft; set A/B/C/D = type code 4/3/2/1) and, once known, its adsbdb - ICAO type. Silhouette and per-class scale come from `aircraftIcons.js` - (×0.8 on the ground), tinted magenta. + ICAO type. The silhouette comes from `aircraftIcons.js`, at the one + size every class draws at (×0.8 on the ground), tinted magenta. - **3D.** The DISPLAY rail's 3D toggle and its proximity/all mode apply: the layer reads the Flights layer's `models3d` params and uses the same ceiling, caps, add/keep radii, visible-first eligibility diff --git a/docs/DATA-LIBRARY.md b/docs/DATA-LIBRARY.md index c549e7b4d2..897eb8e0a7 100644 --- a/docs/DATA-LIBRARY.md +++ b/docs/DATA-LIBRARY.md @@ -167,6 +167,53 @@ code. It reaches only the manifest's host, refuses redirects, caps bodies, caches per `cacheSeconds` and never returns upstream error text. The browser names an entry id, never a URL, so the proxy cannot be pointed anywhere else. +## Serving the library from another server + +The proxy is also a fetch handler, `createLibraryHandler` from +`gods-eye-view/sources/library` (`src/library/proxy.js`): a `Request` in, a +`Response` out, for a server other than the dev server (a Worker, say). Its +options decide what the server offers: + +- `listed(entry)` false hides an entry: `/catalog` marks it `listed: false`, + Browse leaves it out entirely, and no route serves it. +- `proxied(entry)` true routes a `browser-direct` entry through the handler: + `/catalog` marks it `fetch: "proxied"` and the browser asks the server for + its tiles and data. A view-bounded entry then asks `/data/?bbox=…` for + the camera's box snapped out to a power-of-two grid (`libraryViewBox`), so + nearby views share one answer; any other box is refused. +- `keep: false` keeps nothing in the process's memory, for a server with a + shared cache in front. Answers carry `Cache-Control: public, + max-age=` (`private` for a keyed entry). +- `partitionCache` is the map of decoded GeoParquet partitions (at most four + are kept); pass one map per process to cap them there. +- `fetchIndex(entry)` reads a partitioned entry's index, for example the + handler's own `/index/` through a shared cache. A `/data` request never + builds an index itself: without a complete or partial one it answers 503 + `index_unavailable`. +- `subrequestLimit` caps the upstream requests one request may make (a host's + per-request limit); a request that would need more answers 503 + `subrequest_limit` instead. + +Every resource has one spelling: tile paths are `/tile////` with +integers without leading zeros, `x` and `y` below `2^z` and `z` within the +entry's zoom range; a path with an empty segment or a trailing slash is +refused; a view box is accepted only in `libraryViewBox`'s exact spelling. A +shared cache keyed on the path (and a `/data` request's `bbox`) therefore +holds each answer once. + +Same-site gates and rate limits stay with the server that mounts it. An +application can also fetch the library's tiles and proxied datasets itself, +to keep them in its own cache: `createApplicationTools({ library: { fetchTile, +fetchData } })`. `fetchTile` is the imagery spec's tile fetch, told which +entry asks; `fetchData` answers a proxied dataset URL. + +`library: { requireCatalog: true }` makes the server's `/catalog` an +allowlist: the library offers only what it names, and while it does not +answer (an error status, a timeout, a page that is not the catalog) it offers +nothing at all, rather than every entry the browser could fetch itself. It is +asked again after 30 seconds, then at doubling intervals up to ten minutes, +and the viewer's saved entries come back once it answers. + ## Operator switches | Variable | Effect | diff --git a/docs/I18N.md b/docs/I18N.md index cf80ad37b5..4799cded25 100644 --- a/docs/I18N.md +++ b/docs/I18N.md @@ -102,7 +102,8 @@ Call it before views render. `onLocaleChange` listeners word their text again at - **Pass literals.** `t('Close')`, not `t(label)` (unless `label` holds a `msg()` value) and never a template literal with `${…}`. - **Use placeholders, not concatenation.** `t('Flying to {place}…', { place })`, not `t('Flying to') + ' ' + place`. Word order differs between languages. -- **Use `tn()` for counts**, not `count === 1 ? … : …`. Russian has three forms. +- **Give a fallback phrase its own message.** When code has no name to pass and falls back to a phrase ("the view centre", "this spot"), write `t('{source} at the view centre', { source })`, not `t('{source} at {place}', { place: t('the view centre') })`: after a preposition, other languages put the phrase in a case a separately translated phrase does not have. +- **Use `tn()` for counts**, not `count === 1 ? … : …`. Russian has three forms for whole numbers and a fourth for fractions. That includes a number the English writes with a symbol or abbreviation, so both English forms read the same (`tn(hours, 'Last {hours} h', 'Last {hours} h', { hours: formatNumber(hours) })`): other languages inflect the words around it («Última 1 h», «Últimas 24 h»). Fractions take their own form (ru «0,75 МОР. МИЛИ»). - **Translate the label, not the value.** Layer ids, enums, share-link parameters, API fields, voice tool schemas and feed data (callsigns, vessel and place names) stay as they are; translate only the text shown for them. - **No `t()` at module top level.** Keep the English in `msg()` and call `t()` when rendering. - **Numbers and dates** go through `formatNumber`, `formatDate`, `formatRelativeTime` and `formatUtcDayMonth` from `src/i18n/index.js`, which follow the active language. @@ -119,6 +120,8 @@ npm run i18n -- --prune # drop entries whose English no longer exists Changing the English changes the key: the old translation goes unused and the new text shows as missing. Add the translation to every `src/i18n/locales/.json` (or ask a translator), prune, and run `npm test`; it fails until every language is complete. +Do not translate `zh-Hant`: it is generated. After `zh-CN`, run `npm run i18n -- --zh-hant` (see [zh-Hant.md](./translations/zh-Hant.md)). + To see a language, open the app with `?lang=ru`, or use the language picker (the globe button in the bottom-right corner). An empty translation is reported, and so is one left as the English, plural forms included. When English is right on purpose (a code such as CRT, a product name), list it under the language in `src/i18n/same-as-english.json`. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 9b055c2269..b216b7236e 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -163,6 +163,42 @@ optional: - `frame.renderNow()` throws when the frame fails to draw. With `{ifDue: true}` it runs one tick of the loop now, as the loop's own would (camera flight, input, clock), and draws only a frame that is due. +- `ModelItem.parts` (capability `modelParts`, `ModelPartState`) poses a + model's moving parts. It applies to a model whose mesh carries a `_PART` + vertex attribute (each vertex's part index) and whose root node's glTF + `extras.parts` is its part table: each part's name, kind (`body`, `spin`, + `hinge`, `slide`, `deploy`, `separable`, `marker`), pivot, axis, limits, + rest and parent. `spin` turns parts at degrees a second, advanced by the + renderer on its own clock (a change of rate goes on from the angle + reached); `deploy` sets parts between stowed (0) and deployed (1); + `poses` moves, turns, hides or highlights a part by name, in the model's + glTF frame (forward −X, up +Y, right −Z). It changes live without loading + the model again. A model without a part table ignores it, and a renderer + without the capability, or that cannot pose parts, draws the model + whole, at rest, as its file draws it: the application runs fully without + it. The maths is `gods-eye-view/render/modelParts` (`partMatrices`: + deploy, then spin, then the pose, then the parent's), so a renderer that + poses parts draws exactly those; with `axisScale` the parts turn rigidly + in the stretched model. The Cesium port lists it and poses parts where + its context is WebGL 2 with floating-point textures, drawing models whole + elsewhere. A posed model gets a custom shader that moves each vertex by + its part's matrix, read from a small texture written in place when the + parts change and each frame a part of a model in view spins (a model out + of view or under 4 pixels across is not turned and asks for no frame), + composed with `maskColor`, `unlit` and `thermal`. A moved part's material + normal (its normal map and back-face flip kept) turns by the inverse + transpose of its matrix, exact under `axisScale`; a hidden part draws + nothing and a highlighted one is mixed toward its colour. A model at rest + keeps the shader it had, and part shaders go with the draw port. Cesium + culls and picks a model by its bounds as its file draws it, so a part + moved outside them (a large `offsetM`) draws only while those bounds are + in view, and is not picked there. The check `draw.models.parts` poses, + hides, moves, clamps and spins the parts of a model built in code + (`render/conformance/partsModel.js`): a move right lands a quarter turn + clockwise of a move forward, a mesh node turned, scaled and moved changes + nothing, a move stretches with `axisScale`, and a slide and a hinge stop + at their limits. The live layers drive it from each vehicle's record + (`src/data/modelPartDrivers.js`). The Cesium port lists `gpuTiming` where its context has `EXT_disjoint_timer_query_webgl2`: while anyone listens to frame signals, @@ -282,6 +318,9 @@ opaque command and before the translucent pass, which blends order-independently and would undo the addition; ground commands keep their pass and stencil and only blend differently. The checks `draw.sets.blend` (points, icons, lines, shapes) and `draw.models.blend` read the pixels. +`draw.models.paint` reads a lit model's vertex paint (`COLOR_0`) at a fixed +sun: its colour by day, still its colour (not black) with the sun below the +horizon, and its paint kept under a tint mixed in. A model item may bring its glTF bytes (`gltf`): the renderer builds it from them and never fetches its `url`, which stays the model's identity, so a @@ -575,7 +614,10 @@ on (no `renderer.id`, no engine type, no engine object's presence). (`ownCreditDisplay`; otherwise the application's own line, `src/ui/creditsView.js`, shows the credits port's list), and what QA scripts read from `window.__godsEyeView` (Cesium's viewer there, for the - scripts that drive it). Each is optional, none is a contract member, and + scripts that drive it), and its own engine (`engine`, whose `kind` names + it: Cesium's is `{kind: 'cesium', viewer}`) for an application that draws + with that engine directly beside the contract, only with engines whose + kind it knows, adding, updating and removing what it draws. Each is optional, none is a contract member, and a renderer without them runs the application without that behaviour. - **What the renderer should do is in the ports**, each through the application's own code: outward zooms stop at a whole-Earth view that diff --git a/docs/TRANSLATORS.md b/docs/TRANSLATORS.md index a1e1083797..48acab2420 100644 --- a/docs/TRANSLATORS.md +++ b/docs/TRANSLATORS.md @@ -36,6 +36,8 @@ npm run i18n -- --prune # drop entries the code no longer uses Changing English text changes its key: the old translation becomes unused and the new text shows as missing. Translate it and prune. +Do not translate `zh-Hant`: it is generated. Translate `zh-CN`, then run `npm run i18n -- --zh-hant` (see [zh-Hant.md](./translations/zh-Hant.md)). + ## Fixing a translation Edit `src/i18n/locales/.json` and run `npm run i18n`. To see your change, open the app with `?lang=`. diff --git a/docs/translations/ar.md b/docs/translations/ar.md index 22d5e5e354..25fe1f1fd9 100644 --- a/docs/translations/ar.md +++ b/docs/translations/ar.md @@ -66,6 +66,7 @@ Every form must keep `{count}`. For one and two, Arabic names the quantity with | call sign | رمز النداء | | vessel, ship | سفينة | | satellite | قمر صناعي | +| CONFIRMED (sightings chip; a landing) | مؤكَّدة / مؤكَّد | | launch (rocket) / space mission | إطلاق / مهمة فضائية | | contact (tracked object) | هدف | | installation, site / mapped | منشأة، موقع / مرسوم | diff --git a/docs/translations/de.md b/docs/translations/de.md index 86032a2389..fcf7de8fe0 100644 --- a/docs/translations/de.md +++ b/docs/translations/de.md @@ -53,6 +53,7 @@ Keep the verb in agreement: «{count} Station meldet» / «{count} Stationen mel | aircraft / flight / military flights | Luftfahrzeug (HUD and short labels: Flugzeug) / Flug / Militärflüge | | vessel, ship | Schiff | | satellite / shell (Starlink) / DENSE | Satellit / Schale / DICHT | +| CURRENTLY OVER (orbit, before a place name) | ÜBERFLUG | | launch (rocket) / launch site / space mission | Start / Startplatz / Raummission | | ascent / replay / payload / stage / downrange | Aufstieg / Replay, Wiedergabe / Nutzlast / Stufe / Downrange | | contact / tracking | Kontakt / Verfolgung | diff --git a/docs/translations/es.md b/docs/translations/es.md index 22a827a64b..2e893d9695 100644 --- a/docs/translations/es.md +++ b/docs/translations/es.md @@ -45,6 +45,8 @@ The `many` form is the `other` text with «de» after the number: «{count} de c | aircraft, plane / flight / military flights | aeronave / vuelo / vuelos militares | | vessel, ship | buque | | satellite / shell (Starlink) / DENSE | satélite / capa / DENSO | +| FOCUS (the held object; the button) | ENFOQUE / ENFOCAR | +| CONFIRMED (sightings chip; a landing) | CONFIRMADOS / CONFIRMADA | | launch (rocket) / launch site / space mission | lanzamiento / lugar de lanzamiento / misión espacial | | ascent / replay / payload / stage | ascenso / repetición / carga útil / etapa | | contact / tracking | contacto / rastreo | diff --git a/docs/translations/fr.md b/docs/translations/fr.md index e2f5069889..9825aa310a 100644 --- a/docs/translations/fr.md +++ b/docs/translations/fr.md @@ -49,6 +49,8 @@ The `many` form is the `other` text with « de » (« d' » before a vowel) afte | aircraft / flight / military flights | aéronef (avion in short copy) / vol / vols militaires | | vessel, ship / tanker (AIS type) | navire / navire-citerne | | satellite / shell (Starlink) / DENSE | satellite / couche de la constellation / DENSE | +| FOCUS (the held object; the button) | CENTRÉ / CENTRER | +| CONFIRMED (sightings chip; a landing) | CONFIRMÉES / CONFIRMÉE | | launch / launch site / space mission | lancement / site de lancement / mission spatiale | | ascent / replay / payload / stage / downrange | ascension / rejeu / charge utile / étage / distance au sol (DIST. SOL) | | contact / tracking / track (HUD) | contact / suivi / piste | diff --git a/docs/translations/he.md b/docs/translations/he.md index f6a7d1b14f..98f4526589 100644 --- a/docs/translations/he.md +++ b/docs/translations/he.md @@ -41,6 +41,8 @@ With {count} shown as a digit, `two` and `other` share the plural noun (2 מצל | aircraft / flight / military flight | מטוס (כלי טיס in class lists) / טיסה / טיסה צבאית | | vessel / ship / ships | אונייה / אוניות | | satellite | לוויין | +| FOCUS (the held object; the button) | מוקד / התמקד | +| CONFIRMED (sightings chip; a landing) | מאושרות / מאושר | | launch (rocket) / space mission | שיגור / משימת חלל | | contact / tracking | מגע / עקיבה | | installation / site | מתקן / אתר | diff --git a/docs/translations/it.md b/docs/translations/it.md index 7229161011..75f7173103 100644 --- a/docs/translations/it.md +++ b/docs/translations/it.md @@ -52,6 +52,9 @@ The `many` form is the `other` text with «di» after the number when a noun fol | aircraft, plane / flight / military flights | aereo / volo / voli militari | | vessel, ship | nave | | satellite / shell (Starlink) / DENSE | satellite / shell / DENSO | +| FOCUS (the held object; the button) | PUNTAMENTO / FOCUS | +| CONFIRMED (sightings chip; a landing) | CONFERMATI / CONFERMATA | +| CURRENTLY OVER (orbit, before a place name) | SORVOLO | | SPARSE / BALANCED / DENSE (detection modes) | RADO / BILANCIATO / DENSO (agree with «overlay») | | broadband (Starlink shell) | a banda larga | | VISUAL (CelesTrak group) | VISIBILI | diff --git a/docs/translations/pt.md b/docs/translations/pt.md index 682c0a3b95..b10cabe784 100644 --- a/docs/translations/pt.md +++ b/docs/translations/pt.md @@ -57,6 +57,9 @@ The `many` form is the `other` text with «de» after the number: «{count} de c | aircraft, plane / flight / military flights | aeronave, avião / voo / voos militares | | vessel, ship / TANKER (AIS class) | embarcação / NAVIO-TANQUE | | satellite / shell (Starlink) / DENSE | satélite / camada orbital / DENSO | +| FOCUS (the held object; the button) | FOCO / FOCAR | +| CONFIRMED (sightings chip; a landing) | CONFIRMADOS / CONFIRMADA | +| CURRENTLY OVER (orbit, before a place name) | SOBREVOO | | SPARSE / BALANCED / DENSE (detection modes) | ESPARSO / EQUILIBRADO / DENSO (o modo) | | launch (rocket) / launch site / space mission | lançamento / local de lançamento / missão espacial | | KM DOWNRANGE / EST. DOWNRANGE | KM DO LOCAL DE LANÇAMENTO / EST. PELA DIST. DO LANÇAMENTO | @@ -89,7 +92,7 @@ The `many` form is the `other` text with «de» after the number: «{count} de c | detection overlay | sobreposição de detecção | | pin (Draw tool) / box (Recent Imagery) | marcador / área | | Cyber (HUD layout, effect) | Ciber | -| heading / course / altitude / ground speed | rumo / curso / altitude / velocidade solo (VELOC. SOLO) | +| heading / course / altitude / ground speed | rumo / curso (a ship's course: rumo) / altitude / velocidade solo (VELOC. SOLO) | | map heading / bearing (compass, north up) | orientação (do mapa) | | HDG / BRG / CRS / FOV / DEST / SPD / RANGE | HDG / BRG / CRS / FOV / DEST / SPD / RANGE (unchanged) | | V/S (vertical speed code) | V/S (unchanged) | diff --git a/docs/translations/ru.md b/docs/translations/ru.md index a44935b716..9073cec3d7 100644 --- a/docs/translations/ru.md +++ b/docs/translations/ru.md @@ -8,7 +8,7 @@ Catalog: `src/i18n/locales/ru.json`. General rules: [TRANSLATORS.md](../TRANSLAT - Sentence case, not Title Case: "Live Flights" → «Рейсы в реальном времени». - Quotes inside Russian text are «ёлочки». Write ё where it belongs: её, ещё, всё. - In short labels, a standard abbreviation with a period beats a wrapped line: НЕОПРЕД., СЛЕД. -- Units: км, м, км/ч, м/с, уз (knots), фт (feet), ч, мин, с; in UPPERCASE text КМ, М, КМ/С, УЗ, ФТ. MW is МВт in any case. `°` and `%` stay. +- Units: км, м, км/ч, м/с, уз (knots), фт (feet), ч, мин, с; in UPPERCASE text КМ, М, КМ/С, УЗ, ФТ. MW is МВт in any case. `°` and `%` stay. Nautical miles on the bridge radar are «мор. миля», a noun that follows the count: «3 МОР. МИЛИ», «12 МОР. МИЛЬ», «0,75 МОР. МИЛИ». ## Plurals diff --git a/docs/translations/sv.md b/docs/translations/sv.md index 39d7d5aeba..3bdc93cc6a 100644 --- a/docs/translations/sv.md +++ b/docs/translations/sv.md @@ -53,6 +53,7 @@ Abbreviated units and codes do not change: «{count} MEDD.». | aircraft / flight / military flights | luftfartyg (short labels: flygplan) / flygning / militärflyg | | vessel, ship | fartyg | | satellite / shell (Starlink) | satellit / skal | +| CONFIRMED (sightings chip; a landing) | BEKRÄFTADE / BEKRÄFTAD | | launch (rocket) / launch site / space mission | uppskjutning / uppskjutningsplats / rymduppdrag | | contact / tracking | kontakt / följning | | installation / site | anläggning / plats | diff --git a/docs/translations/uk.md b/docs/translations/uk.md index 673748f420..58a3817c6b 100644 --- a/docs/translations/uk.md +++ b/docs/translations/uk.md @@ -12,7 +12,7 @@ Translation source: meirm (#312). - The apostrophe is always ʼ (U+02BC): обʼєкт, звʼязок, памʼять. Not ' or ’. - Quotes inside Ukrainian text are «ялинки»; a button or layer name inside a sentence goes in them: Увімкніть «Вуличні знімки». - In short labels, a standard abbreviation with a period beats a wrapped line: ПОПЕР., ДАЛЬН., КАЛІБР. -- Units: км, м, км/год, м/с, вуз (knots), фт (feet), год, хв, с, МГц, дБ, гПа; in UPPERCASE text КМ, М, КМ/С, ВУЗ, ФТ. MW is МВт in any case. `°` and `%` stay. Decimal comma in coordinates written as text: 28,2710° пн. ш. +- Units: км, м, км/год, м/с, вуз (knots), фт (feet), год, хв, с, МГц, дБ, гПа; in UPPERCASE text КМ, М, КМ/С, ВУЗ, ФТ. Nautical miles on the bridge radar are «мор. миля», a noun that follows the count: «3 МОР. МИЛІ», «12 МОР. МИЛЬ», «0,75 МОР. МИЛІ». MW is МВт in any case. `°` and `%` stay. Decimal comma in coordinates written as text: 28,2710° пн. ш. - Coordinates: пн. ш. / пд. ш. / сх. д. / зх. д.; the HUD hemisphere letters are Пн, Пд, Сх, Зх. ## Plurals @@ -45,6 +45,7 @@ A `tn()` entry needs four forms. `Intl.PluralRules('uk')` picks: | aircraft / flight / military flights | літак (short HUD: борт) / рейс / військові рейси | | vessel, ship / vessels | судно / судна (gen. pl. суден) | | satellite | супутник | +| CURRENTLY OVER (orbit, before a place name) | ПРОЛІТ | | launch (rocket) / space mission | запуск / космічна місія | | ascent (rocket) / booster FLIGHT {n} | виведення / ПОЛІТ {n} (not рейс) | | contact / tracking | контакт / стеження | diff --git a/docs/translations/zh-Hant.md b/docs/translations/zh-Hant.md index d44c510c4a..7875ac9ab9 100644 --- a/docs/translations/zh-Hant.md +++ b/docs/translations/zh-Hant.md @@ -2,16 +2,24 @@ Catalog: `src/i18n/locales/zh-Hant.json`. General rules: [TRANSLATORS.md](../TRANSLATORS.md). -`zh-Hant` is the Simplified Chinese catalog (`zh-CN`, credited to abiyeenzo, #914, and EDIT-Aeterna, #979) written in Traditional characters with OpenCC character conversion. Wording and terminology are the same as in `zh-CN`: change a term in [zh-CN.md](./zh-CN.md) and the `zh-CN` catalog first, then convert. Only the script differs. +**Do not translate or edit this catalog: it is generated.** `zh-Hant` is the Simplified Chinese catalog (`zh-CN`, credited to abiyeenzo, #914, and EDIT-Aeterna, #979) written in Traditional characters. Wording and terminology are the same as in `zh-CN`; only the script differs. To add or change an entry, edit [zh-CN.md](./zh-CN.md) and the `zh-CN` catalog, then run: -After `s2tw` conversion, fix the characters OpenCC picks wrongly: 年曆史 → 年歷史, 下遊 → 下游, 並道 → 併道, 發佈 → 發布, 公佈 → 公布, 控制檯 → 控制台, and 周 → 週 where it means a week (1 週/秒). +```sh +npm run i18n -- --zh-hant # rewrite zh-Hant.json from zh-CN.json +``` + +`npm test` fails when `zh-Hant.json` differs from the conversion of `zh-CN.json`, naming the entry, and `npm run i18n -- --missing zh-Hant` points to this command instead of printing a template. + +The command converts with OpenCC `s2tw` ([opencc-js](https://github.com/nk2028/opencc-js), `cn` → `tw`), which changes characters only. Never `s2twp`: it also swaps in Taiwan vocabulary (影片, 伺服器, 載入, 圖示), which this catalog does not use. After the conversion it fixes the characters OpenCC picks wrongly here: 年曆史 → 年歷史, 下遊 → 下游, 並道 → 併道 (only in entries whose English key says merge), 發佈 → 發布, 公佈 → 公布, 宣佈 → 宣布, 控制檯 → 控制台, 箇中 → 個中 (全部 {n} 個中), and 周 → 週 in ` 周/秒` (1 週/秒, weeks per second). OpenCC writes 週 itself in 每週, 本週, 上週, 一週 and 兩週, but not after a number (過去 2 周, {count} 周前): a new string like that needs its own pair. The list is `ZH_HANT_CORRECTIONS` in `scripts/i18n.mjs`; when the conversion picks another wrong character, add the pair there (with a key pattern if it is right only in some entries) and run the command. + +An entry `zh-CN` keeps in English on purpose needs the same line under `zh-Hant` in `src/i18n/same-as-english.json`. ## Style -- Follow [zh-CN.md](./zh-CN.md) for wording, punctuation, spacing, units and the glossary, written in Traditional characters. +- Wording, punctuation, spacing, units and the glossary are those of [zh-CN.md](./zh-CN.md), written in Traditional characters. - Relative-time placeholders may already include 前. In `LIVE · updated {age}`, the caller supplies the complete relative age; do not append another 前. - The picker displays 中文(繁體) / Chinese (Traditional); explicit Hans tags select Simplified Chinese. ## Plurals -`Intl.PluralRules('zh-Hant')` uses only `other`. Keep the measure words of the `zh-CN` entry: 「{count} 架飛機」、「{count} 艘船」. +`Intl.PluralRules('zh-Hant')` uses only `other`. The measure words come from the `zh-CN` entry: 「{count} 架飛機」、「{count} 艘船」. diff --git a/index.html b/index.html index c159503c16..ded159f2c9 100644 --- a/index.html +++ b/index.html @@ -26,7 +26,7 @@ with the sources: src/materialSymbolsSubset.test.mjs fails when a source names a glyph this list is missing, because a missing glyph does not draw a box — the ligature never forms and the element renders the literal word. --> - +
diff --git a/package-lock.json b/package-lock.json index af748fcd3a..b7fc51b14f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,6 +34,7 @@ "@vue/test-utils": "^2.5.1", "flag-icons": "7.5.0", "happy-dom": "^20.14.6", + "opencc-js": "1.4.2", "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", @@ -2990,6 +2991,13 @@ "node": ">= 0.8" } }, + "node_modules/opencc-js": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/opencc-js/-/opencc-js-1.4.2.tgz", + "integrity": "sha512-EdcspgdROiCCZDM+jZR6Pa670xW+EW2QhctPBQ8gRjg6lrx4IHEl+2s+kt5izk/TkxVRgdWuFgaGkaEdIUfdaw==", + "dev": true, + "license": "MIT AND Apache-2.0" + }, "node_modules/pako": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", diff --git a/package.json b/package.json index e76356a1f9..f4eb8082fd 100644 --- a/package.json +++ b/package.json @@ -90,6 +90,7 @@ "@vue/test-utils": "^2.5.1", "flag-icons": "7.5.0", "happy-dom": "^20.14.6", + "opencc-js": "1.4.2", "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", @@ -292,6 +293,7 @@ "./sources/reference": "./src/sources/reference.js", "./layers/submarine-cables/source": "./src/layers/submarineCables/bundledSource.js", "./sources/http-body": "./src/sources/httpBody.js", + "./sources/library": "./src/library/proxy.js", "./sources/overpass": "./src/sources/overpass.js", "./search/nominatim": "./src/search/nominatim.js", "./sources/nominatim": "./src/sources/nominatim.js", @@ -343,6 +345,7 @@ "./render/vectorBase": "./src/render/vectorBase/index.js", "./render/iconSegment": "./src/data/iconSegment.js", "./render/recession": "./src/render/recession.js", + "./render/modelParts": "./src/render/modelParts.js", "./render/windStreamlines": "./src/layers/wind/streamlines.js", "./render/weather": "./src/render/weather.js", "./weather/effects": "./src/weatherEffectsMath.js", diff --git a/public/models/fleet/aircraft/a320.glb b/public/models/fleet/aircraft/a320.glb index 017d8ed2c3..eee9e70cf0 100644 Binary files a/public/models/fleet/aircraft/a320.glb and b/public/models/fleet/aircraft/a320.glb differ diff --git a/public/models/fleet/aircraft/a333.glb b/public/models/fleet/aircraft/a333.glb index 7daeb83199..999736f1c4 100644 Binary files a/public/models/fleet/aircraft/a333.glb and b/public/models/fleet/aircraft/a333.glb differ diff --git a/public/models/fleet/aircraft/a343.glb b/public/models/fleet/aircraft/a343.glb index a850cea4a9..609833b78b 100644 Binary files a/public/models/fleet/aircraft/a343.glb and b/public/models/fleet/aircraft/a343.glb differ diff --git a/public/models/fleet/aircraft/a359.glb b/public/models/fleet/aircraft/a359.glb index 745681b277..9526bab46e 100644 Binary files a/public/models/fleet/aircraft/a359.glb and b/public/models/fleet/aircraft/a359.glb differ diff --git a/public/models/fleet/aircraft/a388.glb b/public/models/fleet/aircraft/a388.glb index 58e04f2d00..276f203242 100644 Binary files a/public/models/fleet/aircraft/a388.glb and b/public/models/fleet/aircraft/a388.glb differ diff --git a/public/models/fleet/aircraft/at72.glb b/public/models/fleet/aircraft/at72.glb index bbe129d7ed..94f387ddbe 100644 Binary files a/public/models/fleet/aircraft/at72.glb and b/public/models/fleet/aircraft/at72.glb differ diff --git a/public/models/fleet/aircraft/b738.glb b/public/models/fleet/aircraft/b738.glb index 6e4a94a383..2b5552c66b 100644 Binary files a/public/models/fleet/aircraft/b738.glb and b/public/models/fleet/aircraft/b738.glb differ diff --git a/public/models/fleet/aircraft/b744.glb b/public/models/fleet/aircraft/b744.glb index f5f9e421d8..2ee5b6dc8c 100644 Binary files a/public/models/fleet/aircraft/b744.glb and b/public/models/fleet/aircraft/b744.glb differ diff --git a/public/models/fleet/aircraft/b763.glb b/public/models/fleet/aircraft/b763.glb index 34c59a9125..32391ad99a 100644 Binary files a/public/models/fleet/aircraft/b763.glb and b/public/models/fleet/aircraft/b763.glb differ diff --git a/public/models/fleet/aircraft/b77w.glb b/public/models/fleet/aircraft/b77w.glb index a190513002..a0c299d99c 100644 Binary files a/public/models/fleet/aircraft/b77w.glb and b/public/models/fleet/aircraft/b77w.glb differ diff --git a/public/models/fleet/aircraft/b789.glb b/public/models/fleet/aircraft/b789.glb index 5474a55a4a..62b5b4d1a9 100644 Binary files a/public/models/fleet/aircraft/b789.glb and b/public/models/fleet/aircraft/b789.glb differ diff --git a/public/models/fleet/aircraft/bcs3.glb b/public/models/fleet/aircraft/bcs3.glb index 422ebe7008..d3844f24c9 100644 Binary files a/public/models/fleet/aircraft/bcs3.glb and b/public/models/fleet/aircraft/bcs3.glb differ diff --git a/public/models/fleet/aircraft/be20.glb b/public/models/fleet/aircraft/be20.glb index d1a2c4dfda..d1e66b60fe 100644 Binary files a/public/models/fleet/aircraft/be20.glb and b/public/models/fleet/aircraft/be20.glb differ diff --git a/public/models/fleet/aircraft/c17.glb b/public/models/fleet/aircraft/c17.glb index 19c51a523b..a344c055eb 100644 Binary files a/public/models/fleet/aircraft/c17.glb and b/public/models/fleet/aircraft/c17.glb differ diff --git a/public/models/fleet/aircraft/c172.glb b/public/models/fleet/aircraft/c172.glb index 9a5b7d73f9..8a730ca4d4 100644 Binary files a/public/models/fleet/aircraft/c172.glb and b/public/models/fleet/aircraft/c172.glb differ diff --git a/public/models/fleet/aircraft/c30j.glb b/public/models/fleet/aircraft/c30j.glb index b5d4a7122b..a2cca1d708 100644 Binary files a/public/models/fleet/aircraft/c30j.glb and b/public/models/fleet/aircraft/c30j.glb differ diff --git a/public/models/fleet/aircraft/c56x.glb b/public/models/fleet/aircraft/c56x.glb index 2185dfe795..6944e3098e 100644 Binary files a/public/models/fleet/aircraft/c56x.glb and b/public/models/fleet/aircraft/c56x.glb differ diff --git a/public/models/fleet/aircraft/cl35.glb b/public/models/fleet/aircraft/cl35.glb index f2df5f86b9..001e51382a 100644 Binary files a/public/models/fleet/aircraft/cl35.glb and b/public/models/fleet/aircraft/cl35.glb differ diff --git a/public/models/fleet/aircraft/crj9.glb b/public/models/fleet/aircraft/crj9.glb index 24e6448b66..3f8f27acc9 100644 Binary files a/public/models/fleet/aircraft/crj9.glb and b/public/models/fleet/aircraft/crj9.glb differ diff --git a/public/models/fleet/aircraft/dh8d.glb b/public/models/fleet/aircraft/dh8d.glb index f763fec213..ea252476a2 100644 Binary files a/public/models/fleet/aircraft/dh8d.glb and b/public/models/fleet/aircraft/dh8d.glb differ diff --git a/public/models/fleet/aircraft/e175.glb b/public/models/fleet/aircraft/e175.glb index acdc5230ea..21fc3c0970 100644 Binary files a/public/models/fleet/aircraft/e175.glb and b/public/models/fleet/aircraft/e175.glb differ diff --git a/public/models/fleet/aircraft/e55p.glb b/public/models/fleet/aircraft/e55p.glb index b130d2a9ea..7ebae479ff 100644 Binary files a/public/models/fleet/aircraft/e55p.glb and b/public/models/fleet/aircraft/e55p.glb differ diff --git a/public/models/fleet/aircraft/generic_plane.glb b/public/models/fleet/aircraft/generic_plane.glb index a126c8b267..561300adff 100644 Binary files a/public/models/fleet/aircraft/generic_plane.glb and b/public/models/fleet/aircraft/generic_plane.glb differ diff --git a/public/models/fleet/aircraft/glf4.glb b/public/models/fleet/aircraft/glf4.glb index 31ddd2c74e..e5f78158a3 100644 Binary files a/public/models/fleet/aircraft/glf4.glb and b/public/models/fleet/aircraft/glf4.glb differ diff --git a/public/models/fleet/aircraft/glider.glb b/public/models/fleet/aircraft/glider.glb index 60b722726a..b46314ef82 100644 Binary files a/public/models/fleet/aircraft/glider.glb and b/public/models/fleet/aircraft/glider.glb differ diff --git a/public/models/fleet/aircraft/k35r.glb b/public/models/fleet/aircraft/k35r.glb index 7a7cfbe735..f5b89ddbd3 100644 Binary files a/public/models/fleet/aircraft/k35r.glb and b/public/models/fleet/aircraft/k35r.glb differ diff --git a/public/models/fleet/aircraft/md11.glb b/public/models/fleet/aircraft/md11.glb index 885a816243..c1b7ed8f7d 100644 Binary files a/public/models/fleet/aircraft/md11.glb and b/public/models/fleet/aircraft/md11.glb differ diff --git a/public/models/fleet/aircraft/mq9.glb b/public/models/fleet/aircraft/mq9.glb index 737912fc3d..7bd3443c0b 100644 Binary files a/public/models/fleet/aircraft/mq9.glb and b/public/models/fleet/aircraft/mq9.glb differ diff --git a/public/models/fleet/aircraft/p28a.glb b/public/models/fleet/aircraft/p28a.glb index ca47aec1a6..15bd153570 100644 Binary files a/public/models/fleet/aircraft/p28a.glb and b/public/models/fleet/aircraft/p28a.glb differ diff --git a/public/models/fleet/aircraft/pc12.glb b/public/models/fleet/aircraft/pc12.glb index 2b2666a0a2..98180f2a6a 100644 Binary files a/public/models/fleet/aircraft/pc12.glb and b/public/models/fleet/aircraft/pc12.glb differ diff --git a/public/models/fleet/aircraft/sr22.glb b/public/models/fleet/aircraft/sr22.glb index 7c2d66fe6f..3414470c44 100644 Binary files a/public/models/fleet/aircraft/sr22.glb and b/public/models/fleet/aircraft/sr22.glb differ diff --git a/public/models/fleet/aircraft/t38.glb b/public/models/fleet/aircraft/t38.glb index b9c8cd9ee4..b7060e17c8 100644 Binary files a/public/models/fleet/aircraft/t38.glb and b/public/models/fleet/aircraft/t38.glb differ diff --git a/public/models/fleet/aircraft/tex2.glb b/public/models/fleet/aircraft/tex2.glb index 8a3ec3e00a..68c71060d9 100644 Binary files a/public/models/fleet/aircraft/tex2.glb and b/public/models/fleet/aircraft/tex2.glb differ diff --git a/public/models/fleet/aircraft/ultralight.glb b/public/models/fleet/aircraft/ultralight.glb index 965d9cdddd..6bb450ce95 100644 Binary files a/public/models/fleet/aircraft/ultralight.glb and b/public/models/fleet/aircraft/ultralight.glb differ diff --git a/public/models/fleet/aircraft/v22.glb b/public/models/fleet/aircraft/v22.glb index 01021ca2d8..1c2dd0514e 100644 Binary files a/public/models/fleet/aircraft/v22.glb and b/public/models/fleet/aircraft/v22.glb differ diff --git a/public/models/fleet/catalog.json b/public/models/fleet/catalog.json index 91fbc5acdb..c1619de0a9 100644 --- a/public/models/fleet/catalog.json +++ b/public/models/fleet/catalog.json @@ -16,7 +16,8 @@ "beam": 13.253, "clearance": 1.575, "tris": 1464, - "icon": "heli" + "icon": "heli", + "parts": 6 }, "a320": { "category": "aircraft", @@ -34,8 +35,9 @@ "length": 37.57, "beam": 35.611, "clearance": 3.063, - "tris": 2338, - "icon": "jet" + "tris": 2538, + "icon": "jet", + "parts": 16 }, "a333": { "category": "aircraft", @@ -53,8 +55,9 @@ "length": 63.69, "beam": 59.684, "clearance": 4.251, - "tris": 2338, - "icon": "widebody" + "tris": 2538, + "icon": "widebody", + "parts": 16 }, "a343": { "category": "aircraft", @@ -72,8 +75,9 @@ "length": 63.69, "beam": 59.684, "clearance": 3.343, - "tris": 2638, - "icon": "quad" + "tris": 2838, + "icon": "quad", + "parts": 20 }, "a359": { "category": "aircraft", @@ -91,8 +95,9 @@ "length": 66.8, "beam": 64.212, "clearance": 4.83, - "tris": 2338, - "icon": "widebody" + "tris": 2538, + "icon": "widebody", + "parts": 16 }, "a388": { "category": "aircraft", @@ -110,8 +115,9 @@ "length": 73.887, "beam": 78.582, "clearance": 4.827, - "tris": 2658, - "icon": "quad" + "tris": 2858, + "icon": "quad", + "parts": 20 }, "articulated_bus": { "category": "transit", @@ -130,7 +136,8 @@ "beam": 2.675, "clearance": 0.0, "tris": 604, - "icon": "bus" + "icon": "bus", + "parts": 5 }, "as50": { "category": "helicopters", @@ -149,7 +156,8 @@ "beam": 9.418, "clearance": 1.365, "tris": 1488, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "at72": { "category": "aircraft", @@ -167,8 +175,9 @@ "length": 27.17, "beam": 26.509, "clearance": 1.402, - "tris": 2300, - "icon": "turboprop" + "tris": 2500, + "icon": "turboprop", + "parts": 16 }, "b06": { "category": "helicopters", @@ -187,7 +196,8 @@ "beam": 2.057, "clearance": 1.265, "tris": 1476, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "b407": { "category": "helicopters", @@ -206,7 +216,8 @@ "beam": 10.67, "clearance": 1.315, "tris": 1500, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "b738": { "category": "aircraft", @@ -224,8 +235,9 @@ "length": 39.47, "beam": 35.603, "clearance": 2.528, - "tris": 2350, - "icon": "jet" + "tris": 2550, + "icon": "jet", + "parts": 16 }, "b744": { "category": "aircraft", @@ -243,8 +255,9 @@ "length": 71.139, "beam": 63.554, "clearance": 3.786, - "tris": 2910, - "icon": "quad" + "tris": 3110, + "icon": "quad", + "parts": 20 }, "b763": { "category": "aircraft", @@ -262,8 +275,9 @@ "length": 54.9, "beam": 47.385, "clearance": 3.852, - "tris": 2338, - "icon": "widebody" + "tris": 2538, + "icon": "widebody", + "parts": 16 }, "b77w": { "category": "aircraft", @@ -281,8 +295,9 @@ "length": 73.9, "beam": 63.504, "clearance": 5.444, - "tris": 2186, - "icon": "widebody" + "tris": 2386, + "icon": "widebody", + "parts": 16 }, "b789": { "category": "aircraft", @@ -300,8 +315,9 @@ "length": 62.8, "beam": 58.898, "clearance": 4.769, - "tris": 2186, - "icon": "widebody" + "tris": 2386, + "icon": "widebody", + "parts": 16 }, "balloon": { "category": "other", @@ -320,7 +336,8 @@ "beam": 16.999, "clearance": 5.95, "tris": 504, - "icon": "balloon" + "icon": "balloon", + "parts": 2 }, "barrel_yellow": { "category": "buoys", @@ -339,7 +356,8 @@ "beam": 1.0, "clearance": 0.3, "tris": 80, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "bcs3": { "category": "aircraft", @@ -357,8 +375,9 @@ "length": 38.7, "beam": 34.879, "clearance": 3.196, - "tris": 2338, - "icon": "jet" + "tris": 2538, + "icon": "jet", + "parts": 16 }, "be20": { "category": "aircraft", @@ -376,8 +395,9 @@ "length": 13.832, "beam": 16.278, "clearance": 0.871, - "tris": 2386, - "icon": "turboprop" + "tris": 2586, + "icon": "turboprop", + "parts": 16 }, "blimp": { "category": "other", @@ -396,7 +416,8 @@ "beam": 16.855, "clearance": 10.6, "tris": 1044, - "icon": "balloon" + "icon": "balloon", + "parts": 2 }, "bulk_carrier": { "category": "ships", @@ -415,7 +436,8 @@ "beam": 32.0, "clearance": 10.88, "tris": 3121, - "icon": "ship" + "icon": "ship", + "parts": 7 }, "buoy_cardinal_east": { "category": "buoys", @@ -434,7 +456,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 654, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_cardinal_north": { "category": "buoys", @@ -453,7 +476,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 606, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_cardinal_south": { "category": "buoys", @@ -472,7 +496,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 606, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_cardinal_west": { "category": "buoys", @@ -491,7 +516,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 654, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_isolated_danger": { "category": "buoys", @@ -510,7 +536,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 986, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_lateral_port": { "category": "buoys", @@ -529,7 +556,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 558, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_lateral_starboard": { "category": "buoys", @@ -548,7 +576,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 528, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_safe_water": { "category": "buoys", @@ -567,7 +596,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 694, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "buoy_special": { "category": "buoys", @@ -586,7 +616,8 @@ "beam": 3.12, "clearance": 3.2, "tris": 514, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "c17": { "category": "aircraft", @@ -604,8 +635,9 @@ "length": 55.419, "beam": 51.377, "clearance": 3.467, - "tris": 2768, - "icon": "widebody" + "tris": 2968, + "icon": "widebody", + "parts": 20 }, "c172": { "category": "aircraft", @@ -624,7 +656,8 @@ "beam": 10.78, "clearance": 1.49, "tris": 2162, - "icon": "light" + "icon": "light", + "parts": 9 }, "c30j": { "category": "aircraft", @@ -642,8 +675,9 @@ "length": 29.896, "beam": 39.602, "clearance": 2.328, - "tris": 2800, - "icon": "turboprop" + "tris": 3000, + "icon": "turboprop", + "parts": 20 }, "c56x": { "category": "aircraft", @@ -661,8 +695,9 @@ "length": 15.923, "beam": 16.827, "clearance": 0.911, - "tris": 2198, - "icon": "rear_jet" + "tris": 2398, + "icon": "rear_jet", + "parts": 16 }, "cable_tram": { "category": "transit", @@ -681,7 +716,8 @@ "beam": 2.89, "clearance": 0.0, "tris": 384, - "icon": "tram" + "icon": "tram", + "parts": 5 }, "can_red": { "category": "buoys", @@ -700,7 +736,8 @@ "beam": 1.6, "clearance": 0.6, "tris": 228, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "can_red_cylinder": { "category": "buoys", @@ -719,7 +756,8 @@ "beam": 1.6, "clearance": 0.6, "tris": 308, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "car": { "category": "other", @@ -738,7 +776,8 @@ "beam": 2.15, "clearance": 0.0, "tris": 736, - "icon": "vehicle" + "icon": "vehicle", + "parts": 3 }, "car_carrier": { "category": "ships", @@ -757,7 +796,8 @@ "beam": 34.315, "clearance": 8.96, "tris": 3949, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "city_bus": { "category": "transit", @@ -776,7 +816,8 @@ "beam": 2.675, "clearance": 0.0, "tris": 432, - "icon": "bus" + "icon": "bus", + "parts": 4 }, "cl35": { "category": "aircraft", @@ -794,8 +835,9 @@ "length": 22.73, "beam": 20.892, "clearance": 1.189, - "tris": 2434, - "icon": "rear_jet" + "tris": 2634, + "icon": "rear_jet", + "parts": 16 }, "coach": { "category": "transit", @@ -814,7 +856,8 @@ "beam": 2.675, "clearance": 0.0, "tris": 474, - "icon": "bus" + "icon": "bus", + "parts": 5 }, "commuter_emu": { "category": "transit", @@ -833,7 +876,8 @@ "beam": 3.06, "clearance": 0.0, "tris": 1570, - "icon": "rail" + "icon": "rail", + "parts": 20 }, "conical_green": { "category": "buoys", @@ -852,7 +896,8 @@ "beam": 1.7, "clearance": 0.6, "tris": 172, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "conical_green_cone": { "category": "buoys", @@ -871,7 +916,8 @@ "beam": 1.7, "clearance": 0.6, "tris": 222, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "container_ship": { "category": "ships", @@ -890,7 +936,8 @@ "beam": 48.0, "clearance": 13.92, "tris": 14337, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "crj9": { "category": "aircraft", @@ -908,8 +955,9 @@ "length": 36.496, "beam": 24.694, "clearance": 1.339, - "tris": 2334, - "icon": "rear_jet" + "tris": 2534, + "icon": "rear_jet", + "parts": 16 }, "cruise_ship": { "category": "ships", @@ -928,7 +976,8 @@ "beam": 45.0, "clearance": 8.4, "tris": 3759, - "icon": "passenger" + "icon": "passenger", + "parts": 3 }, "dh8d": { "category": "aircraft", @@ -946,8 +995,9 @@ "length": 32.8, "beam": 27.832, "clearance": 1.339, - "tris": 2364, - "icon": "turboprop" + "tris": 2564, + "icon": "turboprop", + "parts": 16 }, "double_decker": { "category": "transit", @@ -966,7 +1016,8 @@ "beam": 2.675, "clearance": 0.0, "tris": 442, - "icon": "bus" + "icon": "bus", + "parts": 4 }, "dredger": { "category": "ships", @@ -985,7 +1036,8 @@ "beam": 21.06, "clearance": 7.0, "tris": 2597, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "e175": { "category": "aircraft", @@ -1003,8 +1055,9 @@ "length": 31.68, "beam": 25.835, "clearance": 2.427, - "tris": 2338, - "icon": "jet" + "tris": 2538, + "icon": "jet", + "parts": 16 }, "e55p": { "category": "aircraft", @@ -1022,8 +1075,9 @@ "length": 16.172, "beam": 16.084, "clearance": 0.896, - "tris": 2414, - "icon": "rear_jet" + "tris": 2614, + "icon": "rear_jet", + "parts": 16 }, "ec35": { "category": "helicopters", @@ -1042,7 +1096,8 @@ "beam": 10.2, "clearance": 1.365, "tris": 1420, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "ec45": { "category": "helicopters", @@ -1061,7 +1116,8 @@ "beam": 11.0, "clearance": 1.54, "tris": 1420, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "fast_ferry": { "category": "ships", @@ -1080,7 +1136,8 @@ "beam": 11.12, "clearance": 1.32, "tris": 4754, - "icon": "passenger" + "icon": "passenger", + "parts": 2 }, "feeder": { "category": "ships", @@ -1099,7 +1156,8 @@ "beam": 23.0, "clearance": 6.67, "tris": 3519, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "ferry": { "category": "ships", @@ -1118,7 +1176,8 @@ "beam": 25.8, "clearance": 5.28, "tris": 3157, - "icon": "passenger" + "icon": "passenger", + "parts": 4 }, "fire_truck": { "category": "other", @@ -1137,7 +1196,8 @@ "beam": 3.014, "clearance": 0.0, "tris": 1016, - "icon": "vehicle" + "icon": "vehicle", + "parts": 5 }, "fishing_boat": { "category": "ships", @@ -1156,7 +1216,8 @@ "beam": 4.0, "clearance": 1.2, "tris": 2839, - "icon": "boat" + "icon": "boat", + "parts": 2 }, "funicular": { "category": "transit", @@ -1175,7 +1236,8 @@ "beam": 2.69, "clearance": 0.0, "tris": 308, - "icon": "rail" + "icon": "rail", + "parts": 3 }, "general_cargo": { "category": "ships", @@ -1194,7 +1256,8 @@ "beam": 14.0, "clearance": 5.32, "tris": 2797, - "icon": "ship" + "icon": "ship", + "parts": 5 }, "generic_heli": { "category": "helicopters", @@ -1213,7 +1276,8 @@ "beam": 11.0, "clearance": 1.365, "tris": 1272, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "generic_plane": { "category": "aircraft", @@ -1231,8 +1295,9 @@ "length": 36.0, "beam": 33.32, "clearance": 2.906, - "tris": 2166, - "icon": "jet" + "tris": 2366, + "icon": "jet", + "parts": 16 }, "generic_vessel": { "category": "ships", @@ -1251,7 +1316,8 @@ "beam": 9.0, "clearance": 2.7, "tris": 2389, - "icon": "ship" + "icon": "ship", + "parts": 2 }, "glf4": { "category": "aircraft", @@ -1269,8 +1335,9 @@ "length": 29.19, "beam": 23.58, "clearance": 1.189, - "tris": 2474, - "icon": "rear_jet" + "tris": 2674, + "icon": "rear_jet", + "parts": 16 }, "glider": { "category": "aircraft", @@ -1289,7 +1356,8 @@ "beam": 14.793, "clearance": 0.398, "tris": 2314, - "icon": "light" + "icon": "light", + "parts": 5 }, "gondola": { "category": "transit", @@ -1308,7 +1376,8 @@ "beam": 1.876, "clearance": 0.0, "tris": 282, - "icon": "unknown" + "icon": "unknown", + "parts": 1 }, "h47": { "category": "helicopters", @@ -1327,7 +1396,8 @@ "beam": 17.254, "clearance": 2.588, "tris": 1430, - "icon": "heli_tandem" + "icon": "heli_tandem", + "parts": 7 }, "h60": { "category": "helicopters", @@ -1346,7 +1416,8 @@ "beam": 16.36, "clearance": 1.765, "tris": 1560, - "icon": "heli" + "icon": "heli", + "parts": 6 }, "h64": { "category": "helicopters", @@ -1365,7 +1436,8 @@ "beam": 14.63, "clearance": 1.475, "tris": 2040, - "icon": "heli" + "icon": "heli", + "parts": 7 }, "high_speed": { "category": "transit", @@ -1384,7 +1456,8 @@ "beam": 3.11, "clearance": 0.0, "tris": 2844, - "icon": "rail" + "icon": "rail", + "parts": 36 }, "inland_cargo": { "category": "ships", @@ -1403,7 +1476,8 @@ "beam": 11.45, "clearance": 3.0, "tris": 3277, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "inland_tanker": { "category": "ships", @@ -1422,7 +1496,8 @@ "beam": 11.45, "clearance": 3.2, "tris": 2709, - "icon": "tanker" + "icon": "tanker", + "parts": 2 }, "intercity": { "category": "transit", @@ -1441,7 +1516,8 @@ "beam": 3.09, "clearance": 0.0, "tris": 3168, - "icon": "rail" + "icon": "rail", + "parts": 32 }, "k35r": { "category": "aircraft", @@ -1459,8 +1535,9 @@ "length": 48.951, "beam": 39.082, "clearance": 2.478, - "tris": 2626, - "icon": "jet" + "tris": 2826, + "icon": "jet", + "parts": 20 }, "light_rail": { "category": "transit", @@ -1479,7 +1556,8 @@ "beam": 2.81, "clearance": 0.0, "tris": 760, - "icon": "tram" + "icon": "tram", + "parts": 10 }, "lng_carrier": { "category": "ships", @@ -1498,7 +1576,8 @@ "beam": 46.0, "clearance": 11.5, "tris": 2951, - "icon": "tanker" + "icon": "tanker", + "parts": 3 }, "md11": { "category": "aircraft", @@ -1516,8 +1595,9 @@ "length": 64.145, "beam": 51.48, "clearance": 4.162, - "tris": 2476, - "icon": "widebody" + "tris": 2676, + "icon": "widebody", + "parts": 18 }, "metro": { "category": "transit", @@ -1536,7 +1616,8 @@ "beam": 3.06, "clearance": 0.0, "tris": 2226, - "icon": "subway" + "icon": "subway", + "parts": 27 }, "monorail": { "category": "transit", @@ -1555,7 +1636,8 @@ "beam": 3.06, "clearance": 0.0, "tris": 814, - "icon": "subway" + "icon": "subway", + "parts": 3 }, "motor_yacht": { "category": "ships", @@ -1574,7 +1656,8 @@ "beam": 4.6, "clearance": 1.15, "tris": 2477, - "icon": "boat" + "icon": "boat", + "parts": 2 }, "mq9": { "category": "aircraft", @@ -1592,8 +1675,9 @@ "length": 11.35, "beam": 19.6, "clearance": 1.616, - "tris": 1936, - "icon": "light" + "tris": 2136, + "icon": "light", + "parts": 13 }, "p28a": { "category": "aircraft", @@ -1612,7 +1696,8 @@ "beam": 10.457, "clearance": 1.341, "tris": 2136, - "icon": "light" + "icon": "light", + "parts": 9 }, "patrol": { "category": "ships", @@ -1631,7 +1716,8 @@ "beam": 9.0, "clearance": 2.7, "tris": 2587, - "icon": "ship" + "icon": "ship", + "parts": 4 }, "pc12": { "category": "aircraft", @@ -1649,8 +1735,9 @@ "length": 14.92, "beam": 16.106, "clearance": 1.435, - "tris": 2292, - "icon": "turboprop" + "tris": 2492, + "icon": "turboprop", + "parts": 13 }, "pile_green_cone": { "category": "buoys", @@ -1669,7 +1756,8 @@ "beam": 0.7, "clearance": 1.5, "tris": 138, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "pile_red_cylinder": { "category": "buoys", @@ -1688,7 +1776,8 @@ "beam": 0.7, "clearance": 1.5, "tris": 168, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "pilot_boat": { "category": "ships", @@ -1707,7 +1796,8 @@ "beam": 5.76, "clearance": 1.3, "tris": 2985, - "icon": "boat" + "icon": "boat", + "parts": 3 }, "product_tanker": { "category": "ships", @@ -1726,7 +1816,8 @@ "beam": 19.0, "clearance": 6.46, "tris": 2995, - "icon": "tanker" + "icon": "tanker", + "parts": 4 }, "psv": { "category": "ships", @@ -1745,7 +1836,8 @@ "beam": 19.0, "clearance": 6.27, "tris": 3059, - "icon": "ship" + "icon": "ship", + "parts": 3 }, "pushback": { "category": "other", @@ -1764,7 +1856,8 @@ "beam": 2.795, "clearance": 0.0, "tris": 490, - "icon": "vehicle" + "icon": "vehicle", + "parts": 3 }, "r44": { "category": "helicopters", @@ -1783,7 +1876,8 @@ "beam": 1.488, "clearance": 1.14, "tris": 1172, - "icon": "heli" + "icon": "heli", + "parts": 4 }, "radio_mast": { "category": "other", @@ -1802,7 +1896,8 @@ "beam": 1.63, "clearance": 0.0, "tris": 940, - "icon": "vehicle" + "icon": "vehicle", + "parts": 1 }, "regional_dmu": { "category": "transit", @@ -1821,7 +1916,8 @@ "beam": 3.06, "clearance": 0.0, "tris": 770, - "icon": "rail" + "icon": "rail", + "parts": 9 }, "river_cruise": { "category": "ships", @@ -1840,7 +1936,8 @@ "beam": 11.4, "clearance": 1.8, "tris": 2675, - "icon": "passenger" + "icon": "passenger", + "parts": 2 }, "s76": { "category": "helicopters", @@ -1859,7 +1956,8 @@ "beam": 13.41, "clearance": 1.525, "tris": 1356, - "icon": "heli" + "icon": "heli", + "parts": 6 }, "sailboat": { "category": "ships", @@ -1878,7 +1976,8 @@ "beam": 4.1, "clearance": 2.695, "tris": 2421, - "icon": "sail" + "icon": "sail", + "parts": 1 }, "spar_lateral_port": { "category": "buoys", @@ -1897,7 +1996,8 @@ "beam": 0.94, "clearance": 1.5, "tris": 290, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "spar_lateral_starboard": { "category": "buoys", @@ -1916,7 +2016,8 @@ "beam": 0.94, "clearance": 1.5, "tris": 262, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "speedboat": { "category": "ships", @@ -1935,7 +2036,8 @@ "beam": 2.6, "clearance": 0.55, "tris": 2369, - "icon": "boat" + "icon": "boat", + "parts": 1 }, "spherical_green": { "category": "buoys", @@ -1954,7 +2056,8 @@ "beam": 1.477, "clearance": 0.4, "tris": 344, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "spherical_yellow": { "category": "buoys", @@ -1973,7 +2076,8 @@ "beam": 1.477, "clearance": 0.4, "tris": 344, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "spherical_yellow_x": { "category": "buoys", @@ -1992,7 +2096,8 @@ "beam": 1.477, "clearance": 0.4, "tris": 380, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "sr22": { "category": "aircraft", @@ -2011,7 +2116,8 @@ "beam": 11.446, "clearance": 1.325, "tris": 2428, - "icon": "light" + "icon": "light", + "parts": 9 }, "stake_green_cone": { "category": "buoys", @@ -2030,7 +2136,8 @@ "beam": 0.396, "clearance": 1.5, "tris": 78, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "stake_red_cylinder": { "category": "buoys", @@ -2049,7 +2156,8 @@ "beam": 0.308, "clearance": 1.5, "tris": 108, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "stake_yellow_x": { "category": "buoys", @@ -2068,7 +2176,8 @@ "beam": 0.463, "clearance": 1.5, "tris": 64, - "icon": "buoy" + "icon": "buoy", + "parts": 1 }, "superyacht": { "category": "ships", @@ -2087,7 +2196,8 @@ "beam": 10.5, "clearance": 3.15, "tris": 2689, - "icon": "passenger" + "icon": "passenger", + "parts": 2 }, "t38": { "category": "aircraft", @@ -2105,8 +2215,9 @@ "length": 14.144, "beam": 7.546, "clearance": 0.746, - "tris": 2246, - "icon": "fighter" + "tris": 2446, + "icon": "fighter", + "parts": 14 }, "tanker": { "category": "ships", @@ -2125,7 +2236,8 @@ "beam": 44.0, "clearance": 14.96, "tris": 3393, - "icon": "tanker" + "icon": "tanker", + "parts": 4 }, "tex2": { "category": "aircraft", @@ -2143,8 +2255,9 @@ "length": 10.586, "beam": 9.986, "clearance": 1.293, - "tris": 2380, - "icon": "turboprop" + "tris": 2580, + "icon": "turboprop", + "parts": 13 }, "tour_boat": { "category": "ships", @@ -2163,7 +2276,8 @@ "beam": 6.0, "clearance": 1.68, "tris": 2449, - "icon": "boat" + "icon": "boat", + "parts": 2 }, "tower": { "category": "other", @@ -2182,7 +2296,8 @@ "beam": 2.27, "clearance": 0.016, "tris": 568, - "icon": "vehicle" + "icon": "vehicle", + "parts": 1 }, "tram": { "category": "transit", @@ -2201,7 +2316,8 @@ "beam": 2.56, "clearance": 0.0, "tris": 1004, - "icon": "tram" + "icon": "tram", + "parts": 10 }, "trawler": { "category": "ships", @@ -2220,7 +2336,8 @@ "beam": 12.676, "clearance": 2.8, "tris": 3121, - "icon": "ship" + "icon": "ship", + "parts": 5 }, "trolleybus": { "category": "transit", @@ -2239,7 +2356,8 @@ "beam": 2.675, "clearance": 0.0, "tris": 458, - "icon": "bus" + "icon": "bus", + "parts": 5 }, "tug": { "category": "ships", @@ -2258,7 +2376,8 @@ "beam": 10.7, "clearance": 3.7, "tris": 3661, - "icon": "ship" + "icon": "ship", + "parts": 2 }, "ultralight": { "category": "aircraft", @@ -2277,7 +2396,8 @@ "beam": 10.486, "clearance": 1.217, "tris": 2068, - "icon": "light" + "icon": "light", + "parts": 9 }, "v22": { "category": "aircraft", @@ -2295,8 +2415,9 @@ "length": 17.48, "beam": 23.294, "clearance": 1.468, - "tris": 2250, - "icon": "turboprop" + "tris": 2450, + "icon": "turboprop", + "parts": 16 }, "van": { "category": "other", @@ -2315,6 +2436,7 @@ "beam": 2.44, "clearance": 0.0, "tris": 736, - "icon": "vehicle" + "icon": "vehicle", + "parts": 3 } -} +} \ No newline at end of file diff --git a/public/models/fleet/helicopters/a139.glb b/public/models/fleet/helicopters/a139.glb index f61975dfb6..2ecebc5b5c 100644 Binary files a/public/models/fleet/helicopters/a139.glb and b/public/models/fleet/helicopters/a139.glb differ diff --git a/public/models/fleet/helicopters/as50.glb b/public/models/fleet/helicopters/as50.glb index 597d916e91..3374b36ca9 100644 Binary files a/public/models/fleet/helicopters/as50.glb and b/public/models/fleet/helicopters/as50.glb differ diff --git a/public/models/fleet/helicopters/b06.glb b/public/models/fleet/helicopters/b06.glb index 25baa7fa49..727a0131c3 100644 Binary files a/public/models/fleet/helicopters/b06.glb and b/public/models/fleet/helicopters/b06.glb differ diff --git a/public/models/fleet/helicopters/b407.glb b/public/models/fleet/helicopters/b407.glb index 09d67e67e1..f4c3f11569 100644 Binary files a/public/models/fleet/helicopters/b407.glb and b/public/models/fleet/helicopters/b407.glb differ diff --git a/public/models/fleet/helicopters/ec35.glb b/public/models/fleet/helicopters/ec35.glb index c52f3d156e..b5d900153c 100644 Binary files a/public/models/fleet/helicopters/ec35.glb and b/public/models/fleet/helicopters/ec35.glb differ diff --git a/public/models/fleet/helicopters/ec45.glb b/public/models/fleet/helicopters/ec45.glb index b9e5cb27ef..a1ca97fe34 100644 Binary files a/public/models/fleet/helicopters/ec45.glb and b/public/models/fleet/helicopters/ec45.glb differ diff --git a/public/models/fleet/helicopters/generic_heli.glb b/public/models/fleet/helicopters/generic_heli.glb index bc8f1a239c..bdae965817 100644 Binary files a/public/models/fleet/helicopters/generic_heli.glb and b/public/models/fleet/helicopters/generic_heli.glb differ diff --git a/public/models/fleet/helicopters/h47.glb b/public/models/fleet/helicopters/h47.glb index bb2f714261..ab5b6eda19 100644 Binary files a/public/models/fleet/helicopters/h47.glb and b/public/models/fleet/helicopters/h47.glb differ diff --git a/public/models/fleet/helicopters/h60.glb b/public/models/fleet/helicopters/h60.glb index 45f79180de..e612e1a1f8 100644 Binary files a/public/models/fleet/helicopters/h60.glb and b/public/models/fleet/helicopters/h60.glb differ diff --git a/public/models/fleet/helicopters/h64.glb b/public/models/fleet/helicopters/h64.glb index 3a44d8e50b..fe7b995e73 100644 Binary files a/public/models/fleet/helicopters/h64.glb and b/public/models/fleet/helicopters/h64.glb differ diff --git a/public/models/fleet/helicopters/r44.glb b/public/models/fleet/helicopters/r44.glb index 845727936a..74385abfec 100644 Binary files a/public/models/fleet/helicopters/r44.glb and b/public/models/fleet/helicopters/r44.glb differ diff --git a/public/models/fleet/helicopters/s76.glb b/public/models/fleet/helicopters/s76.glb index a773aba73f..3e7f4cb49b 100644 Binary files a/public/models/fleet/helicopters/s76.glb and b/public/models/fleet/helicopters/s76.glb differ diff --git a/public/models/fleet/other/balloon.glb b/public/models/fleet/other/balloon.glb index 016ad0719b..70be67087c 100644 Binary files a/public/models/fleet/other/balloon.glb and b/public/models/fleet/other/balloon.glb differ diff --git a/public/models/fleet/other/blimp.glb b/public/models/fleet/other/blimp.glb index 3aba8e86ba..348b8d7ab9 100644 Binary files a/public/models/fleet/other/blimp.glb and b/public/models/fleet/other/blimp.glb differ diff --git a/public/models/fleet/other/car.glb b/public/models/fleet/other/car.glb index 80f50d967c..fe8a713fe5 100644 Binary files a/public/models/fleet/other/car.glb and b/public/models/fleet/other/car.glb differ diff --git a/public/models/fleet/other/fire_truck.glb b/public/models/fleet/other/fire_truck.glb index 47cb6d2459..69a78e76eb 100644 Binary files a/public/models/fleet/other/fire_truck.glb and b/public/models/fleet/other/fire_truck.glb differ diff --git a/public/models/fleet/other/pushback.glb b/public/models/fleet/other/pushback.glb index 565ce426c2..d439e36636 100644 Binary files a/public/models/fleet/other/pushback.glb and b/public/models/fleet/other/pushback.glb differ diff --git a/public/models/fleet/other/van.glb b/public/models/fleet/other/van.glb index 0b79e1db6f..500e1f88a4 100644 Binary files a/public/models/fleet/other/van.glb and b/public/models/fleet/other/van.glb differ diff --git a/public/models/fleet/ships/bulk_carrier.glb b/public/models/fleet/ships/bulk_carrier.glb index 3fe73d3bfb..fe06c31702 100644 Binary files a/public/models/fleet/ships/bulk_carrier.glb and b/public/models/fleet/ships/bulk_carrier.glb differ diff --git a/public/models/fleet/ships/car_carrier.glb b/public/models/fleet/ships/car_carrier.glb index 04ad3e7790..007266bbb2 100644 Binary files a/public/models/fleet/ships/car_carrier.glb and b/public/models/fleet/ships/car_carrier.glb differ diff --git a/public/models/fleet/ships/container_ship.glb b/public/models/fleet/ships/container_ship.glb index f8686176b2..f2be465223 100644 Binary files a/public/models/fleet/ships/container_ship.glb and b/public/models/fleet/ships/container_ship.glb differ diff --git a/public/models/fleet/ships/cruise_ship.glb b/public/models/fleet/ships/cruise_ship.glb index d2dcfd88e8..d15f8ae88a 100644 Binary files a/public/models/fleet/ships/cruise_ship.glb and b/public/models/fleet/ships/cruise_ship.glb differ diff --git a/public/models/fleet/ships/dredger.glb b/public/models/fleet/ships/dredger.glb index 4d9ab52647..aaaf8cc8d8 100644 Binary files a/public/models/fleet/ships/dredger.glb and b/public/models/fleet/ships/dredger.glb differ diff --git a/public/models/fleet/ships/fast_ferry.glb b/public/models/fleet/ships/fast_ferry.glb index 65b008200c..784dadda04 100644 Binary files a/public/models/fleet/ships/fast_ferry.glb and b/public/models/fleet/ships/fast_ferry.glb differ diff --git a/public/models/fleet/ships/feeder.glb b/public/models/fleet/ships/feeder.glb index 1c40203bf6..ba2b5a71c6 100644 Binary files a/public/models/fleet/ships/feeder.glb and b/public/models/fleet/ships/feeder.glb differ diff --git a/public/models/fleet/ships/ferry.glb b/public/models/fleet/ships/ferry.glb index fcaa48abcc..dc2f988916 100644 Binary files a/public/models/fleet/ships/ferry.glb and b/public/models/fleet/ships/ferry.glb differ diff --git a/public/models/fleet/ships/fishing_boat.glb b/public/models/fleet/ships/fishing_boat.glb index 084f5dd3b6..a69d1f9abf 100644 Binary files a/public/models/fleet/ships/fishing_boat.glb and b/public/models/fleet/ships/fishing_boat.glb differ diff --git a/public/models/fleet/ships/general_cargo.glb b/public/models/fleet/ships/general_cargo.glb index 0cd1cd4cd4..91a560f7e9 100644 Binary files a/public/models/fleet/ships/general_cargo.glb and b/public/models/fleet/ships/general_cargo.glb differ diff --git a/public/models/fleet/ships/generic_vessel.glb b/public/models/fleet/ships/generic_vessel.glb index e8c7485445..3540207d5a 100644 Binary files a/public/models/fleet/ships/generic_vessel.glb and b/public/models/fleet/ships/generic_vessel.glb differ diff --git a/public/models/fleet/ships/inland_cargo.glb b/public/models/fleet/ships/inland_cargo.glb index 9f9facc4ab..f626be0c3a 100644 Binary files a/public/models/fleet/ships/inland_cargo.glb and b/public/models/fleet/ships/inland_cargo.glb differ diff --git a/public/models/fleet/ships/inland_tanker.glb b/public/models/fleet/ships/inland_tanker.glb index db46c2476b..540ad33325 100644 Binary files a/public/models/fleet/ships/inland_tanker.glb and b/public/models/fleet/ships/inland_tanker.glb differ diff --git a/public/models/fleet/ships/lng_carrier.glb b/public/models/fleet/ships/lng_carrier.glb index d06330645d..f26c06d5a8 100644 Binary files a/public/models/fleet/ships/lng_carrier.glb and b/public/models/fleet/ships/lng_carrier.glb differ diff --git a/public/models/fleet/ships/motor_yacht.glb b/public/models/fleet/ships/motor_yacht.glb index d7283750a0..34b290e392 100644 Binary files a/public/models/fleet/ships/motor_yacht.glb and b/public/models/fleet/ships/motor_yacht.glb differ diff --git a/public/models/fleet/ships/patrol.glb b/public/models/fleet/ships/patrol.glb index 6b3352e111..cc412b42a2 100644 Binary files a/public/models/fleet/ships/patrol.glb and b/public/models/fleet/ships/patrol.glb differ diff --git a/public/models/fleet/ships/pilot_boat.glb b/public/models/fleet/ships/pilot_boat.glb index f4197ab0fb..2abe1d1fdc 100644 Binary files a/public/models/fleet/ships/pilot_boat.glb and b/public/models/fleet/ships/pilot_boat.glb differ diff --git a/public/models/fleet/ships/product_tanker.glb b/public/models/fleet/ships/product_tanker.glb index 6e31083d35..01ce99903e 100644 Binary files a/public/models/fleet/ships/product_tanker.glb and b/public/models/fleet/ships/product_tanker.glb differ diff --git a/public/models/fleet/ships/psv.glb b/public/models/fleet/ships/psv.glb index d943978ec2..0653b7cb5c 100644 Binary files a/public/models/fleet/ships/psv.glb and b/public/models/fleet/ships/psv.glb differ diff --git a/public/models/fleet/ships/river_cruise.glb b/public/models/fleet/ships/river_cruise.glb index 2da8589f0a..f28724cee3 100644 Binary files a/public/models/fleet/ships/river_cruise.glb and b/public/models/fleet/ships/river_cruise.glb differ diff --git a/public/models/fleet/ships/superyacht.glb b/public/models/fleet/ships/superyacht.glb index 012e69dd38..eefad54825 100644 Binary files a/public/models/fleet/ships/superyacht.glb and b/public/models/fleet/ships/superyacht.glb differ diff --git a/public/models/fleet/ships/tanker.glb b/public/models/fleet/ships/tanker.glb index 68de5a0013..4dac158e5d 100644 Binary files a/public/models/fleet/ships/tanker.glb and b/public/models/fleet/ships/tanker.glb differ diff --git a/public/models/fleet/ships/tour_boat.glb b/public/models/fleet/ships/tour_boat.glb index 22ee9cb430..a1665a93c1 100644 Binary files a/public/models/fleet/ships/tour_boat.glb and b/public/models/fleet/ships/tour_boat.glb differ diff --git a/public/models/fleet/ships/trawler.glb b/public/models/fleet/ships/trawler.glb index bb8651f2cb..7377e8e798 100644 Binary files a/public/models/fleet/ships/trawler.glb and b/public/models/fleet/ships/trawler.glb differ diff --git a/public/models/fleet/ships/tug.glb b/public/models/fleet/ships/tug.glb index f20e72b6b4..e9f2f78fd8 100644 Binary files a/public/models/fleet/ships/tug.glb and b/public/models/fleet/ships/tug.glb differ diff --git a/public/models/fleet/transit/articulated_bus.glb b/public/models/fleet/transit/articulated_bus.glb index 4b10d2ef07..877b3f58ec 100644 Binary files a/public/models/fleet/transit/articulated_bus.glb and b/public/models/fleet/transit/articulated_bus.glb differ diff --git a/public/models/fleet/transit/cable_tram.glb b/public/models/fleet/transit/cable_tram.glb index 10b12a3eec..01d68a1bd3 100644 Binary files a/public/models/fleet/transit/cable_tram.glb and b/public/models/fleet/transit/cable_tram.glb differ diff --git a/public/models/fleet/transit/city_bus.glb b/public/models/fleet/transit/city_bus.glb index 4e2b1dc8a9..74ef791488 100644 Binary files a/public/models/fleet/transit/city_bus.glb and b/public/models/fleet/transit/city_bus.glb differ diff --git a/public/models/fleet/transit/coach.glb b/public/models/fleet/transit/coach.glb index 00e23f7f5d..f8f8800a1b 100644 Binary files a/public/models/fleet/transit/coach.glb and b/public/models/fleet/transit/coach.glb differ diff --git a/public/models/fleet/transit/commuter_emu.glb b/public/models/fleet/transit/commuter_emu.glb index e53f0a1bee..ad42a377d9 100644 Binary files a/public/models/fleet/transit/commuter_emu.glb and b/public/models/fleet/transit/commuter_emu.glb differ diff --git a/public/models/fleet/transit/double_decker.glb b/public/models/fleet/transit/double_decker.glb index 416bd2cbcf..bcbfd1d5fc 100644 Binary files a/public/models/fleet/transit/double_decker.glb and b/public/models/fleet/transit/double_decker.glb differ diff --git a/public/models/fleet/transit/funicular.glb b/public/models/fleet/transit/funicular.glb index 4b14d66225..2727d62fc3 100644 Binary files a/public/models/fleet/transit/funicular.glb and b/public/models/fleet/transit/funicular.glb differ diff --git a/public/models/fleet/transit/high_speed.glb b/public/models/fleet/transit/high_speed.glb index c3f09d0948..c056e218bd 100644 Binary files a/public/models/fleet/transit/high_speed.glb and b/public/models/fleet/transit/high_speed.glb differ diff --git a/public/models/fleet/transit/intercity.glb b/public/models/fleet/transit/intercity.glb index 2845594ec9..b963384c24 100644 Binary files a/public/models/fleet/transit/intercity.glb and b/public/models/fleet/transit/intercity.glb differ diff --git a/public/models/fleet/transit/light_rail.glb b/public/models/fleet/transit/light_rail.glb index 22f80d1970..9d3709fac1 100644 Binary files a/public/models/fleet/transit/light_rail.glb and b/public/models/fleet/transit/light_rail.glb differ diff --git a/public/models/fleet/transit/metro.glb b/public/models/fleet/transit/metro.glb index 6154049b95..d7f57b4765 100644 Binary files a/public/models/fleet/transit/metro.glb and b/public/models/fleet/transit/metro.glb differ diff --git a/public/models/fleet/transit/monorail.glb b/public/models/fleet/transit/monorail.glb index a8dab0f07f..21ac0752a9 100644 Binary files a/public/models/fleet/transit/monorail.glb and b/public/models/fleet/transit/monorail.glb differ diff --git a/public/models/fleet/transit/regional_dmu.glb b/public/models/fleet/transit/regional_dmu.glb index 1a091e2d60..7224cd1687 100644 Binary files a/public/models/fleet/transit/regional_dmu.glb and b/public/models/fleet/transit/regional_dmu.glb differ diff --git a/public/models/fleet/transit/tram.glb b/public/models/fleet/transit/tram.glb index 514cff4360..09015873ba 100644 Binary files a/public/models/fleet/transit/tram.glb and b/public/models/fleet/transit/tram.glb differ diff --git a/public/models/fleet/transit/trolleybus.glb b/public/models/fleet/transit/trolleybus.glb index a7691b71e7..31d5b9d1ec 100644 Binary files a/public/models/fleet/transit/trolleybus.glb and b/public/models/fleet/transit/trolleybus.glb differ diff --git a/public/models/fleet/types.json b/public/models/fleet/types.json index 2b2388bb19..258fe1b0d0 100644 --- a/public/models/fleet/types.json +++ b/public/models/fleet/types.json @@ -2033,5 +2033,199 @@ "monorail": 6.0, "gondola": 20.0 } + }, + "rockets": { + "configurations": { + "Falcon 9": [ + "falcon9", + 70.0 + ], + "Falcon 9 Block 5": [ + "falcon9", + 70.0 + ], + "Falcon 9 v1.2": [ + "falcon9", + 70.0 + ], + "Falcon Heavy": [ + "falcon_heavy", + 70.0 + ], + "Starship": [ + "starship", + 123.3 + ], + "Starship V2": [ + "starship", + 123.3 + ], + "Starship V3": [ + "starship", + 124.4 + ], + "Electron": [ + "electron", + 18.0 + ], + "New Glenn": [ + "new_glenn", + 98.0 + ], + "Ariane 62": [ + "ariane62", + 56.0 + ], + "Ariane 64": [ + "ariane64", + 62.0 + ], + "Soyuz 2.1a": [ + "soyuz", + 46.3 + ], + "Soyuz 2.1b": [ + "soyuz", + 46.3 + ], + "Soyuz-2.1a": [ + "soyuz", + 46.3 + ], + "Soyuz-2.1b": [ + "soyuz", + 46.3 + ], + "Soyuz-FG": [ + "soyuz", + 46.3 + ], + "Soyuz ST-B": [ + "soyuz", + 46.3 + ], + "Soyuz 2.1v": [ + "generic_medium", + 44.0 + ], + "Long March 5": [ + "long_march5", + 57.0 + ], + "Long March 5B": [ + "long_march5", + 53.7 + ], + "Space Launch System (SLS)": [ + "sls", + 98.1 + ], + "SLS Block 1": [ + "sls", + 98.1 + ], + "SLS Block 1B": [ + "sls", + 111.3 + ], + "H3": [ + "h3", + 57.0 + ], + "H3-22": [ + "h3", + 57.0 + ], + "H3-24": [ + "h3", + 57.0 + ], + "H3-30": [ + "h3", + 57.0 + ], + "Vulcan": [ + "vulcan", + 61.6 + ], + "Vulcan VC0S": [ + "vulcan", + 61.6 + ], + "Vulcan VC2S": [ + "vulcan", + 61.6 + ], + "Vulcan VC4L": [ + "vulcan", + 67.3 + ], + "Vulcan VC6L": [ + "vulcan", + 67.3 + ] + }, + "families": { + "Falcon": [ + "falcon9", + 70.0 + ], + "Starship": [ + "starship", + 123.3 + ], + "Electron": [ + "electron", + 18.0 + ], + "New Glenn": [ + "new_glenn", + 98.0 + ], + "Ariane": [ + "ariane62", + 56.0 + ], + "Soyuz": [ + "soyuz", + 46.3 + ], + "Long March 5": [ + "long_march5", + 57.0 + ], + "SLS": [ + "sls", + 98.1 + ], + "H3": [ + "h3", + 57.0 + ], + "Vulcan": [ + "vulcan", + 61.6 + ] + }, + "classes": [ + { + "max_leo_kg": 2000, + "model": "generic_small", + "height": 20.0 + }, + { + "max_leo_kg": 20000, + "model": "generic_medium", + "height": 50.0 + }, + { + "model": "generic_heavy", + "height": 70.0 + } + ], + "default_rocket": [ + "generic_medium", + 50.0 + ] } } \ No newline at end of file diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 76d86f698d..aa51f28c05 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -614,6 +614,7 @@ "src/layers/cctv/ingestion.js", "src/layers/cctv/hover.js", "src/layers/cctv/navigation.js", + "src/layers/cctv/navigation.test.mjs", "src/layers/cctv/index.js", "src/layers/cctv/model.js", "src/layers/cctv/geometryQueue.js", @@ -862,6 +863,7 @@ "src/data/rioRouteNames.js", "src/data/transitFeeds.js", "src/data/transitFeeds.test.mjs", + "src/data/transitFeedsAustralia.test.mjs", "src/data/transitProxy.js", "src/data/transitProxy.test.mjs", "src/data/gtfsRealtime.js", diff --git a/scripts/i18n.mjs b/scripts/i18n.mjs index 7baf43dc22..06464b15cb 100644 --- a/scripts/i18n.mjs +++ b/scripts/i18n.mjs @@ -3,17 +3,21 @@ // npm run i18n check every catalog and find unmarked UI text // npm run i18n -- --prune also drop entries the code no longer uses // npm run i18n -- --missing ru print what ru lacks, as JSON to translate +// npm run i18n -- --zh-hant rewrite zh-Hant from zh-CN (see toZhHant) // // A translation left as the English fails unless src/i18n/same-as-english.json -// lists it. +// lists it. zh-Hant is not translated: it is generated from zh-CN, and the +// check fails when it differs. // // Messages are the English literals passed to t(), tn() and msg() in src/, // plus the markup opted in with data-i18n* in index.html and the Vue views. // It also lists UI text that is not marked at all (see findUnmarked). import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { execFileSync } from 'node:child_process'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { isDeepStrictEqual } from 'node:util'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const LOCALES_DIR = path.join(ROOT, 'src/i18n/locales'); @@ -510,10 +514,11 @@ export function readCatalog(locale) { return JSON.parse(readFileSync(catalogPath(locale), 'utf8')); } +/** Sorted: git lists untracked files first, and main needs zh-CN before zh-Hant. */ export function shippedLocales() { - return trackedFiles('src/i18n/locales/*.json').map((file) => - path.basename(file, '.json'), - ); + return trackedFiles('src/i18n/locales/*.json') + .map((file) => path.basename(file, '.json')) + .sort(); } /** Messages a locale keeps exactly as in English, on purpose. */ @@ -532,7 +537,9 @@ const blank = (value) => value.trim() === ''; const hasLetters = (value) => /\p{L}{2}/u.test(value.replace(/\{[^}]*\}/g, '')); const STILL_ENGLISH = (text, locale) => - `"${text}" is still English: translate it, or list it under "${locale}" in src/i18n/same-as-english.json`; + locale === ZH_HANT + ? `"${text}" is still English: translate it in ${ZH_HANT_SOURCE} and run ${ZH_HANT_COMMAND}, or list it under "${ZH_HANT}" in src/i18n/same-as-english.json as under "${ZH_HANT_SOURCE}"` + : `"${text}" is still English: translate it, or list it under "${locale}" in src/i18n/same-as-english.json`; /** * Compare one catalog with the extracted messages. @@ -619,16 +626,138 @@ export function missingTemplate(locale, catalog, messages) { return out; } +// zh-Hant is zh-CN in Traditional characters (docs/translations/zh-Hant.md): +// the same wording, only the script differs. OpenCC s2tw (opencc-js, cn → tw) +// converts characters only; s2twp would also swap in Taiwan vocabulary +// (影片, 伺服器, 載入), which the catalog does not use. +const ZH_HANT = 'zh-Hant'; +const ZH_HANT_SOURCE = 'zh-CN'; +const ZH_HANT_COMMAND = 'npm run i18n -- --zh-hant'; + +// Characters s2tw picks wrongly in this text, replaced after the conversion. +// A pair with a third item applies only to entries whose English key matches it. +const ZH_HANT_CORRECTIONS = [ + ['年曆史', '年歷史'], + ['下遊', '下游'], + // 併道 is merging lanes; elsewhere 並 (and) stays before 道路, 道謝 and the like. + ['並道', '併道', /\bmerge\b/i], + ['發佈', '發布'], + ['公佈', '公布'], + ['宣佈', '宣布'], + ['控制檯', '控制台'], + // 個 after a count ({n} 个中, of {n}), not the literary 箇中. + ['箇中', '個中'], + // 周 as a week: the time-lapse speed in weeks per second. + [' 周/秒', ' 週/秒'], +]; + +let s2tw; + +// Loaded on first use, so extracting messages needs no node_modules +// (stale-index.test.mjs); main reports a missing package as a zh-Hant error. +function converter() { + try { + s2tw ??= createRequire(import.meta.url)('opencc-js/cn2t').Converter({ + from: 'cn', + to: 'tw', + }); + } catch (error) { + if (error.code !== 'MODULE_NOT_FOUND') throw error; + throw new Error('opencc-js is not installed: run npm ci', { cause: error }); + } + return s2tw; +} + +export function toZhHant(text, key = '') { + return ZH_HANT_CORRECTIONS.reduce( + (out, [wrong, right, keys]) => + !keys || keys.test(key) ? out.replaceAll(wrong, right) : out, + converter()(text), + ); +} + +/** The zh-Hant catalog for a zh-CN catalog: the same keys in the same order. */ +export function zhHantCatalog(zhCN) { + const convert = (entry, text) => { + if (typeof entry === 'string') return toZhHant(entry, text); + if (entry && typeof entry === 'object') + return Object.fromEntries( + Object.entries(entry).map(([category, form]) => [ + category, + convert(form, text), + ]), + ); + return entry; + }; + return Object.fromEntries( + Object.entries(zhCN).map(([text, entry]) => [text, convert(entry, text)]), + ); +} + +/** + * Where a zh-Hant catalog is not the conversion of the zh-CN one. + * @param {Set} [reported] Keys already reported missing from zh-Hant. + * @returns {string[]} One error per entry, naming its key. + */ +export function checkZhHant(zhCN, zhHant, reported = new Set()) { + const expected = zhHantCatalog(zhCN); + const fix = `zh-Hant is generated: edit ${ZH_HANT_SOURCE}, then run ${ZH_HANT_COMMAND}`; + const errors = []; + for (const [text, entry] of Object.entries(expected)) { + if (!Object.hasOwn(zhHant, text)) { + if (!reported.has(text)) + errors.push(`"${text}" is in ${ZH_HANT_SOURCE} but not here. ${fix}`); + } else if (!isDeepStrictEqual(zhHant[text], entry)) + errors.push( + `"${text}" is ${JSON.stringify(zhHant[text])}, not ${ZH_HANT_SOURCE} converted (${JSON.stringify(entry)}). ${fix}`, + ); + } + for (const text of Object.keys(zhHant)) { + if (!Object.hasOwn(expected, text)) + errors.push(`"${text}" is not in ${ZH_HANT_SOURCE}. ${fix}`); + } + const order = Object.keys(expected); + const keys = Object.keys(zhHant); + if (!errors.length && keys.length === order.length) { + const at = order.findIndex((text, i) => keys[i] !== text); + if (at >= 0) + errors.push( + `entries leave the ${ZH_HANT_SOURCE} order at "${order[at]}": run ${ZH_HANT_COMMAND}`, + ); + } + return errors; +} + +const serialize = (catalog) => `${JSON.stringify(catalog, null, 2)}\n`; + +export function writeZhHant() { + const catalog = zhHantCatalog(readCatalog(ZH_HANT_SOURCE)); + writeFileSync(catalogPath(ZH_HANT), serialize(catalog)); + return Object.keys(catalog).length; +} + function main(args) { const messages = extractMessages(); const missingFor = args.includes('--missing') ? args[args.indexOf('--missing') + 1] : null; + if (missingFor?.toLowerCase() === ZH_HANT.toLowerCase()) { + console.error( + `${ZH_HANT} is generated, not translated: add the entries to ${ZH_HANT_SOURCE} (npm run i18n -- --missing ${ZH_HANT_SOURCE}), then run ${ZH_HANT_COMMAND}`, + ); + return 1; + } if (missingFor) { const out = missingTemplate(missingFor, readCatalog(missingFor), messages); console.log(JSON.stringify(out, null, 2)); return 0; } + if (args.includes('--zh-hant')) { + const count = writeZhHant(); + console.log( + `${ZH_HANT}: wrote ${count} entries converted from ${ZH_HANT_SOURCE}`, + ); + } let failed = false; for (const locale of shippedLocales()) { let catalog = readCatalog(locale); @@ -637,10 +766,7 @@ function main(args) { catalog = Object.fromEntries( Object.entries(catalog).filter(([text]) => messages.has(text)), ); - writeFileSync( - catalogPath(locale), - `${JSON.stringify(catalog, null, 2)}\n`, - ); + writeFileSync(catalogPath(locale), serialize(catalog)); console.log(`${locale}: pruned ${stale.length} unused entries`); } else if (stale.length) { failed = true; @@ -649,11 +775,24 @@ function main(args) { ); for (const text of stale) console.log(` ${JSON.stringify(text)}`); } + // shippedLocales() is sorted, so --prune has already pruned zh-CN. + const zhCN = locale === ZH_HANT ? readCatalog(ZH_HANT_SOURCE) : null; + if (zhCN) { + try { + errors.push(...checkZhHant(zhCN, catalog, new Set(missing))); + } catch (error) { + if (error.cause?.code !== 'MODULE_NOT_FOUND') throw error; + errors.push(error.message); + } + } if (missing.length) { failed = true; - console.log( - `${locale}: ${missing.length} missing (npm run i18n -- --missing ${locale}):`, - ); + const fill = !zhCN + ? `npm run i18n -- --missing ${locale}` + : missing.every((text) => Object.hasOwn(zhCN, text)) + ? `run ${ZH_HANT_COMMAND}` + : `add them to ${ZH_HANT_SOURCE}, then ${ZH_HANT_COMMAND}`; + console.log(`${locale}: ${missing.length} missing (${fill}):`); for (const text of missing) console.log(` ${JSON.stringify(text)} ${messages.get(text).where}`); } diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a5a719033b..1c7ceb982b 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -13,6 +13,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconAtlas.js", "src/data/iconSet.js", @@ -285,6 +286,7 @@ "src/ui/views/panels/SatelliteGroundView.vue", "src/data/vesselTypes.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/ui/views/panels/AircraftModelHero.vue" ], "external": ["vue", "pinia", "vue-i18n"] @@ -421,7 +423,11 @@ }, "place-payloads": { "exports": ["./sources/places"], - "modules": ["src/data/placeProviderPayloads.js"], + "modules": [ + "src/data/placeProviderPayloads.js", + "src/data/routeSteps.js", + "src/data/distanceFormat.js" + ], "external": [] }, "space-providers": { @@ -1122,7 +1128,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/layerNames.js" + "src/ui/layerNames.js", + "src/ui/statusText.js" ], "external": [] }, @@ -1150,6 +1157,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/data/iconAtlas.js", @@ -1344,6 +1352,7 @@ "src/data/bundledJson.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/geo/julian.js", @@ -1733,6 +1742,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/data/iconSet.js", @@ -1872,10 +1882,13 @@ "civil-flights": { "exports": ["./layers/flights"], "modules": [ + "src/data/rotorFrames.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/vesselTypes.js", "src/data/fleetTrailAnchors.js", "src/data/fleetModelInstances.js", + "src/data/modelPartDrivers.js", "src/data/headingDegrees.js", "src/i18n/marker.js", "src/cyberSonar.js", @@ -2018,12 +2031,15 @@ "military-flights": { "exports": ["./layers/military"], "modules": [ + "src/data/rotorFrames.js", "src/layers/flights/modelSpec.js", "src/layers/flights/policy.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/vesselTypes.js", "src/data/fleetTrailAnchors.js", "src/data/fleetModelInstances.js", + "src/data/modelPartDrivers.js", "src/data/headingDegrees.js", "src/i18n/marker.js", "src/cyberSonar.js", @@ -2198,10 +2214,15 @@ "vessel-layer": { "exports": ["./layers/vessels"], "modules": [ + "src/data/units.js", + "src/render/color.js", + "src/data/vesselSprites.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/aircraftClass.js", "src/i18n/marker.js", "src/data/fleetModelInstances.js", + "src/data/modelPartDrivers.js", "src/data/aircraftModelLighting.js", "src/data/modelEligibility.js", "src/data/fleetTrailAnchors.js", @@ -2393,6 +2414,7 @@ "src/data/iconAtlas.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/render/motion/iconMotion.js", "src/render/cesium/heights.js", "src/render/baseTilesets.js", @@ -2451,6 +2473,7 @@ "src/render/cesium/tileRequests.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/geo/julian.js", @@ -2616,6 +2639,7 @@ "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", + "src/render/modelParts.js", "src/render/recession.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2714,6 +2738,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -2805,6 +2830,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/geo/julian.js", @@ -2905,6 +2931,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconAtlas.js", "src/data/motionModel.js", @@ -3082,7 +3109,8 @@ "src/loadingFeedback.js", "src/data/installationFeedback.js", "src/ui/layerNames.js", - "src/render/cesium/zoomOutGuard.js" + "src/render/cesium/zoomOutGuard.js", + "src/ui/statusText.js" ], "external": ["cesium", "kdbush"] }, @@ -3133,6 +3161,7 @@ "src/render/rendererOf.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/iconSet.js", "src/geo/horizon.js", "src/data/aircraftRecession.js", @@ -3322,6 +3351,7 @@ "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", + "src/render/modelParts.js", "src/render/recession.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -3415,6 +3445,7 @@ "src/render/cesium/credits.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -3647,6 +3678,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -3850,6 +3882,7 @@ "src/render/baseTilesets.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -4061,6 +4094,9 @@ "./standalone/catalog" ], "modules": [ + "src/data/units.js", + "src/data/vesselSprites.js", + "src/data/rotorFrames.js", "src/render/stub/viewRectangle.js", "src/render/stub/math.js", "src/render/cesium/controlledCamera.js", @@ -4076,8 +4112,10 @@ "src/data/aircraftIconLayer.js", "src/data/fixCurve.js", "src/data/aircraftModelLayer.js", + "src/data/modelPartDrivers.js", "src/data/aircraftMotionRegime.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/fleetTrailAnchors.js", "src/data/fleetModelInstances.js", "src/app/layers/fleetModels.js", @@ -5462,14 +5500,19 @@ "application-layer-construction": { "exports": ["./application/layers"], "modules": [ + "src/data/units.js", + "src/data/vesselSprites.js", + "src/data/rotorFrames.js", "src/layers/flights/icons.js", "src/data/aircraftIconLayer.js", "src/data/fixCurve.js", "src/data/aircraftModelLayer.js", + "src/data/modelPartDrivers.js", "src/data/aircraftMotionRegime.js", "src/geo/julian.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/iconSet.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", @@ -6309,6 +6352,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -6468,6 +6512,7 @@ "src/render/cesium/camera.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", "src/geo/horizon.js", @@ -6678,6 +6723,7 @@ "src/data/aircraftClass.js", "src/data/aircraftEmergency.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/vesselTypes.js", "src/data/fleetTrailAnchors.js", "src/data/courseFromFixes.js" @@ -7038,6 +7084,120 @@ "modules": ["src/sources/httpBody.js", "src/i18n/marker.js"], "external": [] }, + "library-proxy": { + "exports": ["./sources/library"], + "modules": [ + "src/library/proxy.js", + "src/library/catalog.js", + "src/library/manifest.js", + "src/data/libraryLayerIds.js", + "src/library/ledger.json", + "src/library/entries/ak-statewide-imagery.json", + "src/library/entries/ar-statewide-imagery.json", + "src/library/entries/az-statewide-imagery.json", + "src/library/entries/amsterdam-traffic-cameras.json", + "src/library/entries/bayern-dop40.json", + "src/library/entries/bismarck-mandan-nd.json", + "src/library/entries/bkg-topplus-open.json", + "src/library/entries/cctv-florida-fl511.json", + "src/library/entries/cctv-lithuania.json", + "src/library/entries/cctv-nyc-dot.json", + "src/library/entries/ct-statewide-imagery.json", + "src/library/entries/dakota-county-mn.json", + "src/library/entries/dc-statewide-imagery.json", + "src/library/entries/de-statewide-imagery.json", + "src/library/entries/ee-maa-amet-ortofoto.json", + "src/library/entries/eia-power-plants.json", + "src/library/entries/epa-superfund-sites.json", + "src/library/entries/epa-toxic-release-facilities.json", + "src/library/entries/epc-england-wales.json", + "src/library/entries/fema-usa-structures.json", + "src/library/entries/gbif-occurrence-density.json", + "src/library/entries/gdacs-disaster-alerts.json", + "src/library/entries/grand-forks-nd.json", + "src/library/entries/gsi-japan-map.json", + "src/library/entries/gsi-japan-photo.json", + "src/library/entries/gvp-holocene-volcanoes.json", + "src/library/entries/ia-statewide-imagery.json", + "src/library/entries/id-statewide-imagery.json", + "src/library/entries/ign-orthophotos-france.json", + "src/library/entries/il-statewide-imagery.json", + "src/library/entries/imf-portwatch-chokepoints.json", + "src/library/entries/imf-portwatch-disruptions.json", + "src/library/entries/in-statewide-imagery.json", + "src/library/entries/jrc-surface-water.json", + "src/library/entries/kartverket-admin-units.json", + "src/library/entries/kartverket-cadastre.json", + "src/library/entries/kartverket-depth.json", + "src/library/entries/kartverket-hillshade.json", + "src/library/entries/kartverket-nautical-charts.json", + "src/library/entries/kartverket-terrain-relief.json", + "src/library/entries/kartverket-topo-grey.json", + "src/library/entries/kartverket-topo.json", + "src/library/entries/kartverket-toporaster.json", + "src/library/entries/ks-statewide-imagery.json", + "src/library/entries/ky-statewide-imagery.json", + "src/library/entries/lake-county-in.json", + "src/library/entries/lawrence-ks.json", + "src/library/entries/lee-county-fl.json", + "src/library/entries/loudoun-county-va.json", + "src/library/entries/louisville-lojic-ky.json", + "src/library/entries/ma-statewide-imagery.json", + "src/library/entries/macrostrat-geology.json", + "src/library/entries/mapterhorn-terrain.json", + "src/library/entries/maris-ms.json", + "src/library/entries/md-statewide-imagery.json", + "src/library/entries/me-statewide-imagery.json", + "src/library/entries/mi-statewide-imagery.json", + "src/library/entries/mountain-village-co.json", + "src/library/entries/ms-statewide-imagery.json", + "src/library/entries/mt-statewide-imagery.json", + "src/library/entries/naip.json", + "src/library/entries/nasa-black-marble.json", + "src/library/entries/nasa-eonet-events.json", + "src/library/entries/nc-statewide-imagery.json", + "src/library/entries/nctcog-tx.json", + "src/library/entries/nd-statewide-imagery.json", + "src/library/entries/new-orleans-rpc-la.json", + "src/library/entries/nh-statewide-imagery.json", + "src/library/entries/nj-statewide-imagery.json", + "src/library/entries/noaa-tide-stations.json", + "src/library/entries/nrw-dop.json", + "src/library/entries/nsw-imagery.json", + "src/library/entries/ntad-national-bridges.json", + "src/library/entries/nwa-benton-washington-ar.json", + "src/library/entries/nws-active-alerts.json", + "src/library/entries/ny-statewide-imagery.json", + "src/library/entries/oakland-county-mi.json", + "src/library/entries/oh-statewide-imagery.json", + "src/library/entries/or-statewide-imagery.json", + "src/library/entries/pa-statewide-imagery.json", + "src/library/entries/pl-ortofotomapa.json", + "src/library/entries/pnoa-ma.json", + "src/library/entries/portland-metro-or.json", + "src/library/entries/pt-dgt-ortos.json", + "src/library/entries/ri-statewide-imagery.json", + "src/library/entries/swisstopo-swissimage.json", + "src/library/entries/tx-statewide-imagery.json", + "src/library/entries/union-county-oh.json", + "src/library/entries/usgs-hydrography.json", + "src/library/entries/usgs-topo.json", + "src/library/entries/va-statewide-imagery.json", + "src/library/entries/vt-statewide-imagery.json", + "src/library/entries/wallonie-ortho.json", + "src/library/entries/wi-statewide-imagery.json", + "src/library/entries/wri-global-power-plants.json", + "src/library/entries/wv-statewide-imagery.json", + "src/library/formats.js", + "src/library/parquet.js", + "src/sources/httpBody.js", + "src/i18n/marker.js", + "src/library/source.js", + "src/keySetupCore.mjs", + "src/localRequestGate.mjs" + ], + "external": ["hyparquet", "fzstd"] + }, "overpass-lexer": { "exports": ["./sources/overpass"], "modules": ["src/sources/overpass.js"], @@ -7095,10 +7255,12 @@ "exports": ["./layers/transit/standalone"], "modules": [ "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/vesselTypes.js", "src/data/aircraftClass.js", "src/i18n/marker.js", "src/data/fleetModelInstances.js", + "src/data/modelPartDrivers.js", "src/data/modelEligibility.js", "src/data/fleetTrailAnchors.js", "src/data/aircraftModelLighting.js", @@ -7248,8 +7410,10 @@ "modules": [ "src/i18n/marker.js", "src/data/fleetModels.js", + "src/render/modelParts.js", "src/data/vesselTypes.js", "src/data/fleetModelInstances.js", + "src/data/modelPartDrivers.js", "src/data/aircraftClass.js", "src/data/aircraftModelLighting.js", "src/data/fleetTrailAnchors.js", @@ -7637,6 +7801,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/iconSetPrimitive.js", "src/render/recession.js", + "src/render/modelParts.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/data/iconSet.js", @@ -8051,6 +8216,7 @@ "./render/vectorBase", "./render/iconSegment", "./render/recession", + "./render/modelParts", "./render/windStreamlines", "./geo/screenCluster" ], @@ -8073,6 +8239,7 @@ "src/render/input/wheel.js", "src/render/conformance/expect.js", "src/render/conformance/checks/ports.js", + "src/render/conformance/partsModel.js", "src/render/stub/math.js", "src/geo/index.js", "src/geo/julian.js", @@ -8101,7 +8268,8 @@ "src/data/motionModel.js", "src/layers/wind/streamlines.js", "src/layers/wind/model.js", - "src/render/recession.js" + "src/render/recession.js", + "src/render/modelParts.js" ], "external": ["pbf", "@mapbox/vector-tile", "kdbush"] }, diff --git a/scripts/qa-enrich-ambient.mjs b/scripts/qa-enrich-ambient.mjs index abdfddb9dc..a206333e32 100644 --- a/scripts/qa-enrich-ambient.mjs +++ b/scripts/qa-enrich-ambient.mjs @@ -29,7 +29,7 @@ * E4 diversity : ≥5 distinct glyph data-URIs displayed ambiently after * enrichment (expected: 8) * E5 glyphs : every billboard's image === aircraftIcon(classify(typeCode)) - * E6 scales : every billboard's scale === CLASS_SCALE_2D[klass] + * E6 scales : every billboard's scale === 1, whatever its class * E7 bounds : ≤4 concurrent requests, ≥185 ms between dispatches (≤5/s * drip), total ≤300 (budget ceiling) * E8 next poll : another poll neither reverts glyphs nor re-requests hexes @@ -53,7 +53,7 @@ import fs from 'node:fs'; import path from 'node:path'; import puppeteer from 'puppeteer'; -import { classifyAircraft, CLASS_SCALE_2D } from '../src/data/aircraftClass.js'; +import { classifyAircraft } from '../src/data/aircraftClass.js'; import { aircraftIcon } from '../src/data/aircraftIcons.js'; // --------------------------------------------------------------------------- @@ -362,7 +362,7 @@ async function main() { const bb = beforeById.get(hex); if (!bb) baselineBad.push(`${hex}:missing`); else if (bb.image !== AIRLINER_ICON) baselineBad.push(`${hex}:not-default-glyph`); - else if (Math.abs(bb.scale - (CLASS_SCALE_2D.airliner || 1)) > 1e-9) baselineBad.push(`${hex}:scale=${bb.scale}`); + else if (Math.abs(bb.scale - 1) > 1e-9) baselineBad.push(`${hex}:scale=${bb.scale}`); } record('E2 baseline: all 12 category-0 planes default to the airliner glyph', baselineBad.length === 0, @@ -415,13 +415,13 @@ async function main() { for (const [hex, klass] of expected) { const bb = afterById.get(hex); const wantImg = aircraftIcon(klass); - const wantScale = CLASS_SCALE_2D[klass] || 1; + const wantScale = 1; if (!bb || bb.image !== wantImg) glyphBad.push(`${hex}(${klass})${bb ? ':wrong-image' : ':missing'}`); if (bb && Math.abs(bb.scale - wantScale) > 1e-9) scaleBad.push(`${hex}: ${bb.scale} != ${wantScale}`); } record('E5 glyphs: every billboard matches aircraftIcon(classify(typeCode))', glyphBad.length === 0, glyphBad.length ? glyphBad.join(' ') : `${expected.size} matched (incl. the found:false miss staying airliner)`); - record('E6 scales: every billboard has its per-class CLASS_SCALE_2D', + record('E6 scales: every billboard has the one fleet scale', scaleBad.length === 0, scaleBad.length ? scaleBad.join(' ') : 'all scales exact (composes with scaleByDistance)'); await page.screenshot({ path: path.join(SHOT_DIR, 'enrich-after-diverse.png') }); @@ -469,7 +469,7 @@ async function main() { for (const [hex, klass] of expected) { const bb = afterPollById.get(hex); if (!bb || bb.image !== aircraftIcon(klass)) pollBad.push(`${hex}(${klass})${bb ? ':reverted' : ':missing'}`); - else if (Math.abs(bb.scale - (CLASS_SCALE_2D[klass] || 1)) > 1e-9) pollBad.push(`${hex}:scale-reverted`); + else if (Math.abs(bb.scale - 1) > 1e-9) pollBad.push(`${hex}:scale-reverted`); } const noReRequests = afterPoll.starts === Object.keys(TYPES).length; record('E8 next poll: enriched glyphs persist and no hex is re-requested', diff --git a/scripts/qa-sprites-b5.mjs b/scripts/qa-sprites-b5.mjs index 190a0c6513..7f6815c349 100644 --- a/scripts/qa-sprites-b5.mjs +++ b/scripts/qa-sprites-b5.mjs @@ -13,8 +13,8 @@ * B1 ingest : both layers ingest the synthetic planes * B2 billboards : every fleet billboard carries EXACTLY the expected * per-class glyph (image data-URI === aircraftIcon(klass), - * imported from src) and per-class scale (flights: - * CLASS_SCALE_2D; military: 0.7 × CLASS_SCALE_2D) + * imported from src) and one scale for every class + * (flights: 1; military: 0.7) * B3 models : with 3D on, fleet Cesium.Model.scale === the life-size * scale of the fleet model the aircraft's type or category * selects (aircraftModelSpec) per icao; tracked too @@ -33,7 +33,7 @@ import fs from 'node:fs'; import path from 'node:path'; import puppeteer from 'puppeteer'; import { stubPlanespotters } from './qa-photo-stub.mjs'; -import { classifyAircraft, CLASS_SCALE_2D } from '../src/data/aircraftClass.js'; +import { classifyAircraft } from '../src/data/aircraftClass.js'; import { aircraftModelSpec } from '../src/data/fleetModels.js'; // Every aircraft draws its fleet model life size: its type's length over the // model's built length, chosen by type code (military) or category (flights). @@ -381,14 +381,14 @@ async function main() { for (const [id, klass] of expectedFlights) { const bb = bbById.get(id); const wantImg = aircraftIcon(klass); - const wantScale = CLASS_SCALE_2D[klass] || 1; + const wantScale = 1; if (!bb || bb.image !== wantImg) glyphBad.push(`${id}(${klass})${bb ? ':wrong-image' : ':missing'}`); if (bb && Math.abs(bb.scale - wantScale) > 1e-9) scaleBad.push(`${id}: ${bb.scale} != ${wantScale}`); } for (const [id, klass] of expectedMilitary) { const bb = bbById.get(id); const wantImg = aircraftIcon(klass); - const wantScale = MIL_BILLBOARD_SCALE * (CLASS_SCALE_2D[klass] || 1); + const wantScale = MIL_BILLBOARD_SCALE; if (!bb || bb.image !== wantImg) glyphBad.push(`${id}(${klass})${bb ? ':wrong-image' : ':missing'}`); if (bb && Math.abs(bb.scale - wantScale) > 1e-9) scaleBad.push(`${id}: ${bb.scale} != ${wantScale}`); } diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index 4e163cd398..fb745e48d6 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -1453,9 +1453,9 @@ async function main() { // NOTE: we do NOT manually reposition the camera. Tracking follows the // plane with a calibrated viewFrom, so the follow camera lands - // in the few-km band (altitude*1.1+2500, clamped 3–30 km) — far below the - // MODEL_ALT_CEIL_M = 800 km ceiling, so _modelRegimeActive() is true and the - // standalone tracked model renders. That's the exact path the invariants + // in the few-km band (altitude*1.1+2500, clamped 3–30 km) — below the + // MODEL_ALT_CEIL_M ceiling, so _modelRegimeActive() is true; the checks below + // zoom in to within the 3 km model range so the standalone tracked model renders. That's the exact path the invariants // protect, so we exercise it rather than a synthetic setView. // ============================================================ @@ -1518,16 +1518,34 @@ async function main() { // is "tracked model not up yet", not a match. return bestD < 1000 * 1000 ? best : null; }; + // Models draw only within 3 km of the camera, and the follow camera + // frames a cruising plane from farther out: zoom in on the followed + // plane until it is within `metres`. Returns the distance reached. + window.__qaFollowWithin = async function (metres) { + const v = window.__godsEyeView.viewer; + for (let i = 0; i < 20; i++) { + const followed = window.__qaFollowed(); + const t = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null; + if (!t) return null; + const c = v.camera.positionWC; + const d = Math.hypot(c.x - t.x, c.y - t.y, c.z - t.z); + if (d <= metres) return d; + v.camera.zoomIn(d - metres * 0.8); + await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); + } + return null; + }; }); - // Track a synthetic commercial plane. Tracking follows it with a - // viewFrom, so the follow camera lands in the few-km band and the standalone - // 3D model renders (model regime active below the 800 km ceiling). + // Track a synthetic commercial plane, then zoom the follow camera to + // within 2 km of it: models draw only within 3 km, so the standalone 3D + // model renders there. const trackedIcao = SYNTH.flights[0].icao; await evalPage((icao) => { window.__godsEyeView.dataManager.layers.get('flights').module.trackById(icao); }, trackedIcao); - await sleep(1500); // let the follow camera settle + the GLB load kick off + await sleep(1500); // let the follow camera settle + await evalPage(() => window.__qaFollowWithin(2000)); // Wait until the tracked Cesium.Model primitive exists, is ready & shown. const modelUp = await page.waitForFunction((icao) => { @@ -1845,7 +1863,8 @@ async function main() { await evalPage((icao) => { window.__godsEyeView.dataManager.layers.get('flights').module.trackById(icao); }, h1Icao); - await sleep(1500); // follow camera settles; tracked GLB load kicks off + await sleep(1500); // follow camera settles + await evalPage(() => window.__qaFollowWithin(2000)); // within the 3 km model range // (i) The tracked standalone model must expose its pick id (= the icao). const h1ModelUp = await page.waitForFunction((icao) => { @@ -2498,10 +2517,11 @@ async function main() { const milBB = findBB('bbb177'); if (!flBB || !milBB) return { error: `ground billboards missing (fl=${!!flBB} mil=${!!milBB})` }; const radius = (pos) => Math.hypot(pos.x, pos.y, pos.z); - // Park the camera 8 km radially above the flights plane (both in view nadir-ish). + // Park the camera 2 km radially above the flights plane (both in view + // nadir-ish, both within the 3 km model range). const p = flBB.position; const r = Math.hypot(p.x, p.y, p.z); - const k = (r + 8000) / r; + const k = (r + 2000) / r; v.camera.cancelFlight(); v.camera.setView({ destination: { x: p.x * k, y: p.y * k, z: p.z * k }, @@ -3279,8 +3299,8 @@ async function main() { // these pins with it rather than stranding them on stale numbers. const reg = await import(`${window.__gevQaSourceBase || '/src'}/layers/flights/policy.js`); window.__dfRegime = { - enter: reg.MODEL_PROX_ADD_M, - exit: reg.MODEL_PROX_KEEP_M, + enter: reg.MODEL_ADD_M, + exit: reg.MODEL_KEEP_M, }; // Zooming while following is safe: the tracked-camera framer positions // the camera ONCE per selection and is deliberately read-only on normal @@ -3976,7 +3996,7 @@ async function main() { // Hand the camera back to the CLOSE follow range before releasing. The // LOADING scenario below needs BOTH an active tracked regime and a // fleet model for this contact, and the fleet only admits models within - // MODEL_PROX_ADD_M of the camera — parking just inside the enter + // MODEL_ADD_M of the camera — parking just inside the enter // ceiling satisfies the regime but sits outside that add radius, which // silently starved the fleet half into a skip. await window.__dfZoomBelow(belowH + 500); diff --git a/server/providers/library.js b/server/providers/library.js index b0c17ebef5..822d912a3e 100644 --- a/server/providers/library.js +++ b/server/providers/library.js @@ -1,103 +1,25 @@ import { LIBRARY_ENTRIES } from '../../src/library/catalog.js'; -import { loadLibraryDataset } from '../../src/library/formats.js'; -import { buildPartitionIndex } from '../../src/library/parquet.js'; -import { - libraryUpstreamUrl, - parseLibraryIdList, - libraryTileUrl, -} from '../../src/library/manifest.js'; -import { KEY_SETUP_KEYS } from '../../src/keySetupCore.mjs'; -import { - readResponseBytesCapped, - readResponseTextCapped, - coalesceProxyRequest, -} from './common/http.js'; +import { createLibraryHandler } from '../../src/library/proxy.js'; import { makeRateLimiter, clientKey } from './common/rate-limit.js'; import { admitSameSite, admitSameSiteKeyless } from './common/same-site.js'; -const DATASET_TIMEOUT_MS = 30_000; -const TILE_TIMEOUT_MS = 10_000; -/** Each listing page or footer read while building a partition index. */ -const INDEX_TIMEOUT_MS = 20_000; -/** How long an incomplete partition index is served before a rebuild. */ -const PARTIAL_INDEX_MS = 5 * 60_000; -const TILE_MAX_BYTES = 2 * 1024 * 1024; -const TILE_CACHE_LIMIT = 512; -const IN_FLIGHT_LIMIT = 64; +export { + libraryAvailability, + libraryKeyValue, + parseLibraryTilePath, +} from '../../src/library/proxy.js'; + +/** `content-type` as `Content-Type`: a fetch Response's names, as Node writes them. */ +const headerName = (name) => + name.replace( + /(^|-)([a-z])/g, + (_, dash, letter) => dash + letter.toUpperCase(), + ); /** - * Availability of every entry on this instance, decided by the operator's - * environment alone: `GEV_LIBRARY_DISABLE` removes entries, opt-in entries - * need `GEV_LIBRARY_ENABLE` (or, for a pack, its host's own switch), and a - * keyed entry needs its key. The answer names a reason, never a secret. - * @param {object[]} entries - * @param {Record} env - * @returns {Map} - */ -export function libraryAvailability(entries, env) { - const enabled = parseLibraryIdList(env.GEV_LIBRARY_ENABLE); - const disabled = parseLibraryIdList(env.GEV_LIBRARY_DISABLE); - const result = new Map(); - for (const entry of entries) { - let reason = null; - if (disabled.has(entry.id)) reason = 'operator-disabled'; - else if (entry.kind === 'pack') { - if (String(env[entry.pack.env] || '').trim() !== '1') - reason = 'operator-opt-in'; - } else if (entry.licence.operatorOptIn && !enabled.has(entry.id)) - reason = 'operator-opt-in'; - else if (entry.source.key && !libraryKeyValue(entry.source.key, env)) - reason = 'key-missing'; - result.set(entry.id, { available: reason === null, reason }); - } - return result; -} - -/** The configured value for a manifest key, through the key registry. */ -export function libraryKeyValue(key, env) { - const registered = KEY_SETUP_KEYS.find(({ id }) => id === key?.id); - for (const name of registered?.envVars || []) { - const value = String(env[name] || '').trim(); - if (value) return value; - } - return null; -} - -function withKey(url, key, env, headers) { - if (!key) return url; - const value = libraryKeyValue(key, env); - if (!value) throw Object.assign(new Error('key_missing'), { status: 503 }); - if (key.in === 'header') { - headers[key.name] = value; - return url; - } - const keyed = new URL(url); - keyed.searchParams.set(key.name, value); - return keyed.href; -} - -/** - * Parse `////` against a tiles entry's zoom range. - * @returns {{ z: number, x: number, y: number } | null} - */ -export function parseLibraryTilePath(parts, source) { - if (parts.length !== 3 || !parts.every((part) => /^\d{1,8}$/.test(part))) - return null; - const [z, x, y] = parts.map(Number); - const minZoom = source.minZoom ?? 0; - const maxZoom = source.maxZoom ?? 22; - if (z < minZoom || z > maxZoom) return null; - const span = 2 ** z; - if (x >= span || y >= span) return null; - return { z, x, y }; -} - -/** - * The Data Library's one server route. Proxied datasets and tiles reach their - * manifest's fixed upstream only: the browser names an entry id, never a URL, - * so the allowlist is exactly the catalog. Redirects are refused, bodies are - * capped while streaming, keys come from this server's environment and - * upstream error text is never returned. + * The Data Library's one server route on the dev and preview servers: the + * portable handler (`src/library/proxy.js`) behind this server's same-site + * gate and rate limits. */ export function libraryProxy({ entries = LIBRARY_ENTRIES, @@ -106,11 +28,7 @@ export function libraryProxy({ now = () => Date.now(), } = {}) { const byId = new Map(entries.map((entry) => [entry.id, entry])); - const datasets = new Map(); - const tiles = new Map(); - const indexes = new Map(); - const partialIndexes = new Map(); - const inFlight = new Map(); + const handle = createLibraryHandler({ entries, env, fetchImpl, now }); const allowData = makeRateLimiter({ windowMs: 60_000, max: 30, @@ -122,261 +40,54 @@ export function libraryProxy({ globalMax: 6000, }); - async function upstream(url, entry, headers, timeoutMs) { - // Defense in depth: every derived request stays on the manifest's host. - const target = libraryUpstreamUrl(url); - const declared = libraryUpstreamUrl(entry.source.url); - if (!target || !declared || target.host !== declared.host) - throw Object.assign(new Error('off_manifest_host'), { status: 502 }); - const signal = AbortSignal.timeout(timeoutMs); - const response = await fetchImpl(url, { - signal, - redirect: 'error', - headers: { Accept: '*/*', ...headers }, - }); - if (!response.ok) { - await response.body?.cancel?.().catch?.(() => {}); - throw Object.assign(new Error('upstream_unavailable'), { status: 502 }); - } - return { response, signal }; - } - - async function fetchDataset(entry) { - const headers = {}; - const collection = await loadLibraryDataset(entry, async (url, budget) => { - const keyed = withKey(url, entry.source.key, env, headers); - const { response, signal } = await upstream( - keyed, - entry, - headers, - DATASET_TIMEOUT_MS, - ); - const text = await readResponseTextCapped( - response, - budget.remainingBytes, - signal, - ); - budget.remainingBytes -= new TextEncoder().encode(text).byteLength; - return text; - }); - return { ...collection, fetchedAt: now() }; - } - - async function cached(store, key, ttlMs, load, limit = Infinity) { - const previous = store.get(key); - if (previous && now() - previous.savedAt < ttlMs) - return { value: previous.value, stale: false }; - if (!inFlight.has(key) && inFlight.size >= IN_FLIGHT_LIMIT) - throw Object.assign(new Error('busy'), { status: 429 }); - try { - const { promise } = coalesceProxyRequest(inFlight, key, async () => { - const value = await load(); - store.delete(key); - store.set(key, { value, savedAt: now() }); - while (store.size > limit) store.delete(store.keys().next().value); - return value; - }); - return { value: await promise, stale: false }; - } catch (error) { - if (previous) return { value: previous.value, stale: true }; - throw error; - } - } - - function json(res, status, value, extra = {}) { + function refuse(res, status, error) { if (res.destroyed) return; res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(status === 405 ? { Allow: 'GET' } : {}), ...(status === 429 ? { 'Retry-After': '60' } : {}), - ...extra, }); - res.end(JSON.stringify(value)); - } - - function gate(req, res, entry) { - // A keyed entry spends the operator's credential: refuse forwarded - // requests like the other cost-bearing routes. Keyless entries keep - // working behind a reverse proxy, like terrain heights. - return entry?.source?.key - ? admitSameSite(req, res) - : admitSameSiteKeyless(req, res); + res.end(JSON.stringify({ error })); } async function handler(req, res) { - if (req.method !== 'GET') - return json(res, 405, { error: 'method_not_allowed' }); + if (req.method !== 'GET') return refuse(res, 405, 'method_not_allowed'); const path = (req.url || '/').split('?')[0]; - const parts = path.split('/').filter(Boolean); - const availability = libraryAvailability(entries, env); - - if (parts.length === 1 && parts[0] === 'catalog') { - if (admitSameSiteKeyless(req, res)) return undefined; - return json(res, 200, { - entries: entries.map(({ id }) => ({ id, ...availability.get(id) })), - }); - } - - const [route, id, ...rest] = parts; + const [route, id] = path.split('/').filter(Boolean); const entry = byId.get(id); - if (!entry || !['data', 'tile', 'index'].includes(route)) - return json(res, 404, { error: 'unknown_entry' }); - - // A partitioned GeoParquet entry's index: which file covers where, read - // from each file's footer. Built once per cacheSeconds and shared, so - // visitors do not each list the bucket and read every footer. - if (route === 'index') { - if (rest.length || !entry.source?.partitions) - return json(res, 404, { error: 'not_partitioned' }); + if (route === 'catalog' || !entry) { if (admitSameSiteKeyless(req, res)) return undefined; - const { available, reason } = availability.get(id); - if (!available) return json(res, 403, { error: reason }); - if (!allowData(clientKey(req))) - return json(res, 429, { error: 'rate_limited' }); - // Only a complete index is cached for cacheSeconds. An incomplete one - // (footers that kept failing) is served as `complete: false` and kept - // for PARTIAL_INDEX_MS only, so the next request soon rebuilds it; a - // complete index from before keeps being served while rebuilds fail. - const key = `index:${id}`; - const partial = partialIndexes.get(key); - if (partial && now() - partial.savedAt < PARTIAL_INDEX_MS) { - const previous = indexes.get(key); - return json(res, 200, previous?.value ?? partial.value); - } - try { - const { value } = await cached( - indexes, - key, - entry.source.cacheSeconds * 1000, - async () => { - const built = await buildPartitionIndex(entry, { - fetchImpl: (url, options = {}) => - fetchImpl(url, { - ...options, - signal: - options.signal ?? AbortSignal.timeout(INDEX_TIMEOUT_MS), - }), - }); - const value = { - partitions: built.partitions, - complete: built.complete, - builtAt: now(), - }; - if (!built.complete) { - // Recorded here too: with an earlier complete index, cached() - // serves that one and swallows this error, and the rebuild - // still waits PARTIAL_INDEX_MS. - partialIndexes.set(key, { value, savedAt: now() }); - throw Object.assign(new Error('index_incomplete'), { - partialIndex: value, - }); - } - partialIndexes.delete(key); - return value; - }, - ); - return json(res, 200, value); - } catch (error) { - if (error?.partialIndex) return json(res, 200, error.partialIndex); - const status = error?.status === 429 ? 429 : 502; - return json(res, status, { error: 'library_upstream_unavailable' }); - } - } - const isDataset = route === 'data' && rest.length === 0; - const isTile = route === 'tile'; - if ( - entry.source.fetch !== 'proxied' || - (isDataset && entry.kind !== 'dataset') || - (isTile && entry.kind !== 'tiles') || - (!isDataset && !isTile) - ) - return json(res, 404, { error: 'not_proxied' }); - if (gate(req, res, entry)) return undefined; - const { available, reason } = availability.get(id); - if (!available) return json(res, 403, { error: reason }); - - const ttlMs = entry.source.cacheSeconds * 1000; - if (isDataset) { - if (!allowData(clientKey(req))) - return json(res, 429, { error: 'rate_limited' }); - try { - const { value, stale } = await cached( - datasets, - `data:${id}`, - ttlMs, - () => fetchDataset(entry), - ); - return json( - res, - 200, - stale ? { ...value, stale: true } : value, - stale ? { 'X-Data-Stale': 'true' } : {}, - ); - } catch (error) { - const status = [429, 503].includes(error?.status) ? error.status : 502; - return json(res, status, { - error: - status === 503 ? 'key_missing' : 'library_upstream_unavailable', - }); - } - } - - const tile = parseLibraryTilePath(rest, entry.source); - if (!tile) return json(res, 400, { error: 'invalid_tile' }); - if (!allowTiles(clientKey(req))) - return json(res, 429, { error: 'rate_limited' }); - try { - const key = `tile:${id}:${tile.z}/${tile.x}/${tile.y}`; - const { value } = await cached( - tiles, - key, - ttlMs, - async () => { - const headers = {}; - const url = withKey( - libraryTileUrl(entry.source.url, tile.z, tile.x, tile.y), - entry.source.key, - env, - headers, - ); - const { response, signal } = await upstream( - url, - entry, - headers, - TILE_TIMEOUT_MS, - ); - const type = String(response.headers.get('content-type') || '') - .split(';')[0] - .trim() - .toLowerCase(); - if (!/^image\/(png|jpeg|webp)$/.test(type)) { - await response.body?.cancel?.().catch?.(() => {}); - throw Object.assign(new Error('not_an_image'), { status: 502 }); - } - const bytes = await readResponseBytesCapped( - response, - TILE_MAX_BYTES, - signal, - ); - return { type, bytes }; - }, - TILE_CACHE_LIMIT, - ); - if (res.destroyed) return undefined; - res.writeHead(200, { - 'Content-Type': value.type, - 'Cache-Control': `private, max-age=${entry.source.cacheSeconds}`, - 'X-Content-Type-Options': 'nosniff', - }); - res.end(Buffer.from(value.bytes)); - return undefined; - } catch (error) { - const status = [429, 503].includes(error?.status) ? error.status : 502; - return json(res, status, { - error: status === 503 ? 'key_missing' : 'library_upstream_unavailable', - }); + } else { + // A keyed entry spends the operator's credential: refuse forwarded + // requests like the other cost-bearing routes. Keyless entries keep + // working behind a reverse proxy, like terrain heights. + if ( + entry.source?.key + ? admitSameSite(req, res) + : admitSameSiteKeyless(req, res) + ) + return undefined; + const allow = route === 'tile' ? allowTiles : allowData; + if (!allow(clientKey(req))) return refuse(res, 429, 'rate_limited'); } + const response = await handle( + new Request(`http://library.invalid/api/library${req.url || '/'}`, { + headers: { Accept: String(req.headers?.accept || '*/*') }, + }), + ); + if (res.destroyed) return undefined; + const headers = {}; + for (const [name, value] of response.headers) + headers[headerName(name)] = value; + const body = Buffer.from(await response.arrayBuffer()); + res.writeHead(response.status, headers); + res.end( + String(headers['Content-Type']).startsWith('application/json') + ? body.toString('utf8') + : body, + ); + return undefined; } return { diff --git a/src/app/controls.js b/src/app/controls.js index bb53381c49..8e152a1e02 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -8,6 +8,9 @@ import { useDisplayStore } from '../ui/stores/display.js'; import { applicationPinia } from '../ui/vueRuntime.js'; import { t } from '../i18n/index.js'; +/** Where the camera starts unless a host gives a `startView`. */ +export { START_VIEW }; + /** * Construct the existing controls and camera presentation. `initialShareCode` * opens a share code (the `` of `/share/`) at start-up, for a host @@ -15,6 +18,9 @@ import { t } from '../i18n/index.js'; * picker, for a host that offers its own language choice (`switchLocale` from * the `./i18n` entry). `startView` is where the camera starts (the whole * planet by default; a host may pass a city); a shared view flies from there. + * `homeView` is where the title's logo goes back to (with the clock live): the + * start view unless given, for a host whose `startView` only carries a view + * across a rebuild. * `services.cockpitSubjects` adds the application's own first-person subjects * to the Cockpit (src/cockpitSubjectProviders.js). */ @@ -29,6 +35,7 @@ export function createApplicationControls({ initialShareCode = null, localePicker = true, startView = START_VIEW, + homeView = startView, }) { // Every boot starts from the same view, before share restoration flies on. applyStartView(viewer, startView); @@ -51,6 +58,7 @@ export function createApplicationControls({ // A share code to open at start-up instead of the page's address. initialShareCode, localePicker, + homeView, }); defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); diff --git a/src/app/tools.js b/src/app/tools.js index bc16a9af0b..08258691f4 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -48,6 +48,13 @@ import { overlayHost } from './layers/overlayHost.js'; * Attach scene tools, rendering listeners and the application debug handle. * `scene` is what `createApplicationScene` returns; its `trimStaleCommands` * runs after each layer disable (a scene without one keeps that memory). + * `library.fetchTile` and `library.fetchData` fetch the Data Library's tiles + * and proxied datasets in place of the defaults (`createLibrarySource`). + * `library.fetchImpl` asks the library server (its catalog) in place of the + * page's fetch, for a server that wants the application's own credentials. + * `library.requireCatalog` offers only what the server's library catalog + * names, and nothing while it does not answer. `library: false` leaves the + * Data Library out: no catalog is asked, and no Browse button is drawn. */ export function createApplicationTools({ scene, @@ -60,6 +67,7 @@ export function createApplicationTools({ onSceneDirector, sceneDataPacks, drawMarkActions = [], + library = {}, signal, defer, }) { @@ -148,51 +156,60 @@ export function createApplicationTools({ connect: connectDisplay, }); defer(() => geoFileImport?.destroy()); - // DATA ▸ Library: entries register their layers only when a viewer adds - // them, after the core catalog is sealed. The browser dialog and the - // controller share the application lifetime. - const dataLibrary = createDataLibrary({ - dataManager, - services: localGeoJsonServices, - getTileset: () => tileset, - mapStackController, - shareLink: styleManager.shareLinkManager, - requestRender: governorRequestRender, - // Zoom to layer: an immediate navigation, so Cockpit can refuse it and - // the current follow owner is released first (as for imported files). - zoomTo: (extent) => - styleManager.runImmediateNavigation('layer', () => - flyToLibraryExtent(viewer, extent), - ) !== false, - }); - defer(() => dataLibrary.destroy()); - // Browse: the owner presents the dialog through the store; LayerPanelsView - // draws the Browse button and the dialog from it. - const libraryStore = useDataLibraryStore(applicationPinia()); - const libraryBrowser = createLibraryBrowser({ - library: dataLibrary, - publish: (view) => libraryStore.publish(view), - }); - libraryStore.connect(libraryBrowser.controls); - defer(() => { - libraryBrowser.destroy(); - libraryStore.connect(null); - }); - dataLibrary.start({ signal }).catch((error) => { - if (!signal?.aborted) console.warn('[Library] start failed:', error); - }); - // The live gate's handle (scripts/qa-data-library.mjs). - const libraryHandle = { - library: dataLibrary, - browser: libraryBrowser, - // What Copy Link would copy. - buildShareLink: () => styleManager.shareLinkManager?.buildLink?.() ?? null, - }; - window.__gevDataLibrary = libraryHandle; - defer(() => { - if (window.__gevDataLibrary === libraryHandle) - delete window.__gevDataLibrary; - }); + if (library !== false) { + // DATA ▸ Library: entries register their layers only when a viewer adds + // them, after the core catalog is sealed. The browser dialog and the + // controller share the application lifetime. + const dataLibrary = createDataLibrary({ + dataManager, + services: localGeoJsonServices, + getTileset: () => tileset, + mapStackController, + shareLink: styleManager.shareLinkManager, + requestRender: governorRequestRender, + // An application's own tile and dataset fetches, when it keeps them in + // its own cache. + fetchImpl: library.fetchImpl ?? undefined, + fetchTile: library.fetchTile ?? null, + fetchData: library.fetchData ?? null, + requireCatalog: library.requireCatalog === true, + // Zoom to layer: an immediate navigation, so Cockpit can refuse it and + // the current follow owner is released first (as for imported files). + zoomTo: (extent) => + styleManager.runImmediateNavigation('layer', () => + flyToLibraryExtent(viewer, extent), + ) !== false, + }); + defer(() => dataLibrary.destroy()); + // Browse: the owner presents the dialog through the store; LayerPanelsView + // draws the Browse button and the dialog from it. + const libraryStore = useDataLibraryStore(applicationPinia()); + const libraryBrowser = createLibraryBrowser({ + library: dataLibrary, + publish: (view) => libraryStore.publish(view), + }); + libraryStore.connect(libraryBrowser.controls); + defer(() => { + libraryBrowser.destroy(); + libraryStore.connect(null); + }); + dataLibrary.start({ signal }).catch((error) => { + if (!signal?.aborted) console.warn('[Library] start failed:', error); + }); + // The live gate's handle (scripts/qa-data-library.mjs). + const libraryHandle = { + library: dataLibrary, + browser: libraryBrowser, + // What Copy Link would copy. + buildShareLink: () => + styleManager.shareLinkManager?.buildLink?.() ?? null, + }; + window.__gevDataLibrary = libraryHandle; + defer(() => { + if (window.__gevDataLibrary === libraryHandle) + delete window.__gevDataLibrary; + }); + } // DATA ▸ Recent Imagery: the box tool claims the pointer like Draw and the // panel lives on the right rail, so both belong to the application // lifetime. The tileset lets the layer drape while the globe is hidden. diff --git a/src/data/adsbLolFallback.js b/src/data/adsbLolFallback.js index a9d5cbbdf7..d63716e9c9 100644 --- a/src/data/adsbLolFallback.js +++ b/src/data/adsbLolFallback.js @@ -98,7 +98,7 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) { * Normalize an adsb.lol point response to an OpenSky-compatible response. * Invalid rows and positionless contacts are intentionally excluded. * @param {object} payload adsb.lol v2 response. - * @returns {{time:number,states:Array[]}} + * @returns {{time:number,states:Array[],emergencyByIcao?:object,typeByIcao?:object}} */ export function normalizeAdsbLolPointResponse(payload) { const responseNow = finiteNumber(payload?.now); @@ -111,9 +111,10 @@ export function normalizeAdsbLolPointResponse(payload) { const aircraft = Array.isArray(payload?.ac) ? payload.ac : []; const states = []; // Keep the OpenSky vectors unchanged. The regional fallback's extra readsb - // status travels alongside them, keyed only to admitted aircraft. + // status and type travel alongside them, keyed only to admitted aircraft. const admitted = new Set(); const statuses = []; + const types = []; for (const row of aircraft) { const state = normalizeAdsbLolAircraftState(row, nowSeconds); if (!state) continue; @@ -125,11 +126,17 @@ export function normalizeAdsbLolPointResponse(payload) { admitted.add(id); if (typeof row.emergency === 'string') statuses.push([id, row.emergency.trim().toLowerCase()]); + const type = typeof row.t === 'string' ? row.t.trim().toUpperCase() : ''; + if (type) types.push([id, type]); } const emergencyByIcao = Object.fromEntries(statuses); + const typeByIcao = Object.fromEntries(types); return { time: nowSeconds, states, ...(Object.keys(emergencyByIcao).length ? { emergencyByIcao } : {}), + // The ICAO type designator (readsb `t`), so the aircraft is classed from + // its first fix instead of after a lookup. + ...(types.length ? { typeByIcao } : {}), }; } diff --git a/src/data/adsbLolFallback.test.mjs b/src/data/adsbLolFallback.test.mjs index a99d273de9..eb35ec1cd0 100644 --- a/src/data/adsbLolFallback.test.mjs +++ b/src/data/adsbLolFallback.test.mjs @@ -61,3 +61,22 @@ test('an aircraft with no track takes its true heading, never its magnetic one', assert.equal(at({ mag_heading: 278.44 }), null, 'not magnetic'); assert.equal(at({}), null, 'none'); }); + +test('the point response sends each admitted aircraft type alongside the vectors', () => { + const response = normalizeAdsbLolPointResponse({ + now: 1000, + ac: [ + { hex: 'A1B2C3', lat: 30, lon: -97, t: 'ec45' }, + { hex: 'A1B2C3', lat: 31, lon: -97, t: 'B738' }, + { hex: 'D4E5F6', lat: 30, lon: -98 }, + { hex: 'BAD000', t: 'A320' }, + ], + }); + assert.equal(response.states.length, 3); + assert.deepEqual(response.typeByIcao, { a1b2c3: 'EC45' }); + const untyped = normalizeAdsbLolPointResponse({ + now: 1000, + ac: [{ hex: 'D4E5F6', lat: 30, lon: -98 }], + }); + assert.equal(Object.hasOwn(untyped, 'typeByIcao'), false); +}); diff --git a/src/data/aircraftClass.js b/src/data/aircraftClass.js index 4b719b3ecb..2b1da333ff 100644 --- a/src/data/aircraftClass.js +++ b/src/data/aircraftClass.js @@ -401,6 +401,11 @@ const OPENSKY_CATEGORY = { 7: 'fastjet', // High performance (>5g, >400 kt) 8: 'helicopter', // Rotorcraft 9: 'glider', + 16: 'vehicle', // Surface vehicle, emergency + 17: 'vehicle', // Surface vehicle, service + 18: 'station', // Point obstacle + 19: 'station', // Cluster obstacle + 20: 'station', // Line obstacle }; /** ADS-B emitter-category string → class. */ @@ -413,13 +418,35 @@ const EMITTER_CATEGORY = { A6: 'fastjet', A7: 'helicopter', B1: 'glider', + C1: 'vehicle', // Surface vehicle, emergency + C2: 'vehicle', // Surface vehicle, service + C3: 'station', // Point obstacle + C4: 'station', // Cluster obstacle + C5: 'station', // Line obstacle }; +/** + * The type codes feeds give what is not an aircraft: an airport vehicle + * (ZVEH) and a ground station (GRND). + */ +const GROUND_TYPE_CLASS = { ZVEH: 'vehicle', GRND: 'station' }; + +/** + * The class an aircraft draws and reads as, from its ICAO type code (which + * outranks the category), else its OpenSky integer or ADS-B emitter category. + * Besides the aircraft classes, `vehicle` is an airport vehicle (type ZVEH, + * emitter C1 or C2) and `station` a ground station or obstacle (type GRND, + * emitter C3 to C5). A known type code outside every set is an airliner, and + * so is a contact with nothing to go on. + * @param {{typeCode?: string|null, category?: string|number|null}} [record] + * @returns {string} + */ export function classifyAircraft({ typeCode, category } = {}) { const code = String(typeCode || '') .trim() .toUpperCase(); if (code) { + if (GROUND_TYPE_CLASS[code]) return GROUND_TYPE_CLASS[code]; if (FASTJET.has(code)) return 'fastjet'; if (UAV.has(code)) return 'uav'; if (HELI.has(code)) return 'helicopter'; @@ -452,18 +479,13 @@ export const AIRCRAFT_CLASS_LABELS = Object.freeze({ fastjet: msg('Fast jet'), bizjet: msg('Business jet'), uav: msg('Drone'), + vehicle: msg('Airport vehicle'), + station: msg('Ground station / obstacle'), }); -/** Billboard scale multipliers (skylight GLYPH_SCALE, + fastjet). */ -export const CLASS_SCALE_2D = { - light: 0.62, - glider: 0.58, - turboprop: 0.86, - airliner: 1.0, - widebody: 1.3, - quadjet: 1.45, - helicopter: 0.82, - fastjet: 0.8, - bizjet: 0.72, - uav: 0.75, -}; +/** + * The tint an airport vehicle's sprite draws with in Flights and Local + * ADS-B: an orange amber, apart from aircraft white and the military layer's + * yellow amber (#FFB800). + */ +export const VEHICLE_TINT_CSS = '#FF8F1F'; diff --git a/src/data/aircraftClass.test.mjs b/src/data/aircraftClass.test.mjs index 84b7394c28..13ba2242f1 100644 --- a/src/data/aircraftClass.test.mjs +++ b/src/data/aircraftClass.test.mjs @@ -1,7 +1,7 @@ // src/data/aircraftClass.test.mjs import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { classifyAircraft, CLASS_SCALE_2D } from './aircraftClass.js'; +import { AIRCRAFT_CLASS_LABELS, classifyAircraft } from './aircraftClass.js'; test('type-code classification (military layer path)', () => { assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet'); @@ -48,8 +48,53 @@ test('typeCode outranks category; unknown → airliner', () => { assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner'); }); -test('the icon scale table covers every class', () => { - for (const kind of ['light','glider','turboprop','airliner','widebody','quadjet','helicopter','fastjet','bizjet','uav']) { - assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind); +test('every class has a label', () => { + for (const kind of [ + 'light', + 'glider', + 'turboprop', + 'airliner', + 'widebody', + 'quadjet', + 'helicopter', + 'fastjet', + 'bizjet', + 'uav', + 'vehicle', + 'station', + ]) { + assert.ok(AIRCRAFT_CLASS_LABELS[kind], kind); } }); + +test('airport vehicles and ground stations class apart from aircraft', () => { + // A feed's own types, in any case. + assert.equal(classifyAircraft({ typeCode: 'ZVEH' }), 'vehicle'); + assert.equal(classifyAircraft({ typeCode: ' zveh ' }), 'vehicle'); + assert.equal(classifyAircraft({ typeCode: 'GRND' }), 'station'); + // Emitter categories: surface vehicles, then obstacles. + assert.equal(classifyAircraft({ category: 'C1' }), 'vehicle'); + assert.equal(classifyAircraft({ category: 'C2' }), 'vehicle'); + for (const category of ['C3', 'C4', 'C5']) + assert.equal(classifyAircraft({ category }), 'station', category); + // OpenSky's integer categories for the same. + assert.equal(classifyAircraft({ category: 16 }), 'vehicle'); + assert.equal(classifyAircraft({ category: 17 }), 'vehicle'); + assert.equal(classifyAircraft({ category: 18 }), 'station'); + // A type code still outranks the category. + assert.equal( + classifyAircraft({ typeCode: 'ZVEH', category: 'A3' }), + 'vehicle', + ); + assert.equal( + classifyAircraft({ typeCode: 'A320', category: 'C1' }), + 'airliner', + ); +}); + +test('helicopter types and categories', () => { + for (const typeCode of ['EC35', 'R44', 'S76', 'H60', 'AS50', 'B407']) + assert.equal(classifyAircraft({ typeCode }), 'helicopter', typeCode); + assert.equal(classifyAircraft({ category: 'A7' }), 'helicopter'); + assert.equal(classifyAircraft({ category: 8 }), 'helicopter'); +}); diff --git a/src/data/aircraftEmergencyAnalyst.test.mjs b/src/data/aircraftEmergencyAnalyst.test.mjs index 8b846222e1..1ff3d33580 100644 --- a/src/data/aircraftEmergencyAnalyst.test.mjs +++ b/src/data/aircraftEmergencyAnalyst.test.mjs @@ -1,5 +1,3 @@ -import { TRACKED_ICON_COLOR } from '../layers/military/policy.js'; -import { TRACKED_CYAN } from '../layers/flights/policy.js'; import { createRendering as civilRendering } from '../layers/flights/rendering.js'; import { createRendering as militaryRendering } from '../layers/military/rendering.js'; import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js'; @@ -463,15 +461,16 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do assert.equal(rendering._modelColor('civil'), red); if (rendering._cockpitContactColor) assert.equal(rendering._cockpitContactColor('civil'), red); + // Tracking never recolours: a tracked emergency stays red. flightState._trackedIcao = 'civil'; - assert.equal( - rendering._modelColor('civil'), - factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR, - ); + assert.equal(rendering._modelColor('civil'), red); flightState._trackedIcao = null; flightState.records.data.set('civil', { emergency: null }); // An ordinary model draws its mesh's own colours, whatever the billboard's. assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]); + flightState._trackedIcao = 'civil'; + assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]); + flightState._trackedIcao = null; } }); diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js index 9abf527514..cb98c7a47e 100644 --- a/src/data/aircraftIconLayer.js +++ b/src/data/aircraftIconLayer.js @@ -32,6 +32,7 @@ import { TRACKED_ICON_PX, } from './aircraftIcons.js'; import { cockpitContactDotImage } from './cockpitContactDot.js'; +import { rotorFrame, rotorTurns } from './rotorFrames.js'; import { aircraftRecedeSpec } from './aircraftRecession.js'; import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js'; @@ -456,6 +457,14 @@ export function createAircraftIcons({ const { focusPassIsNeeded } = services.focus; // The near-image switch the rows were last written with (CSS px). let switchPx = nearImageSwitchPx(1); + /** + * Airborne helicopters drawn as their glyph, whose rotor turns: the rotor + * frame each was last drawn at, and the frame it was last judged at + * (`_turnRotors`), so one out of view is judged again only once its frame + * has stepped on. + * @type {Map} + */ + const rotors = new Map(); /** The delayed instant (epoch ms) every untracked contact is drawn at. */ const _displayMs = () => @@ -473,6 +482,9 @@ export function createAircraftIcons({ * back before it (`_replanExpired`). */ const planFrom = new Map(); + /** When each placed contact's running ease ends (epoch ms): a new answer + * while it runs eases on from where it is drawn instead of cutting it. */ + const easeEnds = new Map(); /** The display time the rows were last checked against. */ let replannedAt = -Infinity; @@ -543,7 +555,9 @@ export function createAircraftIcons({ state._icons?.dispose(); state._icons = null; liveSet = null; + rotors.clear(); planFrom.clear(); + easeEnds.clear(); replannedAt = -Infinity; } @@ -607,13 +621,19 @@ export function createAircraftIcons({ * Following the clock, a contact not there yet at the time drawn * (`regime.unseen`) is not drawn until its warm-up begins. * @param {string} icao24 - * @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options] + * @param {{fromCourseDeg?: number|null, rewound?: boolean, + * handover?: boolean}} [options] * `fromCourseDeg`: nose to glide from when the row's own motion is not * what was on screen (tracking handoff). `rewound`: the time drawn moved * back before the row's motion; it is drawn where it was then, with no - * easing from where it is drawn now. + * easing from where it is drawn now. `handover`: the clock came back to + * live and this is the contact's first live fix: it eases from where it + * is drawn onto its live path, however its last plan ran out. */ - function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) { + function _planIcon( + icao24, + { fromCourseDeg, rewound = false, handover = false } = {}, + ) { const icons = state._icons; if (!icons?.has(icao24) || holdsPlan(icao24)) return; const history = state._positionHistory.get(icao24); @@ -628,7 +648,7 @@ export function createAircraftIcons({ // A host-supplied placement decides where a live contact is drawn; with // none, or no answer for this contact, the layer's own motion below does. - if (_planPlaced(icao24, info, history, t)) return; + if (_planPlaced(icao24, info, history, t, handover)) return; const regime = parts.motion._motionRegime(history, info, renderTime); if (regime.unseen) { @@ -745,7 +765,7 @@ export function createAircraftIcons({ fromCourseDeg == null && !rewound && icons.shown(icao24) && - icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS + (handover || icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS) ) { const prev = icons.item(icao24); const drawn = motionPosition(prev.motion, prev.pos, t); @@ -804,13 +824,21 @@ export function createAircraftIcons({ * @returns {boolean} False when there is no placement, the layer follows * the world clock, or it has no answer for this contact. */ - function _planPlaced(icao24, info, history, t) { + function _planPlaced(icao24, info, history, t, handover = false) { if (!placeAt || followsClock()) return false; const leadMs = displayDelay.currentMs; const from = vec(); const start = placeAt(icao24, t + leadMs, info, history, from); if (!start) return false; const { courseDeg: course } = start; + // Back at live, or while an ease runs, it eases on from where it is drawn. + const easing = easeEnds.get(icao24) > t; + if ( + (handover || easing) && + _easePlaced(icao24, info, history, t, from, start) + ) + return true; + easeEnds.delete(icao24); const t1 = t + PLACED_PLAN_MS; const to = vec(); const end = placeAt(icao24, t1 + leadMs, info, history, to); @@ -835,6 +863,40 @@ export function createAircraftIcons({ return true; } + /** + * Back at live, a placed contact still on screen eases from where it is + * drawn onto where it is placed, as the layer's own motion recovers (and a + * new answer while that ease runs eases on from where it is then): along + * the straight line to where the placement has it when the ease ends, nose + * along that line, unless it is nearer than a recovery or farther than a + * jump would be. + * @returns {boolean} Whether the contact was planned to ease. + */ + function _easePlaced(icao24, info, history, t, placed, start) { + const icons = state._icons; + if (!icons.shown(icao24)) return false; + const prev = icons.item(icao24); + const drawn = motionPosition(prev.motion, prev.pos, t); + const errorM = distance(drawn, placed); + if (!(errorM > RECOVER_MIN_M && errorM < RECOVER_SNAP_M)) return false; + const speed = start.speedMps ?? info?.velocity ?? 0; + const end = t + recoveryMs(errorM, speed); + const target = vec(); + if (!placeAt(icao24, end + displayDelay.currentMs, info, history, target)) + return false; + const motion = straightSegment(drawn, t, end, target); + const course = motionCourse(motion, undefined, t); + icons.setUnseen(icao24, false); + icons.update( + icao24, + { pos: clone(drawn), course, motion, courseGlide: undefined }, + { expiresAt: end }, + ); + planFrom.set(icao24, t); + easeEnds.set(icao24, end); + return true; + } + /** * Re-plan every row whose regime ended by `t` (epoch ms), and, following * the clock, every row whose motion starts after `t` once the time drawn @@ -906,26 +968,94 @@ export function createAircraftIcons({ * @returns {{image: string, imageLod: {near: string, switchPx: number}, * size: [number, number], scale: number, scaleByDistance: object}} */ - function _fleetLook(icao24, info = state.records.data.get(icao24)) { + function _fleetLook( + icao24, + info = state.records.data.get(icao24), + frame = _rotorFrameOf(icao24, info, Date.now()), + ) { const rendering = parts.rendering; return { image: aircraftIcon( rendering._iconKind(icao24, info?.klass), FLEET_ICON_PX, + frame, ), imageLod: { near: aircraftIcon( rendering._iconKind(icao24, info?.klass), TRACKED_ICON_PX, + frame, ), switchPx, }, size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX], - scale: rendering._fleetBillboardScale(icao24, info?.klass), + scale: rendering._fleetBillboardScale(icao24), scaleByDistance: NORMAL_SCALE_BY_DISTANCE, }; } + /** + * The rotor frame a contact draws at `nowMs` (`rotorFrames.js`): a + * helicopter's, which holds still on the ground unless it taxis; undefined + * for every other kind. + */ + function _rotorFrameOf(icao24, info, nowMs) { + if (parts.rendering._iconKind(icao24, info?.klass) !== 'helicopter') + return undefined; + return rotorFrame(icao24, nowMs, _rotorState(info)); + } + + /** What turns a contact's rotor: whether it is grounded, and its speed (m/s). */ + function _rotorState(info) { + const speed = info?.velocity ?? info?.speedMps; + return { + onGround: info?.onGround === true, + speedMps: Number.isFinite(speed) ? speed : null, + }; + } + + /** + * Turn the rotors of the airborne helicopters in view: each one's images + * are written again only when its rotor frame changed (`ROTOR_FPS`, run + * from the fleet pass). One out of view, below the horizon, or hidden for + * its 3D model keeps its frame. The tracked one is drawn by the tracked + * icon, which is given its new images. With no airborne helicopter drawn + * this does nothing. + * @param {number} nowMs Epoch ms the frame is chosen at. + * @param {number} t The display instant, epoch ms (where icons are drawn). + * @param {((position: {x: number, y: number, z: number}) => boolean)|null} + * [inView] Whether a position is in the camera's view; none: all are. + */ + function _turnRotors(nowMs, t, inView = null) { + const icons = state._icons; + if (!rotors.size || !icons) return; + let occluder; + for (const [id, rotor] of rotors) { + const frame = rotorFrame(id, nowMs); + // Drawn at this frame, or already judged at it: nothing to do. + if (frame === rotor.drawn || frame === rotor.checked) continue; + rotor.checked = frame; + const tracked = id === state._trackedIcao; + if (!icons.has(id) || (!tracked && !icons.shown(id))) continue; + const position = icons.position(id, t); + if (!position) continue; + if (occluder === undefined) occluder = _occluder(); + if (!_aboveHorizon(position, occluder)) continue; + if (inView && !inView(position)) continue; + rotor.drawn = frame; + if (tracked) { + parts.tracking?._syncTrackedBillboardImage?.(); + continue; + } + const { image, imageLod } = _fleetLook( + id, + state.records.data.get(id), + frame, + ); + icons.update(id, { image, imageLod }); + } + } + /** Image, size, scale, tint and freshness for one row under the current * normal/cockpit contract. Motion and course stay with `_planIcon`. */ function _applyIconPresentation(icao24) { @@ -953,8 +1083,27 @@ export function createAircraftIcons({ color: rgba(rendering._fleetBillboardColor(icao24, info)), rotationMode: 'course', }; + // A ground station's mast stands upright. + if (!cockpitDot && info?.klass === 'station') { + look.rotationMode = 'screen'; + look.rotation = 0; + } look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1; icons.update(icao24, look); + // An airborne helicopter drawn as its glyph turns its rotor. + const frame = cockpitDot + ? undefined + : _rotorFrameOf(icao24, info, Date.now()); + if (frame === undefined || !rotorTurns(_rotorState(info))) { + // A tracked helicopter that lands shows the still frame at once. + if (rotors.delete(icao24) && tracked) + parts.tracking?._syncTrackedBillboardImage?.(); + } else rotors.set(icao24, { drawn: frame, checked: frame }); + } + + /** Whether any airborne helicopter's rotor turns (`_turnRotors` has work). */ + function _rotorsTurning() { + return rotors.size > 0; } /** Add a row for a new contact, hidden while it is the tracked one. */ @@ -990,7 +1139,9 @@ export function createAircraftIcons({ /** Drop a contact and everything the layer keeps for it. */ function _forgetContact(icao24) { state._icons?.remove(icao24); + rotors.delete(icao24); planFrom.delete(icao24); + easeEnds.delete(icao24); parts.rendering._releaseModel(icao24); state.records.forget(icao24); // The host-supplied placement, if any, forgets it as well. @@ -1025,6 +1176,8 @@ export function createAircraftIcons({ _focusIcons, _applyIconPresentation, _fleetLook, + _turnRotors, + _rotorsTurning, _addIcon, _forgetContact, _iconIds, diff --git a/src/data/aircraftIconLayer.test.mjs b/src/data/aircraftIconLayer.test.mjs index 73411d7f64..2a09556e5b 100644 --- a/src/data/aircraftIconLayer.test.mjs +++ b/src/data/aircraftIconLayer.test.mjs @@ -6,10 +6,12 @@ import { createContactIcons, floorCoastArc, } from './aircraftIconLayer.js'; -import { COAST_FLOOR_LIFT_M } from './motionModel.js'; +import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js'; import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { createDisplayDelay } from './displayDelay.js'; +import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js'; +import { ROTOR_STILL_FRAME } from './rotorFrames.js'; const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0); @@ -199,3 +201,283 @@ test('a coast over known ground that never rises is planned once', () => { 'held on the ground where the coast stopped', ); }); + +test('only airborne helicopters in view turn their rotor, written when the frame steps', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS }); + const here = fromDegrees(0, 30, 300); + const away = fromDegrees(90, 30, 300); + const records = new Map([ + ['h1', { klass: 'helicopter', onGround: false }], + ['h2', { klass: 'helicopter', onGround: true }], + ['p1', { klass: 'airliner', onGround: false }], + ['h3', { klass: 'helicopter', onGround: false }], + ]); + const state = { + now: () => Date.now(), + _icons: createContactIcons(), + _positionHistory: new Map(), + _cockpitNearContacts: new Set(), + records: { data: records, missingPolls: new Map() }, + }; + const icons = createAircraftIcons({ + state, + services: { focus: { focusPassIsNeeded: () => false } }, + parts: { + rendering: { + _iconKind: (_id, klass) => klass, + _fleetBillboardColor: () => [1, 1, 1, 1], + _fleetBillboardScale: () => 1, + }, + }, + layerId: 'flights', + courseMaxDps: 3, + cockpitContactSizePx: 8, + }); + for (const id of records.keys()) { + state._icons.put( + { + id, + pos: id === 'h3' ? away : here, + motion: { kind: 'hold', courseDeg: 0 }, + size: [20, 20], + }, + { expiresAt: Infinity }, + ); + icons._applyIconPresentation(id); + } + const image = (id) => state._icons.item(id).image; + // The grounded helicopter holds the still frame. + assert.equal( + image('h2'), + aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME), + ); + const h3Before = image('h3'); + const writes = new Map(); + const update = state._icons.update; + state._icons.update = (id, patch, options) => { + writes.set(id, (writes.get(id) ?? 0) + 1); + return update(id, patch, options); + }; + // The fleet pass, every 80 ms for a second; h3 is out of view. + const inView = (p) => Math.abs(p.x - here.x) < 1; + const seen = new Set(); + for (let step = 0; step <= 12; step++) { + if (step) t.mock.timers.tick(80); + icons._turnRotors(Date.now(), Date.now(), inView); + seen.add(image('h1')); + } + // Through every frame, written only on the steps its frame changed. + assert.equal(seen.size, 3); + for (const frame of [0, 1, 2]) + assert.ok(seen.has(aircraftIcon('helicopter', FLEET_ICON_PX, frame))); + assert.ok( + writes.get('h1') >= 8 && writes.get('h1') <= 11, + `${writes.get('h1')} writes`, + ); + assert.equal(writes.get('h2') ?? 0, 0, 'grounded: frozen'); + assert.equal(writes.get('p1') ?? 0, 0, 'not a helicopter'); + assert.equal(writes.get('h3') ?? 0, 0, 'out of view'); + assert.equal(image('h3'), h3Before); + // Landing freezes it on the still frame. + records.get('h1').onGround = true; + icons._applyIconPresentation('h1'); + const landed = writes.get('h1'); + t.mock.timers.tick(400); + icons._turnRotors(Date.now(), Date.now(), inView); + assert.equal(writes.get('h1'), landed); + assert.equal( + image('h1'), + aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME), + ); +}); + +/** An icon layer over helicopters `ids`, all at `here`, for the rotor tests. */ +function rotorFixture(records, positions, tracking = {}) { + const state = { + now: () => Date.now(), + _icons: createContactIcons(), + _positionHistory: new Map(), + _cockpitNearContacts: new Set(), + records: { data: records, missingPolls: new Map() }, + }; + const icons = createAircraftIcons({ + state, + services: { focus: { focusPassIsNeeded: () => false } }, + parts: { + rendering: { + _iconKind: (_id, klass) => klass, + _fleetBillboardColor: () => [1, 1, 1, 1], + _fleetBillboardScale: () => 1, + }, + tracking, + }, + layerId: 'flights', + courseMaxDps: 3, + cockpitContactSizePx: 8, + }); + for (const id of records.keys()) { + state._icons.put( + { + id, + pos: positions[id], + motion: { kind: 'hold', courseDeg: 0 }, + size: [20, 20], + }, + { expiresAt: Infinity }, + ); + icons._applyIconPresentation(id); + } + return { state, icons }; +} + +test('a tracked helicopter that lands shows the still frame at once', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS }); + const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]); + let synced = 0; + const { state, icons } = rotorFixture( + records, + { h1: fromDegrees(0, 30, 300) }, + { _syncTrackedBillboardImage: () => synced++ }, + ); + state._trackedIcao = 'h1'; + assert.equal(icons._rotorsTurning(), true); + records.get('h1').onGround = true; + icons._applyIconPresentation('h1'); + assert.equal(synced, 1, 'the tracked billboard is given its images again'); + assert.equal(icons._rotorsTurning(), false); + assert.equal( + icons._fleetLook('h1').image, + aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME), + ); + // Taxiing faster than 1 m/s, its rotor turns again, as the model's does. + records.get('h1').velocity = 5; + icons._applyIconPresentation('h1'); + assert.equal(icons._rotorsTurning(), true); + records.get('h1').velocity = 0; + icons._applyIconPresentation('h1'); + assert.equal(synced, 2); + assert.equal(icons._rotorsTurning(), false); + // An untracked one landing does not touch the tracked billboard. + records.get('h1').onGround = false; + icons._applyIconPresentation('h1'); + state._trackedIcao = null; + records.get('h1').onGround = true; + icons._applyIconPresentation('h1'); + assert.equal(synced, 2); +}); + +test('a helicopter out of view is judged once per rotor frame, not every pass', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS }); + const records = new Map(); + const positions = {}; + for (let i = 0; i < 300; i++) { + const id = `h${i}`; + records.set(id, { klass: 'helicopter', onGround: false }); + positions[id] = fromDegrees(90, 30, 300); + } + const { state, icons } = rotorFixture(records, positions); + let judged = 0; + const inView = () => { + judged++; + return false; + }; + const writes = []; + const update = state._icons.update; + state._icons.update = (id, ...rest) => { + writes.push(id); + return update(id, ...rest); + }; + // Passes 10 ms apart for 2 s: 200 passes over 300 helicopters, all out of + // view. Each is judged at most once per frame step (20 steps), and not on + // a step back onto the frame it is drawn at. + for (let pass = 0; pass < 200; pass++) { + t.mock.timers.tick(10); + icons._turnRotors(Date.now(), Date.now(), inView); + } + assert.ok(judged <= 300 * 21, `${judged} judgements`); + assert.ok(judged >= 300 * 10, `${judged} judgements`); + assert.equal(writes.length, 0, 'none in view: no image written'); +}); + +test('back at live, a placed contact eases from where it is drawn over a recovery, nose along the way', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS }); + const drawnAt = fromDegrees(0, 30, 3_000); + const SPEED = 200; + // The placement has it 2 km east of where it is drawn, flying east. + const placedAt = (wallMs) => { + const east = 2_000 + (SPEED * (wallMs - WORLD_MS)) / 1000; + return fromDegrees(east / (111_320 * Math.cos(Math.PI / 6)), 30, 3_000); + }; + const plan = (handover, keep = {}) => { + const state = { + now: () => Date.now(), + _icons: createContactIcons(), + _positionHistory: new Map([['c', [{ epochMs: WORLD_MS }]]]), + records: { data: new Map([['c', {}]]) }, + }; + const icons = createAircraftIcons({ + state, + services: { focus: { focusPassIsNeeded: () => false } }, + parts: { + motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs }, + }, + layerId: 'flights', + courseMaxDps: 3, + cockpitContactSizePx: 8, + placeAt: (_id, wallMs, _info, _history, out) => { + Object.assign(out, placedAt(wallMs)); + return { courseDeg: 90, speedMps: SPEED }; + }, + }); + state._icons.put( + { + id: 'c', + pos: drawnAt, + motion: { kind: 'hold', courseDeg: 0 }, + course: 0, + size: [20, 20], + }, + { expiresAt: -Infinity }, + ); + icons._planIcon('c', handover ? { handover: true } : undefined); + keep.icons = icons; + return state._icons; + }; + const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); + + const eased = plan(true); + const end = eased.expires('c'); + assert.equal(end, WORLD_MS + recoveryMs(2_000, SPEED)); + assert.ok(end - WORLD_MS > 1_000, 'longer than a placed plan'); + assert.ok(metres(eased.position('c', WORLD_MS, {}), drawnAt) < 1); + assert.ok(metres(eased.position('c', end, {}), placedAt(end)) < 1); + // The nose points along the way from where it is drawn to where it goes. + assert.ok(Math.abs(eased.course('c', WORLD_MS) - 90) < 1); + + const plain = plan(false); + assert.ok( + metres(plain.position('c', WORLD_MS, {}), placedAt(WORLD_MS)) < 1, + 'without the handover it is drawn where it is placed', + ); + + // The next answer comes 15 s in, the ease still running: it eases on from + // where it is drawn then, not cut to where it is placed. + const keep = {}; + const easing = plan(true, keep); + const firstEnd = easing.expires('c'); + assert.ok(firstEnd - WORLD_MS > 15_000, 'an ease longer than a poll'); + t.mock.timers.tick(15_000); + const at = Date.now(); + const drawnThen = easing.position('c', at, {}); + keep.icons._planIcon('c'); + assert.ok(metres(easing.position('c', at, {}), drawnThen) < 1); + const reEnd = easing.expires('c'); + assert.ok(reEnd > at + 1_000, 'eases on'); + assert.ok(metres(easing.position('c', reEnd, {}), placedAt(reEnd)) < 1); + // Once it has caught up, the next answer draws it where it is placed. + t.mock.timers.tick(reEnd - at + 1); + keep.icons._planIcon('c'); + assert.ok( + metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1, + ); +}); diff --git a/src/data/aircraftIcons.js b/src/data/aircraftIcons.js index 9948fa71b8..5a83925835 100644 --- a/src/data/aircraftIcons.js +++ b/src/data/aircraftIcons.js @@ -8,9 +8,9 @@ * width/height 20 (24 tracked) in flights.js / militaryFlights.js, so Cesium * DOWN-samples this larger, higher-precision source to the same on-screen * footprint — crisp anti-aliased edges instead of an upscaled 32px bitmap. The - * on-screen size is unchanged and CLASS_SCALE_2D is untouched (no scale - * compensation needed: the billboard's explicit width/height, not the SVG's, - * sets the pixel size — the intrinsic SVG size only controls raster fidelity). + * on-screen size is unchanged (the billboard's explicit width/height, not the + * SVG's, sets the pixel size — the intrinsic SVG size only controls raster + * fidelity). * * All glyphs are nose-up (nose toward -Y at rotation 0; the screen-projected * rotation pipeline in iconOrientation.js spins the whole glyph). Fill is white @@ -23,12 +23,19 @@ * quadjet/glider use the "bold" chart-symbol redraw; light/fastjet keep the * original drawings. Raster fidelity doubled (192px source, same 96 coords). * + * The helicopter is a top-down body under a four-blade rotor drawn in three + * frames (`aircraftIcon('helicopter', px, frame)`, turned by + * `rotorFrames.js`). Two kinds are not aircraft: `vehicle`, one sprite for + * every airport vehicle, and `station`, a mast for ground stations, drawn + * upright. + * * Silhouette language follows skylight's type-aware glyphs (MIT, * https://github.com/cpaczek/skylight): slender fuselages, swept wings for * jets, long high-aspect wings for the glider, straight wings + prop discs for * props, a rotor disc + tail boom + tail-rotor for the helicopter, and a delta * for the fast jet. Each class has a DISTINCT planform so it reads at ~20px by - * shape, not just by footprint size. + * shape alone: every glyph is fitted to the same extent, so none is bigger + * than another. */ const VIEW = 96; @@ -130,23 +137,6 @@ const BODIES = { L -3,-25 C -3,-29 -2.4,-33 0,-35 Z" fill="white" ${STROKE_BOLD}/> `, - // ── Helicopter: a SOLID translucent main-rotor disc (survives downscale as an - // obvious circle, unlike a thin ring) with a bold two-blade cross, a - // teardrop cabin, a tail boom, and a tail rotor. Unmistakable "disc on top" - // silhouette that never reads as a fixed-wing. - helicopter: ` - - - - - - - - - - `, - // ── Fast jet: sharp delta/cropped-delta with a pointed nose, LERX root // blend, and twin tail fins. Aggressive, all-wing. fastjet: ` @@ -236,6 +226,87 @@ const BODIES = { L -1.6,30 L -13,36 L -13,32 L -2.1,24 L -2.3,0 L -43,-2.5 L -43,-7 L -2.4,-12 L -4.4,-30 C -4.6,-35 -3.6,-40 0,-40 Z" fill="white" ${STROKE}/>`, + + // ── Airport vehicle (type ZVEH, emitter C1/C2): one service van seen from + // above, front up, for every kind (fire truck, tug, car, de-icer). A + // boxy body, a dark windscreen band and a roof light bar; the layer + // tints it amber so it reads apart from aircraft. + vehicle: ` + + + + `, + + // ── Ground station or obstacle (type GRND, emitter C3–C5): a radio mast + // with two pairs of signal arcs, drawn upright on screen, never turned. + station: ` + + + + `, +}; + +/** + * The helicopter, seen from above: a cabin, tail boom and tail plane under a + * four-blade main rotor. The rotor turns in {@link ROTOR_FRAMES} frames 30° + * apart; four blades repeat every 90°, so the third frame steps back onto + * the first and the loop is seamless. The middle frame (blades as an X) is + * the still one. + */ +const HELI_ROTOR_CENTRE_Y = -11.2; +const HELI_DISC = ``; +const HELI_BODY = ` + + `; +/** Main-rotor blade angle of each frame, degrees clockwise. */ +const ROTOR_ANGLES_DEG = [15, 45, 75]; +/** How many rotor frames the helicopter turns through. */ +export const ROTOR_FRAMES = ROTOR_ANGLES_DEG.length; +/** The frame a helicopter holds when its rotor does not turn. */ +export const ROTOR_STILL_FRAME = 1; + +/** One rotor frame: the disc, two crossed blades at `angle`, the body over them. */ +function helicopterBody(frame) { + const angle = ROTOR_ANGLES_DEG[frame] ?? ROTOR_ANGLES_DEG[ROTOR_STILL_FRAME]; + const blade = (deg) => + ``; + return `${HELI_DISC}${blade(angle)}${blade(angle + 90)}${HELI_BODY}`; +} + +/** + * Every sprite draws at one size. The bodies were drawn at different spans + * (a light aircraft's half-extent is 32.8 units, a quadjet's 47), so each is + * scaled until its farthest painted edge, stroke included, sits + * {@link GLYPH_HALF_EXTENT} units from the centre. Values are each body's + * measured half-extent; aircraftIcons.test.mjs re-measures the rasters. + */ +const GLYPH_HALF_EXTENT = 44; +const BODY_HALF_EXTENT = { + airliner: 42.7, + widebody: 45.7, + quadjet: 47.0, + turboprop: 40.7, + light: 32.8, + glider: 46.0, + fastjet: 44.7, + bizjet: 42.7, + uav: 43.7, + helicopter: 44.0, + vehicle: 40.7, + station: 47.1, + tr3b: 40.8, + tr3bHot: 42.3, }; const _iconCache = new Map(); @@ -259,16 +330,32 @@ export const FLEET_ICON_PX = FLEET_RASTER_PX; * it stays crisp at its biggest on-screen sizes. */ const TRACKED_RASTER_PX = 192; -/** Data URI for a class silhouette (lazily built, cached per kind+size). - * Default size serves the fleet; pass `aircraftIcon(kind, TRACKED_ICON_PX)` - * (re-exported below) for the tracked billboard. */ +/** Raster size of the tracked glyph and every glyph's near image. */ export const TRACKED_ICON_PX = TRACKED_RASTER_PX; -export function aircraftIcon(kind, px = FLEET_RASTER_PX) { - const k = BODIES[kind] ? kind : 'airliner'; - const key = `${k}@${px}`; +/** + * Data URI for a class silhouette (lazily built, cached per kind, size and + * frame). The default size serves the fleet; pass + * `aircraftIcon(kind, TRACKED_ICON_PX)` for the near image. + * @param {string} kind A `classifyAircraft()` class, or a TR-3B kind. + * @param {number} [px] Raster size. + * @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1` + * (the still frame by default); other kinds have one image. + * @returns {string} + */ +export function aircraftIcon(kind, px = FLEET_RASTER_PX, frame) { + const heli = kind === 'helicopter'; + const k = heli || BODIES[kind] ? kind : 'airliner'; + const f = heli + ? Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES + ? frame + : ROTOR_STILL_FRAME + : 0; + const key = `${k}@${px}#${f}`; let uri = _iconCache.get(key); if (!uri) { - const svg = `${BODIES[k]}`; + const body = heli ? helicopterBody(f) : BODIES[k]; + const fit = +(GLYPH_HALF_EXTENT / BODY_HALF_EXTENT[k]).toFixed(4); + const svg = `${body}`; uri = 'data:image/svg+xml;base64,' + _b64(svg); _iconCache.set(key, uri); } diff --git a/src/data/aircraftIcons.test.mjs b/src/data/aircraftIcons.test.mjs new file mode 100644 index 0000000000..ca93d98ad0 --- /dev/null +++ b/src/data/aircraftIcons.test.mjs @@ -0,0 +1,57 @@ +// src/data/aircraftIcons.test.mjs +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import sharp from 'sharp'; + +import { aircraftIcon, ROTOR_FRAMES } from './aircraftIcons.js'; + +const KINDS = [ + 'airliner', + 'widebody', + 'quadjet', + 'turboprop', + 'light', + 'glider', + 'fastjet', + 'bizjet', + 'uav', + 'helicopter', + 'vehicle', + 'station', + 'tr3b', + 'tr3bHot', +]; +const PX = 480; + +/** Farthest painted pixel from the centre, in the 96-unit glyph space. */ +async function halfExtent(uri) { + const svg = Buffer.from(uri.split(',')[1], 'base64'); + const { data, info } = await sharp(svg) + .ensureAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); + let half = 0; + const c = info.width / 2; + for (let y = 0; y < info.height; y++) { + for (let x = 0; x < info.width; x++) { + if (data[(y * info.width + x) * 4 + 3] <= 8) continue; + half = Math.max(half, c - x, x + 1 - c, c - y, y + 1 - c); + } + } + return (half * 96) / info.width; +} + +test('every sprite fills the same extent, whatever its class', async () => { + const extents = {}; + for (const kind of KINDS) { + extents[kind] = await halfExtent(aircraftIcon(kind, PX)); + } + for (let frame = 0; frame < ROTOR_FRAMES; frame++) { + extents[`helicopter#${frame}`] = await halfExtent( + aircraftIcon('helicopter', PX, frame), + ); + } + for (const [kind, half] of Object.entries(extents)) { + assert.ok(Math.abs(half - 44) <= 0.6, `${kind}: ${half.toFixed(2)}`); + } +}); diff --git a/src/data/aircraftModelLayer.js b/src/data/aircraftModelLayer.js index b601b3179e..55b36f44b5 100644 --- a/src/data/aircraftModelLayer.js +++ b/src/data/aircraftModelLayer.js @@ -14,7 +14,8 @@ import { showModel, } from './modelRecord.js'; import { modelDrawnScale } from './modelVisualAnchor.js'; -import { fleetModelSet } from './fleetModels.js'; +import { fleetModelSet, fleetPartTable } from './fleetModels.js'; +import { aircraftLayerPartState } from './modelPartDrivers.js'; import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js'; import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; import { @@ -225,10 +226,10 @@ export function createAircraftModels({ return sets ? [sets.fleet.id, sets.tracked.id] : []; } - /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude - * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the - * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in - * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms + /** The FLEET's 3D-model regime: models3d enabled AND the camera below the altitude ceiling, + * above which no contact can be within the model radius. Since 2026-08-22 the toggle DEFAULTS + * ON in `proximity`, which is itself the budget: models only appear within MODEL_ADD_M of the + * camera and only for the nearest MODEL_MAX. The toggle still OWNS the fleet — an operator who wants every in-view plane arms * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED * contact routes through here too (`_trackedModelRegimeActive`), with its place in the * fleet's cap, so selecting a contact never changes its form. */ @@ -254,20 +255,17 @@ export function createAircraftModels({ : mapCap; } - /** Active ADD radius (m) — new planes inside this range get a model. Mode-aware: 'all' reaches far. */ + /** ADD radius (m) — new planes inside this range get a model. Both modes + * share it; they differ by their caps. */ function _modelAddDistM() { - return state._models3dMode === 'all' - ? policy.MODEL_ALL_ADD_M - : policy.MODEL_PROX_ADD_M; + return policy.MODEL_ADD_M; } - /** Active KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */ + /** KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */ function _modelKeepDistM() { - return state._models3dMode === 'all' - ? policy.MODEL_ALL_KEEP_M - : policy.MODEL_PROX_KEEP_M; + return policy.MODEL_KEEP_M; } /** What a grounded model's ground sample sees through: the vertical sample @@ -341,6 +339,54 @@ export function createAircraftModels({ record.tint = [base[0], base[1], base[2], alpha]; } + /** A finite number of the first of `values` that is one, else null. */ + const _finite = (...values) => + values.find((v) => typeof v === 'number' && Number.isFinite(v)) ?? null; + + /** + * How high an aircraft flies above the ground under it: its render + * altitude over the cached ground floor there; null where that floor is + * not known (the gear then follows the approach rule instead). + */ + function _heightAboveGround(meta) { + const altitude = _finite(meta.renderAltitudeM); + const floor = + Number.isFinite(meta.rawLat) && Number.isFinite(meta.rawLon) + ? services.groundFloor?.cachedGroundFloor?.(meta.rawLat, meta.rawLon) + : null; + return altitude !== null && Number.isFinite(floor) + ? altitude - floor + : null; + } + + /** + * The moving parts a contact's model is posed with, from its record + * (`aircraftLayerPartState`): gear, doors and flaps by its height and climb, + * fans, propellers and rotors while it flies or taxis. An airport vehicle + * is a road vehicle (`groundVehiclePartState`): its wheels roll with its + * speed. Undefined for a model without parts. + */ + function _partsOf(meta, spec) { + if (!meta) return undefined; + const table = fleetPartTable(fleetModelSet(), spec?.model); + if (!table) return undefined; + return aircraftLayerPartState(table, { + klass: meta.klass, + onGround: meta.onGround === true, + heightAboveGroundM: _heightAboveGround(meta), + altitudeM: _finite(meta.altitude, meta.altitudeM), + verticalRateMps: _finite(meta.verticalRate, meta.verticalRateMps), + speedMps: _finite(meta.velocity, meta.speedMps), + }); + } + + /** Pose a record's parts as its contact's record says, and key them for `_send`. */ + function _poseParts(record, meta, spec) { + const pose = _partsOf(meta, spec); + record.parts = pose; + record.partsKey = pose ? JSON.stringify(pose) : ''; + } + /** The record's item, as its set draws it. */ function _itemOf(id, record) { return { @@ -354,10 +400,11 @@ export function createAircraftModels({ minPixelSize: record.minPixelSize, shading: _shadingOf(), tint: record.tint ?? WHITE, - // The mesh's own colours, tinted while tracked or in an emergency; + // The mesh's own colours, tinted red in an emergency; // the IR boost draws it flat white. - colorBlend: aircraftModelBlend(state._irBoost === true), + colorBlend: aircraftModelBlend(state._irBoost === true, record.tint), environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + ...(record.parts ? { parts: record.parts } : {}), show: record.show, }; } @@ -367,7 +414,7 @@ export function createAircraftModels({ if (!set) return; const p = record.position; const t = record.tint ?? WHITE; - const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}`; + const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}|${record.partsKey ?? ''}`; if (key === record.sent) return; record.sent = key; const item = _itemOf(id, record); @@ -426,6 +473,7 @@ export function createAircraftModels({ // Placed BEFORE the readiness test on purpose: a model can turn ready // between ticks, and its first drawn frame must be at this placement. placeModel(record, displayPos, _modelHeading(course, meta)); + _poseParts(record, meta, spec); if (!record.ready) { showModel(record, false); // not loaded yet → keep the 2D icon, no half-model flash _send(set, icao24, record, spec, out); @@ -565,12 +613,11 @@ export function createAircraftModels({ state._lastFleetTickMs = 0; } - /** Admit a fleet model for an aircraft; the icon shows until it is ready. */ + /** Admit a fleet model for an aircraft; the icon shows until it is ready. + * The selected aircraft's is admitted too, and kept loaded but hidden + * while its tracked model draws it (`_keepTrackedFleetModel`). */ function _ensureModel(icao24) { - // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet - // tick skips it, so a model here would be orphaned + double-rendered. - if (icao24 === state._trackedIcao) return; onModelEligible(icao24); if (state._models.has(icao24)) return; // Without model sets (the renderer draws none) the icon stays. @@ -585,7 +632,6 @@ export function createAircraftModels({ specKey: _specKeyFor(meta), // type-change sync compares against this bellyM: spec.bellyM, scale: spec.scale, - minPixelSize: policy.MODEL_MIN_PX, }); record.url = resolveAsset(spec.url); record.gltf = _gltfOf(spec); @@ -676,24 +722,115 @@ export function createAircraftModels({ ); } - /** A fleet model still drawing the tracked contact (it was a model when - * it was selected) lets go once the tracked model draws, or once the - * contact is no longer drawn as a model at all. */ + /** The tracked contact's fleet model lets go once the contact is no + * longer drawn as a model at all (out of range, 3D off, cockpit). */ function _releaseTrackedFleetModel() { if (state._trackedIcao && state._models.has(state._trackedIcao)) _releaseModel(state._trackedIcao); } + /** The tracked contact's fleet model (it was a model when it was + * selected, or was admitted since) stops drawing once the tracked model + * draws, or while the tracked icon carries the contact, but stays loaded: + * deselecting hands the contact straight back to it + * (`_handBackDeselected`), with no load and no icon in between. */ + function _hideTrackedFleetModel() { + const icao24 = state._trackedIcao; + const record = icao24 ? state._models.get(icao24) : null; + if (!record?.show) return; + showModel(record, false); + _send(state._modelSets?.fleet, icao24, record, _modelSpec(_metaOf(icao24))); + } + + /** Keep the tracked contact's fleet model loaded and placed where its icon + * is, one fleet tick at a time, so it is ready to take the contact back + * the moment it is deselected. It never shows here: it draws the contact + * only while the tracked model loads, as it did before the selection. */ + function _keepTrackedFleetModel(icao24, position, course, out) { + _ensureModel(icao24); + const record = state._models.get(icao24); + if (!record) return; + const meta = _metaOf(icao24); + const set = state._modelSets?.fleet ?? null; + _retryFailedFleetModel(set, icao24, record); + const displayPos = _modelDisplayPosition(icao24, position); + if (displayPos) placeModel(record, displayPos, _modelHeading(course, meta)); + else showModel(record, false); // nowhere safe to draw it + _send(set, icao24, record, _modelSpec(meta), out); + } + + /** + * Hand a contact just deselected back to the fleet in the same frame: to + * its fleet model when one is loaded (kept while it was selected), placed + * where its icon is and shown, else to its icon. Runs once the contact no + * longer reads as tracked. + * @param {string} icao24 + */ + function _handBackDeselected(icao24) { + const icons = state._icons; + const record = state._models.get(icao24); + if (!icons?.has(icao24)) { + if (record) _releaseModel(icao24); + return; + } + if (!record) { + icons.setShown(icao24, true); + return; + } + const pose = _pose(); + if (!pose || !_modelRegimeActive(pose) || isTr3b(icao24)) { + _releaseModel(icao24); // the icon takes it back + return; + } + const t = parts.icons._displayMs(); + const position = icons.position(icao24, t); + _driveFleetModelHandoff( + icao24, + record, + position, + icons.course(icao24, t), + () => + _treatFleetModel( + icao24, + record, + distance(pose.position, position), + pose, + ), + ); + } + + /** A fleet model's tint and alpha this tick: the contact's colour, faded + * as its icon is (focus, recession), or the IR boost's full-strength + * white. */ + function _treatFleetModel(icao24, record, cameraDistanceM, pose) { + const icons = state._icons; + _treat(record, { + // IR boost must survive the per-tick treatment write — otherwise + // any alpha change would repaint the ordinary tint over the hot + // white. Boosted models also skip the recession fade: hot targets + // stay full-strength at any range (icons keep their normal + // fade — full-opacity glyph walls read as overwhelming). + base: state._irBoost ? WHITE : rgba(_modelColor(icao24)), + alpha: state._irBoost + ? 1 + : aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(icao24), + focusFactor: icons.focus(icao24), + cameraDistanceM, + cameraHeightM: pose.height, + }), + }); + } + /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet * cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the * follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). * * The model draws exactly as the fleet would draw this contact: the same - * asset at the same scale and `minPixelSize` (`MODEL_MIN_PX`), only its - * tint the tracked colour; whether it draws at all is the fleet's rule too - * (`_trackedModelRegimeActive`). Selecting a contact changes its colour, - * never its size or form. */ + * asset at the same scale (its true size) in the same colours; whether it + * draws at all is the fleet's rule too (`_trackedModelRegimeActive`). + * Selecting a contact changes neither its colour nor its size or form. */ function _updateTrackedModel() { // A failed load is let go (the icon carries the contact); the budget @@ -717,7 +854,7 @@ export function createAircraftModels({ parts.icons._iconPosition(state._trackedIcao); if (!pos) { _hideTrackedModel(); - _releaseTrackedFleetModel(); + _hideTrackedFleetModel(); return; } const icao24 = state._trackedIcao; @@ -729,14 +866,13 @@ export function createAircraftModels({ // The icon carries it: after the load budget is spent, or until the // fleet model set has loaded. if (!_trackedModelLoadAllowed() || !spec.url) { - _releaseTrackedFleetModel(); + _hideTrackedFleetModel(); return; } const record = createModelRecord({ specKey: _specKeyFor(meta), // type-change sync compares against this bellyM: spec.bellyM, scale: spec.scale, - minPixelSize: policy.MODEL_MIN_PX, }); record.id = icao24; record.url = resolveAsset(spec.url); @@ -758,7 +894,7 @@ export function createAircraftModels({ const displayPos = _modelDisplayPosition(icao24, pos); if (!displayPos) { _hideTrackedModel(); // no ground evidence → the icon carries it - _releaseTrackedFleetModel(); + _hideTrackedFleetModel(); return; } placeModel( @@ -766,9 +902,10 @@ export function createAircraftModels({ displayPos, _modelHeading(parts.motion._trackedDisplayCourse(), meta), ); + _poseParts(record, meta, spec); showModel(record, record.ready); _send(state._modelSets.tracked, icao24, record, spec); - if (record.ready) _releaseTrackedFleetModel(); + if (record.ready) _hideTrackedFleetModel(); } /** @@ -841,6 +978,13 @@ export function createAircraftModels({ afterReplan(renderTime, t, nowMs, pose?.position ?? null); const focusTarget = getFocusTarget(); parts.icons._focusIcons(t, nowMs, focusTarget); + // Airborne helicopters in view step their rotor frame (none: no work). + if (parts.icons._rotorsTurning?.()) + parts.icons._turnRotors( + Date.now(), + t, + pose ? (position) => inView(pose, position) : null, + ); // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. @@ -920,8 +1064,6 @@ export function createAircraftModels({ const items = pendingItems; for (const icao24 of modelEligible) { if (isTr3b(icao24)) continue; - // The tracked contact's model is `_updateTrackedModel`'s. - if (icao24 === state._trackedIcao) continue; if (!icons.has(icao24)) continue; const position = icons.position(icao24, t); if ( @@ -944,6 +1086,17 @@ export function createAircraftModels({ } continue; } + // The tracked contact draws as `_updateTrackedModel` says; its fleet + // model is only kept ready for when it is deselected. + if (icao24 === state._trackedIcao) { + _keepTrackedFleetModel( + icao24, + position, + icons.course(icao24, t), + items, + ); + continue; + } _ensureModel(icao24); const record = state._models.get(icao24); const cameraDistanceM = distance(camPos, position); @@ -952,24 +1105,7 @@ export function createAircraftModels({ record, position, icons.course(icao24, t), - () => { - _treat(record, { - // IR boost must survive the per-tick treatment write — otherwise - // any alpha change would repaint the ordinary tint over the hot - // white. Boosted models also skip the recession fade: hot targets - // stay full-strength at any range (icons keep their normal - // fade — full-opacity glyph walls read as overwhelming). - base: state._irBoost ? WHITE : rgba(_modelColor(icao24)), - alpha: state._irBoost - ? 1 - : aircraftTreatmentAlpha({ - baseAlpha: icons.alpha(icao24), - focusFactor: icons.focus(icao24), - cameraDistanceM, - cameraHeightM: pose.height, - }), - }); - }, + () => _treatFleetModel(icao24, record, cameraDistanceM, pose), items, ); } @@ -997,6 +1133,7 @@ export function createAircraftModels({ _releaseModels, _showReleasedIcon, _releaseTrackedModel, + _handBackDeselected, _updateTrackedModel, _fleetTick, }; diff --git a/src/data/aircraftModelLayer.test.mjs b/src/data/aircraftModelLayer.test.mjs index 5db4baa4ce..ed00379d05 100644 --- a/src/data/aircraftModelLayer.test.mjs +++ b/src/data/aircraftModelLayer.test.mjs @@ -4,25 +4,18 @@ import { createAircraftModels } from './aircraftModelLayer.js'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { bindRenderer } from '../render/rendererOf.js'; import { fromDegrees } from '../geo/ellipsoid.js'; +import * as flightsPolicy from '../layers/flights/policy.js'; +// The flights layer's own model policy: its radii, ceiling and caps. const POLICY = { - MODEL_ALT_CEIL_M: 800_000, + ...flightsPolicy, MODEL_MAX: 40, - MODEL_MAX_ALL: 350, - COCKPIT_MODEL_MAX: 60, - MODEL_PROX_ADD_M: 150_000, - MODEL_PROX_KEEP_M: 185_000, - MODEL_ALL_ADD_M: 400_000, - MODEL_ALL_KEEP_M: 450_000, - MODEL_MIN_PX: 24, - TRACKED_MODEL_MIN_PX: 48, - TRACKED_MODEL_MAX_PX: 600, MODEL_HEADING_OFFSET_DEG: 0, - FLEET_DR_INTERVAL_MS: 80, - TRACKED_MODEL_MAX_LOAD_FAILS: 3, - TRACKED_MODEL_RETRY_BACKOFF_MS: 1500, }; +/** The eye's height (m): 1 km above the contacts. */ +const EYE_M = 11_000; + const SPEC = { url: 'plane.glb', scale: 1, @@ -34,9 +27,9 @@ const SPEC = { /** * A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a * models layer over a fake draw port whose fleet set can be told to fail a - * write. The eye sits above them at 30 km. + * write. The eye sits at `eyeM`, by default 1 km above them (`EYE_M`). */ -function fleetFixture(positions) { +function fleetFixture(positions, { eyeM = EYE_M } = {}) { const base = fakeDrawPort(); const removes = []; let failNextUpsert = false; @@ -67,7 +60,7 @@ function fleetFixture(positions) { }; }, }; - const eye = fromDegrees(-97.71, 30.21, 30_000); + const eye = fromDegrees(-97.71, 30.21, eyeM); const viewer = {}; bindRenderer(viewer, { draw, @@ -79,7 +72,7 @@ function fleetFixture(positions) { right: { x: 1, y: 0, z: 0 }, fovy: Math.PI / 3, aspectRatio: 1, - height: 30_000, + height: eyeM, }), }, }); @@ -185,7 +178,10 @@ function fleetFixture(positions) { }; } -const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000); +// About 0.5 km apart, within 2 km of the eye. +const near = (k) => fromDegrees(-97.71 + k * 0.005, 30.21, 10_000); +/** A contact at the eye's height, `m` metres north of it. */ +const north = (m) => fromDegrees(-97.71, 30.21 + m / 110_850, EYE_M); const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000); test('the fleet tick hands contacts to ready models and back without a gap', () => { @@ -326,7 +322,7 @@ test('fleet model alpha is worked out once a fleet tick from the camera then, as const position = near(1); const f = fleetFixture(new Map([['a1', position]])); assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede'); - const eye = fromDegrees(-97.71, 30.21, 30_000); + const eye = fromDegrees(-97.71, 30.21, EYE_M); const expected = (focusFactor) => aircraftTreatmentAlpha({ baseAlpha: 0.8, @@ -336,7 +332,7 @@ test('fleet model alpha is worked out once a fleet tick from the camera then, as eye.y - position.y, eye.z - position.z, ), - cameraHeightM: 30_000, + cameraHeightM: EYE_M, }); try { // Recede from the eye on, so the haze is not 1 here. @@ -389,3 +385,94 @@ test('a contact not there yet at the time drawn has its fleet model hidden, as o f.tick(); assert.equal(f.fleet().items.get('a1').show, true, 'drawn again'); }); + +test('aircraft draw as models only within 3 km of the camera, in either mode', () => { + for (const mode of ['proximity', 'all']) { + const positions = new Map([ + ['inside', north(2_900)], + ['outside', north(3_100)], + ]); + const f = fleetFixture(positions); + f.state._models3dMode = mode; + f.tick(); + for (const id of positions.keys()) + if (f.fleet().items.has(id)) f.draw.ready(f.fleetId, id); + f.tick(); + assert.equal(f.shown.get('inside'), false, `${mode}: a model at 2.9 km`); + assert.equal(f.fleet().items.get('inside').show, true); + assert.equal(f.shown.get('outside'), true, `${mode}: an icon at 3.1 km`); + assert.equal(f.fleet().items.has('outside'), false); + } +}); + +test('a model is kept out to about 3.6 km, then its icon takes over', () => { + const positions = new Map([['a1', north(2_000)]]); + const f = fleetFixture(positions); + f.tick(); + f.draw.ready(f.fleetId, 'a1'); + f.tick(); + assert.equal(f.shown.get('a1'), false, 'a model at 2 km'); + positions.set('a1', north(3_500)); + f.tick(); + assert.equal(f.shown.get('a1'), false, 'kept at 3.5 km'); + assert.equal(f.fleet().items.get('a1').show, true); + positions.set('a1', north(3_700)); + f.tick(); + assert.equal(f.shown.get('a1'), true, 'released at 3.7 km'); + assert.equal(f.fleet().items.has('a1'), false); + positions.set('a1', north(3_300)); + f.tick(); + assert.equal( + f.fleet().items.has('a1'), + false, + 'not taken again until it is back within 3 km', + ); +}); + +test('a camera high above the ground still models an aircraft within 3 km of it', () => { + // A plane at 30 km with the camera 2 km above it: the altitude ceiling + // sits above every contact's height plus the keep radius. + const plane = fromDegrees(-97.71, 30.21, 30_000); + const f = fleetFixture(new Map([['high', plane]]), { eyeM: 32_000 }); + f.tick(); + f.draw.ready(f.fleetId, 'high'); + f.tick(); + assert.equal(f.shown.get('high'), false, 'its model draws it'); + assert.equal( + POLICY.MODEL_ALT_CEIL_M, + POLICY.MODEL_HIGHEST_CONTACT_M + POLICY.MODEL_KEEP_M, + ); +}); + +test('models are drawn at their true size, with no minimum pixel size', () => { + const f = fleetFixture(new Map([['a1', near(1)]])); + f.tick(); + assert.equal(f.fleet().items.get('a1').minPixelSize ?? 0, 0); +}); + +test('the selected contact keeps a loaded, hidden fleet model that takes it back on deselect', () => { + const positions = new Map([['a1', near(1)]]); + const f = fleetFixture(positions); + // Selected while an icon: the fleet pass admits its model all the same. + f.state._trackedIcao = 'a1'; + f.shown.set('a1', false); // selecting it hides its icon + f.tick(); + assert.ok(f.fleet().items.has('a1'), 'admitted and loading while selected'); + f.draw.ready(f.fleetId, 'a1'); + positions.set('a1', near(2)); + f.tick(); + const item = f.fleet().items.get('a1'); + assert.equal(item.show, false, 'never drawn while selected'); + assert.deepEqual( + item.pos, + { x: near(2).x, y: near(2).y, z: near(2).z }, + 'placed where its icon is', + ); + assert.equal(f.shown.get('a1'), false, 'the icon stays hidden'); + + // Deselected: its model draws it in the same frame, its icon never shows. + f.state._trackedIcao = null; + f.models._handBackDeselected('a1'); + assert.equal(f.fleet().items.get('a1').show, true); + assert.equal(f.shown.get('a1'), false); +}); diff --git a/src/data/aircraftModelLighting.js b/src/data/aircraftModelLighting.js index 64d64aebeb..495043761b 100644 --- a/src/data/aircraftModelLighting.js +++ b/src/data/aircraftModelLighting.js @@ -17,15 +17,29 @@ export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({ const HIGHLIGHT = Object.freeze({ mode: 'highlight' }); const FLAT = Object.freeze({ mode: 'mix', amount: 1 }); +/** + * How much of an emergency colour a model takes over its paint. Multiplying + * by a saturated tint zeroes every channel the tint lacks: a cyan tint (no + * red) draws a red helicopter black and a white Cessna flat cyan. Mixed in at + * this share, the paint stays readable and the colour still marks the model. + */ +export const AIRCRAFT_MODEL_TINT_MIX = 0.3; + +const TINTED = Object.freeze({ mode: 'mix', amount: AIRCRAFT_MODEL_TINT_MIX }); + /** * How an aircraft model's colour meets its mesh, as a draw item's - * `colorBlend`. `highlight` multiplies, so white draws the mesh's own - * colours as built, and the tracked or emergency colour tints the mesh - * without hiding its paint. The IR boost draws the model flat white instead - * (`mix` at 1, unlit). + * `colorBlend`. White (no tint) multiplies (`highlight`), which draws the + * mesh's own colours as built. An emergency colour is mixed in at + * `AIRCRAFT_MODEL_TINT_MIX`, so it tints the mesh without hiding its paint. + * The IR boost draws the model flat white instead (`mix` at 1, unlit). * @param {boolean} irBoost + * @param {ArrayLike|null} [tint] The model's RGBA tint, 0..1; white + * or none draws the mesh's own colours. * @returns {{mode: 'highlight'|'mix', amount?: number}} */ -export function aircraftModelBlend(irBoost) { - return irBoost ? FLAT : HIGHLIGHT; +export function aircraftModelBlend(irBoost, tint = null) { + if (irBoost) return FLAT; + const white = !tint || (tint[0] >= 1 && tint[1] >= 1 && tint[2] >= 1); + return white ? HIGHLIGHT : TINTED; } diff --git a/src/data/aircraftModelLighting.test.mjs b/src/data/aircraftModelLighting.test.mjs index b20d3c6497..f171fc9ce4 100644 --- a/src/data/aircraftModelLighting.test.mjs +++ b/src/data/aircraftModelLighting.test.mjs @@ -2,7 +2,12 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { readLayerSource } from '../testSupport/readLayerSource.mjs'; -import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; +import { + AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, + aircraftModelBlend, +} from './aircraftModelLighting.js'; +import * as flightsPolicy from '../layers/flights/policy.js'; +import * as militaryPolicy from '../layers/military/policy.js'; /** * Every aircraft model drawn in the scene skips the renderer's dynamic @@ -48,3 +53,63 @@ test('localAdsb: its draw-port models skip the dynamic environment map', () => { /\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/, ); }); + +/** + * The colour a model draws in, as the renderer blends its tint over the + * shaded paint (`ModelItem.colorBlend`, Cesium's model colour stage): `mix` + * moves the paint toward the tint by `amount`; `highlight` multiplies. + */ +function blended(paint, tint, blend) { + if (blend.mode === 'mix') + return paint.map((c, i) => c + (tint[i] - c) * blend.amount); + if (blend.mode === 'highlight') return paint.map((c, i) => c * tint[i]); + return tint.slice(0, 3); +} + +/** Paints the fleet models carry: a red helicopter, a white airliner, a dark blue tail. */ +const PAINTS = { + red: [0.8, 0.05, 0.05], + white: [0.9, 0.9, 0.9], + blue: [0.05, 0.1, 0.5], +}; + +test('an untinted model draws its mesh in its own colours', () => { + for (const tint of [null, [1, 1, 1, 1], flightsPolicy.MODEL_WHITE]) { + const blend = aircraftModelBlend(false, tint); + for (const paint of Object.values(PAINTS)) + assert.deepEqual(blended(paint, [1, 1, 1], blend), paint); + } +}); + +test('the emergency tints keep every paint, never black or one flat colour', () => { + const tints = { + emergency: flightsPolicy.EMERGENCY_TINT, + 'military emergency': militaryPolicy.EMERGENCY_ICON_COLOR, + // Any saturated tint: one with no red once drew a red helicopter black. + cyan: [0, 1, 1, 1], + }; + for (const [tintName, tint] of Object.entries(tints)) { + const blend = aircraftModelBlend(false, tint); + const drawn = {}; + for (const [paintName, paint] of Object.entries(PAINTS)) { + const out = blended(paint, tint, blend); + drawn[paintName] = out; + // Multiplying by a tint with no red drew a red helicopter black. + paint.forEach((c, i) => + assert.ok( + out[i] >= c * 0.6, + `${tintName} over ${paintName}: channel ${i} ${out[i].toFixed(2)} keeps most of ${c}`, + ), + ); + } + // Paints that differ still differ: the tint is not one flat colour. + const spread = (a, b) => Math.max(...a.map((c, i) => Math.abs(c - b[i]))); + assert.ok(spread(drawn.red, drawn.white) > 0.4, `${tintName}: red and white apart`); + assert.ok(spread(drawn.blue, drawn.white) > 0.4, `${tintName}: blue and white apart`); + } +}); + +test('the IR boost draws every model flat white whatever its tint', () => { + for (const tint of [null, flightsPolicy.EMERGENCY_TINT]) + assert.deepEqual(aircraftModelBlend(true, tint), { mode: 'mix', amount: 1 }); +}); diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 1b091ec4f7..0f94b7b86f 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1461,6 +1461,36 @@ test('enable owns one grace timer and disable/re-enable starts a new session', a } }); +test('the layer turns on and off when its feed fails', async () => { + const harness = installWireHarness(undefined, { enabled: false }); + const priorFetch = globalThis.fetch; + const priorWarn = console.warn; + const clock = makeFakeAisRuntime(); + _setAisRuntimeForTest(clock.runtime); + globalThis.fetch = async () => ({ + ok: false, + status: 503, + json: async () => ({ + status: 'missing-key', + error: 'AISSTREAM_API_KEY is not set', + }), + }); + console.warn = () => {}; + try { + // Turning it on succeeds; the failure is shown on the layer. + assert.notEqual(await aisLiveVesselsLayer.enable(harness.viewer), false); + const feed = _getVesselFeedStateForTest(); + assert.equal(feed.status, 'unavailable'); + assert.equal(feed.error, 'AISSTREAM_API_KEY not set'); + assert.notEqual(aisLiveVesselsLayer.disable(), false); + } finally { + globalThis.fetch = priorFetch; + console.warn = priorWarn; + harness.cleanup(); + _setAisRuntimeForTest(); + } +}); + test('vessel trail lifecycle: deselect clears the selected-vessel trail', () => { const harness = installWireHarness(undefined); try { diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 0d71584fa7..a197928955 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -70,19 +70,24 @@ for (const layer of LAYERS) { 'the tracked-model driver uses the cockpit-aware predicate'); }); - test(`${layer.name}: Cockpit uses standard Proximity and All radii with a lower cap`, () => { - assert.equal(numericConstant(source, 'MODEL_PROX_ADD_M'), 150_000); - assert.equal(numericConstant(source, 'MODEL_PROX_KEEP_M'), 185_000); - assert.equal(numericConstant(source, 'MODEL_ALL_ADD_M'), 400_000); - assert.equal(numericConstant(source, 'MODEL_ALL_KEEP_M'), 450_000); + test(`${layer.name}: models draw within 3 km in both modes; Cockpit's AIR band keeps its own radii`, () => { + assert.equal(numericConstant(source, 'MODEL_ADD_M'), 3000); + assert.equal(numericConstant(source, 'MODEL_KEEP_M'), 3600); assert.equal(numericConstant(source, 'COCKPIT_MODEL_MAX'), 60); const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(add, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_ADD_M\s*:\s*(?:policy\.)?MODEL_PROX_ADD_M/); - assert.match(keep, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_KEEP_M\s*:\s*(?:policy\.)?MODEL_PROX_KEEP_M/); - assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/); - assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/); + assert.match(add, /return\s+(?:policy\.)?MODEL_ADD_M;/, 'Proximity and All share the add radius'); + assert.match(keep, /return\s+(?:policy\.)?MODEL_KEEP_M;/, 'Proximity and All share the keep radius'); + + // The AIR silhouettes are icons, not models: their band stays mode-aware. + assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_ADD_M'), 150_000); + assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_KEEP_M'), 185_000); + assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_ADD_M'), 400_000); + assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_KEEP_M'), 450_000); + const near = /^([ \t]*)function _refreshCockpitNearContacts\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; + assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_ADD_M\s*:\s*COCKPIT_AIR_PROX_ADD_M/); + assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_KEEP_M\s*:\s*COCKPIT_AIR_PROX_KEEP_M/); const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/, @@ -97,7 +102,7 @@ for (const layer of LAYERS) { // `_iconKind` is identity for every unconverted contact (see // tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the // operator explicitly converted into a TR-3B. - assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?\)/, + assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?(?:frame,?\s*)?\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/, 'far dots are reset to a rotation-free presentation'); diff --git a/src/data/detectionOcclusion.js b/src/data/detectionOcclusion.js index 8ef40d4c0f..459b2cfc73 100644 --- a/src/data/detectionOcclusion.js +++ b/src/data/detectionOcclusion.js @@ -19,9 +19,8 @@ * marker the scene itself hides behind geometry. Everything else keeps its * label exactly as before, which covers contacts high above the ground * (aircraft, satellites): their markers are drawn on top of the scene by - * design, their 3D models can be scaled up to a minimum pixel size and so fill - * the very pixel being read, and a label that hid while its marker stayed on - * screen would be the worse mismatch. + * design, their 3D models can fill the very pixel being read, and a label + * that hid while its marker stayed on screen would be the worse mismatch. * * This file is plain arithmetic; it never touches the renderer. */ diff --git a/src/data/entityContext.js b/src/data/entityContext.js index 065d061885..6939034639 100644 --- a/src/data/entityContext.js +++ b/src/data/entityContext.js @@ -1285,6 +1285,8 @@ const AIRCRAFT_CLASS_NAMES = { turboprop: msg('Turboprops'), fastjet: msg('Fast jets'), quadjet: msg('Four-engine jets'), + vehicle: msg('Airport vehicles'), + station: msg('Ground stations / obstacles'), }; /** diff --git a/src/data/fleetModelInstances.js b/src/data/fleetModelInstances.js index 5144eee392..39989a1b73 100644 --- a/src/data/fleetModelInstances.js +++ b/src/data/fleetModelInstances.js @@ -1,6 +1,6 @@ import { selectModelEligible } from './modelEligibility.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; -import { fleetModelSet } from './fleetModels.js'; +import { fleetModelSet, fleetPartTable } from './fleetModels.js'; import { findCamera, findDraw } from '../render/rendererOf.js'; import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; import { horizonFrom } from '../geo/horizon.js'; @@ -111,10 +111,15 @@ let instances = 0; * @param {object} options.viewer The scene host. * @param {() => object|null} [options.display] `{models3d, models3dMode, * irBoost}`. - * @param {object} options.policy `{altitudeCeilingM, minimumPixelSize, - * cap, capAll, addM, addAllM, keepM, keepAllM, intervalMs}`. + * @param {object} options.policy `{altitudeCeilingM, cap, capAll, addM, + * keepM, intervalMs}`: both 3D modes share the add/keep radii and differ + * by their caps. Models are drawn at their true size. * @param {(url: string) => string} [options.resolveAsset] * @param {boolean} [options.waterline] Clip each model at its waterline. + * @param {(item: object, table: object) => object|undefined} [options.partState] + * The moving parts a vehicle's model is posed with (`ModelItem.parts`), + * from its item and its model's part table (`modelPartDrivers.js`); asked + * only for a model that has a part table. * @param {object} [options.draw] Stands in for the viewer's draw port (tests). * @returns {object} */ @@ -124,6 +129,7 @@ export function createFleetModelLayer({ policy, waterline = false, resolveAsset = (url) => url, + partState = null, draw, }) { const port = draw ?? findDraw(viewer); @@ -202,8 +208,7 @@ export function createFleetModelLayer({ function refreshEligibility(items, prefs, eye) { const all = prefs.models3dMode === 'all'; const cap = all ? policy.capAll : policy.cap; - const addM = all ? policy.addAllM : policy.addM; - const keepM = all ? policy.keepAllM : policy.keepM; + const { addM, keepM } = policy; const candidates = []; for (const [id, item] of items) { if (!item.position || item.show === false || !item.spec?.url) continue; @@ -230,8 +235,15 @@ export function createFleetModelLayer({ return fromDegrees(at.lon, at.lat, at.height + lift); } + /** The part state an item's model is posed with, or undefined. */ + function partsOf(item) { + if (!partState) return undefined; + const table = fleetPartTable(fleetModelSet(), item.spec?.model); + return table ? partState(item, table) : undefined; + } + /** The draw item for an admitted model, as the set draws it, at `at`. */ - function itemOf(id, record, item, show, boost, at = placement(item)) { + function itemOf(id, record, item, show, boost, at, parts) { const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null; return { id, @@ -249,7 +261,6 @@ export function createFleetModelLayer({ ...(fleetAxisScale(item.spec) ? { axisScale: fleetAxisScale(item.spec) } : {}), - minPixelSize: policy.minimumPixelSize, environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, ...(boost ? { @@ -260,6 +271,7 @@ export function createFleetModelLayer({ : { shading: 'pbr' }), ...(mask ? { maskColor: mask } : {}), ...(waterline ? { clip: 'belowOrigin' } : {}), + ...(parts ? { parts } : {}), meta: item.pickId ?? id, show, }; @@ -276,6 +288,8 @@ export function createFleetModelLayer({ const heading = item.headingDeg || 0; const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null; const meta = item.pickId ?? id; + const parts = partsOf(item); + const partsKey = parts ? JSON.stringify(parts) : ''; const sent = record.sent; if ( sent !== null && @@ -287,7 +301,8 @@ export function createFleetModelLayer({ sameColor(sent.mask, mask) && sent.boost === boost && sent.show === show && - sent.meta === meta + sent.meta === meta && + sent.partsKey === partsKey ) return null; const next = (record.sent ??= {}); @@ -301,7 +316,8 @@ export function createFleetModelLayer({ next.boost = boost; next.show = show; next.meta = meta; - return itemOf(id, record, item, show, boost, at); + next.partsKey = partsKey; + return itemOf(id, record, item, show, boost, at, parts); } return { diff --git a/src/data/fleetModelInstances.test.mjs b/src/data/fleetModelInstances.test.mjs index 0cf79bf492..ee120eb59b 100644 --- a/src/data/fleetModelInstances.test.mjs +++ b/src/data/fleetModelInstances.test.mjs @@ -19,6 +19,7 @@ import { vesselModelSpec, } from './fleetModels.js'; import { fetchPublicFile } from '../testSupport/fleetGlb.mjs'; +import { FLEET_MODEL_POLICY } from '../layers/flights/policy.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { eastNorthUp } from '../geo/frames.js'; import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; @@ -29,15 +30,11 @@ console.info = () => {}; const set = await loadFleetModelSet({ fetchImpl: fetchPublicFile }); console.info = realInfo; +// The layers' own policy (3 km add, about 3.6 km keep), with small caps. const POLICY = Object.freeze({ - altitudeCeilingM: 800_000, - minimumPixelSize: 16, + ...FLEET_MODEL_POLICY, cap: 2, capAll: 4, - addM: 5_000, - addAllM: 20_000, - keepM: 6_000, - keepAllM: 24_000, intervalMs: 80, }); @@ -117,7 +114,7 @@ test('the icon stays the visual until the model is ready; only the nearest are d ); const near = models.items.get('near'); assert.equal(near.scale, spec.scale, 'drawn life size'); - assert.equal(near.minPixelSize, POLICY.minimumPixelSize); + assert.equal(near.minPixelSize ?? 0, 0, 'at its true size: no pixel floor'); assert.equal(near.meta, 'near', 'picked as its vehicle'); assert.equal(near.show, false, 'hidden until ready'); @@ -158,6 +155,38 @@ test('the icon stays the visual until the model is ready; only the nearest are d assert.equal(models.disposed, true); }); +test('vehicles draw as models within 3 km in either mode, and keep them to about 3.6 km', () => { + // The camera 1 km up: a vehicle `metres` east is sqrt(1 km² + metres²) away. + const at = (km) => Math.sqrt(km * km - 1) * 1_000; + for (const mode of ['proximity', 'all']) { + const { viewer, draw } = fakeViewer(); + const layer = createFleetModelLayer({ + viewer, + display: () => ({ models3d: true, models3dMode: mode }), + policy: POLICY, + }); + const spec = transitModelSpec(set, { mode: 'tram' }); + const items = new Map([ + ['in', itemAt(at(2.9), spec, { pickId: 'in' })], + ['out', itemAt(at(3.1), spec, { pickId: 'out' })], + ]); + layer.frame(items, 0); + const models = modelSet(draw); + assert.deepEqual( + [...models.items.keys()], + ['in'], + `${mode}: 2.9 km, not 3.1 km`, + ); + items.set('in', itemAt(at(3.5), spec, { pickId: 'in' })); + layer.frame(items, 100); + assert.ok(models.items.has('in'), `${mode}: kept at 3.5 km`); + items.set('in', itemAt(at(3.7), spec, { pickId: 'in' })); + layer.frame(items, 200); + assert.equal(models.items.size, 0, `${mode}: released at 3.7 km`); + layer.destroy(); + } +}); + test('models stay off above the altitude ceiling', () => { const { viewer, draw } = fakeViewer(POLICY.altitudeCeilingM + 1); const layer = createFleetModelLayer({ diff --git a/src/data/fleetModels.js b/src/data/fleetModels.js index de0a894eba..4ce09cc896 100644 --- a/src/data/fleetModels.js +++ b/src/data/fleetModels.js @@ -20,6 +20,7 @@ */ import { classifyAircraft } from './aircraftClass.js'; +import { readPartTable } from '../render/modelParts.js'; import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js'; import { isAidToNavigation } from './vesselTypes.js'; @@ -527,6 +528,34 @@ export function namedFleetModels(types) { ]); } +/** Each loaded set's part tables by model name (null for a model without one). */ +const partTables = new WeakMap(); + +/** + * The part table of model `name` in a loaded set, read once from its GLB: + * which moving parts it has (`render/modelParts.js`); null for a model + * without one, or whose GLB did not load. + * @param {{bytes?: Map}|null|undefined} set + * @param {string|null|undefined} name + * @returns {import('../render/modelParts').PartTable|null} + */ +export function fleetPartTable(set, name) { + const bytes = name ? set?.bytes?.get(name) : undefined; + if (!bytes) return null; + let tables = partTables.get(set); + if (!tables) partTables.set(set, (tables = new Map())); + if (!tables.has(name)) { + let table = null; + try { + table = readPartTable(bytes); + } catch { + // A malformed table: the model draws whole. + } + tables.set(name, table); + } + return tables.get(name); +} + let loading = null; let loaded = null; diff --git a/src/data/installationFeedback.js b/src/data/installationFeedback.js index 13e92c8b99..7209ded520 100644 --- a/src/data/installationFeedback.js +++ b/src/data/installationFeedback.js @@ -1,6 +1,7 @@ import { msg } from '../i18n/marker.js'; -// layers/installations/controls.js translates describeInstallationFeedback(). +// installationFeedback() stays English for the analyst. ui/statusText.js and +// ui/shellFeedback.js (HUD) translate it: keep both in step with this wording. const REASONS = Object.freeze({ rate_limited: msg('Overpass rate-limited'), timeout: msg('Overpass timed out'), @@ -19,7 +20,7 @@ const FALLBACK_REASON = msg('Overpass temporarily unavailable'); * @param {number} [now] * @returns {{text: string, reason?: string, seconds?: number}|{count: number, km: ?number}} */ -export function describeInstallationFeedback(stats = {}, now = Date.now()) { +function describeInstallationFeedback(stats = {}, now = Date.now()) { const reason = REASONS[stats.failureReason] || FALLBACK_REASON; if (stats.loading) return { diff --git a/src/data/modelPartDrivers.js b/src/data/modelPartDrivers.js new file mode 100644 index 0000000000..4a70f6ecb3 --- /dev/null +++ b/src/data/modelPartDrivers.js @@ -0,0 +1,243 @@ +/** + * @module modelPartDrivers + * @description What the live layers ask of a fleet model's moving parts + * (`ModelItem.parts`), from a vehicle's own record: each a pure function of + * the model's part table and what the record says, so the same record poses + * the same parts at any time. A model without a part table gets none, and a + * renderer that does not pose parts draws the model whole, at rest. + * + * Which parts each rule drives is read from the table by kind and name: + * + * - **Aircraft and helicopters** ({@link aircraftPartState}). Spin parts + * named `fan…`, `prop…` and `rotor…` turn while the aircraft is airborne, + * or on the ground moving faster than {@link MOVING_MPS}. Hinge parts named + * `gear…` are down on the ground; in the air they come down between + * {@link GEAR_APPROACH_M} metres above the ground when descending faster + * than {@link DESCENDING_MPS} (an approach), and otherwise are down below + * {@link GEAR_TAKEOFF_M}`[0]` and up above `[1]` (after take-off), in + * between in proportion. Without a height above the ground (no ground + * height known under it), the gear is down while it descends faster than + * {@link DESCENDING_MPS} slower than {@link APPROACH_MPS} below + * {@link APPROACH_CEILING_M} (an approach: the highest runways are about + * 4,400 m up), and up otherwise. Their doors (`door…`) open over the first + * quarter of the gear's travel and stay open while it is out; flaps + * (`flap…`) follow the gear in the air and are up on the ground. + * - **Vessels** ({@link vesselPartState}): spin parts named `radar…` sweep + * while the vessel is under way, faster than {@link UNDER_WAY_MPS}. + * - **Road and rail vehicles** ({@link groundVehiclePartState}): spin parts + * named `axle…` roll with the vehicle's speed (their pivot's height is the + * wheel's radius), and slide parts named `doors…` are open while the + * vehicle is stopped at a stop. + * + * Fractions and speeds are rounded ({@link DEPLOY_STEP}, {@link SPEED_STEP_MPS}) + * so a record that barely changes asks for the same state. + */ + +/** Ground speed (m/s) above which a grounded aircraft's engines turn. */ +export const MOVING_MPS = 1; +/** Vertical rate (m/s, negative down) below which an aircraft is descending. */ +export const DESCENDING_MPS = -1; +/** Heights above the ground (m) over which the gear comes down on approach: up at the first, down at the second. */ +export const GEAR_APPROACH_M = Object.freeze([750, 600]); +/** Heights above the ground (m) over which the gear goes up otherwise: down at the first, up at the second. */ +export const GEAR_TAKEOFF_M = Object.freeze([100, 300]); +/** Ground speed (m/s) under which a descending aircraft is on approach, where no ground height is known (about 165 kt). */ +export const APPROACH_MPS = 85; +/** Altitude (m) under which a descending aircraft may be on approach, where no ground height is known. */ +export const APPROACH_CEILING_M = 5000; +/** Speed (m/s) above which a vessel is under way. */ +export const UNDER_WAY_MPS = 0.5; +/** Speed (m/s) under which a vehicle at a stop is stopped there. */ +export const STOPPED_MPS = 0.5; +/** Deploy fractions are rounded to this step. */ +export const DEPLOY_STEP = 1 / 32; +/** Speeds are rounded to this step (m/s) before they turn wheels. */ +export const SPEED_STEP_MPS = 0.5; + +/** Degrees a second each spinning part turns at, by name. */ +export const SPIN_RATES_DPS = Object.freeze({ + rotor_tail: 3000, + rotor: 1080, + prop: 1500, + fan: 900, + radar: 144, +}); + +/** A wheel's radius (m) where its axle's pivot does not say. */ +const DEFAULT_WHEEL_RADIUS_M = 0.4; + +const RADIANS_TO_DEGREES = 180 / Math.PI; + +/** `value` rounded to `step`. */ +const rounded = (value, step) => Math.round(value / step) * step; + +/** 0..1 between `from` (0) and `to` (1), linear, clamped. */ +function ramp(value, from, to) { + const t = (value - from) / (to - from); + return Math.min(1, Math.max(0, t)); +} + +/** + * Whether an aircraft's engines and rotors turn: airborne, or on the ground + * moving faster than {@link MOVING_MPS}. The rotor sprite (`rotorFrames.js`) + * follows the same rule as the model's spinning parts. + * @param {{onGround?: boolean, speedMps?: number|null}} aircraft + * @returns {boolean} + */ +export function enginesTurn({ onGround, speedMps }) { + return ( + !onGround || + (typeof speedMps === 'number' && + Number.isFinite(speedMps) && + speedMps > MOVING_MPS) + ); +} + +/** A spin part's rate by its name, or 0 for a name not listed. */ +function spinRate(name) { + if (name === 'rotor_tail') return SPIN_RATES_DPS.rotor_tail; + for (const prefix of ['rotor', 'prop', 'fan', 'radar']) + if (name.startsWith(prefix)) return SPIN_RATES_DPS[prefix]; + return 0; +} + +/** Each part of `kind` whose name starts with one of `prefixes`. */ +function* partsOf(table, kind, prefixes) { + for (const part of table?.parts ?? []) + if (part.kind === kind && prefixes.some((p) => part.name.startsWith(p))) + yield part; +} + +/** A state with only the members that name a part; undefined for none. */ +function stateOf(spin, deploy) { + const out = {}; + if (Object.keys(spin).length) out.spin = spin; + if (Object.keys(deploy).length) out.deploy = deploy; + return out.spin || out.deploy ? out : undefined; +} + +/** + * How far an aircraft's gear is down, 0 (up) to 1 (down), by the rule in the + * module comment. + * @param {{onGround?: boolean, heightAboveGroundM?: number|null, + * altitudeM?: number|null, verticalRateMps?: number|null, + * speedMps?: number|null}} aircraft + * @returns {number} + */ +export function gearDown({ + onGround, + heightAboveGroundM, + altitudeM, + verticalRateMps, + speedMps, +}) { + if (onGround) return 1; + const known = (v) => typeof v === 'number' && Number.isFinite(v); + const descending = known(verticalRateMps) && verticalRateMps < DESCENDING_MPS; + const h = heightAboveGroundM; + if (!known(h)) + return descending && + known(speedMps) && + speedMps < APPROACH_MPS && + (!known(altitudeM) || altitudeM < APPROACH_CEILING_M) + ? 1 + : 0; + const down = descending + ? Math.max( + ramp(h, GEAR_APPROACH_M[0], GEAR_APPROACH_M[1]), + ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]), + ) + : ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]); + return rounded(down, DEPLOY_STEP); +} + +/** + * An aircraft's or helicopter's part state, by the rule in the module + * comment; undefined when its model has no part the rule drives. + * @param {import('../render/modelParts').PartTable|null|undefined} table + * @param {{onGround?: boolean, heightAboveGroundM?: number|null, + * altitudeM?: number|null, verticalRateMps?: number|null, + * speedMps?: number|null}} aircraft + * @returns {import('../render/contract/draw').ModelPartState|undefined} + */ +export function aircraftPartState(table, aircraft) { + if (!table) return undefined; + const spin = {}; + const deploy = {}; + if (enginesTurn(aircraft)) + for (const part of partsOf(table, 'spin', ['fan', 'prop', 'rotor'])) + spin[part.name] = spinRate(part.name); + const gear = gearDown(aircraft); + const doors = Math.min(1, rounded(gear * 4, DEPLOY_STEP)); + for (const part of partsOf(table, 'hinge', ['gear'])) + deploy[part.name] = gear; + for (const part of partsOf(table, 'hinge', ['door'])) + deploy[part.name] = doors; + for (const part of partsOf(table, 'hinge', ['flap'])) + deploy[part.name] = aircraft.onGround ? 0 : gear; + return stateOf(spin, deploy); +} + +/** + * The part state of a contact in an aircraft layer: an airport vehicle + * (class `vehicle`) is a road vehicle ({@link groundVehiclePartState}, its + * wheels rolling with its speed, never at a stop), every other contact an + * aircraft ({@link aircraftPartState}). + * @param {import('../render/modelParts').PartTable|null|undefined} table + * @param {{klass?: string|null, onGround?: boolean, + * heightAboveGroundM?: number|null, altitudeM?: number|null, + * verticalRateMps?: number|null, speedMps?: number|null}} contact + * @returns {import('../render/contract/draw').ModelPartState|undefined} + */ +export function aircraftLayerPartState(table, contact) { + return contact.klass === 'vehicle' + ? groundVehiclePartState(table, { speedMps: contact.speedMps }) + : aircraftPartState(table, contact); +} + +/** + * A vessel's part state, by the rule in the module comment; undefined when + * it is not under way or its model has no radar. + * @param {import('../render/modelParts').PartTable|null|undefined} table + * @param {{speedMps?: number|null}} vessel + * @returns {import('../render/contract/draw').ModelPartState|undefined} + */ +export function vesselPartState(table, { speedMps }) { + if (!table || !(typeof speedMps === 'number' && speedMps > UNDER_WAY_MPS)) + return undefined; + const spin = {}; + for (const part of partsOf(table, 'spin', ['radar'])) + spin[part.name] = SPIN_RATES_DPS.radar; + return stateOf(spin, {}); +} + +/** + * A road or rail vehicle's part state, by the rule in the module comment; + * undefined when it neither moves nor stands at a stop, or its model has no + * part the rule drives. + * @param {import('../render/modelParts').PartTable|null|undefined} table + * @param {{speedMps?: number|null, atStop?: boolean}} vehicle + * @returns {import('../render/contract/draw').ModelPartState|undefined} + */ +export function groundVehiclePartState(table, { speedMps, atStop }) { + if (!table) return undefined; + const speed = + typeof speedMps === 'number' && Number.isFinite(speedMps) + ? rounded(Math.max(0, speedMps), SPEED_STEP_MPS) + : 0; + const spin = {}; + const deploy = {}; + if (speed > 0) + for (const part of partsOf(table, 'spin', ['axle'])) { + const radius = + part.pivot[1] > 0.05 ? part.pivot[1] : DEFAULT_WHEEL_RADIUS_M; + // Rolling forward (−X) on the ground turns a wheel about +Z (its left). + const sign = Math.sign(part.axis?.[2] ?? 0); + if (sign !== 0) + spin[part.name] = (sign * speed * RADIANS_TO_DEGREES) / radius; + } + if (atStop && speed < STOPPED_MPS) + for (const part of partsOf(table, 'slide', ['doors'])) + deploy[part.name] = 1; + return stateOf(spin, deploy); +} diff --git a/src/data/modelPartDrivers.test.mjs b/src/data/modelPartDrivers.test.mjs new file mode 100644 index 0000000000..9841026e58 --- /dev/null +++ b/src/data/modelPartDrivers.test.mjs @@ -0,0 +1,257 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + aircraftLayerPartState, + aircraftPartState, + enginesTurn, + gearDown, + groundVehiclePartState, + SPIN_RATES_DPS, + vesselPartState, +} from './modelPartDrivers.js'; +import { fleetPartTable } from './fleetModels.js'; +import { partTableOf } from '../render/modelParts.js'; +import { partsModelGlb } from '../render/conformance/partsModel.js'; + +const AIRLINER = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { name: 'flap_right', kind: 'hinge', axis: [0, 0, -1], limits: [0, 40] }, + { name: 'engine_right', kind: 'marker' }, + { + name: 'fan_right', + kind: 'spin', + parent: 'engine_right', + axis: [1, 0, 0], + }, + { name: 'gear_nose', kind: 'hinge', axis: [0, 0, 1], limits: [90, 0] }, + { + name: 'door_nose_right', + kind: 'hinge', + axis: [1, 0, 0], + limits: [0, 90], + }, + { name: 'gear_right', kind: 'hinge', axis: [-1, 0, 0], limits: [90, 0] }, + ], +}); + +const HELICOPTER = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] }, + { name: 'rotor_tail', kind: 'spin', axis: [0, 0, -1] }, + { name: 'skids', kind: 'marker' }, + ], +}); + +const TRAWLER = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { name: 'radar', kind: 'spin', pivot: [-4, 10, 0], axis: [0, 1, 0] }, + { name: 'bridge', kind: 'marker' }, + ], +}); + +const BUS = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { + name: 'doors_right', + kind: 'slide', + pivot: [-4.75, 0.35, -1.3], + axis: [1, 0, 0], + limits: [0, 1.08], + }, + { name: 'axle_1', kind: 'spin', pivot: [-3.3, 0.5, 0], axis: [0, 0, -1] }, + { name: 'axle_2', kind: 'spin', pivot: [2.6, 0.5, 0], axis: [0, 0, -1] }, + ], +}); + +test('the gear is down on the ground and up in cruise', () => { + assert.equal(gearDown({ onGround: true }), 1); + assert.equal(gearDown({ heightAboveGroundM: 10000, verticalRateMps: 0 }), 0); + assert.equal( + gearDown({ heightAboveGroundM: 10000, verticalRateMps: -10 }), + 0, + ); + // No height known: up. + assert.equal(gearDown({ heightAboveGroundM: null }), 0); +}); + +test('without a ground height, the gear is down on approach: descending, slow and low', () => { + // Denver: 1,650 m up, the ground under it unknown. + const at = (fields) => gearDown({ heightAboveGroundM: null, ...fields }); + assert.equal(at({ altitudeM: 2000, verticalRateMps: -4, speedMps: 70 }), 1); + // Climbing out, cruising, or descending fast: up. + assert.equal(at({ altitudeM: 2000, verticalRateMps: 8, speedMps: 70 }), 0); + assert.equal(at({ altitudeM: 11000, verticalRateMps: -4, speedMps: 70 }), 0); + assert.equal(at({ altitudeM: 3000, verticalRateMps: -8, speedMps: 140 }), 0); + // Without a speed it cannot tell: up. + assert.equal(at({ altitudeM: 2000, verticalRateMps: -4 }), 0); +}); + +test('on approach the gear comes down between 750 and 600 m above the ground', () => { + const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: -4 }); + assert.equal(at(800), 0); + assert.equal(at(675), 0.5); + assert.equal(at(600), 1); + assert.equal(at(50), 1); +}); + +test('climbing or level, the gear goes up between 100 and 300 m', () => { + const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: 8 }); + assert.equal(at(50), 1); + assert.equal(at(200), 0.5); + assert.equal(at(300), 0); + assert.equal(at(700), 0); + // Level at 700 m: up; descending through it: up until the approach band. + assert.equal(gearDown({ heightAboveGroundM: 700, verticalRateMps: 0 }), 0); +}); + +test('an airliner in cruise spins its fans, gear, doors and flaps up', () => { + const state = aircraftPartState(AIRLINER, { + onGround: false, + heightAboveGroundM: 11000, + verticalRateMps: 0, + speedMps: 230, + }); + assert.deepEqual(state, { + spin: { fan_right: SPIN_RATES_DPS.fan }, + deploy: { + flap_right: 0, + gear_nose: 0, + door_nose_right: 0, + gear_right: 0, + }, + }); +}); + +test('an airliner on final has gear, doors and flaps down', () => { + const state = aircraftPartState(AIRLINER, { + onGround: false, + heightAboveGroundM: 300, + verticalRateMps: -4, + speedMps: 70, + }); + assert.deepEqual(state.deploy, { + flap_right: 1, + gear_nose: 1, + door_nose_right: 1, + gear_right: 1, + }); + // The doors open over the first quarter of the gear's travel. + const coming = aircraftPartState(AIRLINER, { + heightAboveGroundM: 745, + verticalRateMps: -4, + }); + assert.ok(coming.deploy.gear_nose > 0 && coming.deploy.gear_nose < 0.25); + assert.ok(coming.deploy.door_nose_right > coming.deploy.gear_nose); +}); + +test('parked, its engines stop; taxiing, they turn; its flaps are up on the ground', () => { + const parked = aircraftPartState(AIRLINER, { onGround: true, speedMps: 0 }); + assert.equal(parked.spin, undefined); + assert.equal(parked.deploy.gear_nose, 1); + assert.equal(parked.deploy.flap_right, 0); + const taxiing = aircraftPartState(AIRLINER, { onGround: true, speedMps: 8 }); + assert.equal(taxiing.spin.fan_right, SPIN_RATES_DPS.fan); +}); + +test('a helicopter’s rotors turn in the air and stop on the ground', () => { + const flying = aircraftPartState(HELICOPTER, { + onGround: false, + heightAboveGroundM: 300, + }); + assert.deepEqual(flying, { + spin: { + rotor_main: SPIN_RATES_DPS.rotor, + rotor_tail: SPIN_RATES_DPS.rotor_tail, + }, + }); + assert.equal( + aircraftPartState(HELICOPTER, { onGround: true, speedMps: 0 }), + undefined, + ); +}); + +test('a vessel’s radar sweeps while it is under way', () => { + assert.deepEqual(vesselPartState(TRAWLER, { speedMps: 4 }), { + spin: { radar: SPIN_RATES_DPS.radar }, + }); + assert.equal(vesselPartState(TRAWLER, { speedMps: 0.2 }), undefined); + assert.equal(vesselPartState(TRAWLER, { speedMps: null }), undefined); + // A model without a radar, or without a table, gets nothing. + assert.equal(vesselPartState(HELICOPTER, { speedMps: 4 }), undefined); + assert.equal(vesselPartState(null, { speedMps: 4 }), undefined); +}); + +test('a bus’s wheels roll with its speed, top forward; its doors open at a stop', () => { + const moving = groundVehiclePartState(BUS, { speedMps: 10 }); + // 10 m/s on 0.5 m wheels: 20 rad/s, about +Z (its left), the top rolling forward. + const rate = -(10 / 0.5) * (180 / Math.PI); + assert.ok(Math.abs(moving.spin.axle_1 - rate) < 1e-9); + assert.equal(moving.deploy, undefined); + const stopped = groundVehiclePartState(BUS, { speedMps: 0, atStop: true }); + assert.deepEqual(stopped, { deploy: { doors_right: 1 } }); + assert.equal( + groundVehiclePartState(BUS, { speedMps: 0, atStop: false }), + undefined, + ); + // Speeds are rounded: 10.1 m/s turns the wheels as 10 does. + assert.deepEqual(groundVehiclePartState(BUS, { speedMps: 10.1 }), moving); +}); + +test('an airport vehicle rolls its wheels and never holds its doors open; an aircraft is posed as one', () => { + // A van: wheels roll with its speed. + const rolling = aircraftLayerPartState(BUS, { + klass: 'vehicle', + onGround: true, + speedMps: 10, + }); + assert.deepEqual(rolling, groundVehiclePartState(BUS, { speedMps: 10 })); + assert.ok(rolling.spin.axle_1 !== 0); + // Stopped on the apron it is not at a stop: its doors stay shut. + assert.equal( + aircraftLayerPartState(BUS, { + klass: 'vehicle', + onGround: true, + speedMps: 0, + }), + undefined, + ); + // Every other class is an aircraft. + const flying = { + klass: 'helicopter', + onGround: false, + heightAboveGroundM: 300, + }; + assert.deepEqual( + aircraftLayerPartState(HELICOPTER, flying), + aircraftPartState(HELICOPTER, flying), + ); +}); + +test('engines and rotors turn in the air, or on the ground faster than 1 m/s', () => { + assert.equal(enginesTurn({ onGround: false }), true); + assert.equal(enginesTurn({ onGround: true, speedMps: 0 }), false); + assert.equal(enginesTurn({ onGround: true, speedMps: 1 }), false); + assert.equal(enginesTurn({ onGround: true, speedMps: 1.5 }), true); + assert.equal(enginesTurn({ onGround: true, speedMps: null }), false); + assert.equal(enginesTurn({ onGround: true, speedMps: Number.NaN }), false); +}); + +test('a model of a loaded set has its part table, read once', () => { + const set = { bytes: new Map([['pod', partsModelGlb()]]) }; + const table = fleetPartTable(set, 'pod'); + assert.deepEqual( + table.parts.map((p) => p.name), + ['body', 'pod', 'ram', 'arm'], + ); + assert.equal(fleetPartTable(set, 'pod'), table); + assert.equal(fleetPartTable(set, 'missing'), null); + assert.equal(fleetPartTable(null, 'pod'), null); + // A model without a table has none. + const plain = { bytes: new Map([['x', new Uint8Array(4)]]) }; + assert.equal(fleetPartTable(plain, 'x'), null); +}); diff --git a/src/data/motionModel.js b/src/data/motionModel.js index 7546c73101..b4b7ade051 100644 --- a/src/data/motionModel.js +++ b/src/data/motionModel.js @@ -127,19 +127,27 @@ export function courseSlewCapDps(speedMps, maxDps, minDps = COURSE_MIN_DPS) { * fixes still describe clear movement. The delayed renderer already derives a * matching segment speed and course from those fixes, so tracking and cockpit * consumers should prefer that pair over stale poll fields. + * + * A host-supplied placement's speed (`derivedFromPlacement`) is how fast the + * marker is drawn, not how fast the aircraft goes: a placement waiting for its + * fixes to catch up stands still at 0. The reported ground speed is shown + * then, and the placement's only when nothing is reported. */ export function displayedKinematics({ derivedSpeedMps, derivedTrackDeg, reportedSpeedMps, reportedTrackDeg, + derivedFromPlacement = false, } = {}) { + const reported = Number.isFinite(reportedSpeedMps); return { - speedMps: Number.isFinite(derivedSpeedMps) - ? Math.max(0, derivedSpeedMps) - : Number.isFinite(reportedSpeedMps) - ? Math.max(0, reportedSpeedMps) - : null, + speedMps: + Number.isFinite(derivedSpeedMps) && !(derivedFromPlacement && reported) + ? Math.max(0, derivedSpeedMps) + : reported + ? Math.max(0, reportedSpeedMps) + : null, trackDeg: Number.isFinite(derivedTrackDeg) ? derivedTrackDeg : Number.isFinite(reportedTrackDeg) diff --git a/src/data/motionModel.test.mjs b/src/data/motionModel.test.mjs index fbdcc2cbd6..23dcd851a0 100644 --- a/src/data/motionModel.test.mjs +++ b/src/data/motionModel.test.mjs @@ -43,6 +43,13 @@ test('displayedKinematics preserves a derived stop and falls back when unavailab }), { speedMps: 80, trackDeg: 180 }); }); +test('displayedKinematics shows the reported speed over a placement standing still', () => { + const placed = { derivedSpeedMps: 0, derivedTrackDeg: 90, derivedFromPlacement: true }; + assert.deepEqual(displayedKinematics({ ...placed, reportedSpeedMps: 230, reportedTrackDeg: 88 }), + { speedMps: 230, trackDeg: 90 }); + assert.deepEqual(displayedKinematics(placed), { speedMps: 0, trackDeg: 90 }); +}); + test('stale coasting follows last source contact without allowing indefinite drift', () => { const fix = 1_000_000; assert.equal(staleCoastLimitSeconds({ fixEpochMs: fix }), 60); diff --git a/src/data/placeProviderPayloads.js b/src/data/placeProviderPayloads.js index 8adf935a91..a0d7690899 100644 --- a/src/data/placeProviderPayloads.js +++ b/src/data/placeProviderPayloads.js @@ -1,3 +1,7 @@ +// Turn-by-turn steps for a route, as Core's own /api/route serves them with +// steps=1; a hosted route proxy projects the same OSRM answer. +export { normalizeOsrmSteps } from './routeSteps.js'; + function placeContextPriority(types) { const typeSet = new Set(types); if (typeSet.has('historical_landmark') || typeSet.has('monument')) return 100; diff --git a/src/data/rotorFrames.js b/src/data/rotorFrames.js new file mode 100644 index 0000000000..6747a37578 --- /dev/null +++ b/src/data/rotorFrames.js @@ -0,0 +1,75 @@ +/** + * @module rotorFrames + * @description Which rotor frame a helicopter icon shows at a time + * (`aircraftIcon('helicopter', px, frame)`). The frames step at + * {@link ROTOR_FPS}; each contact starts at its own phase, taken from its + * id, so helicopters flying together do not change frame in step. The + * rotor turns as the 3D model's does (`enginesTurn`): airborne, or on the + * ground moving faster than 1 m/s; otherwise it holds the still frame. + */ + +import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './aircraftIcons.js'; +import { enginesTurn } from './modelPartDrivers.js'; + +export { ROTOR_FRAMES, ROTOR_STILL_FRAME }; + +/** Rotor frames shown per second. */ +export const ROTOR_FPS = 10; + +/** Phase by id: hashing each id once, as many as the helicopters seen. */ +const phases = new Map(); +const PHASES_MAX = 4096; + +/** + * A contact's phase, 0 (inclusive) to 1, the same for the same id every + * time (FNV-1a over its characters, mixed). + * @param {string} id + * @returns {number} + */ +export function rotorPhase(id) { + const key = String(id ?? ''); + let phase = phases.get(key); + if (phase !== undefined) return phase; + let hash = 0x811c9dc5; + for (let i = 0; i < key.length; i++) { + hash ^= key.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + // Mixed (MurmurHash3's finaliser), so ids differing in their last + // characters, as ICAO addresses do, spread over the whole range. + hash ^= hash >>> 16; + hash = Math.imul(hash, 0x85ebca6b); + hash ^= hash >>> 13; + hash = Math.imul(hash, 0xc2b2ae35); + hash ^= hash >>> 16; + phase = (hash >>> 0) / 0x100000000; + if (phases.size >= PHASES_MAX) phases.clear(); + phases.set(key, phase); + return phase; +} + +/** + * Whether a helicopter's rotor turns: airborne, or taxiing (`enginesTurn`). + * @param {{onGround?: boolean, speedMps?: number|null}} [state] + * @returns {boolean} + */ +export function rotorTurns({ onGround = false, speedMps = null } = {}) { + return enginesTurn({ onGround, speedMps }); +} + +/** + * The rotor frame a helicopter shows at `nowMs`: the still frame while its + * rotor does not turn ({@link rotorTurns}), else stepping through the frames + * at `ROTOR_FPS` from its phase. + * @param {string} id + * @param {number} nowMs Epoch ms (any steady clock). + * @param {{onGround?: boolean, speedMps?: number|null}} [state] Ground speed in m/s. + * @returns {number} 0 to `ROTOR_FRAMES - 1`. + */ +export function rotorFrame(id, nowMs, state = {}) { + if (!rotorTurns(state) || !Number.isFinite(nowMs)) return ROTOR_STILL_FRAME; + const step = Math.floor( + (nowMs / 1000) * ROTOR_FPS + rotorPhase(id) * ROTOR_FRAMES, + ); + return ((step % ROTOR_FRAMES) + ROTOR_FRAMES) % ROTOR_FRAMES; +} diff --git a/src/data/rotorFrames.test.mjs b/src/data/rotorFrames.test.mjs new file mode 100644 index 0000000000..0337041fe7 --- /dev/null +++ b/src/data/rotorFrames.test.mjs @@ -0,0 +1,102 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { aircraftPartState } from './modelPartDrivers.js'; +import { partTableOf } from '../render/modelParts.js'; +import { + ROTOR_FPS, + ROTOR_FRAMES, + ROTOR_STILL_FRAME, + rotorFrame, + rotorPhase, + rotorTurns, +} from './rotorFrames.js'; +import { aircraftIcon } from './aircraftIcons.js'; + +const svg = (uri) => + Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8'); + +test('the helicopter has three rotor frames, each its own image', () => { + assert.equal(ROTOR_FRAMES, 3); + const frames = [0, 1, 2].map((frame) => + aircraftIcon('helicopter', 64, frame), + ); + assert.equal(new Set(frames).size, 3); + // Frames 30° apart on a four-blade rotor: the third steps back onto the + // first, a seamless loop. + assert.match(svg(frames[0]), /rotate\(15 0 -11\.2\)/); + assert.match(svg(frames[1]), /rotate\(45 0 -11\.2\)/); + assert.match(svg(frames[2]), /rotate\(75 0 -11\.2\)/); + // No frame, or one out of range, is the still frame. + assert.equal(aircraftIcon('helicopter', 64), frames[ROTOR_STILL_FRAME]); + assert.equal(aircraftIcon('helicopter', 64, 7), frames[ROTOR_STILL_FRAME]); + // Other kinds have one image whatever the frame. + assert.equal(aircraftIcon('airliner', 64, 2), aircraftIcon('airliner', 64)); +}); + +test('frames step at the rotor rate through every frame in order', () => { + const id = 'abc123'; + const stepMs = 1000 / ROTOR_FPS; + const start = 1_700_000_000_000; + const seen = []; + for (let i = 0; i < 9; i++) seen.push(rotorFrame(id, start + i * stepMs + 1)); + for (let i = 1; i < seen.length; i++) + assert.equal(seen[i], (seen[i - 1] + 1) % ROTOR_FRAMES, seen.join(',')); + // Within one step it holds. + const at = start + 5 * stepMs + 1; + const held = rotorFrame(id, at); + for (let ms = 0; ms < stepMs; ms += 10) { + const frame = rotorFrame(id, at + ms); + assert.ok(frame === held || frame === (held + 1) % ROTOR_FRAMES); + } +}); + +test('each contact has its own phase, so a group does not change in step', () => { + assert.equal(rotorPhase('abc123'), rotorPhase('abc123')); + const ids = Array.from( + { length: 24 }, + (_, i) => `a${i.toString(16).padStart(5, '0')}`, + ); + const phases = ids.map(rotorPhase); + for (const phase of phases) assert.ok(phase >= 0 && phase < 1); + assert.ok(new Set(phases).size > 20, 'phases differ by contact'); + // At one instant the group shows every frame, not one. + const at = 1_700_000_000_000; + const frames = new Set(ids.map((id) => rotorFrame(id, at))); + assert.equal(frames.size, ROTOR_FRAMES); +}); + +test('the rotor sprite turns exactly when the model’s rotor does: in the air, or taxiing', () => { + const table = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] }, + ], + }); + const stepMs = 1000 / ROTOR_FPS; + for (const state of [ + { onGround: false }, + { onGround: true, speedMps: 0 }, + { onGround: true, speedMps: 1 }, + { onGround: true, speedMps: 3 }, + { onGround: true, speedMps: null }, + ]) { + const modelSpins = aircraftPartState(table, state)?.spin?.rotor_main > 0; + assert.equal(rotorTurns(state), modelSpins, JSON.stringify(state)); + const frames = new Set( + [0, 1, 2, 3].map((i) => + rotorFrame('abc123', 1_700_000_000_000 + i * stepMs + 1, state), + ), + ); + assert.equal(frames.size, modelSpins ? ROTOR_FRAMES : 1); + } +}); + +test('a helicopter on the ground holds the still frame', () => { + const stepMs = 1000 / ROTOR_FPS; + for (let i = 0; i < 6; i++) + assert.equal( + rotorFrame('abc123', 1_700_000_000_000 + i * stepMs, { onGround: true }), + ROTOR_STILL_FRAME, + ); + assert.equal(rotorFrame('abc123', Number.NaN), ROTOR_STILL_FRAME); +}); diff --git a/src/data/timelineHistory.js b/src/data/timelineHistory.js index 3b4216b4e8..dae9a07865 100644 --- a/src/data/timelineHistory.js +++ b/src/data/timelineHistory.js @@ -38,6 +38,29 @@ function courseBetween(from, to) { return (toDegrees(Math.atan2(y, x)) + 360) % 360; } +/** + * Where in `fixes` (in time order) the fixes to make begin: the last at or + * before the newest a contact holds, so the held run goes on into the new + * one and its seam is made again from the new run (its course heads where + * the new run goes, at the new record's height), and those after it. 0 + * unless `history` is its own fixes around a time (`timeline` entries) and + * `fixes` starts at or before the newest of them and reaches it. + * @param {object[]|undefined} history + * @param {Array<{atMs: number}>} fixes + * @returns {number} + */ +function heldThrough(history, fixes) { + const newest = history?.[history.length - 1]; + if (!newest || history[0].timeline !== true || newest.timeline !== true) + return 0; + const heldMs = newest.epochMs; + if (!(fixes[0].atMs <= heldMs && fixes[fixes.length - 1].atMs >= heldMs)) + return 0; + let index = 0; + while (index < fixes.length && fixes[index].atMs <= heldMs) index++; + return index - 1; +} + /** * An aircraft's motion history with the fixes its record carries at a time * (`observation.fixes`, see src/time/timelineFixes.js) merged in, so the @@ -65,7 +88,12 @@ export function mergeAircraftTimelineFixes( const baroM = Number.isFinite(observation.baroAltitudeM) ? observation.baroAltitudeM : null; - const entries = fixes.map((fix, index) => { + // Playing on, the next snapshot's fixes mostly repeat those held: when its + // run reaches back into the held fixes, those stay as they are and only + // the seam and the fixes past it are made and added. + const from = heldThrough(history, fixes); + const entries = fixes.slice(from).map((fix, offset) => { + const index = from + offset; const course = index + 1 < fixes.length ? courseBetween(fix, fixes[index + 1]) diff --git a/src/data/timelineHistory.test.mjs b/src/data/timelineHistory.test.mjs index e3689b5821..07205d834a 100644 --- a/src/data/timelineHistory.test.mjs +++ b/src/data/timelineHistory.test.mjs @@ -145,3 +145,85 @@ test("a tracked trail takes the fixes after its newest point, up to the snapshot ); assert.equal(historyAfterTrail(history, [], 120_000).length, 3); }); + +test('playing on, the fixes a contact holds stay as they are and only the seam and newer ones are made', () => { + const held = mergeAircraftTimelineFixes( + [], + { fixes: [fix(0, 0), fix(60_000, 1), fix(120_000, 2)] }, + META, + 100, + 60_000, + ); + const kept = held.map((entry) => entry); + // The next snapshot's run reaches back into the held fixes, a little + // differently picked: those held stay, the newer are added after them. + const next = mergeAircraftTimelineFixes( + held, + { + fixes: [ + fix(30_000, 0.6), + fix(90_000, 1.6), + fix(120_000, 2.1), + fix(180_000, 3), + fix(240_000, 4), + ], + }, + META, + 100, + 120_000, + ); + assert.deepEqual( + next.map((entry) => entry.epochMs), + [0, 60_000, 120_000, 180_000, 240_000], + ); + for (const [k, entry] of kept.slice(0, -1).entries()) + assert.equal(next[k], entry, 'a held entry is kept, not made again'); + // The seam is made again from the new run: its course heads where the + // new run goes, so the course and height do not step there. + assert.notEqual(next[2], kept[2]); + const lat = (entry) => + Cesium.Math.toDegrees( + Cesium.Cartographic.fromCartesian(entry.position).latitude, + ); + assert.ok(Math.abs(lat(next[2]) - 2.1) < 1e-9); + assert.ok(Math.abs(lat(next[3]) - 3) < 1e-9); + // Each new fix heads where the track goes next, read from the new run. + assert.ok( + Math.abs(next[3].track) < 1e-6 || Math.abs(next[3].track - 360) < 1e-6, + ); +}); + +test('a run that starts after the held fixes, or a history not of its own fixes, is merged whole', () => { + const held = mergeAircraftTimelineFixes( + [], + { fixes: [fix(0, 0), fix(60_000, 1)] }, + META, + 100, + 0, + ); + const later = mergeAircraftTimelineFixes( + held, + { fixes: [fix(120_000, 2), fix(180_000, 3)] }, + META, + 100, + 120_000, + ); + assert.deepEqual( + later.map((entry) => entry.epochMs), + [0, 60_000, 120_000, 180_000], + ); + // A run reaching back over the held fixes replaces them, as before, when + // the history holds a live report. + const report = { ...held[1], timeline: undefined }; + const mixed = mergeAircraftTimelineFixes( + [held[0], report], + { fixes: [fix(30_000, 0.5), fix(90_000, 1.5)] }, + META, + 100, + 60_000, + ); + assert.deepEqual( + mixed.map((entry) => entry.epochMs), + [0, 30_000, 90_000], + ); +}); diff --git a/src/data/trackedAircraftIcon.js b/src/data/trackedAircraftIcon.js index b9fd332195..3f57771cee 100644 --- a/src/data/trackedAircraftIcon.js +++ b/src/data/trackedAircraftIcon.js @@ -28,6 +28,33 @@ const sameColor = (a, b) => a.length === b.length && a.every((value, i) => value === b[i])); +/** `trackedIconColor`'s answers, by base colour then alpha. */ +const tintsAtAlpha = new Map(); + +/** + * The tracked icon's colour: the contact's own colour (the one its fleet + * icon draws in), at `alpha`. Tracking never recolours a contact; only the + * alpha changes (faded while stale, clear while its model draws it). One + * frozen array per colour and alpha, so a frame allocates nothing. + * @param {ArrayLike} color The contact's RGBA colour, 0..1. + * @param {number} alpha + * @returns {readonly number[]} + */ +export function trackedIconColor(color, alpha) { + if (color[3] === alpha && Object.isFrozen(color)) return color; + let byAlpha = tintsAtAlpha.get(color); + if (!byAlpha) { + byAlpha = new Map(); + tintsAtAlpha.set(color, byAlpha); + } + let tint = byAlpha.get(alpha); + if (!tint) { + tint = Object.freeze([color[0], color[1], color[2], alpha]); + byAlpha.set(alpha, tint); + } + return tint; +} + /** * Whether `setId` names another layer's tracked icon set: a layer must not * take a pick of that icon for one of its own contacts. diff --git a/src/data/trackedAircraftIcon.test.mjs b/src/data/trackedAircraftIcon.test.mjs index d707bebe68..cb3eef8e7b 100644 --- a/src/data/trackedAircraftIcon.test.mjs +++ b/src/data/trackedAircraftIcon.test.mjs @@ -5,6 +5,7 @@ import { createTrackedAircraftIcon, isOtherTrackedIconSet, trackedContactHolder, + trackedIconColor, } from './trackedAircraftIcon.js'; /** A viewer double with a fake draw port and a frame port whose preRender the test runs. */ @@ -188,3 +189,13 @@ test("a layer tells another layer's tracked icon set from its own sets", () => { ); assert.equal(isOtherTrackedIconSet(undefined, 'military'), false); }); + +test('the tracked icon keeps its contact\'s colour; only the alpha changes', () => { + const amber = Object.freeze([1, 0.72, 0, 1]); + assert.equal(trackedIconColor(amber, 1), amber, 'unchanged at its own alpha'); + const stale = trackedIconColor(amber, 0.45); + assert.deepEqual(stale, [1, 0.72, 0, 0.45]); + assert.equal(trackedIconColor(amber, 0.45), stale, 'one array per alpha'); + assert.ok(Object.isFrozen(stale)); + assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]); +}); diff --git a/src/data/trackedModelForm.test.mjs b/src/data/trackedModelForm.test.mjs index 27a137c8e4..ce1c37e678 100644 --- a/src/data/trackedModelForm.test.mjs +++ b/src/data/trackedModelForm.test.mjs @@ -1176,11 +1176,10 @@ for (const fixture of LAYERS) { viewer.draw.ready(modelSet(fixture, viewer, 'tracked').spec.id, ICAO); fixture.driveTrackedModel(); - assert.equal( - fixture.ensureFleetModel(ICAO), - null, - 'once the tracked model draws, the fleet model lets go', - ); + const kept = fixture.ensureFleetModel(ICAO); + assert.ok(kept, 'once the tracked model draws, the fleet model is kept'); + assert.equal(kept.ready, true, 'loaded'); + assert.equal(kept.show, false, 'but hidden: one model draws the contact'); assert.equal( fixture.trackedBillboardColor()[3], 0, @@ -1192,6 +1191,99 @@ for (const fixture of LAYERS) { } }); + test(`${fixture.name}: deselecting hands the contact straight back to its loaded fleet model, with no icon flash`, () => { + clearTr3bRegistry(); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(30_000); + const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668); + const icon = fixture.seed({ + viewer, + models: [ + [ + ICAO, + { + ready: true, + show: true, + modelMatrix: Cesium.Matrix4.fromTranslation(position), + }, + ], + ], + trackedModelEligible: null, + }); + fixture.driveTrackedModel(); + viewer.draw.ready(modelSet(fixture, viewer, 'tracked').spec.id, ICAO); + fixture.driveTrackedModel(); + assert.equal( + fixture.trackedModel().ready, + true, + 'the tracked model draws', + ); + icon.show = false; // as selecting it hides it + + fixture.layer.stopTracking(); + const fleetItem = modelSet(fixture, viewer, 'fleet').items.get(ICAO); + assert.equal( + fleetItem?.show, + true, + 'the kept fleet model draws the contact in the same frame', + ); + assert.equal(icon.show, false, 'and its icon never shows'); + assert.equal( + modelSet(fixture, viewer, 'tracked').items.has(ICAO), + false, + 'the tracked model is gone', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } + }); + + test(`${fixture.name}: deselecting shows the icon only when no fleet model is loaded`, () => { + clearTr3bRegistry(); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(30_000); + // Selected as an icon: no fleet model at all. + let icon = fixture.seed({ + viewer, + models: [], + trackedModelEligible: null, + }); + fixture.layer.stopTracking(); + assert.equal(icon.show, true, 'no fleet model: the icon'); + + // A fleet model still loading when it is deselected. + icon = fixture.seed({ + viewer, + models: [[ICAO, { ready: false, show: false }]], + trackedModelEligible: null, + }); + fixture.layer.stopTracking(); + assert.equal(icon.show, true, 'a fleet model not loaded yet: the icon'); + assert.notEqual( + modelSet(fixture, viewer, 'fleet').items.get(ICAO)?.show, + true, + 'and the model stays hidden until it loads', + ); + + // 3D turned off meanwhile: the icon, and the fleet model goes. + icon = fixture.seed({ + viewer, + models: [[ICAO, { ready: true, show: false }]], + trackedModelEligible: null, + }); + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + assert.equal(icon.show, true, '3D off: the icon'); + assert.equal(fixture.ensureFleetModel(ICAO), null, 'no fleet model kept'); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } + }); + test(`${fixture.name}: the tracked model draws at the fleet's scale and minimum pixel size, even up close`, () => { clearTr3bRegistry(); try { @@ -1229,10 +1321,11 @@ for (const fixture of LAYERS) { fleetItem.minPixelSize, 'the same minimum pixel size', ); - assert.notDeepEqual( - trackedItem.tint, - fleetItem.tint, - 'only the colour differs', + assert.deepEqual(trackedItem.tint, fleetItem.tint, 'the same colour'); + assert.deepEqual( + trackedItem.colorBlend, + fleetItem.colorBlend, + 'the same colour blend', ); } finally { fixture.layer.setParams({ models3d: false }); @@ -1263,6 +1356,7 @@ for (const fixture of LAYERS) { fleet.scaleByDistance, 'the same scale by distance', ); + assert.deepEqual(tracked.color, fleet.color, 'the same colour'); // A landing changes the fleet icon's scale, and the tracked one's with it. fixture.seed({ viewer, onGround: true }); const grounded = fixture.trackedIconLook(ICAO); diff --git a/src/data/trailContinuity.js b/src/data/trailContinuity.js index d50c503cc4..a18a4e32b3 100644 --- a/src/data/trailContinuity.js +++ b/src/data/trailContinuity.js @@ -293,6 +293,68 @@ export function trailHeadCurvePoints(fixes, count, displayMs) { return curvePoints(curve, last.timeMs, displayMs); } +/** @constant {number} How far back from the newest report `trailTimeAt` looks for the aircraft (ms). */ +export const TRAIL_TIME_AT_SEARCH_MS = 15 * 60_000; + +/** + * The time on the trail at which `position` lies: the pair of consecutive + * reports, one path, whose straight line passes closest to it (the newest + * pair when two are as close), and the time that far along between them. + * Past the newest report the time runs on at that pair's pace; before the + * oldest pair it runs back the same way. Only pairs ending within + * TRAIL_TIME_AT_SEARCH_MS of the newest report are looked at, so a loop + * flown earlier is not mistaken for where the aircraft is now. + * + * This is how the trail finds the time an aircraft placed by someone else + * (a host-supplied placement) is drawn at: whatever delay that placement + * draws with, the trail then ends where the aircraft is drawn. + * @param {object[]} fixes - The trail, chronological. + * @param {{x: number, y: number, z: number}|null|undefined} position - Where the aircraft is drawn. + * @returns {number} Epoch ms; NaN when no pair of reports is one path. + */ +export function trailTimeAt(fixes, position) { + if (!position || fixes.length < 2) return NaN; + const newestMs = fixes[fixes.length - 1].timeMs; + let bestM = Infinity; + let bestMs = NaN; + for (let i = fixes.length - 1; i > 0; i--) { + const b = fixes[i]; + if (newestMs - b.timeMs > TRAIL_TIME_AT_SEARCH_MS) break; + const a = fixes[i - 1]; + if (!a.position || !b.position || b.breakBefore) continue; + const spanMs = b.timeMs - a.timeMs; + if (!(spanMs > 0)) continue; + const dx = b.position.x - a.position.x; + const dy = b.position.y - a.position.y; + const dz = b.position.z - a.position.z; + const lengthSq = dx * dx + dy * dy + dz * dz; + let u = + lengthSq > 0 + ? ((position.x - a.position.x) * dx + + (position.y - a.position.y) * dy + + (position.z - a.position.z) * dz) / + lengthSq + : 0; + // Only the newest pair runs on past its end, only the oldest looked at + // back past its start; the rest are their own segment. + const newest = i === fixes.length - 1; + const oldest = + i === 1 || newestMs - fixes[i - 1].timeMs > TRAIL_TIME_AT_SEARCH_MS; + const along = Math.min(Math.max(u, 0), 1); + const offM = Math.hypot( + position.x - (a.position.x + along * dx), + position.y - (a.position.y + along * dy), + position.z - (a.position.z + along * dz), + ); + if (!(offM < bestM)) continue; + if (!(u > 1 && newest)) u = Math.min(u, 1); + if (!(u < 0 && oldest)) u = Math.max(u, 0); + bestM = offM; + bestMs = a.timeMs + u * spanMs; + } + return bestMs; +} + /** * Draw body segments. A trail without breaks support draws only the newest * segment, never a line across a break. diff --git a/src/data/transitFeeds.js b/src/data/transitFeeds.js index 0f6844c652..96f33a85f8 100644 --- a/src/data/transitFeeds.js +++ b/src/data/transitFeeds.js @@ -454,6 +454,66 @@ function burlingtonRouteLabel(routeId) { return BURLINGTON_ROUTE_NAMES[routeId] || routeId; } +/** + * TransLink route ids are `-`. Rail lines pair two station + * codes (`BRBN`), ferries are `F` and `SMBI`, light rail is `L1`. Buses, + * the `SHUT` rail-replacement bus included, stay on the feed default, which + * movement plausibility treats as a guess. + * @param {string|null} routeId + * @returns {string} + */ +function translinkRouteMode(routeId) { + if (!routeId) return 'unknown'; + const route = routeId.replace(/-\d+$/, ''); + if (/^F\d+$/.test(route) || route === 'SMBI') return 'ferry'; + if (route === 'L1') return 'tram'; + if (/^[A-Z]{4}$/.test(route) && route !== 'SHUT') return 'rail'; + return 'unknown'; +} + +/** + * The route a rider would say: `200-4` → `200`, `L1-32` → `L1`, and Cairns + * `C123-33` → `123`. Only Cairns has `C` routes; rail codes such as + * `CLSH` are letters only. + * @param {string|null} routeId + * @returns {string|null} + */ +function translinkRouteLabel(routeId) { + const route = routeId.replace(/-\d+$/, ''); + const cairns = /^C(\d+)$/.exec(route); + return cairns ? cairns[1] : route; +} + +/** Adelaide Metro train and tram route ids, from its static routes.txt. */ +const ADELAIDE_RAIL_ROUTES = new Set([ + 'BEL', + 'FLNDRS', + 'GAW', + 'GAWC', + 'GRNG', + 'NOAR', + 'OSBORN', + 'OUTHA', + 'PTDOCK', + 'SALIS', + 'SEAFRD', +]); +const ADELAIDE_TRAM_ROUTES = new Set(['BTANIC', 'FESTVL', 'GLNELG']); + +/** + * Adelaide Metro route ids are the line codes; all-letter bus routes exist + * (`INDSTA`), so trains and trams are listed rather than pattern-matched. + * @param {string|null} routeId + * @returns {string} + */ +function adelaideMetroRouteMode(routeId) { + if (!routeId) return 'unknown'; + if (ADELAIDE_RAIL_ROUTES.has(routeId)) return 'rail'; + if (ADELAIDE_TRAM_ROUTES.has(routeId)) return 'tram'; + if (routeId === 'SEALNK') return 'ferry'; + return 'unknown'; +} + /** * Rio route key to the line a rider would say. One SMTR `routes.txt` covers * both feeds (see rioRouteNames.js). @@ -898,7 +958,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([ url: 'https://gtfsrt.api.translink.com.au/api/realtime/seq/VehiclePositions', license: 'CC BY 4.0', licenseUrl: 'https://translink.com.au/about-translink/open-data', - attribution: 'TransLink — Queensland Government (CC BY 4.0)', + attribution: 'Translink, Department of Transport and Main Roads', defaultEnabled: true, terms: Object.freeze({ quote: @@ -906,6 +966,28 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([ note: 'No key, no stated rate limit, no caching rule. Logos and network imagery need separate approval, so the credit is text only.', }), defaultMode: 'bus', + routeMode: translinkRouteMode, + routeLabel: translinkRouteLabel, + }), + transitFeed({ + id: 'translink-cairns', + name: 'TransLink', + operator: 'TransLink (Queensland Government)', + region: 'Cairns, Australia', + center: { lat: -16.9186, lon: 145.7781 }, + loadRadiusKm: 60, + url: 'https://gtfsrt.api.translink.com.au/api/realtime/CNS/VehiclePositions', + license: 'CC BY 4.0', + licenseUrl: 'https://translink.com.au/about-translink/open-data', + attribution: 'Translink, Department of Transport and Main Roads', + terms: { + quote: + 'Our data is licensed under a Creative Commons Attribution 4.0 International License. Authentication is not required to use the feed.', + note: 'The same open-data page lists Cairns (CNS) vehicle positions beside South East Queensland; same terms, text-only credit.', + }, + defaultMode: 'bus', + routeMode: translinkRouteMode, + routeLabel: translinkRouteLabel, }), Object.freeze({ id: 'ttc-toronto', @@ -1535,6 +1617,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([ note: 'Official keyless endpoint; the state catalogue page refused automated reads, so no licence is quoted. Same basis as Metro Transit and OVapi. Speeds are m/s. The server picks its encoding from Accept, hence the override.', }, defaultMode: 'bus', + routeMode: adelaideMetroRouteMode, }), transitFeed({ id: 'marta-atlanta', diff --git a/src/data/transitFeeds.test.mjs b/src/data/transitFeeds.test.mjs index 85a3a8243a..beebfe7eaa 100644 --- a/src/data/transitFeeds.test.mjs +++ b/src/data/transitFeeds.test.mjs @@ -396,6 +396,31 @@ test('a feed with rider-facing route ids is left alone', () => { assert.equal(transitRouteLabel(null, '7'), '7'); }); +test('TransLink route keys lose their GTFS version; Cairns loses its C prefix', () => { + // Ids seen in the live feeds, 9 Nov 2026. + const seq = getTransitFeed('translink-seq'); + assert.equal(transitRouteLabel(seq, '200-4'), '200'); + assert.equal(transitRouteLabel(seq, 'L1-32'), 'L1', 'Gold Coast light rail'); + assert.equal(transitRouteLabel(seq, 'BNVL-5'), 'BNVL', 'a rail line code'); + assert.equal( + transitRouteLabel(seq, 'CLSH-5'), + 'CLSH', + 'a rail code starting with C is not a Cairns bus', + ); + assert.equal(transitRouteLabel(seq, 'F1-18'), 'F1'); + const cairns = getTransitFeed('translink-cairns'); + assert.equal(transitRouteLabel(cairns, 'C123-33'), '123'); + assert.equal(transitRouteLabel(cairns, 'C110-33'), '110'); + assert.equal( + transitRouteLabel(cairns, '143W-33'), + '143W', + 'a variant keeps its letter', + ); + assert.equal(transitRouteLabel(cairns, 'C123'), '123', 'an unversioned key'); + assert.equal(transitRouteLabel(seq, '600'), '600', 'nothing to strip'); + assert.equal(transitRouteLabel(seq, null), null); +}); + test('the feeds whose licences are accepted by use are switched on', () => { // Barrie and YRT each ask for acceptance through a form, and each licence // also says that using the data is itself acceptance. That reading was diff --git a/src/data/transitFeedsAustralia.test.mjs b/src/data/transitFeedsAustralia.test.mjs new file mode 100644 index 0000000000..f4a3d379ef --- /dev/null +++ b/src/data/transitFeedsAustralia.test.mjs @@ -0,0 +1,107 @@ +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { transitFeedCredit } from './dataCredits.js'; +import { + getTransitFeed, + publicTransitCatalog, + transitFeedsInRange, + transitModeFor, + transitModeResolved, +} from './transitFeeds.js'; + +// Route ids below are as published in the live feeds and the operators' +// static routes.txt (checked 16 Oct 2026). + +test('TransLink Cairns is routable and each TransLink feed covers its own city', () => { + const cairns = getTransitFeed('translink-cairns'); + assert.equal( + cairns.url, + 'https://gtfsrt.api.translink.com.au/api/realtime/CNS/VehiclePositions', + ); + const ids = (lat, lon) => transitFeedsInRange(lat, lon).map((f) => f.id); + assert.deepEqual(ids(-27.4698, 153.0251), ['translink-seq']); + assert.deepEqual(ids(-16.9186, 145.7781), ['translink-cairns']); + assert.deepEqual(ids(-37.8136, 144.9631), [], 'Melbourne has no feed'); +}); + +test('TransLink route ids resolve rail, light rail and ferries; buses stay a default', () => { + const seq = getTransitFeed('translink-seq'); + const cases = [ + ['BRBN-5187', 'rail'], + ['SHCL-5187', 'rail'], + ['RPIP-5201', 'rail'], + ['L1-5029', 'tram'], + ['F1-4055', 'ferry'], + ['F23-4055', 'ferry'], + ['F50-4430', 'ferry'], + ['SMBI-3779', 'ferry'], + ]; + for (const [routeId, mode] of cases) { + assert.equal(transitModeFor(seq, routeId), mode, routeId); + assert.equal(transitModeResolved(seq, routeId), true, routeId); + } + // Buses stay on the feed default, so movement plausibility treats them as a guess. + for (const routeId of ['600', '250-5169', 'M1-4949', 'SHUT-5213', null]) { + assert.equal(transitModeFor(seq, routeId), 'bus', String(routeId)); + assert.equal(transitModeResolved(seq, routeId), false, String(routeId)); + } + const cairns = getTransitFeed('translink-cairns'); + assert.equal(transitModeFor(cairns, 'C111-5061'), 'bus'); + assert.equal(transitModeResolved(cairns, 'C111-5061'), false); +}); + +test('Adelaide Metro route ids resolve trains, trams and the SeaLink ferry', () => { + const adelaide = getTransitFeed('adelaide-metro'); + const cases = [ + ['BEL', 'rail'], + ['GAWC', 'rail'], + ['OUTHA', 'rail'], + ['SEAFRD', 'rail'], + ['PTDOCK', 'rail'], + ['BTANIC', 'tram'], + ['GLNELG', 'tram'], + ['FESTVL', 'tram'], + ['SEALNK', 'ferry'], + ]; + for (const [routeId, mode] of cases) { + assert.equal(transitModeFor(adelaide, routeId), mode, routeId); + assert.equal(transitModeResolved(adelaide, routeId), true, routeId); + } + // All-letter bus routes exist (INDSTA/INDSTB), so letters alone are not rail. + for (const routeId of ['100', 'G10', 'H33C', 'INDSTA', 'T721', null]) { + assert.equal(transitModeFor(adelaide, routeId), 'bus', String(routeId)); + assert.equal( + transitModeResolved(adelaide, routeId), + false, + String(routeId), + ); + } +}); + +test('TransLink feeds credit the operator and department as text', () => { + const credit = (id) => + transitFeedCredit(publicTransitCatalog().find((feed) => feed.id === id)) + .html; + for (const id of ['translink-seq', 'translink-cairns']) { + assert.match( + credit(id), + /^Transit \(Translink, Department of Transport and Main Roads\): ]*>CC BY 4\.0<\/a>$/, + ); + } +}); + +test('DATA_SOURCES documents the TransLink feeds in the transit row style', () => { + const rows = readFileSync( + new URL('../../DATA_SOURCES.md', import.meta.url), + 'utf8', + ).split('\n'); + const translink = rows.find((line) => line.startsWith('| **TransLink**')); + assert.match(translink, /South East Queensland and Cairns/); + assert.match(translink, /open realtime vehicle data/); + assert.match( + translink, + /published for developer use and not against their use/, + ); + assert.doesNotMatch(translink, /licen[cs]e|CC BY|terms/i); +}); diff --git a/src/data/units.js b/src/data/units.js new file mode 100644 index 0000000000..741f63380c --- /dev/null +++ b/src/data/units.js @@ -0,0 +1,7 @@ +/** + * @module units + * @description Unit conversions the layers share. + */ + +/** Metres a second in one knot (one nautical mile, 1852 m, an hour). */ +export const KNOT_MPS = 1852 / 3600; diff --git a/src/data/vesselLabels.js b/src/data/vesselLabels.js index 3a237f53b3..a261bb4b4b 100644 --- a/src/data/vesselLabels.js +++ b/src/data/vesselLabels.js @@ -5,7 +5,11 @@ */ import { t, msg } from '../i18n/index.js'; -import { normalizeVesselType } from './vesselTypes.js'; +import { + normalizeVesselType, + vesselKind, + VESSEL_KIND_STYLES, +} from './vesselTypes.js'; export { normalizeVesselType }; @@ -22,32 +26,7 @@ export const VESSEL_CARD_FADE_DISTANCE_M = 5_000_000; export const VESSEL_CARD_FADE_START_RATIO = 0.7; /** - * AIS type family → chevron hue + card accent. Single source of truth for - * vessel type colors so billboard chevrons and host cards cannot drift apart. - */ -const TYPE_STYLES = [ - { pattern: /tanker/i, css: '#ffb347', accent: '255, 179, 71' }, - { - pattern: /cargo|container|bulk|carrier/i, - css: '#39d5ff', - accent: '57, 213, 255', - }, - { - pattern: /passenger|ferry|cruise/i, - css: '#ff7adf', - accent: '255, 122, 223', - }, - { pattern: /fishing/i, css: '#7cff9b', accent: '124, 255, 155' }, - { - pattern: /tug|tow|pilot|supply|service/i, - css: '#f7f0a3', - accent: '247, 240, 163', - }, -]; -const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' }; - -/** - * An aid to navigation's disc and card accent: a bone white apart from every + * An aid to navigation's buoy and card accent: a bone white apart from every * ship type's colour. */ export const AID_TO_NAVIGATION_STYLE = Object.freeze({ @@ -55,8 +34,8 @@ export const AID_TO_NAVIGATION_STYLE = Object.freeze({ accent: '217, 210, 192', }); -// Card text for the type tokens above. The tokens stay English: TYPE_STYLES -// and tests match on them. +// Card text for the type tokens above. The tokens stay English: the vessel +// kinds (`vesselKind`) and tests match on them. const TYPE_DISPLAY_KEYS = Object.freeze({ FISHING: msg('FISHING'), TOWING: msg('TOWING'), @@ -91,19 +70,18 @@ export function displayVesselType(type) { return key ? t(key) : normalized; } -/** AIS ship type → CSS hex hue for the billboard chevron. */ +/** + * AIS ship type → CSS hex colour its sprite is tinted with. The sprite and + * the card take it from the vessel's kind (`vesselKind`), so they cannot + * drift apart. + */ export function vesselTypeCss(type) { - return styleForType(type).css; + return VESSEL_KIND_STYLES[vesselKind(type)].css; } /** AIS ship type → "r, g, b" accent string for the host card. */ export function accentForVesselType(type) { - return styleForType(type).accent; -} - -function styleForType(type) { - const text = normalizeVesselType(type); - return TYPE_STYLES.find((entry) => entry.pattern.test(text)) || DEFAULT_STYLE; + return VESSEL_KIND_STYLES[vesselKind(type)].accent; } /** diff --git a/src/data/vesselSprites.js b/src/data/vesselSprites.js new file mode 100644 index 0000000000..f321290f76 --- /dev/null +++ b/src/data/vesselSprites.js @@ -0,0 +1,167 @@ +/** + * @module vesselSprites + * @description The map sprites of the vessel layer, as SVG data URIs: one hull + * per vessel kind (`vesselKind` in vesselTypes.js), seen from above with its + * bow up (north), and one buoy for every aid to navigation, standing upright. + * + * Every sprite is white with dark detail, drawn on the 96-unit frame of + * aircraftIcons.js (centre 48,48). The layer tints it at draw time (the + * kind's colour, white while selected), so one image serves every colour and + * state, as the aircraft glyphs do: one icon-atlas slot per shape. Hulls + * share one length and differ in shape only; widths are exaggerated so they + * read at small sizes. + */ + +const VIEW = 96; +const C = VIEW / 2; + +/** Raster size of every vessel sprite (px): sharp at its largest drawn size. */ +export const VESSEL_SPRITE_PX = 64; + +/** The hull edge: dark so a light tint still reads on light ground. */ +const EDGE = + 'stroke="rgba(4,18,24,0.9)" stroke-width="2.1" stroke-linejoin="round"'; +/** Superstructure and deck detail: dark, so tinting leaves it dark. */ +const DETAIL = 'fill="rgba(4,18,24,0.42)"'; + +/** Each kind's hull and detail, centred, bow toward −Y. */ +const HULLS = { + // Container ship: fine bow, long parallel sides, square stern; container + // rows forward and the bridge aft. + cargo: ` + + `, + + // Tanker: full bow, a pipe run down the centre line with its manifold + // across, the bridge aft. + tanker: ` + + `, + + // Passenger ship or ferry: a superstructure covering nearly the whole deck. + passenger: ` + + + `, + + // High-speed craft: a catamaran, two slim bows and a square stern. + highspeed: ` + + `, + + // Fishing vessel: a narrow hull, the wheelhouse forward and outrigger + // booms across amidships. + fishing: ` + + + `, + + // Tug, pilot or service boat: short, wide and blunt, the wheelhouse + // amidships and two towing bitts aft. + tug: ` + + `, + + // Sailing boat: a rounded hull with its sail filled to one side. + sailing: ` + + + `, + + // Pleasure craft: a motor yacht, fine bow and a long cabin. + pleasure: ` + + `, + + // Military, law enforcement or rescue: a patrol boat, sharp bow, a gun + // forward of the bridge. + military: ` + + + `, + + // Any other vessel: a plain hull with a deckhouse aft. + other: ` + + `, +}; + +/** + * The buoy every aid to navigation is drawn as, seen from the side: a + * flared float with a dark waterline band, a tapering body, a lantern and a + * round top-mark, centred on the frame. No halo; it is never turned. + */ +const BUOY = ` + + + + `; + +const cache = new Map(); + +const b64 = (s) => + typeof btoa === 'function' + ? btoa(s) + : Buffer.from(s, 'utf8').toString('base64'); + +function sprite(key, body) { + let uri = cache.get(key); + if (!uri) { + const px = VESSEL_SPRITE_PX; + const svg = `${body}`; + uri = 'data:image/svg+xml;base64,' + b64(svg); + cache.set(key, uri); + } + return uri; +} + +/** + * The hull sprite of a vessel kind (`other` for one it does not know). + * @param {string} kind One of `VESSEL_KINDS`. + * @returns {string} SVG data URI. + */ +export function vesselSprite(kind) { + const k = HULLS[kind] ? kind : 'other'; + return sprite(k, HULLS[k]); +} + +/** + * The buoy sprite of every aid to navigation. + * @returns {string} SVG data URI. + */ +export function aidSprite() { + return sprite('aid', BUOY); +} diff --git a/src/data/vesselSprites.test.mjs b/src/data/vesselSprites.test.mjs new file mode 100644 index 0000000000..30ec70ccd4 --- /dev/null +++ b/src/data/vesselSprites.test.mjs @@ -0,0 +1,71 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { aidSprite, vesselSprite, VESSEL_SPRITE_PX } from './vesselSprites.js'; +import { VESSEL_KINDS, VESSEL_KIND_STYLES, vesselKind } from './vesselTypes.js'; +import { AID_TO_NAVIGATION_STYLE, accentForVesselType, vesselTypeCss } from './vesselLabels.js'; + +const svg = (uri) => + Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8'); + +test('vessel types pick their kind by AIS code or text family', () => { + const cases = { + cargo: ['70', '79', 'Container Ship', 'Bulk Carrier', 'Ro-Ro Cargo'], + tanker: ['80', '89', 'Crude Oil Tanker', 'LNG Carrier', 'LPG'], + passenger: ['60', '69', 'Passenger/Ferry', 'Cruise Ship'], + highspeed: ['40', '49', 'High-Speed Craft', 'HSC'], + fishing: ['30', 'Fishing Vessel', 'Trawler'], + tug: ['31', '32', '50', '52', '53', '54', 'Tug', 'Pilot Vessel', 'Supply'], + sailing: ['36', 'Sailing Vessel'], + pleasure: ['37', 'Pleasure Craft', 'Yacht'], + military: ['35', '55', '51', 'Military', 'Law Enforcement', 'Coast Guard', 'SAR'], + other: ['0', '20', '33', '34', '58', '90', 'Dredger', '', null, undefined, '255'], + }; + for (const [kind, types] of Object.entries(cases)) + for (const type of types) assert.equal(vesselKind(type), kind, String(type)); + assert.deepEqual(new Set(Object.keys(cases)), new Set(VESSEL_KINDS)); +}); + +test('each vessel kind has its own white hull sprite, bow up', () => { + const sprites = VESSEL_KINDS.map(vesselSprite); + assert.equal(new Set(sprites).size, VESSEL_KINDS.length); + for (const uri of sprites) { + const text = svg(uri); + assert.match(text, new RegExp(`width="${VESSEL_SPRITE_PX}"`)); + assert.match(text, /viewBox="0 0 96 96"/); + // Drawn white for the tint; nothing baked in colour. + assert.match(text, /fill="white"/); + assert.doesNotMatch(text, /#[0-9a-f]{6}/i); + } + assert.equal(vesselSprite('unknown'), vesselSprite('other')); +}); + +test('vessel colours: one per kind, the new kinds apart from the rest', () => { + const css = VESSEL_KINDS.map((kind) => VESSEL_KIND_STYLES[kind].css); + // Only cargo and other share the default cyan. + assert.equal(new Set(css).size, VESSEL_KINDS.length - 1); + assert.equal(VESSEL_KIND_STYLES.cargo.css, VESSEL_KIND_STYLES.other.css); + for (const kind of ['sailing', 'pleasure', 'military', 'highspeed']) { + const own = VESSEL_KIND_STYLES[kind].css; + for (const other of VESSEL_KINDS) + if (other !== kind) assert.notEqual(own, VESSEL_KIND_STYLES[other].css, `${kind} vs ${other}`); + assert.notEqual(own, AID_TO_NAVIGATION_STYLE.css); + } + // The sprite tint and the card accent are the same colour. + for (const [type, kind] of [['36', 'sailing'], ['37', 'pleasure'], ['55', 'military'], ['41', 'highspeed'], ['71', 'cargo']]) { + const { css: hex, accent } = VESSEL_KIND_STYLES[kind]; + assert.equal(vesselTypeCss(type), hex); + assert.equal(accentForVesselType(type), accent); + const rgb = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join(', '); + assert.equal(accent, rgb, kind); + } +}); + +test('an aid to navigation is the one buoy sprite, white with no halo', () => { + const text = svg(aidSprite()); + assert.equal(aidSprite(), aidSprite()); + assert.ok(!VESSEL_KINDS.map(vesselSprite).includes(aidSprite())); + assert.match(text, /fill="white"/); + // No light halo stroke around it. + assert.doesNotMatch(text, /rgba\(235,240,245/); + assert.doesNotMatch(text, /#[0-9a-f]{6}/i); +}); diff --git a/src/data/vesselTypes.js b/src/data/vesselTypes.js index 7421875487..503d235bb1 100644 --- a/src/data/vesselTypes.js +++ b/src/data/vesselTypes.js @@ -46,6 +46,76 @@ export function normalizeVesselType(type) { return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER'; } +/** + * The vessel kinds a ship is drawn as, each with its own hull sprite and + * colour (`vesselSprites.js`), by the type family its AIS type resolves to + * ({@link normalizeVesselType}), in order: the first that matches. + */ +const VESSEL_KIND_RULES = [ + ['tanker', /tanker|\blng\b|\blpg\b|gas carrier/i], + ['highspeed', /high[- ]?speed|\bhsc\b/i], + ['passenger', /passenger|ferry|cruise/i], + ['cargo', /cargo|container|bulk|carrier|freighter|ro-?ro/i], + ['fishing', /fishing|trawler/i], + [ + 'military', + /military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i, + ], + ['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i], + ['sailing', /sail/i], + ['pleasure', /pleasure|yacht/i], +]; + +/** Every vessel kind {@link vesselKind} names, `other` last. */ +export const VESSEL_KINDS = Object.freeze([ + ...VESSEL_KIND_RULES.map(([kind]) => kind), + 'other', +]); + +/** + * Each vessel kind's colour on the map and on its card, as CSS and as the + * card's "r, g, b" accent. Every one reads on dark water and differs from + * the rest; cargo and other share the default cyan. + */ +export const VESSEL_KIND_STYLES = Object.freeze({ + cargo: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }), + tanker: Object.freeze({ css: '#ffb347', accent: '255, 179, 71' }), + passenger: Object.freeze({ css: '#ff7adf', accent: '255, 122, 223' }), + highspeed: Object.freeze({ css: '#c6ff3d', accent: '198, 255, 61' }), + fishing: Object.freeze({ css: '#7cff9b', accent: '124, 255, 155' }), + tug: Object.freeze({ css: '#f7f0a3', accent: '247, 240, 163' }), + sailing: Object.freeze({ css: '#b49cff', accent: '180, 156, 255' }), + pleasure: Object.freeze({ css: '#ff6f61', accent: '255, 111, 97' }), + military: Object.freeze({ css: '#a9bccb', accent: '169, 188, 203' }), + other: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }), +}); + +/** Kind by type text: a feed uses few distinct type texts. */ +const KIND_MEMO = new Map(); +const KIND_MEMO_MAX = 1024; + +/** + * The kind of vessel an AIS type names, a numeric ship-type code (ITU-R + * M.1371) or a text type: `cargo` (70 to 79), `tanker` (80 to 89), + * `passenger` (60 to 69), `highspeed` (40 to 49), `fishing` (30), `tug` + * (tugs, towing, pilots, tenders, anti-pollution: 31, 32, 50, 52 to 54), + * `sailing` (36), `pleasure` (37), `military` (military, law enforcement, + * search and rescue: 35, 55, 51) or `other` (anything else, unknown types + * included). + * @param {string|number|null|undefined} type + * @returns {string} One of {@link VESSEL_KINDS}. + */ +export function vesselKind(type) { + const text = normalizeVesselType(type); + let kind = KIND_MEMO.get(text); + if (kind !== undefined) return kind; + kind = VESSEL_KIND_RULES.find(([, pattern]) => pattern.test(text))?.[0]; + kind ??= 'other'; + if (KIND_MEMO.size >= KIND_MEMO_MAX) KIND_MEMO.clear(); + KIND_MEMO.set(text, kind); + return kind; +} + /** * The kind of aid to navigation an AIS aid-to-navigation report (message 21) * names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and diff --git a/src/i18n/catalog.test.mjs b/src/i18n/catalog.test.mjs index 8107a86e96..1b35c41417 100644 --- a/src/i18n/catalog.test.mjs +++ b/src/i18n/catalog.test.mjs @@ -3,13 +3,16 @@ import assert from 'node:assert/strict'; import { checkCatalog, + checkZhHant, extractMessages, findUnmarked, markedTemplate, readCatalog, shippedLocales, + toZhHant, unmarkedMarkup, unmarkedScript, + zhHantCatalog, } from '../../scripts/i18n.mjs'; import { LOCALES } from './locale.js'; @@ -36,6 +39,95 @@ for (const locale of shippedLocales()) { }); } +test('zh-Hant is zh-CN converted to Traditional characters (npm run i18n -- --zh-hant)', () => { + assert.deepEqual( + checkZhHant(readCatalog('zh-CN'), readCatalog('zh-Hant')), + [], + ); +}); + +test('toZhHant converts characters, not vocabulary, and fixes what s2tw picks wrongly', () => { + // s2twp would write 影片, 伺服器 and 載入; zh-Hant keeps the zh-CN words. + assert.equal(toZhHant('视频'), '視頻'); + assert.equal(toZhHant('服务器'), '服務器'); + assert.equal(toZhHant('加载'), '加載'); + assert.equal(toZhHant('50 年历史'), '50 年歷史'); + assert.equal(toZhHant('发布于 {date}'), '發布於 {date}'); + assert.equal(toZhHant('1 周/秒'), '1 週/秒'); + assert.equal(toZhHant('已宣布紧急情况'), '已宣布緊急情況'); + assert.equal(toZhHant('全部 {n} 个中'), '全部 {n} 個中'); + // 併道 only where the English key is about merging. + assert.equal(toZhHant('前方并道路段', 'Merge ahead'), '前方併道路段'); + assert.equal( + toZhHant('事故并道路封闭', 'Crash, road closed'), + '事故並道路封閉', + ); + assert.equal(toZhHant('挥手并道谢', 'Waved and thanked'), '揮手並道謝'); + assert.deepEqual( + zhHantCatalog({ + 'Merge {direction} onto {road}': '{direction}并道,进入 {road}', + 'maneuver|Merge': '并道', + 'Closed and apologized': '已关闭并道歉', + }), + { + 'Merge {direction} onto {road}': '{direction}併道,進入 {road}', + 'maneuver|Merge': '併道', + 'Closed and apologized': '已關閉並道歉', + }, + ); +}); + +test('checkZhHant names each entry that is not the conversion of zh-CN', () => { + const zhCN = { + Video: '视频', + Server: '服务器', + '{count} ships': { other: '{count} 艘船' }, + }; + const generated = zhHantCatalog(zhCN); + assert.deepEqual(generated, { + Video: '視頻', + Server: '服務器', + '{count} ships': { other: '{count} 艘船' }, + }); + assert.deepEqual(checkZhHant(zhCN, generated), []); + + const fix = + 'zh-Hant is generated: edit zh-CN, then run npm run i18n -- --zh-hant'; + const { Server, ...withoutServer } = generated; + assert.deepEqual( + checkZhHant(zhCN, { + ...withoutServer, + Video: '影片', + '{count} ships': { other: '{count} 艘船隻' }, + Extra: '多餘', + }), + [ + `"Video" is "影片", not zh-CN converted ("視頻"). ${fix}`, + `"Server" is in zh-CN but not here. ${fix}`, + `"{count} ships" is {"other":"{count} 艘船隻"}, not zh-CN converted ({"other":"{count} 艘船"}). ${fix}`, + `"Extra" is not in zh-CN. ${fix}`, + ], + ); + assert.deepEqual(checkZhHant(zhCN, { Server, ...withoutServer }), [ + 'entries leave the zh-CN order at "Video": run npm run i18n -- --zh-hant', + ]); + // A key checkCatalog already lists as missing is not reported twice. + assert.deepEqual(checkZhHant(zhCN, withoutServer, new Set(['Server'])), []); +}); + +test('a zh-Hant entry still in English points to zh-CN and its same-as-English line', () => { + const fixture = new Map([['Bloom', { plural: false }]]); + const errors = (locale) => + checkCatalog(locale, { Bloom: 'Bloom' }, fixture, new Set()).errors; + assert.deepEqual(errors('zh-Hant'), [ + '"Bloom" is still English: translate it in zh-CN and run npm run i18n -- --zh-hant, or list it under "zh-Hant" in src/i18n/same-as-english.json as under "zh-CN"', + ]); + assert.match( + errors('zh-CN')[0], + /^"Bloom" is still English: translate it, or/, + ); +}); + test('every UI string is marked for translation or kept on purpose (npm run i18n)', () => { assert.deepEqual( findUnmarked().map(({ where, text }) => `${where} ${text}`), diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index d8c32ba3dc..092d56b5b5 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -77,8 +77,22 @@ "{severity} only": "{severity} فقط", "All categories": "كل الفئات", "Reading the news…": "جارٍ قراءة الأخبار…", - "News, last {hours} hours": "الأخبار، الساعات الأخيرة: {hours}", - "Last {hours} h": "آخر {hours} س", + "News, last {hours} hours": { + "zero": "الأخبار، آخر {hours} ساعة", + "one": "الأخبار، آخر ساعة ({hours})", + "two": "الأخبار، آخر ساعتين ({hours})", + "few": "الأخبار، آخر {hours} ساعات", + "many": "الأخبار، آخر {hours} ساعة", + "other": "الأخبار، آخر {hours} ساعة" + }, + "Last {hours} h": { + "zero": "آخر {hours} ساعة", + "one": "آخر ساعة ({hours})", + "two": "آخر ساعتين ({hours})", + "few": "آخر {hours} ساعات", + "many": "آخر {hours} ساعة", + "other": "آخر {hours} ساعة" + }, "Time window": "الفترة الزمنية", "Conflicts": "النزاعات", "Local": "محلي", @@ -87,9 +101,23 @@ "Hotspots": "بؤر ساخنة", "Severity": "الخطورة", "Category": "الفئة", - "Nothing reported near here in the last {hours} h": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} س", + "Nothing reported near here in the last {hours} h": { + "zero": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} ساعة", + "one": "لم يُبلَّغ عن شيء قريب من هنا في آخر ساعة ({hours})", + "two": "لم يُبلَّغ عن شيء قريب من هنا في آخر ساعتين ({hours})", + "few": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} ساعات", + "many": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} ساعة", + "other": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} ساعة" + }, "Latest news": "آخر الأخبار", - "No news matches these filters in the last {hours} h": "لا أخبار تطابق هذه المرشحات في آخر {hours} س", + "No news matches these filters in the last {hours} h": { + "zero": "لا أخبار تطابق هذه المرشحات في آخر {hours} ساعة", + "one": "لا أخبار تطابق هذه المرشحات في آخر ساعة ({hours})", + "two": "لا أخبار تطابق هذه المرشحات في آخر ساعتين ({hours})", + "few": "لا أخبار تطابق هذه المرشحات في آخر {hours} ساعات", + "many": "لا أخبار تطابق هذه المرشحات في آخر {hours} ساعة", + "other": "لا أخبار تطابق هذه المرشحات في آخر {hours} ساعة" + }, "Load older news": "تحميل أخبار أقدم", "How to read the map": "كيف تقرأ الخريطة", "Colour: severity · icon: type of event": "اللون: الخطورة · الرمز: نوع الحدث", @@ -259,7 +287,14 @@ "ALTITUDE": "الارتفاع", "CONTACT": "الهدف", "CONTACTS · 250 KM": "الأهداف · 250 كم", - "RINGS {spacing} NM": "الحلقات كل {spacing} ميل بحري", + "RINGS {spacing} NM": { + "zero": "الحلقات كل {spacing} ميل بحري", + "one": "الحلقات كل ميل بحري ({spacing})", + "two": "الحلقات كل ميلين بحريين ({spacing})", + "few": "الحلقات كل {spacing} أميال بحرية", + "many": "الحلقات كل {spacing} ميلًا بحريًا", + "other": "الحلقات كل {spacing} ميل بحري" + }, "{count} CONTACTS": { "zero": "لا أهداف ({count})", "one": "هدف واحد ({count})", @@ -388,7 +423,14 @@ "ROUTE DATA UNAVAILABLE": "بيانات المسار غير متاحة", "CONTACT NAVIGATION OFF": "التنقل بين الأهداف متوقف", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "تبقى غرفة القيادة مع السفينة المحددة", - "{range} NM": "{range} ميل بحري", + "{range} NM": { + "zero": "{range} ميل بحري", + "one": "ميل بحري واحد ({range})", + "two": "ميلان بحريان ({range})", + "few": "{range} أميال بحرية", + "many": "{range} ميلًا بحريًا", + "other": "{range} ميل بحري" + }, "AIS DESTINATION · CREW REPORTED": "وجهة AIS · أبلغ عنها الطاقم", "FROM": "من", "TO": "إلى", @@ -472,6 +514,7 @@ "Current style: {style} — click for next": "النمط الحالي: {style} — انقر للتالي", "TRACK ACQUIRED": "تم التقاط الهدف", "{label} · COURSE {heading}°": "{label} · المسار {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · المسار {heading}°", "{label} · HEADING {heading}°": "{label} · الاتجاه {heading}°", "{label} · NO HEADING": "{label} · لا اتجاه", "{label} · NADIR VIEW": "{label} · عرض باتجاه النظير", @@ -673,6 +716,7 @@ "NEAREST": "الأقرب", "CCTV camera": "كاميرا CCTV", "FOCUS": "تركيز", + "site status|FOCUS": "تركيز", "COVERAGE OFF": "التغطية متوقفة", "AUTO HOP OFF": "التنقل التلقائي متوقف", "PROJECTION ON": "الإسقاط مفعّل", @@ -1065,6 +1109,7 @@ "awaiting first AIS message…": "بانتظار أول رسالة AIS…", "EST. DOWNRANGE": "تقدير على امتداد المسار", "CONFIRMED": "مؤكَّد", + "sightings filter|CONFIRMED": "مؤكَّدة", "PAD / RTLS": "منصة الإطلاق / RTLS", "Pick a shape, then click the map.": "اختر شكلًا، ثم انقر على الخريطة.", "Enter to place the pin, Esc to cancel.": "Enter لوضع الدبوس، وEsc للإلغاء.", @@ -1100,6 +1145,10 @@ "Fast jet": "نفاثة سريعة", "Business jet": "طائرة رجال أعمال", "Drone": "طائرة مسيّرة", + "Airport vehicle": "مركبة مطار", + "Ground station / obstacle": "محطة أرضية / عائق", + "Airport vehicles": "مركبات المطار", + "Ground stations / obstacles": "محطات أرضية / عوائق", "General emergency": "طوارئ عامة", "Unlawful interference": "تدخل غير مشروع", "Radio failure": "عطل في الاتصال اللاسلكي", @@ -2537,7 +2586,7 @@ "RESUME": "استئناف", "Clear reading": "مسح القراءة", "Observed history": "سجل الأرصاد", - "Latest": "الأحدث", + "news list|Latest": "الأحدث", "Imagery on Esri · Google 3D returns when cleared": "الصور على Esri · تعود Google 3D عند المسح", "Point the camera at the ground to use the view": "وجّه الكاميرا نحو الأرض لاستخدام العرض", "That point cannot anchor a box": "لا يمكن تثبيت منطقة على تلك النقطة", @@ -2642,9 +2691,7 @@ "Delete scene \"{scene}\" and all shots?": "حذف المشهد «{scene}» وكل لقطاته؟", "Stopped (Esc)": "متوقف (Esc)", "No shots yet. Use CAPTURE SHOT to save current look.": "لا لقطات بعد. استخدم «التقاط لقطة» لحفظ المنظر الحالي.", - "Double-click to rename": "انقر نقرًا مزدوجًا لإعادة التسمية", "Shot name": "اسم اللقطة", - "LOAD": "تحميل", "{duration}s + {hold}s": "{duration} ث + {hold} ث", "Choose files": "اختيار ملفات", "{count} files selected": { @@ -3401,7 +3448,6 @@ "Add the current view, style and layers as the next shot": "إضافة العرض الحالي والنمط والطبقات كلقطة تالية", "+ CAPTURE SHOT": "+ التقاط لقطة", "Replace the selected shot with the current view": "استبدال اللقطة المحددة بالعرض الحالي", - "Click a shot to select it, double-click to rename.": "انقر على لقطة لتحديدها، وانقر عليها نقرًا مزدوجًا لإعادة تسميتها.", "Play from this scene through the rest of the project": "تشغيل من هذا المشهد حتى نهاية المشروع", "Stop playback (Esc)": "إيقاف التشغيل (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "تشغيل اللقطة التي تلي المحددة، مع الانتقال إلى المشهد التالي عند الحاجة", @@ -3706,7 +3752,14 @@ "Photo of {name}": "صورة {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "المشاهدات في نطاق العرض: {count}", + "{count} sightings in view": { + "zero": "{count} مشاهدة في نطاق العرض", + "one": "مشاهدة واحدة ({count}) في نطاق العرض", + "two": "مشاهدتان ({count}) في نطاق العرض", + "few": "{count} مشاهدات في نطاق العرض", + "many": "{count} مشاهدة في نطاق العرض", + "other": "{count} مشاهدة في نطاق العرض" + }, "Close sighting": "إغلاق المشاهدة", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "حياة برية شوهدت خلال 48 ساعة (الحيتان 7 أيام). يوضح اللون ورمز الشارة المجموعة التصنيفية. تُعرض الأنواع الحساسة في خلايا بحجم 0.2° فقط؛ وتُقرّب مشاهدات الثدييات البحرية في بحر ساليش عبر Acartia إلى 0.01°. ليست إحصاءً شاملًا.", "Open {name} on iNaturalist": "فتح {name} على iNaturalist", @@ -3717,20 +3770,37 @@ "{days}d": "{days} ي", "All markers": "كل العلامات", "Show markers of every age": "عرض العلامات من جميع الأعمار", - "Maximum event age: {days}d; undated markers are kept": "الحد الأقصى لعمر الحدث: {days} ي؛ تبقى العلامات غير المؤرخة ظاهرة", + "Maximum event age: {days}d; undated markers are kept": { + "zero": "الحد الأقصى لعمر الحدث: {days} يوم؛ تبقى العلامات غير المؤرخة ظاهرة", + "one": "الحد الأقصى لعمر الحدث: يوم واحد ({days})؛ تبقى العلامات غير المؤرخة ظاهرة", + "two": "الحد الأقصى لعمر الحدث: يومان ({days})؛ تبقى العلامات غير المؤرخة ظاهرة", + "few": "الحد الأقصى لعمر الحدث: {days} أيام؛ تبقى العلامات غير المؤرخة ظاهرة", + "many": "الحد الأقصى لعمر الحدث: {days} يومًا؛ تبقى العلامات غير المؤرخة ظاهرة", + "other": "الحد الأقصى لعمر الحدث: {days} يوم؛ تبقى العلامات غير المؤرخة ظاهرة" + }, "event age filter|All": "الكل", "Event age": "عمر الحدث", - "Event age: {days}d · undated kept": "عمر الحدث: {days} ي · غير المؤرخة تبقى ظاهرة", + "Event age: {days}d · undated kept": { + "zero": "عمر الحدث: {days} يوم · غير المؤرخة تبقى ظاهرة", + "one": "عمر الحدث: يوم واحد ({days}) · غير المؤرخة تبقى ظاهرة", + "two": "عمر الحدث: يومان ({days}) · غير المؤرخة تبقى ظاهرة", + "few": "عمر الحدث: {days} أيام · غير المؤرخة تبقى ظاهرة", + "many": "عمر الحدث: {days} يومًا · غير المؤرخة تبقى ظاهرة", + "other": "عمر الحدث: {days} يوم · غير المؤرخة تبقى ظاهرة" + }, "Close camera preview": "إغلاق معاينة الكاميرا", "Refresh map still": "تحديث صورة الخريطة الثابتة", "The map still uses a separate request and may show a different moment.": "تستخدم صورة الخريطة طلبًا منفصلًا وقد تعرض لحظة مختلفة.", "Video plays from Québec 511, which sees your IP address.": "يُشغَّل الفيديو من Québec 511، الذي يرى عنوان IP الخاص بك.", "Press OPEN to load the photo": "اضغط «فتح» لتحميل الصورة", "Captured {month}": "التُقطت في {month}", - "this spot": "هذا الموضع", "the view centre": "مركز العرض", "{source} at {place}": "{source} في {place}", + "{source} at this spot": "{source} في هذا الموضع", + "{source} at the view centre": "{source} في مركز العرض", "Street level at {place}": "مستوى الشارع في {place}", + "Street level at this spot": "مستوى الشارع في هذا الموضع", + "Street level at the view centre": "مستوى الشارع في مركز العرض", "Switching map": "جارٍ تبديل الخريطة", "Opening imagery": "جارٍ فتح الصور", "Street View is ready: press {open} to load it": "Street View جاهز: اضغط «{open}» لتحميله", @@ -3942,7 +4012,14 @@ "REMOVE ALL": "إزالة الكل", "Confirm: remove every added entry from Data Layers": "تأكيد: إزالة كل الإدخالات المُضافة من طبقات البيانات", "Remove every added entry from Data Layers": "إزالة كل الإدخالات المُضافة من طبقات البيانات", - "Showing {shown} of {total}": "عرض {shown} من {total}", + "Showing {shown} of {total}": { + "zero": "عرض {shown} من {total}", + "one": "عرض {shown} من {total}", + "two": "عرض {shown} من {total}", + "few": "عرض {shown} من {total}", + "many": "عرض {shown} من {total}", + "other": "عرض {shown} من {total}" + }, "BROWSE DATA LIBRARY": "تصفّح مكتبة البيانات", "Atmosphere": "الغلاف الجوي", "Day and night": "الليل والنهار", @@ -4467,5 +4544,11 @@ "KT": "عقدة", "Course to {code}: {course}": "المسار إلى {code}: {course}", "Over {place}": "فوق {place}", - "Below": "في الأسفل" + "Below": "في الأسفل", + "Go to this shot. Double-click to rename.": "انتقل إلى هذه اللقطة. انقر نقرًا مزدوجًا لإعادة التسمية.", + "Move up": "نقل لأعلى", + "Move down": "نقل لأسفل", + "Click a shot to go to it, double-click to rename.": "انقر على لقطة للانتقال إليها، وانقر عليها نقرًا مزدوجًا لإعادة تسميتها.", + "Back to live at the starting view": "العودة إلى البث المباشر في العرض الأولي", + "Exit cockpit to fly to a bike share city": "اخرج من قمرة القيادة للانتقال إلى مدينة بها مشاركة دراجات" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 4e80ebba3b..4fb272f5e3 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -65,8 +65,14 @@ "{severity} only": "Nur {severity}", "All categories": "Alle Kategorien", "Reading the news…": "Nachrichten werden gelesen…", - "News, last {hours} hours": "Nachrichten, letzte {hours} h", - "Last {hours} h": "Letzte {hours} h", + "News, last {hours} hours": { + "one": "Nachrichten der letzten {hours} Stunde", + "other": "Nachrichten der letzten {hours} Stunden" + }, + "Last {hours} h": { + "one": "Letzte {hours} h", + "other": "Letzte {hours} h" + }, "Time window": "Zeitraum", "Conflicts": "Konflikte", "Local": "Lokal", @@ -75,9 +81,15 @@ "Hotspots": "Brennpunkte", "Severity": "Schweregrad", "Category": "Kategorie", - "Nothing reported near here in the last {hours} h": "In den letzten {hours} h nichts in der Nähe gemeldet", + "Nothing reported near here in the last {hours} h": { + "one": "In der letzten {hours} h nichts in der Nähe gemeldet", + "other": "In den letzten {hours} h nichts in der Nähe gemeldet" + }, "Latest news": "Neueste Nachrichten", - "No news matches these filters in the last {hours} h": "Keine Nachrichten der letzten {hours} h passen zu diesen Filtern", + "No news matches these filters in the last {hours} h": { + "one": "Keine Nachrichten der letzten {hours} h passen zu diesen Filtern", + "other": "Keine Nachrichten der letzten {hours} h passen zu diesen Filtern" + }, "Load older news": "Ältere Nachrichten laden", "How to read the map": "So liest man die Karte", "Colour: severity · icon: type of event": "Farbe: Schweregrad · Symbol: Art des Ereignisses", @@ -197,6 +209,7 @@ "Previous — prior visited contact in the 250 km window": "Zurück: zuvor besuchter Kontakt im 250-km-Fenster", "PREVIOUS": "ZURÜCK", "FOCUS": "FOKUS", + "site status|FOCUS": "FOKUS", "Next — nearest unvisited contact in the 250 km window": "Weiter: nächstgelegener unbesuchter Kontakt im 250-km-Fenster", "NEXT": "WEITER", "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Kontext aus offenen Quellen, kartiert/beobachtet. Fehlende Funksignale, nicht geladene Kartenbereiche oder nicht kartierte Standorte sind kein Beleg für Abwesenheit.", @@ -301,7 +314,7 @@ "ORBITAL VELOCITY": "BAHNGESCHWINDIGKEIT", "SUB-SATELLITE POINT": "SUBSATELLITENPUNKT", "NORTH UP": "NORDEN OBEN", - "CURRENTLY OVER": "AKTUELL ÜBER", + "CURRENTLY OVER": "ÜBERFLUG", "{division}, {country}": "{division}, {country}", "{region} · near {place}": "{region} · nahe {place}", "NORAD {id}": "NORAD {id}", @@ -560,7 +573,10 @@ "ROUTE DATA UNAVAILABLE": "ROUTENDATEN NICHT VERFÜGBAR", "CONTACT NAVIGATION OFF": "KONTAKTNAVIGATION AUS", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "DIE BRÜCKE BLEIBT BEIM GEWÄHLTEN SCHIFF", - "{range} NM": "{range} SM", + "{range} NM": { + "one": "{range} SM", + "other": "{range} SM" + }, "AIS DESTINATION · CREW REPORTED": "AIS-ZIEL · VON DER BESATZUNG GEMELDET", "DEST {bearing}": "DEST {bearing}", "Disable cockpit weather effects": "Cockpit-Wettereffekte deaktivieren", @@ -606,6 +622,7 @@ "Reclassify as TR-3B": "Als TR-3B umklassifizieren", "TRACK ACQUIRED": "TRACK ERFASST", "{label} · COURSE {heading}°": "{label} · KURS {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · KURS {heading}°", "{label} · HEADING {heading}°": "{label} · STEUERKURS {heading}°", "{label} · NO HEADING": "{label} · KEIN STEUERKURS", "{label} · NADIR VIEW": "{label} · NADIRANSICHT", @@ -838,7 +855,10 @@ "Contact cockpit summary": "Cockpit-Zusammenfassung des Kontakts", "CONTACT": "KONTAKT", "CONTACTS · 250 KM": "KONTAKTE · 250 KM", - "RINGS {spacing} NM": "RINGE {spacing} SM", + "RINGS {spacing} NM": { + "one": "RINGE {spacing} SM", + "other": "RINGE {spacing} SM" + }, "{count} CONTACTS": { "one": "{count} KONTAKT", "other": "{count} KONTAKTE" @@ -1060,6 +1080,10 @@ "Fast jet": "Kampfjet", "Business jet": "Businessjet", "Drone": "Drohne", + "Airport vehicle": "Flughafenfahrzeug", + "Ground station / obstacle": "Bodenstation / Hindernis", + "Airport vehicles": "Flughafenfahrzeuge", + "Ground stations / obstacles": "Bodenstationen / Hindernisse", "General emergency": "Allgemeiner Notfall", "Unlawful interference": "Widerrechtlicher Eingriff", "Radio failure": "Funkausfall", @@ -2397,7 +2421,7 @@ "RESUME": "FORTSETZEN", "Clear reading": "Wert ausblenden", "Observed history": "Beobachteter Verlauf", - "Latest": "Neueste", + "news list|Latest": "Neueste", "Imagery on Esri · Google 3D returns when cleared": "Bilder auf Esri · nach LÖSCHEN wieder Google 3D", "Point the camera at the ground to use the view": "Kamera auf den Boden richten, um die Ansicht zu verwenden", "That point cannot anchor a box": "Dieser Punkt kann keinen Bereich verankern", @@ -2498,9 +2522,7 @@ "Delete scene \"{scene}\" and all shots?": "Szene „{scene}“ und alle Aufnahmen löschen?", "Stopped (Esc)": "Gestoppt (Esc)", "No shots yet. Use CAPTURE SHOT to save current look.": "Noch keine Aufnahmen. Mit AUFNAHME SPEICHERN die aktuelle Ansicht sichern.", - "Double-click to rename": "Doppelklick zum Umbenennen", "Shot name": "Name der Aufnahme", - "LOAD": "LADEN", "{duration}s + {hold}s": "{duration} s + {hold} s", "Choose files": "Dateien wählen", "{count} files selected": { @@ -3109,7 +3131,6 @@ "+ CAPTURE SHOT": "+ AUFNAHME SPEICHERN", "Add the current view, style and layers as the next shot": "Aktuelle Ansicht, Stil und Ebenen als nächste Aufnahme hinzufügen", "Replace the selected shot with the current view": "Ausgewählte Aufnahme durch die aktuelle Ansicht ersetzen", - "Click a shot to select it, double-click to rename.": "Aufnahme anklicken zum Auswählen, Doppelklick zum Umbenennen.", "Play from this scene through the rest of the project": "Ab dieser Szene bis zum Ende des Projekts abspielen", "Stop playback (Esc)": "Wiedergabe stoppen (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Aufnahme nach der ausgewählten abspielen, bei Bedarf in der nächsten Szene", @@ -3122,6 +3143,7 @@ "Left panels": "Linke Bereiche", "Right panels": "Rechte Bereiche", "CONFIRMED": "BESTÄTIGT", + "sightings filter|CONFIRMED": "BESTÄTIGT", "PAD / RTLS": "STARTPLATZ / RTLS", "fire confidence filter|All": "Alle", "fire confidence filter|Nominal+": "Mittel+", @@ -3382,7 +3404,10 @@ "Photo of {name}": "Foto von {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Beobachtungen im Bild: {count}", + "{count} sightings in view": { + "one": "{count} Beobachtung im Bild", + "other": "{count} Beobachtungen im Bild" + }, "Close sighting": "Beobachtung schließen", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "In den letzten 48 h beobachtete Wildtiere (Wale 7 Tage). Farbe und Symbol der Markierung zeigen die Artengruppe. Empfindliche Arten erscheinen nur als 0,2°-Zellen; Acartia-Meldungen zu Meeressäugern aus der Salish-See werden auf 0,01° gerundet. Keine Bestandszählung.", "Open {name} on iNaturalist": "{name} auf iNaturalist öffnen", @@ -3393,20 +3418,29 @@ "{days}d": "{days} T", "All markers": "Alle Markierungen", "Show markers of every age": "Markierungen jeden Alters anzeigen", - "Maximum event age: {days}d; undated markers are kept": "Maximales Ereignisalter: {days} T; undatierte Markierungen bleiben erhalten", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Maximales Ereignisalter: {days} Tag; undatierte Markierungen bleiben erhalten", + "other": "Maximales Ereignisalter: {days} Tage; undatierte Markierungen bleiben erhalten" + }, "event age filter|All": "Alle", "Event age": "Ereignisalter", - "Event age: {days}d · undated kept": "Ereignisalter: {days} T · undatierte bleiben", + "Event age: {days}d · undated kept": { + "one": "Ereignisalter: {days} Tag · undatierte bleiben", + "other": "Ereignisalter: {days} Tage · undatierte bleiben" + }, "Close camera preview": "Kameravorschau schließen", "Refresh map still": "Kartenstandbild aktualisieren", "The map still uses a separate request and may show a different moment.": "Das Kartenstandbild wird separat abgerufen und kann einen anderen Moment zeigen.", "Video plays from Québec 511, which sees your IP address.": "Das Video wird von Québec 511 abgespielt; die IP-Adresse ist für diesen Anbieter sichtbar.", "Press OPEN to load the photo": "Auf ÖFFNEN klicken, um das Foto zu laden", "Captured {month}": "Aufgenommen im {month}", - "this spot": "diese Stelle", "the view centre": "die Bildmitte", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} an dieser Stelle", + "{source} at the view centre": "{source} in der Bildmitte", "Street level at {place}": "Straßenebene: {place}", + "Street level at this spot": "Straßenebene an dieser Stelle", + "Street level at the view centre": "Straßenebene in der Bildmitte", "Switching map": "Karte wird gewechselt", "Opening imagery": "Bilder werden geöffnet", "Street View is ready: press {open} to load it": "Street View ist bereit: Auf {open} klicken, um es zu laden", @@ -3594,7 +3628,10 @@ "REMOVE ALL": "ALLE ENTFERNEN", "Confirm: remove every added entry from Data Layers": "Bestätigen: alle hinzugefügten Einträge aus Datenebenen entfernen", "Remove every added entry from Data Layers": "Alle hinzugefügten Einträge aus Datenebenen entfernen", - "Showing {shown} of {total}": "{shown} von {total} angezeigt", + "Showing {shown} of {total}": { + "one": "{shown} von {total} angezeigt", + "other": "{shown} von {total} angezeigt" + }, "BROWSE DATA LIBRARY": "DATENBIBLIOTHEK DURCHSUCHEN", "Atmosphere": "Atmosphäre", "Day and night": "Tag und Nacht", @@ -4095,5 +4132,11 @@ "KT": "KT", "Course to {code}: {course}": "Kurs nach {code}: {course}", "Over {place}": "Über {place}", - "Below": "Darunter" + "Below": "Darunter", + "Go to this shot. Double-click to rename.": "Zu dieser Aufnahme wechseln. Doppelklick zum Umbenennen.", + "Move up": "Nach oben verschieben", + "Move down": "Nach unten verschieben", + "Click a shot to go to it, double-click to rename.": "Aufnahme anklicken, um zu ihr zu wechseln, Doppelklick zum Umbenennen.", + "Back to live at the starting view": "Zurück zu Live in der Startansicht", + "Exit cockpit to fly to a bike share city": "Cockpit verlassen, um zu einer Stadt mit Bike-Sharing zu fliegen" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index cd59e6f97e..51c9620487 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -68,8 +68,16 @@ "{severity} only": "Solo {severity}", "All categories": "Todas las categorías", "Reading the news…": "Leyendo las noticias…", - "News, last {hours} hours": "Noticias desde hace {hours} h", - "Last {hours} h": "Desde hace {hours} h", + "News, last {hours} hours": { + "one": "Noticias de la última {hours} hora", + "many": "Noticias de las últimas {hours} de horas", + "other": "Noticias de las últimas {hours} horas" + }, + "Last {hours} h": { + "one": "Última {hours} h", + "many": "Últimas {hours} h", + "other": "Últimas {hours} h" + }, "Time window": "Periodo", "Conflicts": "Conflictos", "Local": "Local", @@ -78,9 +86,17 @@ "Hotspots": "Focos", "Severity": "Gravedad", "Category": "Categoría", - "Nothing reported near here in the last {hours} h": "No hay noticias cerca de aquí desde hace {hours} h", + "Nothing reported near here in the last {hours} h": { + "one": "No hay noticias cerca de aquí en la última {hours} h", + "many": "No hay noticias cerca de aquí en las últimas {hours} h", + "other": "No hay noticias cerca de aquí en las últimas {hours} h" + }, "Latest news": "Últimas noticias", - "No news matches these filters in the last {hours} h": "Desde hace {hours} h no hay noticias que coincidan con estos filtros", + "No news matches these filters in the last {hours} h": { + "one": "En la última {hours} h no hay noticias que coincidan con estos filtros", + "many": "En las últimas {hours} h no hay noticias que coincidan con estos filtros", + "other": "En las últimas {hours} h no hay noticias que coincidan con estos filtros" + }, "Load older news": "Cargar noticias anteriores", "How to read the map": "Cómo leer el mapa", "Colour: severity · icon: type of event": "Color: gravedad · icono: tipo de suceso", @@ -138,7 +154,11 @@ "ALTITUDE": "ALTITUD", "CONTACT": "CONTACTO", "CONTACTS · 250 KM": "CONTACTOS · 250 KM", - "RINGS {spacing} NM": "ANILLOS {spacing} MN", + "RINGS {spacing} NM": { + "one": "ANILLOS {spacing} MN", + "many": "ANILLOS {spacing} MN", + "other": "ANILLOS {spacing} MN" + }, "{count} CONTACTS": { "one": "{count} CONTACTO", "many": "{count} DE CONTACTOS", @@ -265,7 +285,11 @@ "ROUTE DATA UNAVAILABLE": "DATOS DE RUTA NO DISPONIBLES", "CONTACT NAVIGATION OFF": "NAVEGACIÓN DE CONTACTOS DESACTIVADA", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "EL PUENTE PERMANECE EN EL BUQUE SELECCIONADO", - "{range} NM": "{range} MN", + "{range} NM": { + "one": "{range} MN", + "many": "{range} MN", + "other": "{range} MN" + }, "AIS DESTINATION · CREW REPORTED": "DESTINO AIS · NOTIFICADO POR LA TRIPULACIÓN", "FROM": "DESDE", "TO": "HACIA", @@ -351,6 +375,7 @@ "Current style: {style} — click for next": "Estilo actual: {style} — haz clic para el siguiente", "TRACK ACQUIRED": "RASTREO ADQUIRIDO", "{label} · COURSE {heading}°": "{label} · RUMBO {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · RUMBO {heading}°", "{label} · HEADING {heading}°": "{label} · PROA {heading}°", "{label} · NO HEADING": "{label} · PROA N/D", "{label} · NADIR VIEW": "{label} · VISTA AL NADIR", @@ -545,6 +570,7 @@ "NEAREST": "MÁS CERCANA", "CCTV camera": "Cámara CCTV", "FOCUS": "ENFOCAR", + "site status|FOCUS": "ENFOQUE", "COVERAGE OFF": "COBERTURA DESACTIVADA", "AUTO HOP OFF": "SALTO AUTO: NO", "PROJECTION ON": "PROYECCIÓN ACTIVADA", @@ -900,6 +926,7 @@ "awaiting first AIS message…": "esperando el primer mensaje AIS…", "EST. DOWNRANGE": "DIST. ESTIMADA", "CONFIRMED": "CONFIRMADA", + "sightings filter|CONFIRMED": "CONFIRMADOS", "PAD / RTLS": "PLATAFORMA / RTLS", "MISSION CONTROL · FIRST LAUNCH": "CENTRO DE MANDO · PRIMER INICIO", "Choose your first view": "Elige tu primera vista", @@ -1664,7 +1691,7 @@ "Station unavailable after directory refresh": "Emisora no disponible tras actualizar el directorio", "Clear reading": "Borrar lectura", "Observed history": "Historial observado", - "Latest": "Último", + "news list|Latest": "Últimas", "S on another day replaces it · × unpins": "S en otro día lo reemplaza · × quita la fijación", "← → preview · S shows the focused day": "← → vista previa · S muestra el día enfocado", "Recent imagery": "Imágenes recientes", @@ -1757,9 +1784,7 @@ "Export failed · {error}": "La exportación falló · {error}", "← → preview · A or B pins the focused day": "← → vista previa · A o B fija el día enfocado", "← → preview the other side · A or B pins it": "← → vista previa del otro lado · A o B lo fija", - "LOAD": "CARGAR", "No shots yet. Use CAPTURE SHOT to save current look.": "Aún no hay planos. Usa CAPTURAR PLANO para guardar el aspecto actual.", - "Double-click to rename": "Doble clic para cambiar el nombre", "Shot name": "Nombre del plano", "RETRYING ALPR CAMERAS": "REINTENTANDO CÁMARAS ALPR", "FETCHING ALPR CAMERAS": "OBTENIENDO CÁMARAS ALPR", @@ -2836,6 +2861,10 @@ "Fast jet": "Avión de alto rendimiento", "Business jet": "Reactor ejecutivo", "Drone": "Dron", + "Airport vehicle": "Vehículo de aeropuerto", + "Ground station / obstacle": "Estación terrestre / obstáculo", + "Airport vehicles": "Vehículos de aeropuerto", + "Ground stations / obstacles": "Estaciones terrestres / obstáculos", "fire cause|Human": "humana", "fire cause|Natural": "natural", "fire cause|Undetermined": "indeterminada", @@ -3204,7 +3233,6 @@ "+ CAPTURE SHOT": "+ CAPTURAR PLANO", "Add the current view, style and layers as the next shot": "Añade la vista, el estilo y las capas actuales como el siguiente plano", "Replace the selected shot with the current view": "Sustituye el plano seleccionado por la vista actual", - "Click a shot to select it, double-click to rename.": "Haz clic en un plano para seleccionarlo y doble clic para cambiarle el nombre.", "scene|PLAY": "REPRODUCIR", "Stop playback (Esc)": "Detén la reproducción (Esc)", "SAVE & SHARE": "GUARDAR Y COMPARTIR", @@ -3463,7 +3491,11 @@ "Photo of {name}": "Foto de {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Avistamientos a la vista: {count}", + "{count} sightings in view": { + "one": "{count} avistamiento a la vista", + "many": "{count} de avistamientos a la vista", + "other": "{count} avistamientos a la vista" + }, "Close sighting": "Cerrar avistamiento", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Fauna y flora observadas en las últimas 48 h (cetáceos 7 días). El color y el símbolo de la insignia indican el grupo taxonómico. Las especies sensibles solo se muestran en celdas de 0,2°; los informes de mamíferos marinos de Acartia en el mar de Salish se redondean a 0,01°. No es un censo.", "Open {name} on iNaturalist": "Abrir {name} en iNaturalist", @@ -3474,20 +3506,31 @@ "{days}d": "{days} d", "All markers": "Todos los marcadores", "Show markers of every age": "Mostrar marcadores de cualquier antigüedad", - "Maximum event age: {days}d; undated markers are kept": "Antigüedad máxima: {days} d; se conservan los marcadores sin fecha", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Antigüedad máxima: {days} día; se conservan los marcadores sin fecha", + "many": "Antigüedad máxima: {days} de días; se conservan los marcadores sin fecha", + "other": "Antigüedad máxima: {days} días; se conservan los marcadores sin fecha" + }, "event age filter|All": "Todos", "Event age": "Antigüedad", - "Event age: {days}d · undated kept": "Antigüedad: {days} d · se conservan los marcadores sin fecha", + "Event age: {days}d · undated kept": { + "one": "Antigüedad: {days} día · se conservan los marcadores sin fecha", + "many": "Antigüedad: {days} de días · se conservan los marcadores sin fecha", + "other": "Antigüedad: {days} días · se conservan los marcadores sin fecha" + }, "Close camera preview": "Cerrar vista previa de la cámara", "Refresh map still": "Actualizar imagen fija del mapa", "The map still uses a separate request and may show a different moment.": "La imagen del mapa usa una solicitud independiente y puede mostrar otro momento.", "Video plays from Québec 511, which sees your IP address.": "El vídeo se reproduce desde Québec 511, que ve tu dirección IP.", "Press OPEN to load the photo": "Pulsa ABRIR para cargar la foto", "Captured {month}": "Capturada en {month}", - "this spot": "este punto", "the view centre": "el centro de la vista", "{source} at {place}": "{source} en {place}", + "{source} at this spot": "{source} en este punto", + "{source} at the view centre": "{source} en el centro de la vista", "Street level at {place}": "A pie de calle en {place}", + "Street level at this spot": "A pie de calle en este punto", + "Street level at the view centre": "A pie de calle en el centro de la vista", "Switching map": "Cambiando de mapa", "Opening imagery": "Abriendo imágenes", "Street View is ready: press {open} to load it": "Street View está listo: pulsa {open} para cargarlo", @@ -3661,7 +3704,11 @@ "switch on a dataset to load features": "activa un conjunto de datos para cargar elementos", "Data Library at a glance": "La biblioteca de datos de un vistazo", "Map features": "Elementos del mapa", - "Showing {shown} of {total}": "Mostrando {shown} de {total}", + "Showing {shown} of {total}": { + "one": "Mostrando {shown} de {total}", + "many": "Mostrando {shown} de {total}", + "other": "Mostrando {shown} de {total}" + }, "Datasets": "Conjuntos de datos", "Themes": "Temas", "zoom in to load this layer": "acércate para cargar esta capa", @@ -4188,5 +4235,11 @@ "KT": "KT", "Course to {code}: {course}": "Rumbo a {code}: {course}", "Over {place}": "Sobre {place}", - "Below": "Debajo" + "Below": "Debajo", + "Go to this shot. Double-click to rename.": "Ir a este plano. Doble clic para cambiar el nombre.", + "Move up": "Subir", + "Move down": "Bajar", + "Click a shot to go to it, double-click to rename.": "Haz clic en un plano para ir a él y doble clic para cambiarle el nombre.", + "Back to live at the starting view": "Volver al directo en la vista inicial", + "Exit cockpit to fly to a bike share city": "Sal de la cabina para volar a una ciudad con bicicletas compartidas" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index ecbb2eb634..a32d5848a3 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -68,8 +68,16 @@ "{severity} only": "{severity} uniquement", "All categories": "Toutes les catégories", "Reading the news…": "Lecture des actualités…", - "News, last {hours} hours": "Actualités sur {hours} h", - "Last {hours} h": "Sur {hours} h", + "News, last {hours} hours": { + "one": "Actualités de la dernière {hours} heure", + "many": "Actualités des dernières {hours} d'heures", + "other": "Actualités des dernières {hours} heures" + }, + "Last {hours} h": { + "one": "Dernière {hours} h", + "many": "Dernières {hours} h", + "other": "Dernières {hours} h" + }, "Time window": "Période", "Conflicts": "Conflits", "Local": "Local", @@ -78,9 +86,17 @@ "Hotspots": "Foyers", "Severity": "Gravité", "Category": "Catégorie", - "Nothing reported near here in the last {hours} h": "Rien de signalé près d'ici en {hours} h", + "Nothing reported near here in the last {hours} h": { + "one": "Rien de signalé près d'ici cette dernière {hours} h", + "many": "Rien de signalé près d'ici ces dernières {hours} h", + "other": "Rien de signalé près d'ici ces dernières {hours} h" + }, "Latest news": "Dernières actualités", - "No news matches these filters in the last {hours} h": "Aucune actualité ne correspond à ces filtres sur {hours} h", + "No news matches these filters in the last {hours} h": { + "one": "Aucune actualité de la dernière {hours} h ne correspond à ces filtres", + "many": "Aucune actualité des dernières {hours} h ne correspond à ces filtres", + "other": "Aucune actualité des dernières {hours} h ne correspond à ces filtres" + }, "Load older news": "Charger des actualités plus anciennes", "How to read the map": "Comment lire la carte", "Colour: severity · icon: type of event": "Couleur : gravité · icône : type d'événement", @@ -127,6 +143,10 @@ "Fast jet": "Avion de chasse", "Business jet": "Jet d'affaires", "Drone": "Drone", + "Airport vehicle": "Véhicule d'aéroport", + "Ground station / obstacle": "Station au sol / obstacle", + "Airport vehicles": "Véhicules d'aéroport", + "Ground stations / obstacles": "Stations au sol / obstacles", "General emergency": "Urgence générale", "Unlawful interference": "Intervention illicite", "Radio failure": "Panne radio", @@ -580,6 +600,7 @@ "Previous — prior visited contact in the 250 km window": "Précédent — contact visité précédemment dans la fenêtre de 250 km", "PREVIOUS": "PRÉC.", "FOCUS": "CENTRER", + "site status|FOCUS": "CENTRÉ", "Next — nearest unvisited contact in the 250 km window": "Suivant — contact non visité le plus proche dans la fenêtre de 250 km", "NEXT": "SUIV.", "Named areas ({n})": "Zones nommées ({n})", @@ -1827,7 +1848,11 @@ "ROUTE DATA UNAVAILABLE": "DONNÉES DE ROUTE INDISPONIBLES", "CONTACT NAVIGATION OFF": "NAVIGATION DES CONTACTS DÉSACTIVÉE", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "LA PASSERELLE RESTE SUR LE NAVIRE SÉLECTIONNÉ", - "{range} NM": "{range} NM", + "{range} NM": { + "one": "{range} NM", + "many": "{range} NM", + "other": "{range} NM" + }, "AIS DESTINATION · CREW REPORTED": "DESTINATION AIS · DÉCLARÉE PAR L'ÉQUIPAGE", "DEST {bearing}": "DEST {bearing}", "Disable cockpit weather effects": "Désactiver les effets météo du cockpit", @@ -1875,6 +1900,7 @@ "Reclassify as TR-3B": "Reclasser en TR-3B", "TRACK ACQUIRED": "PISTE ACQUISE", "{label} · COURSE {heading}°": "{label} · ROUTE {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · ROUTE {heading}°", "{label} · HEADING {heading}°": "{label} · CAP {heading}°", "{label} · NO HEADING": "{label} · SANS CAP", "{label} · NADIR VIEW": "{label} · VUE AU NADIR", @@ -2144,7 +2170,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "État de la Radio incertain — utilisez Activer ou Désactiver pour le rétablir", "Clear reading": "Effacer le relevé", "Observed history": "Historique des observations", - "Latest": "Dernière", + "news list|Latest": "Dernières", "Imagery on Esri · Google 3D returns when cleared": "Sur Esri · EFFACER rétablit Google 3D", "Point the camera at the ground to use the view": "Orientez la caméra vers le sol pour utiliser la vue", "That point cannot anchor a box": "Ce point ne peut pas ancrer une zone", @@ -2250,9 +2276,7 @@ "SPARSE": "ÉPARS", "BALANCED": "ÉQUILIBRÉ", "No shots yet. Use CAPTURE SHOT to save current look.": "Aucun plan pour l'instant. Utilisez CAPTURER UN PLAN pour enregistrer le rendu actuel.", - "Double-click to rename": "Double-cliquez pour renommer", "Shot name": "Nom du plan", - "LOAD": "CHARGER", "DEL": "SUPPR.", "{duration}s + {hold}s": "{duration} s + {hold} s", "Choose files": "Choisir des fichiers", @@ -2870,7 +2894,11 @@ "Contact cockpit summary": "Résumé cockpit du contact", "CONTACT": "CONTACT", "CONTACTS · 250 KM": "CONTACTS · 250 KM", - "RINGS {spacing} NM": "CERCLES {spacing} NM", + "RINGS {spacing} NM": { + "one": "CERCLES {spacing} NM", + "many": "CERCLES {spacing} NM", + "other": "CERCLES {spacing} NM" + }, "{count} CONTACTS": { "one": "{count} CONTACT", "many": "{count} DE CONTACTS", @@ -3184,7 +3212,6 @@ "+ CAPTURE SHOT": "+ CAPTURER UN PLAN", "Add the current view, style and layers as the next shot": "Ajouter la vue, le style et les couches actuels comme plan suivant", "Replace the selected shot with the current view": "Remplacer le plan sélectionné par la vue actuelle", - "Click a shot to select it, double-click to rename.": "Cliquez sur un plan pour le sélectionner, double-cliquez pour le renommer.", "Play from this scene through the rest of the project": "Lire à partir de cette scène jusqu'à la fin du projet", "Stop playback (Esc)": "Arrêter la lecture (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Lire le plan qui suit la sélection, en passant à la scène suivante si besoin", @@ -3197,6 +3224,7 @@ "Left panels": "Panneaux de gauche", "Right panels": "Panneaux de droite", "CONFIRMED": "CONFIRMÉE", + "sightings filter|CONFIRMED": "CONFIRMÉES", "PAD / RTLS": "PAS DE TIR / RTLS", "fire confidence filter|All": "Toutes", "fire confidence filter|Nominal+": "Nominale+", @@ -3463,7 +3491,11 @@ "Photo of {name}": "Photo : {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Observations dans la vue : {count}", + "{count} sightings in view": { + "one": "{count} observation dans la vue", + "many": "{count} d'observations dans la vue", + "other": "{count} observations dans la vue" + }, "Close sighting": "Fermer l'observation", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Faune observée au cours des dernières 48 h (cétacés 7 jours). La couleur et le pictogramme du badge indiquent le groupe taxonomique. Les espèces sensibles sont limitées à des cellules de 0,2° ; les signalements de mammifères marins en mer des Salish provenant d'Acartia sont arrondis à 0,01°. Pas un recensement.", "Open {name} on iNaturalist": "Ouvrir {name} sur iNaturalist", @@ -3474,20 +3506,31 @@ "{days}d": "{days} j", "All markers": "Tous les marqueurs", "Show markers of every age": "Afficher les marqueurs de tout âge", - "Maximum event age: {days}d; undated markers are kept": "Ancienneté maximale : {days} j ; marqueurs sans date conservés", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Ancienneté maximale : {days} j ; marqueurs sans date conservés", + "many": "Ancienneté maximale : {days} j ; marqueurs sans date conservés", + "other": "Ancienneté maximale : {days} j ; marqueurs sans date conservés" + }, "event age filter|All": "Tous", "Event age": "Ancienneté", - "Event age: {days}d · undated kept": "Ancienneté : {days} j · marqueurs sans date conservés", + "Event age: {days}d · undated kept": { + "one": "Ancienneté : {days} j · marqueurs sans date conservés", + "many": "Ancienneté : {days} j · marqueurs sans date conservés", + "other": "Ancienneté : {days} j · marqueurs sans date conservés" + }, "Close camera preview": "Fermer l'aperçu de la caméra", "Refresh map still": "Actualiser l'image fixe sur la carte", "The map still uses a separate request and may show a different moment.": "L'image fixe de la carte utilise une requête distincte et peut montrer un autre moment.", "Video plays from Québec 511, which sees your IP address.": "La vidéo est lue depuis Québec 511, qui voit votre adresse IP.", "Press OPEN to load the photo": "Appuyez sur OUVRIR pour charger la photo", "Captured {month}": "Prise en {month}", - "this spot": "cet endroit", "the view centre": "le centre de la vue", "{source} at {place}": "{source} : {place}", + "{source} at this spot": "{source} à cet endroit", + "{source} at the view centre": "{source} au centre de la vue", "Street level at {place}": "Niveau rue : {place}", + "Street level at this spot": "Niveau rue à cet endroit", + "Street level at the view centre": "Niveau rue au centre de la vue", "Switching map": "Changement de carte", "Opening imagery": "Ouverture des images", "Street View is ready: press {open} to load it": "Street View est prêt : appuyez sur {open} pour le charger", @@ -3681,7 +3724,11 @@ "REMOVE ALL": "TOUT RETIRER", "Confirm: remove every added entry from Data Layers": "Confirmer : retirer du panneau Couches toutes les entrées ajoutées", "Remove every added entry from Data Layers": "Retirer du panneau Couches toutes les entrées ajoutées", - "Showing {shown} of {total}": "Affichées : {shown} sur {total}", + "Showing {shown} of {total}": { + "one": "{shown} sur {total} affichée", + "many": "{shown} sur {total} affichées", + "other": "{shown} sur {total} affichées" + }, "BROWSE DATA LIBRARY": "PARCOURIR LA BIBLIOTHÈQUE DE DONNÉES", "Atmosphere": "Atmosphère", "Day and night": "Jour et nuit", @@ -4188,5 +4235,11 @@ "KT": "KT", "Course to {code}: {course}": "Cap vers {code} : {course}", "Over {place}": "Au-dessus de {place}", - "Below": "En dessous" + "Below": "En dessous", + "Go to this shot. Double-click to rename.": "Aller à ce plan. Double-cliquez pour renommer.", + "Move up": "Monter", + "Move down": "Descendre", + "Click a shot to go to it, double-click to rename.": "Cliquez sur un plan pour y aller, double-cliquez pour le renommer.", + "Back to live at the starting view": "Revenir au direct dans la vue de départ", + "Exit cockpit to fly to a bike share city": "Quittez le cockpit pour aller vers une ville avec vélos en libre-service" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 55ec11684d..2c667d78ec 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -52,6 +52,10 @@ "Fast jet": "מטוס סילון מהיר", "Business jet": "מטוס מנהלים", "Drone": "רחפן", + "Airport vehicle": "רכב שדה תעופה", + "Ground station / obstacle": "תחנה קרקעית / מכשול", + "Airport vehicles": "רכבי שדה תעופה", + "Ground stations / obstacles": "תחנות קרקעיות / מכשולים", "General emergency": "חירום כללי", "Unlawful interference": "התערבות בלתי חוקית", "Radio failure": "כשל קשר", @@ -474,6 +478,7 @@ "PREVIOUS": "הקודם", "Previous — prior visited contact in the 250 km window": "הקודם — מגע שכבר ביקרת בו בחלון של 250 ק\"מ", "FOCUS": "התמקד", + "site status|FOCUS": "מוקד", "NEXT": "הבא", "Next — nearest unvisited contact in the 250 km window": "הבא — המגע הקרוב ביותר שלא ביקרת בו בחלון של 250 ק\"מ", "Named areas ({n})": "אזורים בעלי שם ({n})", @@ -826,6 +831,7 @@ "ORBIT REPLAY · {mission}": "שחזור מסלול · {mission}", "PAUSED · {title}": "מושהה · {title}", "CONFIRMED": "מאושר", + "sightings filter|CONFIRMED": "מאושרות", "PAD / RTLS": "כן שיגור / RTLS", "UNSPECIFIED": "לא צוין", "{value} KM DOWNRANGE": "{value} ק\"מ לאורך המסלול", @@ -1263,7 +1269,11 @@ "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "חיות בר נצפו ב-48 השעות האחרונות (לווייתנים · 7 ימים). הצבע וגליף התג מציגים את קבוצת הטקסון. מינים רגישים מוצגים כתאי 0.2° בלבד; דיווחי יונקי הים של Salish Sea דרך Acartia מעוגלים ל-0.01°. אינו מפקד אוכלוסין.", "iNaturalist contributors · Acartia {count} (Salish Sea) · licences per record": "תורמי iNaturalist · Acartia {count} (Salish Sea) · רישיונות לכל רשומה", "iNaturalist contributors · licences per record": "תורמי iNaturalist · רישיונות לכל רשומה", - "{count} sightings in view": "{count} תצפיות בתצוגה", + "{count} sightings in view": { + "one": "{count} תצפית בתצוגה", + "two": "{count} תצפיות בתצוגה", + "other": "{count} תצפיות בתצוגה" + }, "Zoom in for local sightings": "התקרב לתצפיות מקומיות", "No recent sightings in view": "אין תצפיות אחרונות בתצוגה", "Acartia feed unavailable": "פיד Acartia אינו זמין", @@ -1732,6 +1742,7 @@ "SOURCE STATUS UNAVAILABLE": "מצב המקור אינו זמין", "TRACK ACQUIRED": "המעקב ננעל", "{label} · COURSE {heading}°": "{label} · מהלך {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · מהלך {heading}°", "Context could not restore every layer; try again": "ההקשר לא שיחזר את כל השכבות; נסה שוב", "No selected data layers": "אין שכבות נתונים נבחרות", "{count} data layers could not be cleared": { @@ -1989,7 +2000,7 @@ "READY": "מוכן", "Clear reading": "ניקוי הקריאה", "Observed history": "היסטוריה נצפית", - "Latest": "האחרונה", + "news list|Latest": "האחרונות", "Imagery on Esri · Google 3D returns when cleared": "צילומים ב-Esri · Google 3D חוזר כשמנקים", "Point the camera at the ground to use the view": "כוון את המצלמה אל הקרקע כדי להשתמש בתצוגה", "That point cannot anchor a box": "אין אפשרות לעגן תיבה באותה נקודה", @@ -2345,7 +2356,6 @@ "+ CAPTURE SHOT": "+ לכידת שוט", "Replace the selected shot with the current view": "החלפת השוט הנבחר בתצוגה הנוכחית", "UPDATE SHOT": "עדכון שוט", - "Click a shot to select it, double-click to rename.": "לחץ על שוט לבחירתו, לחיצה כפולה לשינוי שם.", "Play from this scene through the rest of the project": "נגינה מהסצנה הזאת ועד סוף הפרויקט", "Stop playback (Esc)": "עצירת ההשמעה (Esc)", "STOP": "עצירה", @@ -2389,9 +2399,7 @@ "ACTIVE STYLE": "הסגנון הפעיל", "ORBIT": "הקפה", "No shots yet. Use CAPTURE SHOT to save current look.": "אין עדיין שוטים. השתמש בלכידת שוט כדי לשמור את המראה הנוכחי.", - "Double-click to rename": "לחיצה כפולה לשינוי שם", "Shot name": "שם השוט", - "LOAD": "טעינה", "DEL": "מחיקה", "MISSION CONTROL · FIRST LAUNCH": "חדר בקרה · שיגור ראשון", "Choose your first view": "בחירת התצוגה הראשונה", @@ -3228,9 +3236,17 @@ "event age filter|All": "הכול", "{days}d": "{days} ימ׳", "Show markers of every age": "הצגת סמנים בכל גיל", - "Maximum event age: {days}d; undated markers are kept": "גיל אירוע מרבי: {days} ימ׳; סמנים ללא תאריך נשמרים", + "Maximum event age: {days}d; undated markers are kept": { + "one": "גיל אירוע מרבי: {days} יום; סמנים ללא תאריך נשמרים", + "two": "גיל אירוע מרבי: {days} ימים; סמנים ללא תאריך נשמרים", + "other": "גיל אירוע מרבי: {days} ימים; סמנים ללא תאריך נשמרים" + }, "All markers": "כל הסמנים", - "Event age: {days}d · undated kept": "גיל האירוע: {days} ימ׳ · ללא תאריך נשמרים", + "Event age: {days}d · undated kept": { + "one": "גיל האירוע: {days} יום · ללא תאריך נשמרים", + "two": "גיל האירוע: {days} ימים · ללא תאריך נשמרים", + "other": "גיל האירוע: {days} ימים · ללא תאריך נשמרים" + }, "30-DAY MISSION INDEX UNAVAILABLE": "רשימת המשימות ל-30 יום אינה זמינה", "STATIONS": "תחנות", "Crewed stations and the craft that visit them": "תחנות מאוישות והחלליות המבקרות בהן", @@ -3266,7 +3282,11 @@ "LIVE AIS": "AIS חי", "CONTACT NAVIGATION OFF": "ניווט המגעים כבוי", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "הגשר נשאר עם האונייה הנבחרת", - "{range} NM": "{range} NM", + "{range} NM": { + "one": "{range} NM", + "two": "{range} NM", + "other": "{range} NM" + }, "AIS DESTINATION · CREW REPORTED": "יעד AIS · דווח על ידי הצוות", "FWD": "קדימה", "AFT": "אחורה", @@ -3285,10 +3305,13 @@ "Video plays from Québec 511, which sees your IP address.": "הווידאו זורם מ-Québec 511, שרואה את כתובת ה-IP שלך.", "Press OPEN to load the photo": "לחץ על \"פתח\" כדי לטעון את התמונה", "Captured {month}": "צולם ב-{month}", - "this spot": "המקום הזה", "the view centre": "מרכז התצוגה", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} במקום הזה", + "{source} at the view centre": "{source} במרכז התצוגה", "Street level at {place}": "צילומי רחוב: {place}", + "Street level at this spot": "צילומי רחוב במקום הזה", + "Street level at the view centre": "צילומי רחוב במרכז התצוגה", "Switching map": "מחליף מפה", "Opening imagery": "פותח צילומים", "Street View is ready: press {open} to load it": "Street View מוכן: לחץ על \"{open}\" כדי לטעון אותו", @@ -3348,7 +3371,11 @@ "Zoom in (+)": "התקרבות (+)", "Zoom to the imaging sensor swath": "זום אל רצועת הסריקה של חיישן הצילום", "SENSOR": "חיישן", - "RINGS {spacing} NM": "טבעות {spacing} NM", + "RINGS {spacing} NM": { + "one": "טבעות {spacing} NM", + "two": "טבעות {spacing} NM", + "other": "טבעות {spacing} NM" + }, "{count} CONTACTS": { "one": "{count} מגע", "two": "{count} מגעים", @@ -3477,20 +3504,36 @@ "{severity} and above": "{severity} ומעלה", "{severity} only": "{severity} בלבד", "All categories": "כל הקטגוריות", - "Last {hours} h": "{hours} שע׳ אחורה", + "Last {hours} h": { + "one": "השעה האחרונה ({hours})", + "two": "{hours} שע׳ אחרונות", + "other": "{hours} שע׳ אחרונות" + }, "News from {area}": "חדשות מ-{area}", "Within {km} km of the view centre": "בטווח {km} ק\"מ ממרכז התצוגה", "Reading the news…": "קורא את החדשות…", - "News, last {hours} hours": "חדשות, {hours} שע׳ אחורה", + "News, last {hours} hours": { + "one": "חדשות, השעה האחרונה ({hours})", + "two": "חדשות, {hours} השעות האחרונות", + "other": "חדשות, {hours} השעות האחרונות" + }, "Time window": "חלון זמן", "News sections": "מדורי חדשות", "Hotspots": "מוקדים", "Severity": "חומרה", "Category": "קטגוריה", "Zoom in to see local news": "התקרב כדי לראות חדשות מקומיות", - "Nothing reported near here in the last {hours} h": "לא דווח דבר בסביבה בחלון של {hours} שע׳", + "Nothing reported near here in the last {hours} h": { + "one": "לא דווח דבר בסביבה בשעה האחרונה ({hours})", + "two": "לא דווח דבר בסביבה ב־{hours} השעות האחרונות", + "other": "לא דווח דבר בסביבה ב־{hours} השעות האחרונות" + }, "Latest news": "חדשות אחרונות", - "No news matches these filters in the last {hours} h": "אין חדשות התואמות למסננים אלה בחלון של {hours} שע׳", + "No news matches these filters in the last {hours} h": { + "one": "אין חדשות התואמות למסננים אלה בשעה האחרונה ({hours})", + "two": "אין חדשות התואמות למסננים אלה ב־{hours} השעות האחרונות", + "other": "אין חדשות התואמות למסננים אלה ב־{hours} השעות האחרונות" + }, "Load older news": "טעינת חדשות ישנות יותר", "How to read the map": "איך לקרוא את המפה", "Colour: severity · icon: type of event": "צבע: חומרה · סמל: סוג האירוע", @@ -3681,7 +3724,11 @@ "REMOVE ALL": "הסרת הכול", "Confirm: remove every added entry from Data Layers": "אישור: הסרת כל הפריטים שנוספו משכבות נתונים", "Remove every added entry from Data Layers": "הסרת כל הפריטים שנוספו משכבות נתונים", - "Showing {shown} of {total}": "מוצגים {shown} מתוך {total}", + "Showing {shown} of {total}": { + "one": "מוצג {shown} מתוך {total}", + "two": "מוצגים {shown} מתוך {total}", + "other": "מוצגים {shown} מתוך {total}" + }, "BROWSE DATA LIBRARY": "עיון בספריית הנתונים", "Atmosphere": "אטמוספרה", "Day and night": "יום ולילה", @@ -4188,5 +4235,11 @@ "KT": "KT", "Course to {code}: {course}": "כיוון אל {code}: {course}", "Over {place}": "מעל {place}", - "Below": "מתחת" + "Below": "מתחת", + "Go to this shot. Double-click to rename.": "מעבר לשוט הזה. לחיצה כפולה לשינוי שם.", + "Move up": "הזזה למעלה", + "Move down": "הזזה למטה", + "Click a shot to go to it, double-click to rename.": "לחץ על שוט כדי לעבור אליו, לחיצה כפולה לשינוי שם.", + "Back to live at the starting view": "חזרה לשידור החי בתצוגת הפתיחה", + "Exit cockpit to fly to a bike share city": "צא מתא הטייס כדי לטוס לעיר עם שיתוף אופניים" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 5f7f14787b..3fec1221ae 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -68,8 +68,16 @@ "{severity} only": "Solo {severity}", "All categories": "Tutte le categorie", "Reading the news…": "Lettura delle notizie…", - "News, last {hours} hours": "Notizie, periodo in ore: {hours}", - "Last {hours} h": "Periodo: {hours} h", + "News, last {hours} hours": { + "one": "Notizie dell'ultima {hours} ora", + "many": "Notizie delle ultime {hours} di ore", + "other": "Notizie delle ultime {hours} ore" + }, + "Last {hours} h": { + "one": "Ultima {hours} h", + "many": "Ultime {hours} h", + "other": "Ultime {hours} h" + }, "Time window": "Periodo", "Conflicts": "Conflitti", "Local": "Locale", @@ -78,9 +86,17 @@ "Hotspots": "Focolai", "Severity": "Gravità", "Category": "Categoria", - "Nothing reported near here in the last {hours} h": "Nessuna segnalazione qui vicino · periodo: {hours} h", + "Nothing reported near here in the last {hours} h": { + "one": "Nessuna segnalazione qui vicino nell'ultima {hours} h", + "many": "Nessuna segnalazione qui vicino nelle ultime {hours} h", + "other": "Nessuna segnalazione qui vicino nelle ultime {hours} h" + }, "Latest news": "Ultime notizie", - "No news matches these filters in the last {hours} h": "Nessuna notizia corrisponde a questi filtri · periodo: {hours} h", + "No news matches these filters in the last {hours} h": { + "one": "Nessuna notizia dell'ultima {hours} h corrisponde a questi filtri", + "many": "Nessuna notizia delle ultime {hours} h corrisponde a questi filtri", + "other": "Nessuna notizia delle ultime {hours} h corrisponde a questi filtri" + }, "Load older news": "Carica notizie precedenti", "How to read the map": "Come leggere la mappa", "Colour: severity · icon: type of event": "Colore: gravità · icona: tipo di evento", @@ -127,6 +143,10 @@ "Fast jet": "Jet ad alte prestazioni", "Business jet": "Business jet", "Drone": "Drone", + "Airport vehicle": "Veicolo aeroportuale", + "Ground station / obstacle": "Stazione a terra / ostacolo", + "Airport vehicles": "Veicoli aeroportuali", + "Ground stations / obstacles": "Stazioni a terra / ostacoli", "General emergency": "Emergenza generale", "Unlawful interference": "Interferenza illecita", "Radio failure": "Avaria radio", @@ -580,6 +600,7 @@ "Previous — prior visited contact in the 250 km window": "Precedente — contatto visitato in precedenza nella finestra di 250 km", "PREVIOUS": "PREC", "FOCUS": "FOCUS", + "site status|FOCUS": "PUNTAMENTO", "Next — nearest unvisited contact in the 250 km window": "Successivo — contatto non visitato più vicino nella finestra di 250 km", "NEXT": "SUCC", "Named areas ({n})": "Aree con nome ({n})", @@ -935,7 +956,7 @@ "ORBITAL VELOCITY": "VELOCITÀ ORBITALE", "SUB-SATELLITE POINT": "PUNTO SUBSATELLITARE", "NORTH UP": "NORD IN ALTO", - "CURRENTLY OVER": "ATTUALMENTE SOPRA", + "CURRENTLY OVER": "SORVOLO", "{division}, {country}": "{division}, {country}", "{region} · near {place}": "{region} · vicino a {place}", "NORAD {id}": "NORAD {id}", @@ -1827,7 +1848,11 @@ "ROUTE DATA UNAVAILABLE": "DATI ROTTA NON DISPONIBILI", "CONTACT NAVIGATION OFF": "NAVIGAZIONE CONTATTI DISATTIVATA", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "LA PLANCIA RESTA SULLA NAVE SELEZIONATA", - "{range} NM": "{range} MN", + "{range} NM": { + "one": "{range} MN", + "many": "{range} MN", + "other": "{range} MN" + }, "AIS DESTINATION · CREW REPORTED": "DESTINAZIONE AIS · DICHIARATA DALL'EQUIPAGGIO", "DEST {bearing}": "DEST {bearing}", "Disable cockpit weather effects": "Disattiva gli effetti meteo del cockpit", @@ -1875,6 +1900,7 @@ "Reclassify as TR-3B": "Riclassifica come TR-3B", "TRACK ACQUIRED": "TRACCIA ACQUISITA", "{label} · COURSE {heading}°": "{label} · ROTTA {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · ROTTA {heading}°", "{label} · HEADING {heading}°": "{label} · PRUA {heading}°", "{label} · NO HEADING": "{label} · PRUA N/D", "{label} · NADIR VIEW": "{label} · VISTA AL NADIR", @@ -2144,7 +2170,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Il ciclo di vita della Radio è incerto: usa Attiva o Disattiva per riconciliare", "Clear reading": "Cancella la lettura", "Observed history": "Storico osservato", - "Latest": "Più recente", + "news list|Latest": "Più recenti", "Imagery on Esri · Google 3D returns when cleared": "Immagini su Esri · Google 3D torna con CANCELLA", "Point the camera at the ground to use the view": "Punta la camera verso il suolo per usare la vista", "That point cannot anchor a box": "Quel punto non può ancorare un riquadro", @@ -2250,9 +2276,7 @@ "SPARSE": "RADO", "BALANCED": "BILANCIATO", "No shots yet. Use CAPTURE SHOT to save current look.": "Ancora nessuno scatto. Usa CATTURA SCATTO per salvare l'aspetto attuale.", - "Double-click to rename": "Doppio clic per rinominare", "Shot name": "Nome dello scatto", - "LOAD": "CARICA", "DEL": "ELIM", "{duration}s + {hold}s": "{duration}s + {hold}s", "Choose files": "Scegli i file", @@ -2870,7 +2894,11 @@ "Contact cockpit summary": "Riepilogo contatto del cockpit", "CONTACT": "CONTATTO", "CONTACTS · 250 KM": "CONTATTI · 250 KM", - "RINGS {spacing} NM": "CERCHI {spacing} MN", + "RINGS {spacing} NM": { + "one": "CERCHI {spacing} MN", + "many": "CERCHI {spacing} MN", + "other": "CERCHI {spacing} MN" + }, "{count} CONTACTS": { "one": "{count} CONTATTO", "many": "{count} DI CONTATTI", @@ -3184,7 +3212,6 @@ "+ CAPTURE SHOT": "+ CATTURA SCATTO", "Add the current view, style and layers as the next shot": "Aggiungi la vista, lo stile e i livelli attuali come scatto successivo", "Replace the selected shot with the current view": "Sostituisci lo scatto selezionato con la vista attuale", - "Click a shot to select it, double-click to rename.": "Fai clic su uno scatto per selezionarlo, doppio clic per rinominarlo.", "Play from this scene through the rest of the project": "Riproduci da questa scena fino alla fine del progetto", "Stop playback (Esc)": "Interrompi la riproduzione (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Riproduci lo scatto dopo quello selezionato, passando alla scena successiva se serve", @@ -3197,6 +3224,7 @@ "Left panels": "Pannelli a sinistra", "Right panels": "Pannelli a destra", "CONFIRMED": "CONFERMATA", + "sightings filter|CONFIRMED": "CONFERMATI", "PAD / RTLS": "RAMPA / RTLS", "fire confidence filter|All": "Tutti", "fire confidence filter|Nominal+": "Nominale+", @@ -3463,7 +3491,11 @@ "Photo of {name}": "Foto di {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Avvistamenti nella vista: {count}", + "{count} sightings in view": { + "one": "{count} avvistamento nella vista", + "many": "{count} di avvistamenti nella vista", + "other": "{count} avvistamenti nella vista" + }, "Close sighting": "Chiudi avvistamento", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Fauna osservata nelle ultime 48 h (cetacei 7 giorni). Colore e simbolo del contrassegno indicano il gruppo tassonomico. Le specie sensibili sono mostrate solo in celle di 0,2°; le segnalazioni di mammiferi marini di Acartia nel mar dei Salish sono arrotondate a 0,01°. Non è un censimento.", "Open {name} on iNaturalist": "Apri {name} su iNaturalist", @@ -3474,20 +3506,31 @@ "{days}d": "{days} g", "All markers": "Tutti i marcatori", "Show markers of every age": "Mostra i marcatori di qualsiasi età", - "Maximum event age: {days}d; undated markers are kept": "Età massima degli eventi: {days} g; marcatori senza data mantenuti", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Età massima degli eventi: {days} giorno; marcatori senza data mantenuti", + "many": "Età massima degli eventi: {days} di giorni; marcatori senza data mantenuti", + "other": "Età massima degli eventi: {days} giorni; marcatori senza data mantenuti" + }, "event age filter|All": "Tutti", "Event age": "Età degli eventi", - "Event age: {days}d · undated kept": "Età degli eventi: {days} g · senza data mantenuti", + "Event age: {days}d · undated kept": { + "one": "Età degli eventi: {days} giorno · senza data mantenuti", + "many": "Età degli eventi: {days} di giorni · senza data mantenuti", + "other": "Età degli eventi: {days} giorni · senza data mantenuti" + }, "Close camera preview": "Chiudi anteprima della telecamera", "Refresh map still": "Aggiorna immagine fissa sulla mappa", "The map still uses a separate request and may show a different moment.": "L'immagine sulla mappa usa una richiesta separata e può mostrare un momento diverso.", "Video plays from Québec 511, which sees your IP address.": "Il video viene riprodotto da Québec 511, che vede il tuo indirizzo IP.", "Press OPEN to load the photo": "Premi APRI per caricare la foto", "Captured {month}": "Scattata: {month}", - "this spot": "questo punto", "the view centre": "il centro della vista", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} in questo punto", + "{source} at the view centre": "{source} al centro della vista", "Street level at {place}": "Vista stradale: {place}", + "Street level at this spot": "Vista stradale in questo punto", + "Street level at the view centre": "Vista stradale al centro della vista", "Switching map": "Cambio mappa", "Opening imagery": "Apertura delle immagini", "Street View is ready: press {open} to load it": "Street View è pronto: premi {open} per caricarlo", @@ -3681,7 +3724,11 @@ "REMOVE ALL": "RIMUOVI TUTTO", "Confirm: remove every added entry from Data Layers": "Conferma: rimuovi da Livelli dati tutte le voci aggiunte", "Remove every added entry from Data Layers": "Rimuovi da Livelli dati tutte le voci aggiunte", - "Showing {shown} of {total}": "Mostrati: {shown} su {total}", + "Showing {shown} of {total}": { + "one": "{shown} di {total} mostrata", + "many": "{shown} di {total} mostrate", + "other": "{shown} di {total} mostrate" + }, "BROWSE DATA LIBRARY": "ESPLORA LIBRERIA DATI", "Atmosphere": "Atmosfera", "Day and night": "Giorno e notte", @@ -4188,5 +4235,11 @@ "KT": "KT", "Course to {code}: {course}": "Rotta verso {code}: {course}", "Over {place}": "Sopra {place}", - "Below": "Sotto" + "Below": "Sotto", + "Go to this shot. Double-click to rename.": "Vai a questo scatto. Doppio clic per rinominare.", + "Move up": "Sposta su", + "Move down": "Sposta giù", + "Click a shot to go to it, double-click to rename.": "Fai clic su uno scatto per andarci, doppio clic per rinominarlo.", + "Back to live at the starting view": "Torna alla diretta nella vista iniziale", + "Exit cockpit to fly to a bike share city": "Esci dalla cabina per volare verso una città con bike sharing" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 1ad167a3ee..d888830101 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -62,8 +62,12 @@ "{severity} only": "{severity}のみ", "All categories": "すべてのカテゴリ", "Reading the news…": "ニュースを読み込み中…", - "News, last {hours} hours": "直近{hours}時間のニュース", - "Last {hours} h": "直近{hours}時間", + "News, last {hours} hours": { + "other": "直近{hours}時間のニュース" + }, + "Last {hours} h": { + "other": "直近{hours}時間" + }, "Time window": "期間", "Conflicts": "紛争", "Local": "ローカル", @@ -72,9 +76,13 @@ "Hotspots": "ホットスポット", "Severity": "深刻度", "Category": "カテゴリ", - "Nothing reported near here in the last {hours} h": "直近{hours}時間、この付近の報道はありません", + "Nothing reported near here in the last {hours} h": { + "other": "直近{hours}時間、この付近の報道はありません" + }, "Latest news": "最新ニュース", - "No news matches these filters in the last {hours} h": "直近{hours}時間で条件に合うニュースはありません", + "No news matches these filters in the last {hours} h": { + "other": "直近{hours}時間で条件に合うニュースはありません" + }, "Load older news": "以前のニュースを読み込む", "How to read the map": "地図の見方", "Colour: severity · icon: type of event": "色:深刻度 · アイコン:出来事の種類", @@ -119,6 +127,10 @@ "Fast jet": "高速ジェット機", "Business jet": "ビジネスジェット", "Drone": "ドローン", + "Airport vehicle": "空港車両", + "Ground station / obstacle": "地上局 / 障害物", + "Airport vehicles": "空港車両", + "Ground stations / obstacles": "地上局 / 障害物", "General emergency": "緊急事態", "Unlawful interference": "不法妨害", "Radio failure": "通信機故障", @@ -560,6 +572,7 @@ "Previous — prior visited contact in the 250 km window": "前へ:250 km圏内で直前に訪れたコンタクト", "PREVIOUS": "前へ", "FOCUS": "フォーカス", + "site status|FOCUS": "フォーカス", "Next — nearest unvisited contact in the 250 km window": "次へ:250 km圏内で最も近い未訪問のコンタクト", "NEXT": "次へ", "Named areas ({n})": "名前付きエリア({n})", @@ -1771,7 +1784,9 @@ "ROUTE DATA UNAVAILABLE": "経路データなし", "CONTACT NAVIGATION OFF": "コンタクトナビゲーション オフ", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "ブリッジは選択中の船舶に固定", - "{range} NM": "{range}海里", + "{range} NM": { + "other": "{range}海里" + }, "AIS DESTINATION · CREW REPORTED": "AIS目的地 · 乗組員入力", "DEST {bearing}": "目的地 {bearing}", "Disable cockpit weather effects": "コックピットの天候エフェクトを無効にする", @@ -1817,6 +1832,7 @@ "Reclassify as TR-3B": "TR-3Bに再分類", "TRACK ACQUIRED": "追跡開始", "{label} · COURSE {heading}°": "{label} · 対地針路 {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · 対地針路 {heading}°", "{label} · HEADING {heading}°": "{label} · 船首方位 {heading}°", "{label} · NO HEADING": "{label} · 船首方位なし", "{label} · NADIR VIEW": "{label} · 直下視", @@ -2070,7 +2086,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "ラジオのライフサイクルが不明確です。有効化または無効化で再調整してください", "Clear reading": "読み取り値を消去", "Observed history": "観測履歴", - "Latest": "最新", + "news list|Latest": "最新", "Imagery on Esri · Google 3D returns when cleared": "画像はEsri上に表示 · 消去するとGoogle 3Dに戻ります", "Point the camera at the ground to use the view": "このビューを使うにはカメラを地面に向けてください", "That point cannot anchor a box": "その地点は範囲の基点にできません", @@ -2174,9 +2190,7 @@ "SPARSE": "低密度", "BALANCED": "標準", "No shots yet. Use CAPTURE SHOT to save current look.": "ショットはまだありません。[ショット取得]で現在の表示を保存してください。", - "Double-click to rename": "ダブルクリックで名前を変更", "Shot name": "ショット名", - "LOAD": "読込", "DEL": "削除", "{duration}s + {hold}s": "{duration}秒 + {hold}秒", "Choose files": "ファイルを選択", @@ -2720,7 +2734,9 @@ "Contact cockpit summary": "コンタクトのコックピット概要", "CONTACT": "コンタクト", "CONTACTS · 250 KM": "コンタクト · 250 km", - "RINGS {spacing} NM": "距離環 {spacing}海里", + "RINGS {spacing} NM": { + "other": "距離環 {spacing}海里" + }, "{count} CONTACTS": { "other": "コンタクト {count}件" }, @@ -3034,7 +3050,6 @@ "+ CAPTURE SHOT": "+ ショット取得", "Add the current view, style and layers as the next shot": "現在の視点・スタイル・レイヤーを次のショットとして追加", "Replace the selected shot with the current view": "選択中のショットを現在の視点で置き換え", - "Click a shot to select it, double-click to rename.": "ショットをクリックして選択、ダブルクリックで名前を変更します。", "Play from this scene through the rest of the project": "このシーンからプロジェクトの最後まで再生", "Stop playback (Esc)": "再生を停止(Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "選択中のショットの次を再生(必要に応じて次のシーンへ進む)", @@ -3047,6 +3062,7 @@ "Left panels": "左パネル", "Right panels": "右パネル", "CONFIRMED": "確認済み", + "sightings filter|CONFIRMED": "確認済み", "PAD / RTLS": "射場 / RTLS", "fire confidence filter|All": "すべて", "fire confidence filter|Nominal+": "中以上", @@ -3301,7 +3317,9 @@ "Photo of {name}": "{name}の写真", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "表示範囲に{count}件の目撃情報", + "{count} sightings in view": { + "other": "表示範囲に{count}件の目撃情報" + }, "Close sighting": "目撃情報を閉じる", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "過去48時間以内に観察された野生生物(クジラ類は7日間)。色とバッジのアイコンは分類群を表します。保護が必要な種は0.2°のセルとしてのみ表示し、セイリッシュ海のAcartiaによる海生哺乳類の目撃情報は0.01°に丸めます。個体数調査ではありません。", "Open {name} on iNaturalist": "iNaturalistで{name}を開く", @@ -3312,20 +3330,27 @@ "{days}d": "{days}日", "All markers": "すべてのマーカー", "Show markers of every age": "日付にかかわらずすべてのマーカーを表示", - "Maximum event age: {days}d; undated markers are kept": "イベントの最大経過日数:{days}日。日付のないマーカーは保持", + "Maximum event age: {days}d; undated markers are kept": { + "other": "イベントの最大経過日数:{days}日。日付のないマーカーは保持" + }, "event age filter|All": "すべて", "Event age": "経過日数", - "Event age: {days}d · undated kept": "経過日数:{days}日以内 · 日付なしは保持", + "Event age: {days}d · undated kept": { + "other": "経過日数:{days}日以内 · 日付なしは保持" + }, "Close camera preview": "カメラのプレビューを閉じる", "Refresh map still": "地図上の静止画を更新", "The map still uses a separate request and may show a different moment.": "地図上の静止画は別のリクエストで取得されるため、異なる時点を表示する場合があります。", "Video plays from Québec 511, which sees your IP address.": "動画はQuébec 511から再生され、お使いのIPアドレスはQuébec 511側から見えます。", "Press OPEN to load the photo": "[開く]を押して写真を読み込む", "Captured {month}": "{month}撮影", - "this spot": "この地点", "the view centre": "表示中心", "{source} at {place}": "{place}の{source}", + "{source} at this spot": "この地点の{source}", + "{source} at the view centre": "表示中心の{source}", "Street level at {place}": "{place}のストリートレベル", + "Street level at this spot": "この地点のストリートレベル", + "Street level at the view centre": "表示中心のストリートレベル", "Switching map": "地図を切り替え中", "Opening imagery": "画像を開いています", "Street View is ready: press {open} to load it": "ストリートビューの準備ができました:[{open}]を押して読み込んでください", @@ -3507,7 +3532,9 @@ "REMOVE ALL": "すべて削除", "Confirm: remove every added entry from Data Layers": "確認:追加したすべての項目をデータレイヤーから削除", "Remove every added entry from Data Layers": "追加したすべての項目をデータレイヤーから削除", - "Showing {shown} of {total}": "{total}件中{shown}件を表示", + "Showing {shown} of {total}": { + "other": "{total}件中{shown}件を表示" + }, "BROWSE DATA LIBRARY": "データライブラリを見る", "Atmosphere": "大気", "Day and night": "昼と夜", @@ -4002,5 +4029,11 @@ "KT": "KT", "Course to {code}: {course}": "{code}への針路: {course}", "Over {place}": "{place}上空", - "Below": "直下" + "Below": "直下", + "Go to this shot. Double-click to rename.": "このショットへ移動。ダブルクリックで名前を変更。", + "Move up": "上へ移動", + "Move down": "下へ移動", + "Click a shot to go to it, double-click to rename.": "ショットをクリックしてそこへ移動、ダブルクリックで名前を変更します。", + "Back to live at the starting view": "ライブに戻り、最初の表示へ", + "Exit cockpit to fly to a bike share city": "シェアサイクルのある都市へ移動するにはコックピットを終了してください" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 9701b55eef..fb8db96a34 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -68,8 +68,16 @@ "{severity} only": "Apenas {severity}", "All categories": "Todas as categorias", "Reading the news…": "Lendo as notícias…", - "News, last {hours} hours": "Notícias de até {hours} h atrás", - "Last {hours} h": "Até {hours} h atrás", + "News, last {hours} hours": { + "one": "Notícias da última {hours} hora", + "many": "Notícias das últimas {hours} de horas", + "other": "Notícias das últimas {hours} horas" + }, + "Last {hours} h": { + "one": "Última {hours} h", + "many": "Últimas {hours} h", + "other": "Últimas {hours} h" + }, "Time window": "Período", "Conflicts": "Conflitos", "Local": "Local", @@ -78,9 +86,17 @@ "Hotspots": "Focos", "Severity": "Gravidade", "Category": "Categoria", - "Nothing reported near here in the last {hours} h": "Nada noticiado aqui perto desde {hours} h atrás", + "Nothing reported near here in the last {hours} h": { + "one": "Nada noticiado aqui perto na última {hours} h", + "many": "Nada noticiado aqui perto nas últimas {hours} h", + "other": "Nada noticiado aqui perto nas últimas {hours} h" + }, "Latest news": "Últimas notícias", - "No news matches these filters in the last {hours} h": "Nenhuma notícia de até {hours} h atrás corresponde a estes filtros", + "No news matches these filters in the last {hours} h": { + "one": "Nenhuma notícia da última {hours} h corresponde a estes filtros", + "many": "Nenhuma notícia das últimas {hours} h corresponde a estes filtros", + "other": "Nenhuma notícia das últimas {hours} h corresponde a estes filtros" + }, "Load older news": "Carregar notícias anteriores", "How to read the map": "Como ler o mapa", "Colour: severity · icon: type of event": "Cor: gravidade · ícone: tipo de evento", @@ -127,6 +143,10 @@ "Fast jet": "Jato de alto desempenho", "Business jet": "Jato executivo", "Drone": "Drone", + "Airport vehicle": "Veículo de aeroporto", + "Ground station / obstacle": "Estação terrestre / obstáculo", + "Airport vehicles": "Veículos de aeroporto", + "Ground stations / obstacles": "Estações terrestres / obstáculos", "General emergency": "Emergência geral", "Unlawful interference": "Interferência ilícita", "Radio failure": "Falha de rádio", @@ -580,6 +600,7 @@ "Previous — prior visited contact in the 250 km window": "Anterior — contato visitado anteriormente na janela de 250 km", "PREVIOUS": "ANT.", "FOCUS": "FOCAR", + "site status|FOCUS": "FOCO", "Next — nearest unvisited contact in the 250 km window": "Próximo — contato não visitado mais próximo na janela de 250 km", "NEXT": "PRÓX.", "Named areas ({n})": "Áreas com nome ({n})", @@ -933,7 +954,7 @@ "ORBITAL VELOCITY": "VELOCIDADE ORBITAL", "SUB-SATELLITE POINT": "PONTO SUBSATÉLITE", "NORTH UP": "NORTE PARA CIMA", - "CURRENTLY OVER": "SOBREVOANDO AGORA", + "CURRENTLY OVER": "SOBREVOO", "{division}, {country}": "{division}, {country}", "{region} · near {place}": "{region} · perto de {place}", "NORAD {id}": "NORAD {id}", @@ -1827,7 +1848,11 @@ "ROUTE DATA UNAVAILABLE": "DADOS DE ROTA INDISPONÍVEIS", "CONTACT NAVIGATION OFF": "NAVEGAÇÃO DE CONTATOS DESLIGADA", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "O PASSADIÇO PERMANECE NA EMBARCAÇÃO SELECIONADA", - "{range} NM": "{range} MN", + "{range} NM": { + "one": "{range} MN", + "many": "{range} MN", + "other": "{range} MN" + }, "AIS DESTINATION · CREW REPORTED": "DESTINO AIS · INFORMADO PELA TRIPULAÇÃO", "DEST {bearing}": "DEST {bearing}", "Disable cockpit weather effects": "Desativar efeitos de clima na cabine", @@ -1874,7 +1899,8 @@ "Restore real aircraft": "Restaurar a aeronave real", "Reclassify as TR-3B": "Reclassificar como TR-3B", "TRACK ACQUIRED": "RASTRO ADQUIRIDO", - "{label} · COURSE {heading}°": "{label} · RUMO {heading}°", + "{label} · COURSE {heading}°": "{label} · CURSO {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · RUMO {heading}°", "{label} · HEADING {heading}°": "{label} · PROA {heading}°", "{label} · NO HEADING": "{label} · SEM PROA", "{label} · NADIR VIEW": "{label} · VISTA AO NADIR", @@ -2144,7 +2170,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "O ciclo de vida do rádio é incerto — use Ativar ou Desativar para reconciliar", "Clear reading": "Limpar leitura", "Observed history": "Histórico observado", - "Latest": "Mais recente", + "news list|Latest": "Mais recentes", "Imagery on Esri · Google 3D returns when cleared": "Imagens sobre o Esri · LIMPAR restaura o Google 3D", "Point the camera at the ground to use the view": "Aponte a câmera para o chão para usar a vista", "That point cannot anchor a box": "Esse ponto não pode ancorar uma área", @@ -2250,9 +2276,7 @@ "SPARSE": "ESPARSO", "BALANCED": "EQUILIBRADO", "No shots yet. Use CAPTURE SHOT to save current look.": "Ainda não há planos. Use CAPTURAR PLANO para salvar o visual atual.", - "Double-click to rename": "Clique duplo para renomear", "Shot name": "Nome do plano", - "LOAD": "CARREGAR", "DEL": "EXCL.", "{duration}s + {hold}s": "{duration} s + {hold} s", "Choose files": "Escolher arquivos", @@ -2872,7 +2896,11 @@ "Contact cockpit summary": "Resumo do contato na cabine", "CONTACT": "CONTATO", "CONTACTS · 250 KM": "CONTATOS · 250 KM", - "RINGS {spacing} NM": "ANÉIS {spacing} MN", + "RINGS {spacing} NM": { + "one": "ANÉIS {spacing} MN", + "many": "ANÉIS {spacing} MN", + "other": "ANÉIS {spacing} MN" + }, "{count} CONTACTS": { "one": "{count} CONTATO", "many": "{count} DE CONTATOS", @@ -3184,7 +3212,6 @@ "+ CAPTURE SHOT": "+ CAPTURAR PLANO", "Add the current view, style and layers as the next shot": "Adicionar a vista, o estilo e as camadas atuais como próximo plano", "Replace the selected shot with the current view": "Substituir o plano selecionado pela vista atual", - "Click a shot to select it, double-click to rename.": "Clique em um plano para selecioná-lo e clique duas vezes para renomeá-lo.", "Play from this scene through the rest of the project": "Reproduzir desta cena até o fim do projeto", "Stop playback (Esc)": "Parar a reprodução (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Reproduzir o plano após o selecionado, passando à próxima cena se necessário", @@ -3197,6 +3224,7 @@ "Left panels": "Painéis à esquerda", "Right panels": "Painéis à direita", "CONFIRMED": "CONFIRMADA", + "sightings filter|CONFIRMED": "CONFIRMADOS", "PAD / RTLS": "PLATAFORMA / RTLS", "fire confidence filter|All": "Todas", "fire confidence filter|Nominal+": "Nominal+", @@ -3463,7 +3491,11 @@ "Photo of {name}": "Foto de {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Avistamentos na vista: {count}", + "{count} sightings in view": { + "one": "{count} avistamento na vista", + "many": "{count} de avistamentos na vista", + "other": "{count} avistamentos na vista" + }, "Close sighting": "Fechar avistamento", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Vida selvagem observada nas últimas 48 h (cetáceos 7 dias). A cor e o símbolo do emblema indicam o grupo taxonômico. Espécies sensíveis aparecem apenas em células de 0,2°; os relatos de mamíferos marinhos do mar de Salish via Acartia são arredondados para 0,01°. Não é um censo.", "Open {name} on iNaturalist": "Abrir {name} no iNaturalist", @@ -3474,20 +3506,31 @@ "{days}d": "{days} d", "All markers": "Todos os marcadores", "Show markers of every age": "Mostrar marcadores de qualquer idade", - "Maximum event age: {days}d; undated markers are kept": "Idade máxima do evento: {days} d; marcadores sem data são mantidos", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Idade máxima do evento: {days} dia; marcadores sem data são mantidos", + "many": "Idade máxima do evento: {days} de dias; marcadores sem data são mantidos", + "other": "Idade máxima do evento: {days} dias; marcadores sem data são mantidos" + }, "event age filter|All": "Todos", "Event age": "Idade do evento", - "Event age: {days}d · undated kept": "Idade do evento: {days} d · sem data mantidos", + "Event age: {days}d · undated kept": { + "one": "Idade do evento: {days} dia · sem data mantidos", + "many": "Idade do evento: {days} de dias · sem data mantidos", + "other": "Idade do evento: {days} dias · sem data mantidos" + }, "Close camera preview": "Fechar prévia da câmera", "Refresh map still": "Atualizar imagem fixa no mapa", "The map still uses a separate request and may show a different moment.": "A imagem no mapa usa uma solicitação separada e pode mostrar outro momento.", "Video plays from Québec 511, which sees your IP address.": "O vídeo é reproduzido a partir do Québec 511, que vê o seu endereço IP.", "Press OPEN to load the photo": "Clique em ABRIR para carregar a foto", "Captured {month}": "Capturada em {month}", - "this spot": "este ponto", "the view centre": "o centro da vista", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} neste ponto", + "{source} at the view centre": "{source} no centro da vista", "Street level at {place}": "Nível da rua: {place}", + "Street level at this spot": "Nível da rua neste ponto", + "Street level at the view centre": "Nível da rua no centro da vista", "Switching map": "Mudando de mapa", "Opening imagery": "Abrindo imagens", "Street View is ready: press {open} to load it": "O Street View está pronto: clique em {open} para carregar", @@ -3681,7 +3724,11 @@ "REMOVE ALL": "REMOVER TUDO", "Confirm: remove every added entry from Data Layers": "Confirmar: remover de \"Camadas de dados\" todas as entradas adicionadas", "Remove every added entry from Data Layers": "Remover de \"Camadas de dados\" todas as entradas adicionadas", - "Showing {shown} of {total}": "Mostrando {shown} de {total}", + "Showing {shown} of {total}": { + "one": "Mostrando {shown} de {total}", + "many": "Mostrando {shown} de {total}", + "other": "Mostrando {shown} de {total}" + }, "BROWSE DATA LIBRARY": "EXPLORAR BIBLIOTECA DE DADOS", "Atmosphere": "Atmosfera", "Day and night": "Dia e noite", @@ -4188,5 +4235,11 @@ "KT": "KT", "Course to {code}: {course}": "Rumo para {code}: {course}", "Over {place}": "Sobre {place}", - "Below": "Abaixo" + "Below": "Abaixo", + "Go to this shot. Double-click to rename.": "Ir para este plano. Clique duplo para renomear.", + "Move up": "Mover para cima", + "Move down": "Mover para baixo", + "Click a shot to go to it, double-click to rename.": "Clique em um plano para ir até ele e clique duas vezes para renomeá-lo.", + "Back to live at the starting view": "Voltar ao vivo na vista inicial", + "Exit cockpit to fly to a bike share city": "Saia do cockpit para voar até uma cidade com bicicletas compartilhadas" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 64fbd8153b..bd2171f4ee 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -71,8 +71,18 @@ "{severity} only": "Только: {severity}", "All categories": "Все категории", "Reading the news…": "Читаем новости…", - "News, last {hours} hours": "Новости за последние {hours} ч", - "Last {hours} h": "За {hours} ч", + "News, last {hours} hours": { + "one": "Новости за последний {hours} час", + "few": "Новости за последние {hours} часа", + "many": "Новости за последние {hours} часов", + "other": "Новости за последние {hours} часа" + }, + "Last {hours} h": { + "one": "За {hours} ч", + "few": "За {hours} ч", + "many": "За {hours} ч", + "other": "За {hours} ч" + }, "Time window": "Период", "Conflicts": "Конфликты", "Local": "Местные", @@ -81,9 +91,19 @@ "Hotspots": "Горячие точки", "Severity": "Тяжесть", "Category": "Категория", - "Nothing reported near here in the last {hours} h": "За последние {hours} ч поблизости ничего не сообщалось", + "Nothing reported near here in the last {hours} h": { + "one": "За последний {hours} ч поблизости ничего не сообщалось", + "few": "За последние {hours} ч поблизости ничего не сообщалось", + "many": "За последние {hours} ч поблизости ничего не сообщалось", + "other": "За последние {hours} ч поблизости ничего не сообщалось" + }, "Latest news": "Последние новости", - "No news matches these filters in the last {hours} h": "За последние {hours} ч нет новостей по этим фильтрам", + "No news matches these filters in the last {hours} h": { + "one": "За последний {hours} ч нет новостей по этим фильтрам", + "few": "За последние {hours} ч нет новостей по этим фильтрам", + "many": "За последние {hours} ч нет новостей по этим фильтрам", + "other": "За последние {hours} ч нет новостей по этим фильтрам" + }, "Load older news": "Загрузить более ранние новости", "How to read the map": "Как читать карту", "Colour: severity · icon: type of event": "Цвет: тяжесть · значок: тип события", @@ -178,6 +198,7 @@ "Previous — prior visited contact in the 250 km window": "Назад — предыдущий посещённый контакт в радиусе 250 км", "PREVIOUS": "ПРЕД.", "FOCUS": "ФОКУС", + "site status|FOCUS": "ФОКУС", "Next — nearest unvisited contact in the 250 km window": "Далее — ближайший непосещённый контакт в радиусе 250 км", "NEXT": "СЛЕД.", "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Контекст из открытых источников. Отсутствие трансляций, незагруженные области карты или неотмеченные объекты — не доказательство отсутствия.", @@ -345,6 +366,7 @@ "Cancel replay": "Отменить повтор", "EST. DOWNRANGE": "РАСЧЁТ ПО ТРАССЕ", "CONFIRMED": "ПОДТВЕРЖДЕНО", + "sightings filter|CONFIRMED": "ПОДТВЕРЖДЕНО", "PAD / RTLS": "ПЛОЩАДКА / RTLS", "PLANNED · ": "ПЛАН · ", "SUPPLIED TRAJECTORY POINTS": "ПРЕДОСТАВЛЕННЫЕ ТОЧКИ ТРАЕКТОРИИ", @@ -546,7 +568,12 @@ "ROUTE DATA UNAVAILABLE": "ДАННЫЕ МАРШРУТА НЕДОСТУПНЫ", "CONTACT NAVIGATION OFF": "НАВИГАЦИЯ ПО КОНТАКТАМ ВЫКЛЮЧЕНА", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "МОСТИК ОСТАЁТСЯ НА ВЫБРАННОМ СУДНЕ", - "{range} NM": "{range} МОР. МИЛ.", + "{range} NM": { + "one": "{range} МОР. МИЛЯ", + "few": "{range} МОР. МИЛИ", + "many": "{range} МОР. МИЛЬ", + "other": "{range} МОР. МИЛИ" + }, "AIS DESTINATION · CREW REPORTED": "ПУНКТ НАЗНАЧЕНИЯ AIS · УКАЗАН ЭКИПАЖЕМ", "DEST {bearing}": "НАЗН. {bearing}", "Disable cockpit weather effects": "Выключить погодные эффекты кабины", @@ -592,6 +619,7 @@ "Select flight {title}": "Выбрать рейс {title}", "TRACK ACQUIRED": "ЦЕЛЬ ЗАХВАЧЕНА", "{label} · COURSE {heading}°": "{label} · ПУТЕВОЙ УГОЛ {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · ПУТЕВОЙ УГОЛ {heading}°", "{label} · HEADING {heading}°": "{label} · КУРС {heading}°", "{label} · NO HEADING": "{label} · НЕТ КУРСА", "{label} · NADIR VIEW": "{label} · ВИД В НАДИР", @@ -843,7 +871,12 @@ "EXIT BRIDGE": "ВЫЙТИ С МОСТИКА", "EXIT ORBIT": "ВЫЙТИ С ОРБИТЫ", "CONTACTS · 250 KM": "КОНТАКТЫ · 250 КМ", - "RINGS {spacing} NM": "КОЛЬЦА {spacing} МОР. МИЛ.", + "RINGS {spacing} NM": { + "one": "КОЛЬЦА {spacing} МОР. МИЛЯ", + "few": "КОЛЬЦА {spacing} МОР. МИЛИ", + "many": "КОЛЬЦА {spacing} МОР. МИЛЬ", + "other": "КОЛЬЦА {spacing} МОР. МИЛИ" + }, "{count} CONTACTS": { "one": "{count} КОНТАКТ", "few": "{count} КОНТАКТА", @@ -1694,7 +1727,7 @@ "Station unavailable after directory refresh": "Станция недоступна после обновления каталога", "Clear reading": "Очистить показания", "Observed history": "История наблюдений", - "Latest": "Последние", + "news list|Latest": "Последние", "S on another day replaces it · × unpins": "S в другой день заменяет его · × открепляет", "← → preview · S shows the focused day": "← → просмотр · S показывает выбранный день", "Recent imagery": "Свежие снимки", @@ -1788,9 +1821,7 @@ "Export failed · {error}": "Ошибка экспорта · {error}", "← → preview · A or B pins the focused day": "← → просмотр · A или B закрепляет выбранный день", "← → preview the other side · A or B pins it": "← → просмотр другой стороны · A или B закрепляет её", - "LOAD": "ЗАГРУЗИТЬ", "No shots yet. Use CAPTURE SHOT to save current look.": "Кадров пока нет. Нажмите «СДЕЛАТЬ КАДР», чтобы сохранить текущий вид.", - "Double-click to rename": "Дважды щёлкните, чтобы переименовать", "Shot name": "Название кадра", "RETRYING ALPR CAMERAS": "ПОВТОРНАЯ ЗАГРУЗКА КАМЕР ALPR", "FETCHING ALPR CAMERAS": "ЗАГРУЗКА КАМЕР ALPR", @@ -2898,6 +2929,10 @@ "Fast jet": "Высокоманёвренный самолёт", "Business jet": "Бизнес-джет", "Drone": "Беспилотник", + "Airport vehicle": "Аэродромная машина", + "Ground station / obstacle": "Наземная станция / препятствие", + "Airport vehicles": "Аэродромные машины", + "Ground stations / obstacles": "Наземные станции / препятствия", "fire cause|Human": "деятельность человека", "fire cause|Natural": "природная", "fire cause|Undetermined": "не установлена", @@ -3279,7 +3314,6 @@ "+ CAPTURE SHOT": "+ СДЕЛАТЬ КАДР", "Add the current view, style and layers as the next shot": "Добавить текущий вид, стиль и слои следующим кадром", "Replace the selected shot with the current view": "Заменить выбранный кадр текущим видом", - "Click a shot to select it, double-click to rename.": "Щёлкните кадр, чтобы выбрать его, дважды — чтобы переименовать.", "scene|PLAY": "ПУСК", "Stop playback (Esc)": "Остановить воспроизведение (Esc)", "SAVE & SHARE": "СОХРАНЕНИЕ И ОБМЕН", @@ -3544,7 +3578,12 @@ "Photo of {name}": "Фото: {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Наблюдений в кадре: {count}", + "{count} sightings in view": { + "one": "{count} наблюдение в кадре", + "few": "{count} наблюдения в кадре", + "many": "{count} наблюдений в кадре", + "other": "{count} наблюдения в кадре" + }, "Close sighting": "Закрыть наблюдение", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Наблюдения живой природы за 48 ч (китообразные — 7 дней). Цвет и символ значка обозначают таксономическую группу. Уязвимые виды показаны только ячейками 0,2°; сообщения Acartia о морских млекопитающих моря Селиш округлены до 0,01°. Это не учёт численности.", "Open {name} on iNaturalist": "Открыть {name} в iNaturalist", @@ -3555,20 +3594,33 @@ "{days}d": "{days} дн.", "All markers": "Все метки", "Show markers of every age": "Показать метки любого возраста", - "Maximum event age: {days}d; undated markers are kept": "Максимальный возраст события: {days} дн.; метки без даты остаются", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Максимальный возраст события: {days} дн.; метки без даты остаются", + "few": "Максимальный возраст события: {days} дн.; метки без даты остаются", + "many": "Максимальный возраст события: {days} дн.; метки без даты остаются", + "other": "Максимальный возраст события: {days} дн.; метки без даты остаются" + }, "event age filter|All": "Все", "Event age": "Возраст события", - "Event age: {days}d · undated kept": "Возраст события: {days} дн. · метки без даты остаются", + "Event age: {days}d · undated kept": { + "one": "Возраст события: {days} дн. · метки без даты остаются", + "few": "Возраст события: {days} дн. · метки без даты остаются", + "many": "Возраст события: {days} дн. · метки без даты остаются", + "other": "Возраст события: {days} дн. · метки без даты остаются" + }, "Close camera preview": "Закрыть просмотр камеры", "Refresh map still": "Обновить кадр на карте", "The map still uses a separate request and may show a different moment.": "Кадр на карте запрашивается отдельно и может показывать другой момент.", "Video plays from Québec 511, which sees your IP address.": "Видео воспроизводится с Québec 511, который видит ваш IP-адрес.", "Press OPEN to load the photo": "Нажмите ОТКРЫТЬ, чтобы загрузить снимок", "Captured {month}": "Снято: {month}", - "this spot": "эта точка", "the view centre": "центр вида", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} в этой точке", + "{source} at the view centre": "{source} в центре вида", "Street level at {place}": "Уличные снимки: {place}", + "Street level at this spot": "Уличные снимки в этой точке", + "Street level at the view centre": "Уличные снимки в центре вида", "Switching map": "Смена карты", "Opening imagery": "Открытие снимков", "Street View is ready: press {open} to load it": "Просмотр улиц готов: нажмите {open}, чтобы загрузить", @@ -3748,7 +3800,12 @@ "switch on a dataset to load features": "включите набор данных, чтобы загрузить объекты", "Data Library at a glance": "Библиотека данных вкратце", "Map features": "Объекты на карте", - "Showing {shown} of {total}": "Показано {shown} из {total}", + "Showing {shown} of {total}": { + "one": "Показано {shown} из {total}", + "few": "Показано {shown} из {total}", + "many": "Показано {shown} из {total}", + "other": "Показано {shown} из {total}" + }, "Datasets": "Наборы данных", "Themes": "Темы", "zoom in to load this layer": "приблизьте, чтобы загрузить этот слой", @@ -4281,5 +4338,11 @@ "KT": "УЗ", "Course to {code}: {course}": "Курс на {code}: {course}", "Over {place}": "Над: {place}", - "Below": "Под спутником" + "Below": "Под спутником", + "Go to this shot. Double-click to rename.": "Перейти к этому кадру. Дважды щёлкните, чтобы переименовать.", + "Move up": "Переместить вверх", + "Move down": "Переместить вниз", + "Click a shot to go to it, double-click to rename.": "Щёлкните кадр, чтобы перейти к нему, дважды — чтобы переименовать.", + "Back to live at the starting view": "Вернуться в прямой эфир в начальном виде", + "Exit cockpit to fly to a bike share city": "Выйдите из кабины, чтобы перелететь в город с прокатом велосипедов" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index a1c9c13e64..480c92ca35 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -67,18 +67,30 @@ "{severity} and above": "{severity} och uppåt", "{severity} only": "Endast ”{severity}”", "All categories": "Alla kategorier", - "Last {hours} h": "Senaste {hours} h", + "Last {hours} h": { + "one": "Senaste {hours} h", + "other": "Senaste {hours} h" + }, "Reading the news…": "Läser in nyheterna …", - "News, last {hours} hours": "Nyheter, senaste {hours} h", + "News, last {hours} hours": { + "one": "Nyheter, senaste {hours} h", + "other": "Nyheter, senaste {hours} h" + }, "Time window": "Tidsfönster", "News sections": "Nyhetssektioner", "Hotspots": "Oroshärdar", "Severity": "Allvarlighetsgrad", "Category": "Kategori", "Zoom in to see local news": "Zooma in för att se lokala nyheter", - "Nothing reported near here in the last {hours} h": "Inget rapporterat i närheten senaste {hours} h", + "Nothing reported near here in the last {hours} h": { + "one": "Inget rapporterat i närheten senaste {hours} h", + "other": "Inget rapporterat i närheten senaste {hours} h" + }, "Latest news": "Senaste nyheterna", - "No news matches these filters in the last {hours} h": "Inga nyheter matchar filtren senaste {hours} h", + "No news matches these filters in the last {hours} h": { + "one": "Inga nyheter matchar filtren senaste {hours} h", + "other": "Inga nyheter matchar filtren senaste {hours} h" + }, "Load older news": "Ladda äldre nyheter", "How to read the map": "Så läses kartan", "Colour: severity · icon: type of event": "Färg: allvarlighetsgrad · ikon: typ av händelse", @@ -197,6 +209,7 @@ "Previous — prior visited contact in the 250 km window": "Förra – senast besökta kontakt inom 250 km", "PREVIOUS": "FÖRRA", "FOCUS": "FOKUS", + "site status|FOCUS": "FOKUS", "Next — nearest unvisited contact in the 250 km window": "Nästa – närmaste obesökta kontakt inom 250 km", "NEXT": "NÄSTA", "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Kartlagd/observerad kontext från öppna källor. Uteblivna sändningar, kartområden som inte har laddats eller platser som inte är kartlagda bevisar inte att något saknas.", @@ -566,6 +579,7 @@ "Reclassify as TR-3B": "Klassa om som TR-3B", "TRACK ACQUIRED": "SPÅR LÅST", "{label} · COURSE {heading}°": "{label} · FÄRDRIKTNING {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · FÄRDRIKTNING {heading}°", "Context could not restore every layer; try again": "Läget ”Kontext” kunde inte återställa alla lager – försök igen", "No selected data layers": "Inga valda datalager", "{count} data layers could not be cleared": { @@ -982,6 +996,10 @@ "Fast jet": "Stridsflygplan", "Business jet": "Affärsjet", "Drone": "Drönare", + "Airport vehicle": "Flygplatsfordon", + "Ground station / obstacle": "Markstation / hinder", + "Airport vehicles": "Flygplatsfordon", + "Ground stations / obstacles": "Markstationer / hinder", "General emergency": "Allmänt nödläge", "Unlawful interference": "Olagligt ingripande", "Radio failure": "Radiobortfall", @@ -2319,7 +2337,7 @@ "RESUME": "FORTSÄTT", "Clear reading": "Rensa avläsningen", "Observed history": "Observerad historik", - "Latest": "Senaste", + "news list|Latest": "Senaste", "Imagery on Esri · Google 3D returns when cleared": "Bilder på Esri · Google 3D återkommer när de rensas", "Point the camera at the ground to use the view": "Rikta kameran mot marken för att använda vyn", "That point cannot anchor a box": "Den punkten kan inte förankra ett område", @@ -2420,9 +2438,7 @@ "Delete scene \"{scene}\" and all shots?": "Radera scenen ”{scene}” och alla tagningar?", "Stopped (Esc)": "Stoppad (Esc)", "No shots yet. Use CAPTURE SHOT to save current look.": "Inga tagningar än. Använd SPARA TAGNING för att spara nuvarande vy.", - "Double-click to rename": "Dubbelklicka för att byta namn", "Shot name": "Namn på tagning", - "LOAD": "LADDA", "{duration}s + {hold}s": "{duration} s + {hold} s", "Choose files": "Välj filer", "{count} files selected": { @@ -3026,7 +3042,6 @@ "+ CAPTURE SHOT": "+ SPARA TAGNING", "Add the current view, style and layers as the next shot": "Lägg till aktuell vy, stil och lager som nästa tagning", "Replace the selected shot with the current view": "Ersätt vald tagning med aktuell vy", - "Click a shot to select it, double-click to rename.": "Klicka på en tagning för att välja den, dubbelklicka för att byta namn.", "Play from this scene through the rest of the project": "Spela upp från den här scenen genom resten av projektet", "Stop playback (Esc)": "Stoppa uppspelningen (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Spela upp tagningen efter den valda och gå vidare till nästa scen vid behov", @@ -3039,6 +3054,7 @@ "Left panels": "Vänstra paneler", "Right panels": "Högra paneler", "CONFIRMED": "BEKRÄFTAD", + "sightings filter|CONFIRMED": "BEKRÄFTADE", "PAD / RTLS": "RAMP / RTLS", "fire confidence filter|All": "Alla", "fire confidence filter|Nominal+": "Normal+", @@ -3299,7 +3315,10 @@ "Photo of {name}": "Foto av {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Observationer i vyn: {count}", + "{count} sightings in view": { + "one": "{count} observation i vyn", + "other": "{count} observationer i vyn" + }, "Close sighting": "Stäng observationen", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Djur, växter och svampar observerade de senaste 48 h (valar 7 d). Färg och symbol visar artgruppen. Känsliga arter visas bara som rutor på 0,2°; rapporter om marina däggdjur i Salish Sea via Acartia avrundas till 0,01°. Ingen inventering.", "Open {name} on iNaturalist": "Öppna {name} på iNaturalist", @@ -3310,20 +3329,29 @@ "{days}d": "{days} d", "All markers": "Alla markörer", "Show markers of every age": "Visa markörer oavsett ålder", - "Maximum event age: {days}d; undated markers are kept": "Högsta ålder på händelser: {days} d; markörer utan datum behålls", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Högsta ålder på händelser: {days} d; markörer utan datum behålls", + "other": "Högsta ålder på händelser: {days} d; markörer utan datum behålls" + }, "event age filter|All": "Alla", "Event age": "Händelsernas ålder", - "Event age: {days}d · undated kept": "Händelsernas ålder: {days} d · utan datum behålls", + "Event age: {days}d · undated kept": { + "one": "Händelsernas ålder: {days} d · utan datum behålls", + "other": "Händelsernas ålder: {days} d · utan datum behålls" + }, "Close camera preview": "Stäng förhandsvisningen av kameran", "Refresh map still": "Uppdatera stillbilden på kartan", "The map still uses a separate request and may show a different moment.": "Stillbilden på kartan hämtas separat och kan visa ett annat ögonblick.", "Video plays from Québec 511, which sees your IP address.": "Videon spelas upp från Québec 511, som ser din IP-adress.", "Press OPEN to load the photo": "Tryck på ÖPPNA för att ladda fotot", "Captured {month}": "Tagen {month}", - "this spot": "den här platsen", "the view centre": "vyns mitt", "{source} at {place}": "{source} vid {place}", + "{source} at this spot": "{source} på den här platsen", + "{source} at the view centre": "{source} i vyns mitt", "Street level at {place}": "Gatunivå vid {place}", + "Street level at this spot": "Gatunivå på den här platsen", + "Street level at the view centre": "Gatunivå i vyns mitt", "Switching map": "Byter karta", "Opening imagery": "Öppnar bilder", "Street View is ready: press {open} to load it": "Street View är redo: tryck på {open} för att ladda den", @@ -3357,7 +3385,10 @@ "LIVE AIS": "LIVE-AIS", "CONTACT NAVIGATION OFF": "KONTAKTNAVIGERING AV", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "BRYGGAN STANNAR PÅ DET VALDA FARTYGET", - "{range} NM": "{range} NM", + "{range} NM": { + "one": "{range} NM", + "other": "{range} NM" + }, "AIS DESTINATION · CREW REPORTED": "AIS-DESTINATION · ANGIVEN AV BESÄTTNINGEN", "{label} · NADIR VIEW": "{label} · NADIRVY", "SITES STANDBY": "PLATSER I VÄNTLÄGE", @@ -3436,7 +3467,10 @@ "Zoom in (+)": "Zooma in (+)", "Zoom to the imaging sensor swath": "Zooma till sensorns avbildningsstråk", "SENSOR": "SENSOR", - "RINGS {spacing} NM": "RINGAR {spacing} NM", + "RINGS {spacing} NM": { + "one": "RINGAR {spacing} NM", + "other": "RINGAR {spacing} NM" + }, "{count} CONTACTS": { "one": "{count} KONTAKT", "other": "{count} KONTAKTER" @@ -3594,7 +3628,10 @@ "REMOVE ALL": "TA BORT ALLA", "Confirm: remove every added entry from Data Layers": "Bekräfta: ta bort alla tillagda poster från Datalager", "Remove every added entry from Data Layers": "Ta bort alla tillagda poster från Datalager", - "Showing {shown} of {total}": "Visar {shown} av {total}", + "Showing {shown} of {total}": { + "one": "Visar {shown} av {total}", + "other": "Visar {shown} av {total}" + }, "BROWSE DATA LIBRARY": "BLÄDDRA I DATABIBLIOTEKET", "Atmosphere": "Atmosfär", "Day and night": "Dag och natt", @@ -4095,5 +4132,11 @@ "KT": "KT", "Course to {code}: {course}": "Kurs mot {code}: {course}", "Over {place}": "Över {place}", - "Below": "Nedanför" + "Below": "Nedanför", + "Go to this shot. Double-click to rename.": "Gå till den här tagningen. Dubbelklicka för att byta namn.", + "Move up": "Flytta upp", + "Move down": "Flytta ned", + "Click a shot to go to it, double-click to rename.": "Klicka på en tagning för att gå till den, dubbelklicka för att byta namn.", + "Back to live at the starting view": "Tillbaka till live i startvyn", + "Exit cockpit to fly to a bike share city": "Lämna cockpit för att flyga till en stad med lånecyklar" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index fe0a0dd209..afd2ec608e 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -71,8 +71,18 @@ "{severity} only": "Лише {severity}", "All categories": "Усі категорії", "Reading the news…": "Читаємо новини…", - "News, last {hours} hours": "Новини за {hours} год", - "Last {hours} h": "За {hours} год", + "News, last {hours} hours": { + "one": "Новини за останню {hours} годину", + "few": "Новини за останні {hours} години", + "many": "Новини за останні {hours} годин", + "other": "Новини за останні {hours} години" + }, + "Last {hours} h": { + "one": "За {hours} год", + "few": "За {hours} год", + "many": "За {hours} год", + "other": "За {hours} год" + }, "Time window": "Період", "Conflicts": "Конфлікти", "Local": "Місцеві", @@ -81,9 +91,19 @@ "Hotspots": "Гарячі точки", "Severity": "Тяжкість", "Category": "Категорія", - "Nothing reported near here in the last {hours} h": "За {hours} год поблизу нічого не повідомлялося", + "Nothing reported near here in the last {hours} h": { + "one": "За останню {hours} год поблизу нічого не повідомлялося", + "few": "За останні {hours} год поблизу нічого не повідомлялося", + "many": "За останні {hours} год поблизу нічого не повідомлялося", + "other": "За останні {hours} год поблизу нічого не повідомлялося" + }, "Latest news": "Останні новини", - "No news matches these filters in the last {hours} h": "За {hours} год немає новин за цими фільтрами", + "No news matches these filters in the last {hours} h": { + "one": "За останню {hours} год немає новин за цими фільтрами", + "few": "За останні {hours} год немає новин за цими фільтрами", + "many": "За останні {hours} год немає новин за цими фільтрами", + "other": "За останні {hours} год немає новин за цими фільтрами" + }, "Load older news": "Завантажити давніші новини", "How to read the map": "Як читати карту", "Colour: severity · icon: type of event": "Колір: тяжкість · значок: тип події", @@ -131,6 +151,10 @@ "Fast jet": "Швидкісний реактивний літак", "Business jet": "Бізнес-джет", "Drone": "Безпілотник", + "Airport vehicle": "Аеродромний автомобіль", + "Ground station / obstacle": "Наземна станція / перешкода", + "Airport vehicles": "Аеродромні автомобілі", + "Ground stations / obstacles": "Наземні станції / перешкоди", "General emergency": "Загальна аварійна ситуація", "Unlawful interference": "Незаконне втручання", "Radio failure": "Відмова радіозвʼязку", @@ -590,6 +614,7 @@ "Previous — prior visited contact in the 250 km window": "Назад — попередній переглянутий контакт у радіусі 250 км", "PREVIOUS": "НАЗАД", "FOCUS": "ФОКУС", + "site status|FOCUS": "ФОКУС", "Next — nearest unvisited contact in the 250 km window": "Далі — найближчий ще не переглянутий контакт у радіусі 250 км", "NEXT": "ДАЛІ", "Named areas ({n})": "Іменовані зони ({n})", @@ -950,7 +975,7 @@ "ORBITAL VELOCITY": "ОРБІТАЛЬНА ШВИДКІСТЬ", "SUB-SATELLITE POINT": "ПІДСУПУТНИКОВА ТОЧКА", "NORTH UP": "ПІВНІЧ УГОРІ", - "CURRENTLY OVER": "ЗАРАЗ НАД", + "CURRENTLY OVER": "ПРОЛІТ", "{division}, {country}": "{division}, {country}", "{region} · near {place}": "{region} · поблизу: {place}", "NORAD {id}": "NORAD {id}", @@ -1854,7 +1879,12 @@ "ROUTE DATA UNAVAILABLE": "ДАНІ МАРШРУТУ НЕДОСТУПНІ", "CONTACT NAVIGATION OFF": "НАВІГАЦІЮ КОНТАКТАМИ ВИМКНЕНО", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "МІСТОК ЗАЛИШАЄТЬСЯ НА ВИБРАНОМУ СУДНІ", - "{range} NM": "{range} МОР. МИЛ.", + "{range} NM": { + "one": "{range} МОР. МИЛЯ", + "few": "{range} МОР. МИЛІ", + "many": "{range} МОР. МИЛЬ", + "other": "{range} МОР. МИЛІ" + }, "AIS DESTINATION · CREW REPORTED": "ПРИЗНАЧЕННЯ AIS · ВКАЗАНО ЕКІПАЖЕМ", "DEST {bearing}": "ПРИЗН. {bearing}", "Disable cockpit weather effects": "Вимкнути погодні ефекти кабіни", @@ -1903,6 +1933,7 @@ "Reclassify as TR-3B": "Перекласифікувати як TR-3B", "TRACK ACQUIRED": "ТРЕК ЗАХОПЛЕНО", "{label} · COURSE {heading}°": "{label} · ШЛЯХОВИЙ КУТ {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · ШЛЯХОВИЙ КУТ {heading}°", "{label} · HEADING {heading}°": "{label} · КУРС {heading}°", "{label} · NO HEADING": "{label} · НЕМАЄ КУРСУ", "{label} · NADIR VIEW": "{label} · ВИГЛЯД У НАДИР", @@ -2180,7 +2211,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Стан радіо невизначений — звірте через «Увімкнути» або «Вимкнути»", "Clear reading": "Очистити покази", "Observed history": "Історія спостережень", - "Latest": "Останні", + "news list|Latest": "Останні", "Imagery on Esri · Google 3D returns when cleared": "Підкладка: Esri · скидання поверне Google 3D", "Point the camera at the ground to use the view": "Наведіть камеру на землю, щоб вибрати видиму область", "That point cannot anchor a box": "Від цієї точки не можна побудувати область", @@ -2287,9 +2318,7 @@ "SPARSE": "РІДКО", "BALANCED": "ПОМІРНО", "No shots yet. Use CAPTURE SHOT to save current look.": "Кадрів поки немає. Натисніть «ЗНЯТИ КАДР», щоб зберегти поточний вигляд.", - "Double-click to rename": "Двічі клацніть, щоб перейменувати", "Shot name": "Назва кадру", - "LOAD": "ЗАВАНТАЖИТИ", "DEL": "ВИДАЛ.", "{duration}s + {hold}s": "{duration} с + {hold} с", "Choose files": "Вибрати файли", @@ -2944,7 +2973,12 @@ "Contact cockpit summary": "Зведення контакту в кабіні", "CONTACT": "КОНТАКТ", "CONTACTS · 250 KM": "КОНТАКТИ · 250 КМ", - "RINGS {spacing} NM": "КІЛЬЦЯ {spacing} МОР. МИЛ.", + "RINGS {spacing} NM": { + "one": "КІЛЬЦЯ {spacing} МОР. МИЛЯ", + "few": "КІЛЬЦЯ {spacing} МОР. МИЛІ", + "many": "КІЛЬЦЯ {spacing} МОР. МИЛЬ", + "other": "КІЛЬЦЯ {spacing} МОР. МИЛІ" + }, "{count} CONTACTS": { "one": "{count} КОНТАКТ", "few": "{count} КОНТАКТИ", @@ -3272,7 +3306,6 @@ "+ CAPTURE SHOT": "+ ЗНЯТИ КАДР", "Add the current view, style and layers as the next shot": "Додати поточний вигляд, стиль і шари як наступний кадр", "Replace the selected shot with the current view": "Замінити вибраний кадр поточним виглядом", - "Click a shot to select it, double-click to rename.": "Клацніть кадр, щоб вибрати його, двічі — щоб перейменувати.", "Play from this scene through the rest of the project": "Відтворити від цієї сцени до кінця проєкту", "Stop playback (Esc)": "Зупинити відтворення (Esc)", "Play the shot after the selected one, moving on to the next scene when needed": "Відтворити кадр після вибраного, за потреби перейшовши до наступної сцени", @@ -3285,6 +3318,7 @@ "Left panels": "Ліві панелі", "Right panels": "Праві панелі", "CONFIRMED": "ПІДТВЕРДЖЕНО", + "sightings filter|CONFIRMED": "ПІДТВЕРДЖЕНО", "PAD / RTLS": "МІСЦЕ ЗАПУСКУ / RTLS", "Name of {name}": "Назва: {name}", "Change the colour of {name}": "Змінити колір: {name}", @@ -3544,7 +3578,12 @@ "Photo of {name}": "Фото {name}", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "Спостережень у кадрі: {count}", + "{count} sightings in view": { + "one": "{count} спостереження в кадрі", + "few": "{count} спостереження в кадрі", + "many": "{count} спостережень у кадрі", + "other": "{count} спостереження в кадрі" + }, "Close sighting": "Закрити спостереження", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "Спостереження живої природи за 48 год (китоподібні — 7 днів). Колір і символ значка позначають таксономічну групу. Вразливі види показано лише комірками 0,2°; повідомлення Acartia про морських ссавців моря Селіш округлено до 0,01°. Не перепис.", "Open {name} on iNaturalist": "Відкрити {name} в iNaturalist", @@ -3555,20 +3594,33 @@ "{days}d": "{days} дн", "All markers": "Усі мітки", "Show markers of every age": "Показати мітки будь-якого віку", - "Maximum event age: {days}d; undated markers are kept": "Максимальний вік події: {days} дн; мітки без дати залишаються", + "Maximum event age: {days}d; undated markers are kept": { + "one": "Максимальний вік події: {days} дн; мітки без дати залишаються", + "few": "Максимальний вік події: {days} дн; мітки без дати залишаються", + "many": "Максимальний вік події: {days} дн; мітки без дати залишаються", + "other": "Максимальний вік події: {days} дн; мітки без дати залишаються" + }, "event age filter|All": "Усі", "Event age": "Вік події", - "Event age: {days}d · undated kept": "Вік події: {days} дн · мітки без дати залишаються", + "Event age: {days}d · undated kept": { + "one": "Вік події: {days} дн · мітки без дати залишаються", + "few": "Вік події: {days} дн · мітки без дати залишаються", + "many": "Вік події: {days} дн · мітки без дати залишаються", + "other": "Вік події: {days} дн · мітки без дати залишаються" + }, "Close camera preview": "Закрити перегляд камери", "Refresh map still": "Оновити кадр на карті", "The map still uses a separate request and may show a different moment.": "Кадр на карті запитується окремо та може показувати інший момент.", "Video plays from Québec 511, which sees your IP address.": "Відео відтворюється з Québec 511, який бачить вашу IP-адресу.", "Press OPEN to load the photo": "Натисніть «ВІДКРИТИ», щоб завантажити фото", "Captured {month}": "Знято: {month}", - "this spot": "це місце", "the view centre": "центр карти", "{source} at {place}": "{source}: {place}", + "{source} at this spot": "{source} у цьому місці", + "{source} at the view centre": "{source} у центрі карти", "Street level at {place}": "Вуличні знімки: {place}", + "Street level at this spot": "Вуличні знімки в цьому місці", + "Street level at the view centre": "Вуличні знімки в центрі карти", "Switching map": "Перемикання карти", "Opening imagery": "Відкриття знімків", "Street View is ready: press {open} to load it": "Перегляд вулиць готовий: натисніть «{open}», щоб завантажити", @@ -3768,7 +3820,12 @@ "REMOVE ALL": "ВИДАЛИТИ ВСЕ", "Confirm: remove every added entry from Data Layers": "Підтвердити: видалити всі додані записи з «Шарів даних»", "Remove every added entry from Data Layers": "Видалити всі додані записи з «Шарів даних»", - "Showing {shown} of {total}": "Показано {shown} з {total}", + "Showing {shown} of {total}": { + "one": "Показано {shown} з {total}", + "few": "Показано {shown} з {total}", + "many": "Показано {shown} з {total}", + "other": "Показано {shown} з {total}" + }, "BROWSE DATA LIBRARY": "ВІДКРИТИ БІБЛІОТЕКУ ДАНИХ", "Atmosphere": "Атмосфера", "Day and night": "День і ніч", @@ -4281,5 +4338,11 @@ "KT": "ВУЗ", "Course to {code}: {course}": "Курс на {code}: {course}", "Over {place}": "Над: {place}", - "Below": "Під супутником" + "Below": "Під супутником", + "Go to this shot. Double-click to rename.": "Перейти до цього кадру. Двічі клацніть, щоб перейменувати.", + "Move up": "Перемістити вгору", + "Move down": "Перемістити вниз", + "Click a shot to go to it, double-click to rename.": "Клацніть кадр, щоб перейти до нього, двічі — щоб перейменувати.", + "Back to live at the starting view": "Повернутися до прямого ефіру в початковому вигляді", + "Exit cockpit to fly to a bike share city": "Вийдіть із кабіни, щоб перелетіти до міста з прокатом велосипедів" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 9ff0de98b2..4d0b3c0de0 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -62,8 +62,12 @@ "{severity} only": "仅{severity}", "All categories": "所有类别", "Reading the news…": "正在读取新闻…", - "News, last {hours} hours": "最近 {hours} 小时的新闻", - "Last {hours} h": "最近 {hours} 小时", + "News, last {hours} hours": { + "other": "最近 {hours} 小时的新闻" + }, + "Last {hours} h": { + "other": "最近 {hours} 小时" + }, "Time window": "时间范围", "Conflicts": "冲突", "Local": "本地", @@ -72,9 +76,13 @@ "Hotspots": "热点", "Severity": "严重程度", "Category": "类别", - "Nothing reported near here in the last {hours} h": "最近 {hours} 小时附近无报道", + "Nothing reported near here in the last {hours} h": { + "other": "最近 {hours} 小时附近无报道" + }, "Latest news": "最新新闻", - "No news matches these filters in the last {hours} h": "最近 {hours} 小时没有符合这些筛选条件的新闻", + "No news matches these filters in the last {hours} h": { + "other": "最近 {hours} 小时没有符合这些筛选条件的新闻" + }, "Load older news": "加载更早的新闻", "How to read the map": "如何解读地图", "Colour: severity · icon: type of event": "颜色:严重程度 · 图标:事件类型", @@ -119,6 +127,10 @@ "Fast jet": "喷气战机", "Business jet": "公务机", "Drone": "无人机", + "Airport vehicle": "机场车辆", + "Ground station / obstacle": "地面站 / 障碍物", + "Airport vehicles": "机场车辆", + "Ground stations / obstacles": "地面站 / 障碍物", "General emergency": "一般紧急情况", "Unlawful interference": "非法干扰", "Radio failure": "无线电失效", @@ -559,6 +571,7 @@ "Previous — prior visited contact in the 250 km window": "上一个:250 km 范围内先前访问过的目标", "PREVIOUS": "上一个", "FOCUS": "聚焦", + "site status|FOCUS": "聚焦", "Next — nearest unvisited contact in the 250 km window": "下一个:250 km 范围内最近的未访问目标", "NEXT": "下一个", "Named areas ({n})": "已命名区域({n})", @@ -923,6 +936,7 @@ "Cancel replay": "取消回放", "EST. DOWNRANGE": "预估落点距离", "CONFIRMED": "已确认", + "sightings filter|CONFIRMED": "已确认", "PAD / RTLS": "发射台 / RTLS", "PLANNED · ": "计划 · ", "SUPPLIED TRAJECTORY POINTS": "提供的轨迹点", @@ -1745,7 +1759,9 @@ "ROUTE DATA UNAVAILABLE": "航线数据不可用", "CONTACT NAVIGATION OFF": "目标导航已关闭", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "驾驶台保持在所选船舶上", - "{range} NM": "{range} 海里", + "{range} NM": { + "other": "{range} 海里" + }, "AIS DESTINATION · CREW REPORTED": "AIS 目的地 · 船员申报", "DEST {bearing}": "目的地 {bearing}", "Disable cockpit weather effects": "停用座舱天气效果", @@ -1791,6 +1807,7 @@ "Reclassify as TR-3B": "重新归类为 TR-3B", "TRACK ACQUIRED": "已获取航迹", "{label} · COURSE {heading}°": "{label} · 对地航向 {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · 对地航向 {heading}°", "{label} · HEADING {heading}°": "{label} · 船首向 {heading}°", "{label} · NO HEADING": "{label} · 无船首向", "{label} · NADIR VIEW": "{label} · 天底视图", @@ -2040,7 +2057,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "电台生命周期状态不确定——请使用“启用”或“停用”进行核对", "Clear reading": "清除读数", "Observed history": "观测历史", - "Latest": "最新", + "news list|Latest": "最新", "Imagery on Esri · Google 3D returns when cleared": "影像显示在 Esri 底图上 · 清除后恢复 Google 3D", "Point the camera at the ground to use the view": "将相机对准地面才能使用当前视野", "That point cannot anchor a box": "该点无法作为框选锚点", @@ -2144,9 +2161,7 @@ "SPARSE": "稀疏", "BALANCED": "均衡", "No shots yet. Use CAPTURE SHOT to save current look.": "暂无镜头。使用“保存镜头”保存当前视角及设置。", - "Double-click to rename": "双击重命名", "Shot name": "镜头名称", - "LOAD": "加载", "DEL": "删除", "{duration}s + {hold}s": "{duration} 秒 + {hold} 秒", "Choose files": "选择文件", @@ -2619,7 +2634,9 @@ "Contact cockpit summary": "目标座舱摘要", "CONTACT": "目标", "CONTACTS · 250 KM": "目标 · 250 km", - "RINGS {spacing} NM": "距标圈 {spacing} 海里", + "RINGS {spacing} NM": { + "other": "距标圈 {spacing} 海里" + }, "{count} CONTACTS": { "other": "{count} 个目标" }, @@ -3054,7 +3071,6 @@ "+ CAPTURE SHOT": "+ 保存镜头", "Add the current view, style and layers as the next shot": "将当前视角、样式和图层添加为下一个镜头", "Replace the selected shot with the current view": "用当前视角替换所选镜头", - "Click a shot to select it, double-click to rename.": "单击镜头即可选中,双击可重命名。", "scene|PLAY": "播放", "Stop playback (Esc)": "停止播放(Esc)", "SAVE & SHARE": "保存与分享", @@ -3301,7 +3317,9 @@ "Photo of {name}": "{name} 的照片", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "视野内有 {count} 次目击", + "{count} sightings in view": { + "other": "视野内有 {count} 次目击" + }, "Close sighting": "关闭目击记录", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "近 48 小时内观察到的野生生物(鲸类为 7 天)。颜色与徽章图标表示分类群。敏感物种仅以 0.2° 网格显示;Acartia 提供的萨利希海海洋哺乳动物目击位置四舍五入到 0.01°。并非种群普查。", "Open {name} on iNaturalist": "在 iNaturalist 上打开 {name}", @@ -3312,20 +3330,27 @@ "{days}d": "{days} 天", "All markers": "所有标记", "Show markers of every age": "显示所有时间的标记", - "Maximum event age: {days}d; undated markers are kept": "仅显示 {days} 天内的事件;保留无日期标记", + "Maximum event age: {days}d; undated markers are kept": { + "other": "仅显示 {days} 天内的事件;保留无日期标记" + }, "event age filter|All": "全部", "Event age": "事件时间", - "Event age: {days}d · undated kept": "事件时间:{days} 天内 · 保留无日期标记", + "Event age: {days}d · undated kept": { + "other": "事件时间:{days} 天内 · 保留无日期标记" + }, "Close camera preview": "关闭摄像头预览", "Refresh map still": "刷新地图静止画面", "The map still uses a separate request and may show a different moment.": "地图静止画面通过单独的请求获取,可能显示不同的时刻。", "Video plays from Québec 511, which sees your IP address.": "视频从 Québec 511 播放,Québec 511 会看到你的 IP 地址。", "Press OPEN to load the photo": "点击“打开”加载照片", "Captured {month}": "拍摄于 {month}", - "this spot": "此处", "the view centre": "视野中心", "{source} at {place}": "{place} 的 {source}", + "{source} at this spot": "此处的 {source}", + "{source} at the view centre": "视图中心的 {source}", "Street level at {place}": "{place} 的街景", + "Street level at this spot": "此处的街景", + "Street level at the view centre": "视图中心的街景", "Switching map": "正在切换地图", "Opening imagery": "正在打开影像", "Street View is ready: press {open} to load it": "街景已就绪:点击“{open}”加载", @@ -3507,7 +3532,9 @@ "REMOVE ALL": "全部移除", "Confirm: remove every added entry from Data Layers": "确认:从数据图层中移除所有已添加条目", "Remove every added entry from Data Layers": "从数据图层中移除所有已添加条目", - "Showing {shown} of {total}": "显示 {shown} / {total}", + "Showing {shown} of {total}": { + "other": "显示 {shown} / {total}" + }, "BROWSE DATA LIBRARY": "浏览数据资源库", "Atmosphere": "大气", "Day and night": "昼夜", @@ -4002,5 +4029,11 @@ "KT": "kt", "Course to {code}: {course}": "前往 {code} 的航向:{course}", "Over {place}": "{place}上空", - "Below": "下方" + "Below": "下方", + "Go to this shot. Double-click to rename.": "转到此镜头。双击重命名。", + "Move up": "上移", + "Move down": "下移", + "Click a shot to go to it, double-click to rename.": "单击镜头即可转到该镜头,双击可重命名。", + "Back to live at the starting view": "回到实时并返回初始视图", + "Exit cockpit to fly to a bike share city": "退出驾驶舱以飞往有共享单车的城市" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index af2b1f963d..c10cc827f3 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -62,8 +62,12 @@ "{severity} only": "僅{severity}", "All categories": "所有類別", "Reading the news…": "正在讀取新聞…", - "News, last {hours} hours": "最近 {hours} 小時的新聞", - "Last {hours} h": "最近 {hours} 小時", + "News, last {hours} hours": { + "other": "最近 {hours} 小時的新聞" + }, + "Last {hours} h": { + "other": "最近 {hours} 小時" + }, "Time window": "時間範圍", "Conflicts": "衝突", "Local": "本地", @@ -72,9 +76,13 @@ "Hotspots": "熱點", "Severity": "嚴重程度", "Category": "類別", - "Nothing reported near here in the last {hours} h": "最近 {hours} 小時附近無報道", + "Nothing reported near here in the last {hours} h": { + "other": "最近 {hours} 小時附近無報道" + }, "Latest news": "最新新聞", - "No news matches these filters in the last {hours} h": "最近 {hours} 小時沒有符合這些篩選條件的新聞", + "No news matches these filters in the last {hours} h": { + "other": "最近 {hours} 小時沒有符合這些篩選條件的新聞" + }, "Load older news": "加載更早的新聞", "How to read the map": "如何解讀地圖", "Colour: severity · icon: type of event": "顏色:嚴重程度 · 圖標:事件類型", @@ -119,6 +127,10 @@ "Fast jet": "噴氣戰機", "Business jet": "公務機", "Drone": "無人機", + "Airport vehicle": "機場車輛", + "Ground station / obstacle": "地面站 / 障礙物", + "Airport vehicles": "機場車輛", + "Ground stations / obstacles": "地面站 / 障礙物", "General emergency": "一般緊急情況", "Unlawful interference": "非法干擾", "Radio failure": "無線電失效", @@ -559,6 +571,7 @@ "Previous — prior visited contact in the 250 km window": "上一個:250 km 範圍內先前訪問過的目標", "PREVIOUS": "上一個", "FOCUS": "聚焦", + "site status|FOCUS": "聚焦", "Next — nearest unvisited contact in the 250 km window": "下一個:250 km 範圍內最近的未訪問目標", "NEXT": "下一個", "Named areas ({n})": "已命名區域({n})", @@ -608,6 +621,7 @@ "Cyclone advisories unavailable": "氣旋公告不可用", "Cyclone data unavailable": "氣旋數據不可用", "Potential tropical cyclone": "潛在熱帶氣旋", + "Post-tropical cyclone": "後熱帶氣旋", "Hurricane": "颶風", "Tropical storm": "熱帶風暴", "Tropical depression": "熱帶低壓", @@ -705,11 +719,15 @@ "Merge onto {road}": "併入 {road}", "maneuver|Merge": "併道", "Take the ramp on the {direction} onto {road}": "{direction}駛入匝道,進入 {road}", + "Take the ramp {direction} onto {road}": "{direction}駛入匝道,進入 {road}", "Take the ramp on the {direction}": "{direction}駛入匝道", + "Take the ramp {direction}": "{direction}駛入匝道", "Take the ramp onto {road}": "駛入匝道,進入 {road}", "Take the ramp": "駛入匝道", "Take the exit on the {direction} onto {road}": "從出口{direction}駛出,進入 {road}", + "Take the exit {direction} onto {road}": "從出口{direction}駛出,進入 {road}", "Take the exit on the {direction}": "從出口{direction}駛出", + "Take the exit {direction}": "從出口{direction}駛出", "Take the exit onto {road}": "從出口駛出,進入 {road}", "Take the exit": "從出口駛出", "At the roundabout, take the {exit} exit onto {road}": "在環島從{exit}出口駛出,進入 {road}", @@ -918,6 +936,7 @@ "Cancel replay": "取消回放", "EST. DOWNRANGE": "預估落點距離", "CONFIRMED": "已確認", + "sightings filter|CONFIRMED": "已確認", "PAD / RTLS": "發射臺 / RTLS", "PLANNED · ": "計劃 · ", "SUPPLIED TRAJECTORY POINTS": "提供的軌跡點", @@ -1594,6 +1613,9 @@ "LIVE SIGNALS": "實時信號", "CCTV layer unavailable": "CCTV 圖層不可用", "Link copied!": "鏈接已複製!", + "Link shared": "鏈接已分享", + "This share link can't be opened": "無法打開此分享鏈接", + "Shared vessel is unavailable": "分享的船舶不可用", "Copy failed": "複製失敗", "Return map to straight-down view": "將地圖恢復為垂直俯視", "Tilt map to oblique view": "將地圖傾斜至斜視角", @@ -1737,7 +1759,9 @@ "ROUTE DATA UNAVAILABLE": "航線數據不可用", "CONTACT NAVIGATION OFF": "目標導航已關閉", "THE BRIDGE STAYS WITH THE SELECTED VESSEL": "駕駛臺保持在所選船舶上", - "{range} NM": "{range} 海里", + "{range} NM": { + "other": "{range} 海里" + }, "AIS DESTINATION · CREW REPORTED": "AIS 目的地 · 船員申報", "DEST {bearing}": "目的地 {bearing}", "Disable cockpit weather effects": "停用座艙天氣效果", @@ -1783,6 +1807,7 @@ "Reclassify as TR-3B": "重新歸類為 TR-3B", "TRACK ACQUIRED": "已獲取航跡", "{label} · COURSE {heading}°": "{label} · 對地航向 {heading}°", + "vessel|{label} · COURSE {heading}°": "{label} · 對地航向 {heading}°", "{label} · HEADING {heading}°": "{label} · 船首向 {heading}°", "{label} · NO HEADING": "{label} · 無船首向", "{label} · NADIR VIEW": "{label} · 天底視圖", @@ -1947,6 +1972,8 @@ "ORBIT": "環繞", "Location not found": "未找到位置", "Search failed": "搜索失敗", + "Check the spelling and press Enter to search again.": "請檢查拼寫,然後按 Enter 重新搜索。", + "Press Enter to try again.": "按 Enter 重試。", "Detailed outline unavailable": "無法獲取詳細輪廓", "Fly to a POI first": "請先飛往一個 POI", "Reset to full globe view": "重置為完整地球視圖", @@ -2030,7 +2057,7 @@ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "電臺生命週期狀態不確定——請使用“啟用”或“停用”進行核對", "Clear reading": "清除讀數", "Observed history": "觀測歷史", - "Latest": "最新", + "news list|Latest": "最新", "Imagery on Esri · Google 3D returns when cleared": "影像顯示在 Esri 底圖上 · 清除後恢復 Google 3D", "Point the camera at the ground to use the view": "將相機對準地面才能使用當前視野", "That point cannot anchor a box": "該點無法作為框選錨點", @@ -2134,9 +2161,7 @@ "SPARSE": "稀疏", "BALANCED": "均衡", "No shots yet. Use CAPTURE SHOT to save current look.": "暫無鏡頭。使用“保存鏡頭”保存當前視角及設置。", - "Double-click to rename": "雙擊重命名", "Shot name": "鏡頭名稱", - "LOAD": "加載", "DEL": "刪除", "{duration}s + {hold}s": "{duration} 秒 + {hold} 秒", "Choose files": "選擇文件", @@ -2322,7 +2347,7 @@ "Release Space to send": "鬆開空格鍵發送", "Hold Space to talk": "按住空格鍵說話", "Ask or command": "提問或下達指令", - "Voice is disabled in Stories.": "故事模式下語音控制已停用。", + "Voice is disabled in Stories.": "故事模式下語音控制已禁用。", "Voice off": "語音已關閉", "VOICE UNAVAILABLE": "語音不可用", "VOICE ACTIVE": "語音已啟用", @@ -2609,7 +2634,9 @@ "Contact cockpit summary": "目標座艙摘要", "CONTACT": "目標", "CONTACTS · 250 KM": "目標 · 250 km", - "RINGS {spacing} NM": "距標圈 {spacing} 海里", + "RINGS {spacing} NM": { + "other": "距標圈 {spacing} 海里" + }, "{count} CONTACTS": { "other": "{count} 個目標" }, @@ -2967,16 +2994,6 @@ "Search": "搜索", "More": "更多", "Panels": "面板", - "Post-tropical cyclone": "後熱帶氣旋", - "Take the ramp {direction} onto {road}": "{direction}駛入匝道,進入 {road}", - "Take the ramp {direction}": "{direction}駛入匝道", - "Take the exit {direction} onto {road}": "從出口{direction}駛出,進入 {road}", - "Take the exit {direction}": "從出口{direction}駛出", - "Link shared": "鏈接已分享", - "This share link can't be opened": "無法打開此分享鏈接", - "Shared vessel is unavailable": "分享的船舶不可用", - "Check the spelling and press Enter to search again.": "請檢查拼寫,然後按 Enter 重新搜索。", - "Press Enter to try again.": "按 Enter 重試。", "Recent speech": "最近語音", "Voice Settings": "語音設置", "Preview": "預覽", @@ -3015,45 +3032,6 @@ "other": "{count} 個地標" }, "S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.": "S2 Underground 在 GitHub 發布這些 KMZ 產品。新上傳的內容會在數秒內被檢測到,並自動替換舊版本。點擊標記查看報告。", - "routing busy — too many routes at once": "路線服務繁忙:同時請求的路線過多", - "route proxy error": "路線代理出錯", - "{lower} to {upper}": "{lower} 至 {upper}", - "Up to {upper}": "最高 {upper}", - "From {lower}": "最低 {lower}", - "Informational only · not for flight planning": "僅供參考 · 不可用於飛行規劃", - "Unnamed zone": "未命名空域", - "Restricted airspace source unavailable": "禁區與限制區空域數據源不可用", - "Prohibited (P)": "禁區(P)", - "Restricted (R)": "限制區(R)", - "FAA prohibited and restricted special-use airspace only, not the UAS Facility Map or UAS flight restrictions. Informational only — not a substitute for official UAS flight-planning tools (B4UFLY / LAANC).": "僅包含 FAA 禁區和限制區特殊用途空域,不含 UAS Facility Map 和無人機飛行限制。僅供參考,不能替代官方無人機飛行規劃工具(B4UFLY / LAANC)。", - "Prohibited": "禁區", - "Restricted": "限制區", - "Prohibited & Restricted Airspace": "禁區與限制區空域", - "AUTHORING": "創作", - "Create and edit scenes": "創建和編輯場景", - "SCENE": "場景", - "Scene": "場景", - "NEW SCENE": "新建場景", - "Start a new, empty scene": "新建一個空場景", - "DELETE": "刪除", - "Delete this scene and all of its shots": "刪除此場景及其所有鏡頭", - "SHOTS": "鏡頭", - "+ CAPTURE SHOT": "+ 保存鏡頭", - "Add the current view, style and layers as the next shot": "將當前視角、樣式和圖層添加為下一個鏡頭", - "Replace the selected shot with the current view": "用當前視角替換所選鏡頭", - "Click a shot to select it, double-click to rename.": "單擊鏡頭即可選中,雙擊可重命名。", - "scene|PLAY": "播放", - "Stop playback (Esc)": "停止播放(Esc)", - "SAVE & SHARE": "保存與分享", - "Download every scene as a JSON file you can import later": "將所有場景下載為 JSON 文件,以便日後導入", - "Load scenes from an exported JSON file": "從導出的 JSON 文件加載場景", - "Download the timing log of the last play": "下載上次播放的計時日誌", - "Play from this scene through the rest of the project": "從此場景開始播放項目中的其餘場景", - "Play the shot after the selected one, moving on to the next scene when needed": "播放所選鏡頭的下一個鏡頭,必要時進入下一個場景", - "Edit anchors, data packs and shot details": "編輯錨點、數據包和鏡頭詳情", - "Download this scene as JSON or an asset bundle": "將此場景下載為 JSON 或資源包", - "Left panels": "左側面板", - "Right panels": "右側面板", "fire confidence filter|All": "全部", "fire confidence filter|Nominal+": "中+", "fire confidence filter|High": "高", @@ -3067,6 +3045,44 @@ "fire intensity filter|All": "全部", "Detection confidence": "探測置信度", "{shown} of {total} shown": "顯示 {shown} / {total}", + "{lower} to {upper}": "{lower} 至 {upper}", + "Up to {upper}": "最高 {upper}", + "From {lower}": "最低 {lower}", + "Informational only · not for flight planning": "僅供參考 · 不可用於飛行規劃", + "Unnamed zone": "未命名空域", + "Restricted airspace source unavailable": "禁區與限制區空域數據源不可用", + "Prohibited (P)": "禁區(P)", + "Restricted (R)": "限制區(R)", + "FAA prohibited and restricted special-use airspace only, not the UAS Facility Map or UAS flight restrictions. Informational only — not a substitute for official UAS flight-planning tools (B4UFLY / LAANC).": "僅包含 FAA 禁區和限制區特殊用途空域,不含 UAS Facility Map 和無人機飛行限制。僅供參考,不能替代官方無人機飛行規劃工具(B4UFLY / LAANC)。", + "Prohibited": "禁區", + "Restricted": "限制區", + "Prohibited & Restricted Airspace": "禁區與限制區空域", + "routing busy — too many routes at once": "路線服務繁忙:同時請求的路線過多", + "route proxy error": "路線代理出錯", + "AUTHORING": "創作", + "Create and edit scenes": "創建和編輯場景", + "SCENE": "場景", + "Scene": "場景", + "NEW SCENE": "新建場景", + "Start a new, empty scene": "新建一個空場景", + "DELETE": "刪除", + "Delete this scene and all of its shots": "刪除此場景及其所有鏡頭", + "SHOTS": "鏡頭", + "+ CAPTURE SHOT": "+ 保存鏡頭", + "Add the current view, style and layers as the next shot": "將當前視角、樣式和圖層添加為下一個鏡頭", + "Replace the selected shot with the current view": "用當前視角替換所選鏡頭", + "scene|PLAY": "播放", + "Stop playback (Esc)": "停止播放(Esc)", + "SAVE & SHARE": "保存與分享", + "Download every scene as a JSON file you can import later": "將所有場景下載為 JSON 文件,以便日後導入", + "Load scenes from an exported JSON file": "從導出的 JSON 文件加載場景", + "Download the timing log of the last play": "下載上次播放的計時日誌", + "Play from this scene through the rest of the project": "從此場景開始播放項目中的其餘場景", + "Play the shot after the selected one, moving on to the next scene when needed": "播放所選鏡頭的下一個鏡頭,必要時進入下一個場景", + "Edit anchors, data packs and shot details": "編輯錨點、數據包和鏡頭詳情", + "Download this scene as JSON or an asset bundle": "將此場景下載為 JSON 或資源包", + "Left panels": "左側面板", + "Right panels": "右側面板", "UTILITIES": "工具", "Exit cockpit to fly to a drawing": "請先退出座艙,再飛往已繪製的形狀", "Directions, drawing and your own files": "路線導航、繪製和你自己的文件", @@ -3301,7 +3317,9 @@ "Photo of {name}": "{name} 的照片", "Acartia": "Acartia", "CC BY 4.0": "CC BY 4.0", - "{count} sightings in view": "視野內有 {count} 次目擊", + "{count} sightings in view": { + "other": "視野內有 {count} 次目擊" + }, "Close sighting": "關閉目擊記錄", "Wildlife observed within 48 h (whales 7 d). Color and badge glyph show the taxon group. Sensitive species are shown only as 0.2° cells; Salish Sea marine mammal reports via Acartia are rounded to 0.01°. Not a census.": "近 48 小時內觀察到的野生生物(鯨類為 7 天)。顏色與徽章圖標表示分類群。敏感物種僅以 0.2° 網格顯示;Acartia 提供的薩利希海海洋哺乳動物目擊位置四捨五入到 0.01°。並非種群普查。", "Open {name} on iNaturalist": "在 iNaturalist 上打開 {name}", @@ -3312,20 +3330,27 @@ "{days}d": "{days} 天", "All markers": "所有標記", "Show markers of every age": "顯示所有時間的標記", - "Maximum event age: {days}d; undated markers are kept": "僅顯示 {days} 天內的事件;保留無日期標記", + "Maximum event age: {days}d; undated markers are kept": { + "other": "僅顯示 {days} 天內的事件;保留無日期標記" + }, "event age filter|All": "全部", "Event age": "事件時間", - "Event age: {days}d · undated kept": "事件時間:{days} 天內 · 保留無日期標記", + "Event age: {days}d · undated kept": { + "other": "事件時間:{days} 天內 · 保留無日期標記" + }, "Close camera preview": "關閉攝像頭預覽", "Refresh map still": "刷新地圖靜止畫面", "The map still uses a separate request and may show a different moment.": "地圖靜止畫面通過單獨的請求獲取,可能顯示不同的時刻。", "Video plays from Québec 511, which sees your IP address.": "視頻從 Québec 511 播放,Québec 511 會看到你的 IP 地址。", "Press OPEN to load the photo": "點擊“打開”加載照片", "Captured {month}": "拍攝於 {month}", - "this spot": "此處", "the view centre": "視野中心", "{source} at {place}": "{place} 的 {source}", + "{source} at this spot": "此處的 {source}", + "{source} at the view centre": "視圖中心的 {source}", "Street level at {place}": "{place} 的街景", + "Street level at this spot": "此處的街景", + "Street level at the view centre": "視圖中心的街景", "Switching map": "正在切換地圖", "Opening imagery": "正在打開影像", "Street View is ready: press {open} to load it": "街景已就緒:點擊“{open}”加載", @@ -3507,7 +3532,9 @@ "REMOVE ALL": "全部移除", "Confirm: remove every added entry from Data Layers": "確認:從數據圖層中移除所有已添加條目", "Remove every added entry from Data Layers": "從數據圖層中移除所有已添加條目", - "Showing {shown} of {total}": "顯示 {shown} / {total}", + "Showing {shown} of {total}": { + "other": "顯示 {shown} / {total}" + }, "BROWSE DATA LIBRARY": "瀏覽數據資源庫", "Atmosphere": "大氣", "Day and night": "晝夜", @@ -3518,7 +3545,7 @@ "The globe stopped drawing": "地球已停止繪製", "The browser took back the globe's 3D graphics. Layers and controls still work, but the map cannot draw until the page reloads.": "瀏覽器收回了地球的 3D 圖形。圖層和控件仍可使用,但在重新加載頁面之前地圖無法繪製。", "Rendering stopped after an error. Layers and controls still work, but the map is not updating.": "渲染因錯誤而停止。圖層和控件仍可使用,但地圖不再更新。", - "Reset view reloads the app without the view restored from the address bar.": "「重置視圖」會重新加載應用,不使用從地址欄恢復的視圖。", + "Reset view reloads the app without the view restored from the address bar.": "“重置視圖”會重新加載應用,不使用從地址欄恢復的視圖。", "Reload": "重新加載", "Retry": "重試", "Reset view": "重置視圖", @@ -3528,26 +3555,26 @@ "Funicular": "纜索鐵路", "Gondola": "纜車", "Move panels back beside the rail": "將面板移回側欄旁", - "Move panels over the rail, to the edge": "將面板移到側欄上方,貼齊邊緣", + "Move panels over the rail, to the edge": "將面板移到側欄上方,貼靠邊緣", "panel|VISUAL": "視覺", "Look": "外觀", "Overlay": "疊加層", "Effects": "效果", "Scope opacity": "視域不透明度", "How dark the scope shades the view outside the keyhole": "視域遮罩使視域之外的畫面變暗的程度", - "Reset to default": "還原預設", - "Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "將視覺還原為預設設定:常規外觀、HUD、視域、標籤和效果", + "Reset to default": "恢復默認", + "Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "將視覺恢復為默認設置:常規外觀、HUD、視域、標籤和效果", "All layers": "全部圖層", "On": "已開啟", "Off": "已關閉", - "Search layers": "搜尋圖層", + "Search layers": "搜索圖層", "Filter layers": "篩選圖層", "Status": "狀態", - "Search layers…": "搜尋圖層…", + "Search layers…": "搜索圖層…", "Layer groups": "圖層分組", - "Jump to {name}": "跳至{name}", - "No layers match": "沒有符合的圖層", - "A GEV scene, played on the live globe.": "在即時地球上播放的 GEV 場景。", + "Jump to {name}": "跳轉到{name}", + "No layers match": "沒有匹配的圖層", + "A GEV scene, played on the live globe.": "在實時地球上播放的 GEV 場景。", "Drag the map to explore · Resume any time": "拖動地圖進行探索 · 隨時可繼續", "Region": "地區", "Europe": "歐洲", @@ -3583,13 +3610,13 @@ "Filters": "篩選", "Search stories": "搜索故事", "Search stories, places, creators": "搜索故事、地點、創作者", - "Clear search": "清除搜尋", + "Clear search": "清除搜索", "Topics": "主題", "Filter stories": "篩選故事", "Show {count} stories": { "other": "顯示 {count} 個故事" }, - "No stories match": "沒有符合的故事", + "No stories match": "沒有匹配的故事", "Try another word or clear the filters.": "請換個關鍵詞或清除篩選。", "Clear all": "全部清除", "STORY": "故事", @@ -3610,12 +3637,12 @@ "Share": "分享", "Back to GEV": "返回 GEV", "Chapter {n}": "第 {n} 章", - "Context. Swipe up or press to open": "背景資訊。上滑或按下以打開", - "Context. Swipe down or press to close": "背景資訊。下滑或按下以關閉", + "Context. Swipe up or press to open": "背景信息。上滑或按下以打開", + "Context. Swipe down or press to close": "背景信息。下滑或按下以關閉", "Search this story": "在此故事中搜索", - "Voice search (not in this build)": "語音搜索 (此版本不支援)", + "Voice search (not in this build)": "語音搜索 (此版本不支持)", "Search results": "搜索結果", - "Nothing in this story matches.": "此故事中沒有符合項目。", + "Nothing in this story matches.": "此故事中沒有匹配項。", "Chapters": "章節", "now": "現在", "About": "簡介", @@ -3639,25 +3666,25 @@ "Minimise card": "最小化卡片", "Expand card": "展開卡片", "Card pages": "卡片頁面", - "Resize context panel": "調整背景資訊面板大小", - "Swipe up for context": "上滑查看背景資訊", + "Resize context panel": "調整背景信息面板大小", + "Swipe up for context": "上滑查看背景信息", "Chapter start": "章節開始", "Story time": "故事時間", "chapter": "章節", "Key moment: {label}": "關鍵時刻:{label}", "Exit expanded map": "退出放大地圖", "Expand map": "放大地圖", - "Exit cockpit to open Stories": "請先退出座艙,再開啟故事", - "Stories could not load. Check the connection and try again.": "無法載入故事。請檢查網路連線後重試。", + "Exit cockpit to open Stories": "請先退出座艙,再打開故事", + "Stories could not load. Check the connection and try again.": "無法加載故事。請檢查網絡連接後重試。", "Shot {n} of {total}": "鏡頭 {n}/{total}", "GEV scene": "GEV 場景", - "SAVE TO STORIES": "儲存到 STORIES", + "SAVE TO STORIES": "保存到 STORIES", "REMOVE FROM STORIES": "從 STORIES 移除", "Show this scene on the Stories page": "在 Stories 頁面顯示此場景", "Take this scene off the Stories page": "將此場景從 Stories 頁面移除", - "Saved to Stories": "已儲存到 Stories", + "Saved to Stories": "已保存到 Stories", "Removed from Stories": "已從 Stories 移除", - "A scene you made in GEV, played on the live globe.": "你在 GEV 中製作的場景,在即時地球上播放。", + "A scene you made in GEV, played on the live globe.": "你在 GEV 中製作的場景,在實時地球上播放。", "Floods": "洪水", "Wildfires": "山火", "Storms": "風暴", @@ -3666,20 +3693,20 @@ "Space": "太空", "Conflict": "衝突", "Climate": "氣候", - "Switch to Esri World Imagery to capture a thumbnail": "請切換至 Esri World Imagery 以擷取縮圖", - "Thumbnail could not be captured": "無法擷取縮圖", - "Thumbnail captured": "已擷取縮圖", + "Switch to Esri World Imagery to capture a thumbnail": "請切換至 Esri World Imagery 以截取縮略圖", + "Thumbnail could not be captured": "無法截取縮略圖", + "Thumbnail captured": "已截取縮略圖", "Stories tags": "故事標籤", - "Story thumbnail": "故事縮圖", - "Use the current view as the Stories card image": "將目前檢視用作故事卡片圖片", - "Aircraft positions come from ADS-B: the OpenSky Network’s worldwide snapshot, with adsb.lol where OpenSky has none.": "飛機位置來自 ADS-B:OpenSky Network 的全球快照,OpenSky 沒有資料的地方由 adsb.lol 補充。", - "Live-flight fallback (ODbL 1.0)": "即時航班備用來源 (ODbL 1.0)", - "Satellite orbits are propagated from CelesTrak’s current element sets.": "衛星軌道根據 CelesTrak 目前的軌道根數推算。", - "Earthquakes come from the U.S. Geological Survey’s live feed.": "地震資料來自美國地質調查局 (USGS) 的即時資料流。", + "Story thumbnail": "故事縮略圖", + "Use the current view as the Stories card image": "將當前視圖用作故事卡片圖片", + "Aircraft positions come from ADS-B: the OpenSky Network’s worldwide snapshot, with adsb.lol where OpenSky has none.": "飛機位置來自 ADS-B:OpenSky Network 的全球快照,OpenSky 沒有數據的地方由 adsb.lol 補充。", + "Live-flight fallback (ODbL 1.0)": "實時航班備用來源 (ODbL 1.0)", + "Satellite orbits are propagated from CelesTrak’s current element sets.": "衛星軌道根據 CelesTrak 當前的軌道根數推算。", + "Earthquakes come from the U.S. Geological Survey’s live feed.": "地震數據來自美國地質調查局 (USGS) 的實時數據流。", "Traffic": "交通", - "Road traffic; live congestion needs your own TomTom key.": "道路交通;即時壅塞需要你自己的 TomTom 金鑰。", - "Live traffic flow, with your own key": "即時交通流量,需使用你自己的金鑰", - "Live air traffic around the world: the Atlantic, Europe, Japan and San Francisco.": "全球即時空中交通:大西洋、歐洲、日本和舊金山。", + "Road traffic; live congestion needs your own TomTom key.": "道路交通;實時擁堵需要你自己的 TomTom 密鑰。", + "Live traffic flow, with your own key": "實時交通流量,需使用你自己的密鑰", + "Live air traffic around the world: the Atlantic, Europe, Japan and San Francisco.": "全球實時空中交通:大西洋、歐洲、日本和舊金山。", "The Atlantic": "大西洋", "Western Europe": "西歐", "Japan": "日本", @@ -3690,30 +3717,30 @@ "Over Africa": "非洲上空", "Over Tokyo": "東京上空", "Over Paris": "巴黎上空", - "Recent earthquakes in the thermal look: California, Japan, New Zealand and off Portugal.": "熱成像風格下的近期地震:加利福尼亞、日本、紐西蘭和葡萄牙外海。", + "Recent earthquakes in the thermal look: California, Japan, New Zealand and off Portugal.": "熱成像風格下的近期地震:加利福尼亞、日本、新西蘭和葡萄牙近海。", "California": "加利福尼亞", - "New Zealand": "紐西蘭", - "Off Portugal": "葡萄牙外海", + "New Zealand": "新西蘭", + "Off Portugal": "葡萄牙近海", "Flights, satellites and traffic together over New York, Los Angeles and London.": "紐約、洛杉磯和倫敦上空的航班、衛星與交通。", "New York, closer": "紐約,更近", "New York, closer still": "紐約,再近一些", - "Every live layer at once, pulling back from Tokyo to the whole planet.": "同時顯示所有即時圖層,從東京拉遠到整個地球。", + "Every live layer at once, pulling back from Tokyo to the whole planet.": "同時顯示所有實時圖層,從東京拉遠到整個地球。", "Tokyo, pulling back": "東京,拉遠", "Japan and East Asia": "日本與東亞", "South China Sea": "南海", "The whole globe": "整個地球", "The 26 August 2026 Bhote Koshi outburst flood in Nepal, followed down the valley to Trishuli.": "2026 年 8 月 26 日尼泊爾 Bhote Koshi 潰決洪水,沿河谷而下追蹤至 Trishuli。", "Reconstructed flood path (CC BY-NC 4.0)": "重建的洪水路徑 (CC BY-NC 4.0)", - "THUMBNAIL": "縮圖", - "Worldwide live-flight snapshot (non-commercial research and education licence)": "全球即時航班快照(非商業研究與教育授權)", - "Satellite element sets and catalogue (U.S. government data)": "衛星軌道根數與目錄(美國政府資料)", - "Satellite operators, owners and purposes": "衛星營運者、擁有者與用途", - "Earthquake feed (U.S. public domain)": "地震資料流(美國公有領域)", + "THUMBNAIL": "縮略圖", + "Worldwide live-flight snapshot (non-commercial research and education licence)": "全球實時航班快照(非商業研究與教育許可)", + "Satellite element sets and catalogue (U.S. government data)": "衛星軌道根數與目錄(美國政府數據)", + "Satellite operators, owners and purposes": "衛星運營者、所有者與用途", + "Earthquake feed (U.S. public domain)": "地震數據流(美國公有領域)", "Historical and post-event satellite imagery (CC BY-NC 4.0)": "歷史與事件後衛星影像 (CC BY-NC 4.0)", - "A visualization of the 26 August 2026 Bhote Koshi outburst flood, not an official hazard model. The historical (2021) and post-event views are Vantor WorldView imagery; the river’s path is GeoPera’s reconstruction. Witness clips link to their original posts, and their capture times are unverified.": "這是 2026 年 8 月 26 日 Bhote Koshi 潰決洪水的視覺化,並非官方災害模型。歷史(2021 年)與事件後畫面為 Vantor WorldView 影像;河流路徑為 GeoPera 的重建結果。目擊者影片連結到其原始貼文,拍攝時間未經核實。", - "That story is not available here": "該故事在此處無法使用", + "A visualization of the 26 August 2026 Bhote Koshi outburst flood, not an official hazard model. The historical (2021) and post-event views are Vantor WorldView imagery; the river’s path is GeoPera’s reconstruction. Witness clips link to their original posts, and their capture times are unverified.": "這是 2026 年 8 月 26 日 Bhote Koshi 潰決洪水的可視化,並非官方災害模型。歷史(2021 年)與事件後視圖為 Vantor WorldView 影像;河流路徑為 GeoPera 的重建結果。目擊者視頻鏈接到其原始帖子,拍攝時間未經核實。", + "That story is not available here": "該故事在此處不可用", "DRAFT": "草稿", - "A draft, not saved as a story yet. Use SAVE TO STORIES in AUTHORING to save it.": "尚未儲存為故事的草稿。在「創作」中使用「儲存到 STORIES」即可儲存。", + "A draft, not saved as a story yet. Use SAVE TO STORIES in AUTHORING to save it.": "尚未保存為故事的草稿。在“創作”中使用“保存到 STORIES”即可保存。", "Heading to next stop": "前往下一站", "Arriving at a stop": "即將到站", "Stopped at a stop": "停靠站點", @@ -3724,12 +3751,12 @@ "Flight level": "飛行高度層", "Mach": "馬赫", "Squawk {code}": "應答機編碼 {code}", - "Signal": "訊號", + "Signal": "信號", "Civilian, in the air": "民用,空中", "Military, in the air": "軍用,空中", "On the ground": "地面", "Motion": "運動", - "Operator": "營運商", + "Operator": "運營商", "Last reported": "最近報告", "Crowding": "擁擠程度", "Class": "類別", @@ -3742,7 +3769,7 @@ "Wildfire": "野火", "{n} acres": "{n} 英畝", "{n}% contained": "已控制 {n}%", - "prescribed burn": "計畫燒除", + "prescribed burn": "計劃燒除", "{count} satellite fire hits": { "other": "{count} 個衛星火點" }, @@ -3758,45 +3785,45 @@ "Snow showers": "陣雪", "Thunderstorm": "雷暴", "Mixed conditions": "天氣多變", - "Search {name} and nearby": "搜尋 {name} 及附近", - "Search what is in view": "搜尋視野內內容", - "Close Context search": "關閉態勢搜尋", - "Search in Context": "在態勢中搜尋", - "Close search": "關閉搜尋", + "Search {name} and nearby": "搜索 {name} 及附近", + "Search what is in view": "搜索視野內內容", + "Close Context search": "關閉態勢搜索", + "Search in Context": "在態勢中搜索", + "Close search": "關閉搜索", "Shrink Context back to a panel": "將態勢縮回面板", "Expand Context to a full-height column": "將態勢展開為全高欄", - "Context tabs": "態勢分頁", + "Context tabs": "態勢標籤頁", "Inspector": "檢查器", "Properties": "屬性", "Level": "等級", "Last {n} min": "最近 {n} 分鐘", "Just now": "剛剛", - "Since selected": "自選取起", + "Since selected": "自選中起", "Altitude": "高度", "Heading": "航向", - "Field of view": "視野", - "Camera frame": "攝影機畫面", - "Acquiring frame…": "正在取得畫面…", - "Show a bigger view": "放大檢視", - "Camera view": "攝影機視圖", - "More info": "更多資訊", + "Field of view": "視場", + "Camera frame": "攝像頭畫面", + "Acquiring frame…": "正在獲取畫面…", + "Show a bigger view": "放大查看", + "Camera view": "攝像頭視圖", + "More info": "更多信息", "{n} s ago": "{n} 秒前", "{n} min ago": "{n} 分鐘前", "{n} h ago": "{n} 小時前", "{n} d ago": "{n} 天前", - "Out of feed · last reading": "已離開資料源 · 最後讀數", + "Out of feed · last reading": "已離開數據源 · 最後讀數", "Live · {age}": "實時 · {age}", "{n} m": "{n} m", "{n} km": "{n} km", "updated {age}": "更新於 {age}", - "Selected on the map": "地圖上的選取項", + "Selected on the map": "地圖上的選中項", "Close card": "關閉卡片", "{n}% flown": "已飛 {n}%", "to go": "剩餘", - "The scheduled route for this flight number does not match where the plane is; it may be another leg of the same flight.": "該航班號的計畫航線與飛機位置不符,可能是同一航班的另一航段。", - "Scheduled · unverified: does not match where the plane is": "計畫 · 未核實:與飛機位置不符", - "Nothing in this item’s details matches “{text}”.": "此項詳情中沒有與「{text}」相符的內容。", - "Matching details": "相符的詳情", + "The scheduled route for this flight number does not match where the plane is; it may be another leg of the same flight.": "該航班號的計劃航線與飛機位置不符,可能是同一航班的另一航段。", + "Scheduled · unverified: does not match where the plane is": "計劃 · 未核實:與飛機位置不符", + "Nothing in this item’s details matches “{text}”.": "此項詳情中沒有與“{text}”匹配的內容。", + "Matching details": "匹配的詳情", "Enter orbital view": "進入軌道視圖", "Enter Cockpit": "進入座艙", "Fly to": "飛往", @@ -3812,10 +3839,10 @@ "Conditions here": "此處狀況", "feels {n}°": "體感 {n}°", "Reading conditions here…": "正在讀取此處狀況…", - "No weather reading here.": "此處沒有天氣資料。", + "No weather reading here.": "此處沒有天氣數據。", "Local solar time": "當地太陽時", "Nearby radius": "附近半徑", - "How far out the nearby lists look": "附近清單的範圍", + "How far out the nearby lists look": "附近列表的範圍", "Hazards within {radius}": "{radius} 內的災害", "Turns the layer on": "開啟該圖層", "No earthquakes, tropical storms or wildfires reported within {radius}.": "{radius} 內未報告地震、熱帶風暴或野火。", @@ -3833,29 +3860,29 @@ "{things} in view from {layers}": "視野內有來自 {layers} 的 {things}", "{n} km up": "高 {n} km", "{n} m up": "高 {n} m", - "This view": "目前視圖", + "This view": "當前視圖", "Day": "白天", "Twilight": "晨昏", "Night": "夜間", "Daylight": "日照", "sun {n}°": "太陽 {n}°", - "Of {n} read, {total} loaded": "讀取 {n} 個,已載入 {total} 個", + "Of {n} read, {total} loaded": "讀取 {n} 個,已加載 {total} 個", "Of all {n}": "全部 {n} 個中", "Of {n} in view": "視野內 {n} 個中", "Error": "錯誤", "Stale": "已過時", "In view": "視野內", "Globe view": "地球視圖", - "Nothing selected": "未選取任何內容", - "Worldwide now": "全球目前", + "Nothing selected": "未選中任何內容", + "Worldwide now": "全球當前", "Turn on {name}": "開啟 {name}", - "{n} loaded": "已載入 {n}", + "{n} loaded": "已加載 {n}", "{n} in view": "視野內 {n}", "Turn off {name}": "關閉 {name}", "Camera height": "相機高度", - "Nothing in view matches “{text}”.": "視野內沒有與「{text}」相符的內容。", - "Nothing from the layers that are on is in view here. Zoom out to see more.": "已開啟的圖層在此處視野內沒有內容。縮小以檢視更多。", - "No loaded layer has anything in view. Turn some on in Data Layers.": "已載入的圖層在視野內都沒有內容。請在數據圖層中開啟一些。", + "Nothing in view matches “{text}”.": "視野內沒有與“{text}”匹配的內容。", + "Nothing from the layers that are on is in view here. Zoom out to see more.": "已開啟的圖層在此處視野內沒有內容。縮小以查看更多。", + "No loaded layer has anything in view. Turn some on in Data Layers.": "已加載的圖層在視野內都沒有內容。請在數據圖層中開啟一些。", "Places in view": "視野內的地點", "Show here": "在此顯示", "Ask GEV what's here": "問問 GEV 這裡有什麼", @@ -3863,19 +3890,19 @@ "vessel": "船舶", "launch": "發射", "fire": "火點", - "Fire detection": "火點偵測", + "Fire detection": "火點探測", "fire perimeter": "火場範圍", "earthquake": "地震", "storm": "風暴", - "air quality station": "空氣品質站", + "air quality station": "空氣質量站", "installation": "設施", "dam": "水壩", - "data centre": "資料中心", + "data centre": "數據中心", "place": "地點", "vehicle": "車輛", "bike station": "單車站", - "plate reader": "車牌辨識器", - "camera": "攝影機", + "plate reader": "車牌識別器", + "camera": "攝像頭", "airspace": "空域", "sighting": "目擊", "Callsign": "呼號", @@ -3893,8 +3920,8 @@ "Place": "地點", "Fire power": "火點功率", "Satellite": "衛星", - "Sensor": "感測器", - "Detected": "偵測時間", + "Sensor": "傳感器", + "Detected": "探測時間", "Contained": "已控制", "Discovered": "發現時間", "Basin": "海域", @@ -3932,7 +3959,7 @@ "Typhoon": "颱風", "Super typhoon": "超強颱風", "Tropical cyclone": "熱帶氣旋", - "Prescribed burn": "計畫燒除", + "Prescribed burn": "計劃燒除", "Atlantic": "大西洋", "Eastern Pacific": "東太平洋", "Central Pacific": "中太平洋", @@ -3969,7 +3996,7 @@ "Emergency: {kind}": "緊急情況:{kind}", "Emergency declared": "已宣布緊急情況", "Tsunami warning issued": "已發布海嘯警報", - "VFR, no flight plan": "VFR,無飛行計畫", + "VFR, no flight plan": "VFR,無飛行計劃", "VFR conspicuity": "VFR 識別碼", "IFR, no code yet": "IFR,尚未分配編碼", "Hijack": "劫機", @@ -3977,12 +4004,12 @@ "Descending {n} ft/min": "下降 {n} ft/min", "Cruising, level": "巡航,平飛", "Airliners": "客機", - "Widebodies": "廣體機", + "Widebodies": "寬體機", "Business jets": "公務機", "Helicopters": "直升機", "Turboprops": "渦槳飛機", - "Fast jets": "高速噴射機", - "Four-engine jets": "四發噴射機", + "Fast jets": "高速噴氣機", + "Four-engine jets": "四發噴氣機", "M6 and above": "M6 及以上", "M5 to 6": "M5 至 6", "M4 to 5": "M4 至 5", @@ -4002,5 +4029,11 @@ "KT": "kt", "Course to {code}: {course}": "前往 {code} 的航向:{course}", "Over {place}": "{place}上空", - "Below": "下方" + "Below": "下方", + "Go to this shot. Double-click to rename.": "轉到此鏡頭。雙擊重命名。", + "Move up": "上移", + "Move down": "下移", + "Click a shot to go to it, double-click to rename.": "單擊鏡頭即可轉到該鏡頭,雙擊可重命名。", + "Back to live at the starting view": "回到實時並返回初始視圖", + "Exit cockpit to fly to a bike share city": "退出駕駛艙以飛往有共享單車的城市" } diff --git a/src/i18n/zh-hant-cli.test.mjs b/src/i18n/zh-hant-cli.test.mjs new file mode 100644 index 0000000000..47b7e62664 --- /dev/null +++ b/src/i18n/zh-hant-cli.test.mjs @@ -0,0 +1,145 @@ +// The zh-Hant branches of `npm run i18n` (main in scripts/i18n.mjs), run in a +// throwaway repository like stale-index.test.mjs. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const REPO = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../..', +); +const json = (catalog) => `${JSON.stringify(catalog, null, 2)}\n`; + +function sandbox(zhCN, { modules = true } = {}) { + const root = mkdtempSync(path.join(tmpdir(), 'zh-hant-cli-')); + const write = (file, text) => { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), text); + }; + mkdirSync(path.join(root, 'scripts')); + copyFileSync( + path.join(REPO, 'scripts/i18n.mjs'), + path.join(root, 'scripts/i18n.mjs'), + ); + if (modules) { + // The package wherever node finds it, from its dist/umd entry; a junction + // needs no symlink privilege on Windows. + const entry = createRequire(import.meta.url).resolve('opencc-js/cn2t'); + mkdirSync(path.join(root, 'node_modules')); + symlinkSync( + path.resolve(path.dirname(entry), '../..'), + path.join(root, 'node_modules/opencc-js'), + 'junction', + ); + } + write('.gitignore', 'node_modules\n'); + write('src/a.js', "export const a = [t('Video'), t('Server')];\n"); + write('src/i18n/same-as-english.json', '{}\n'); + write('src/i18n/locales/zh-CN.json', json(zhCN)); + const git = (...args) => + execFileSync('git', args, { cwd: root, encoding: 'utf8' }); + git('init', '-q'); + return { + git, + write, + read: (file) => readFileSync(path.join(root, file), 'utf8'), + run: (...args) => + spawnSync(process.execPath, ['scripts/i18n.mjs', ...args], { + cwd: root, + encoding: 'utf8', + }), + done: () => rmSync(root, { recursive: true, force: true }), + }; +} + +const ZH_CN = { Video: '视频', Server: '服务器' }; +const ZH_HANT = { Video: '視頻', Server: '服務器' }; + +test('--missing zh-Hant points to --zh-hant instead of printing a template', () => { + const box = sandbox(ZH_CN); + try { + for (const locale of ['zh-Hant', 'zh-hant']) { + const result = box.run('--missing', locale); + assert.equal(result.status, 1); + assert.equal(result.stdout, ''); + assert.match(result.stderr, /then run npm run i18n -- --zh-hant/); + } + } finally { + box.done(); + } +}); + +test('--zh-hant writes zh-CN converted, in its key order, indent 2 and a final newline', () => { + const box = sandbox(ZH_CN); + try { + const result = box.run('--zh-hant'); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.equal(box.read('src/i18n/locales/zh-Hant.json'), json(ZH_HANT)); + assert.match(result.stdout, /zh-Hant: 2 messages, complete/); + } finally { + box.done(); + } +}); + +test('--prune drops a stale entry from both catalogs, whichever git lists first', () => { + const box = sandbox({ ...ZH_CN, Old: '旧' }); + try { + // zh-CN tracked and zh-Hant not: git ls-files lists zh-Hant first. + box.git('add', '-A'); + box.run('--zh-hant'); + const result = box.run('--prune'); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.match(result.stdout, /zh-CN: pruned 1 unused entries/); + assert.match(result.stdout, /zh-Hant: pruned 1 unused entries/); + assert.equal(box.read('src/i18n/locales/zh-Hant.json'), json(ZH_HANT)); + } finally { + box.done(); + } +}); + +test('a missing zh-Hant entry says to add it to zh-CN only when zh-CN lacks it too', () => { + for (const [zhCN, fill] of [ + [ZH_CN, 'run npm run i18n -- --zh-hant'], + [{ Video: '视频' }, 'add them to zh-CN, then npm run i18n -- --zh-hant'], + ]) { + const box = sandbox(zhCN); + try { + box.write('src/i18n/locales/zh-Hant.json', json({ Video: '視頻' })); + const result = box.run(); + assert.equal(result.status, 1); + assert.ok( + result.stdout.includes(`zh-Hant: 1 missing (${fill}):`), + result.stdout, + ); + } finally { + box.done(); + } + } +}); + +test('without node_modules the zh-Hant check says to install and the other checks still run', () => { + const box = sandbox(ZH_CN, { modules: false }); + try { + box.write('src/i18n/locales/zh-Hant.json', json(ZH_HANT)); + box.write('index.html', '

Unmarked words

\n'); + const result = box.run(); + assert.equal(result.status, 1); + assert.match(result.stdout, /zh-Hant: .*run npm ci/); + assert.match(result.stdout, /1 UI strings not marked for translation/); + } finally { + box.done(); + } +}); diff --git a/src/layers/awareness/panel.js b/src/layers/awareness/panel.js index 9ccda4e923..33f206e225 100644 --- a/src/layers/awareness/panel.js +++ b/src/layers/awareness/panel.js @@ -2,13 +2,9 @@ import { formatAwarenessLabel, AWARENESS_RADIUS_M, } from '../../data/militaryAwarenessEngine.js'; -import { - formatNumber, - onLocaleChange, - t, - translateKnown, -} from '../../i18n/index.js'; +import { formatNumber, onLocaleChange, t } from '../../i18n/index.js'; import { sourceStatusLabel } from '../../ui/layerNames.js'; +import { translateStatusMessage } from '../../ui/statusText.js'; import { formatQuantity } from '../../ui/unitLabels.js'; import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js'; import { distanceParts } from '../../data/distanceFormat.js'; @@ -45,7 +41,7 @@ export function presentAwarenessDistance(meters) { function presentAwarenessReason(summary = {}) { return summary.reasonTemplate ? t(summary.reasonTemplate, summary.reasonValues) - : translateKnown(summary.reason || ''); + : translateStatusMessage(summary.reason || ''); } /** diff --git a/src/layers/bikeshare/coverage.test.mjs b/src/layers/bikeshare/coverage.test.mjs new file mode 100644 index 0000000000..781253e669 --- /dev/null +++ b/src/layers/bikeshare/coverage.test.mjs @@ -0,0 +1,139 @@ +// Bike Share's covered cities on the globe (HAL-921): above the height +// stations draw at, every system in the registry has a marker, so the globe +// says where bike share is, and a click on one flies down into its city. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { GBFS_CITY_REGISTRY } from './registry.js'; +import { createState } from './state.js'; +import { createIngestion } from './ingestion.js'; +import { createModel } from './model.js'; +import { createViewport } from './viewport.js'; +import { createRendering } from './rendering.js'; +import { createSelection } from './selection.js'; +import { createLifecycle } from './lifecycle.js'; +import { COVERAGE_FLY_HEIGHT_M } from './policy.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import { fakeInput } from '../../input/testDoubles.mjs'; + +globalThis.document ??= { + addEventListener() {}, + removeEventListener() {}, +}; + +function makeLayer() { + const owners = new Map(); + const services = { + render: { governorRequestRender() {} }, + overlays: { + setOverlayEntries() {}, + setOverlaySourceVisible() {}, + clearOverlaySource() {}, + }, + sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} }, + picking: { + registerPickOwner: (id, owns) => owners.set(id, owns), + unregisterPickOwner: (id) => owners.delete(id), + }, + }; + const source = { getStations: async () => ({ data: { stations: [] } }) }; + const state = createState({ services }); + const parts = {}; + const context = { state, services, parts, source }; + parts.ingestion = createIngestion(context); + parts.model = createModel(context); + parts.viewport = createViewport(context); + parts.rendering = createRendering(context); + parts.selection = createSelection(context); + parts.queries = { collectDetectableStations: () => [] }; + parts.lifecycle = createLifecycle(context); + + const camera = { lat: 20, lon: 0, height: 18_000_000 }; + const flights = []; + const viewer = { scene: { pick: () => undefined, canvas: {} } }; + const { draw } = bindFakeDraw(viewer, { + camera: { + pose: () => ({ ...camera }), + viewRectangle: () => null, + on: () => () => {}, + flyTo: (destination, options) => flights.push({ destination, options }), + }, + }); + // The layer's click subscription, called with a hit as the dispatcher gives it. + const fake = fakeInput(viewer); + const clicks = []; + const subscribe = fake.input.onClick; + fake.input.onClick = (fn) => { + clicks.push(fn); + return subscribe.call(fake.input, () => {}); + }; + parts.lifecycle.methods.init(viewer); + const coverage = () => + draw.find('bikeshare:') && + [...draw.sets.values()].find( + (set) => !set.disposed && set.spec.id.endsWith(':coverage'), + ); + return { + state, + parts, + owners, + flights, + coverage, + click: (hit) => clicks.at(-1)({ drawHit: hit }), + async moveTo(height) { + camera.height = height; + await parts.viewport.runProximityCheck(); + }, + enable: () => parts.lifecycle.methods.enable(viewer), + disable: () => parts.lifecycle.methods.disable(), + }; +} + +test('every covered city has a marker, shown only while the layer is on and too high for stations', async () => { + const layer = makeLayer(); + const set = layer.coverage(); + assert.equal(set.items.size, GBFS_CITY_REGISTRY.length); + assert.equal(set.show, false, 'hidden while the layer is off'); + layer.enable(); + await layer.moveTo(18_000_000); + assert.equal(set.show, true, 'the globe shows where bike share is'); + await layer.moveTo(20_000); + assert.equal( + set.show, + false, + 'stations take over below the activation height', + ); + await layer.moveTo(18_000_000); + assert.equal(set.show, true); + layer.disable(); + assert.equal(set.show, false, 'gone with the layer'); +}); + +test('a marker belongs to the layer and its click flies straight down into the city', async () => { + const layer = makeLayer(); + layer.enable(); + await layer.moveTo(18_000_000); + const city = GBFS_CITY_REGISTRY.find( + (each) => each.id === 'boston-bluebikes', + ); + const id = `city:${city.id}`; + assert.equal(layer.owners.get('bikeshare')(id), true); + assert.equal(layer.owners.get('bikeshare')('city:nowhere'), false); + const navigated = []; + layer.parts.lifecycle.methods.attachShellServices({ + runNavigation: (navigate) => { + navigated.push('explicit'); + return navigate(); + }, + }); + layer.click({ set: layer.coverage().spec.id, id }); + assert.deepEqual(navigated, ['explicit'], 'an explicit camera action'); + assert.equal(layer.flights.length, 1); + const { destination, options } = layer.flights[0]; + assert.deepEqual(destination, { + lon: city.centerLon, + lat: city.centerLat, + height: COVERAGE_FLY_HEIGHT_M, + }); + assert.equal(options.orientation.pitch, -Math.PI / 2); + assert.ok(COVERAGE_FLY_HEIGHT_M < 48_000, 'below the activation height'); +}); diff --git a/src/layers/bikeshare/lifecycle.js b/src/layers/bikeshare/lifecycle.js index e7c4b04896..4079b0c80e 100644 --- a/src/layers/bikeshare/lifecycle.js +++ b/src/layers/bikeshare/lifecycle.js @@ -20,6 +20,18 @@ export function createLifecycle({ } const methods = { + /** + * The shell's services: `runNavigation(navigate)` runs a covered city's + * flight as an explicit camera action, as the other camera controls are. + * @param {{ runNavigation?: Function }|null} shellServices + */ + attachShellServices(shellServices) { + layerState._runNavigation = + typeof shellServices?.runNavigation === 'function' + ? shellServices.runNavigation + : null; + }, + /** * Initialize the bikeshare layer. Makes the station draw sets on the * viewer's renderer (`drawOf`), resets all internal state, and installs @@ -81,8 +93,11 @@ export function createLifecycle({ ); parts.selection._installClickHandler(viewer); // Pick-ownership (H2): station point ids are string render-map keys. - registerPickOwner('bikeshare', (pickedId) => - layerState._stationRenderMap.has(pickedId), + registerPickOwner( + 'bikeshare', + (pickedId) => + layerState._stationRenderMap.has(pickedId) || + parts.selection.coverageCityOf(pickedId) !== null, ); if (!layerState._cameraChangedOff) { @@ -124,6 +139,7 @@ export function createLifecycle({ parts.viewport.deactivateAllCities(); layerState._cityRuntime.clear(); if (layerState._stationSet) layerState._stationSet.show = false; + parts.viewport.showCoverage(false); layerState._count = 0; layerState._loading = false; layerState._loadingOps = 0; diff --git a/src/layers/bikeshare/policy.js b/src/layers/bikeshare/policy.js index cf928a9dae..7686ca116c 100644 --- a/src/layers/bikeshare/policy.js +++ b/src/layers/bikeshare/policy.js @@ -15,6 +15,22 @@ const ACTIVATION_ALTITUDE_M = 50000; export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 2000; +/** + * Where a covered city's marker flies to: straight down from this height, + * well inside the activation band, with the city's stations in view. + */ +export const COVERAGE_FLY_HEIGHT_M = 20000; + +/** A covered city's marker: the stations' green, larger, ringed in white. */ +export const COVERAGE_PIXEL_SIZE = 11; +export const COVERAGE_OUTLINE_WIDTH = 2; + +/** + * A marker's height: above the highest covered city's ground, so terrain + * never hides it, while the globe itself hides the markers behind it. + */ +export const COVERAGE_HEIGHT_M = 5000; + /** Hysteresis exit threshold — layer deactivates when camera rises above this. */ export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000; diff --git a/src/layers/bikeshare/rendering.js b/src/layers/bikeshare/rendering.js index e0f29fb75e..1111da9e17 100644 --- a/src/layers/bikeshare/rendering.js +++ b/src/layers/bikeshare/rendering.js @@ -13,7 +13,11 @@ import { POINT_SCALE_BY_DISTANCE, POINT_FADE_BY_DISTANCE, POINT_DISABLE_DEPTH_TEST_M, + COVERAGE_PIXEL_SIZE, + COVERAGE_OUTLINE_WIDTH, + COVERAGE_HEIGHT_M, } from './policy.js'; +import { GBFS_CITY_REGISTRY } from './registry.js'; import { heightsOf } from '../../queries/heights.js'; import { fromDegrees } from '../../geo/ellipsoid.js'; import { drawOf } from '../../render/rendererOf.js'; @@ -24,6 +28,9 @@ import { drawOf } from '../../render/rendererOf.js'; * share a renderer. Picks name them as `Hit.set`. */ export const BIKESHARE_SET_ID = 'bikeshare'; + +/** A covered city's marker id: its registry id under this prefix. */ +export const COVERAGE_ID_PREFIX = 'city:'; let instances = 0; export function createRendering({ @@ -51,6 +58,23 @@ export function createRendering({ drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0, }); layerState._selectedSet = draw.points({ id: `${prefix}:selected` }); + // One marker per covered city, drawn while the camera is too high for + // stations: the globe shows where bike share is. + layerState._coverageSet = draw.points({ + id: `${prefix}:coverage`, + show: false, + drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0, + }); + layerState._coverageSet.set( + GBFS_CITY_REGISTRY.map((city) => ({ + id: `${COVERAGE_ID_PREFIX}${city.id}`, + pos: fromDegrees(city.centerLon, city.centerLat, COVERAGE_HEIGHT_M), + pixelSize: COVERAGE_PIXEL_SIZE, + color: COLOR_GREEN, + outlineColor: [1, 1, 1, 0.9], + outlineWidth: COVERAGE_OUTLINE_WIDTH, + })), + ); // Drawn from the start, empty, so both take their place in the scene // now, as the layer's collections did; the stations' place among the // other sprite layers is their draw order (`spriteDrawOrder`). @@ -62,8 +86,10 @@ export function createRendering({ function detachSets() { layerState._stationSet?.dispose(); layerState._selectedSet?.dispose(); + layerState._coverageSet?.dispose(); layerState._stationSet = null; layerState._selectedSet = null; + layerState._coverageSet = null; } /** diff --git a/src/layers/bikeshare/selection.js b/src/layers/bikeshare/selection.js index bbf962d8d3..cb3a5bf315 100644 --- a/src/layers/bikeshare/selection.js +++ b/src/layers/bikeshare/selection.js @@ -4,7 +4,11 @@ import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID, BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS, SELECTED_POINT_STYLE, + COVERAGE_FLY_HEIGHT_M, } from './policy.js'; +import { GBFS_CITY_REGISTRY } from './registry.js'; +import { COVERAGE_ID_PREFIX } from './rendering.js'; +import { cameraOf } from '../../render/rendererOf.js'; export function createSelection({ state: layerState, @@ -139,6 +143,38 @@ export function createSelection({ * @param {object} viewer - The viewer the layer draws on. */ + /** + * The covered city a marker id names, or null. + * @param {unknown} id + */ + function coverageCityOf(id) { + if (typeof id !== 'string' || !id.startsWith(COVERAGE_ID_PREFIX)) + return null; + const cityId = id.slice(COVERAGE_ID_PREFIX.length); + return GBFS_CITY_REGISTRY.find((city) => city.id === cityId) ?? null; + } + + /** + * Straight down over a covered city, low enough for its stations, as the + * shell's camera action when it gave one. + * @param {{ centerLat: number, centerLon: number }} city + */ + function flyIntoCity(city) { + const viewer = layerState._viewer; + if (!viewer) return; + const fly = () => + cameraOf(viewer).flyTo( + { + lon: city.centerLon, + lat: city.centerLat, + height: COVERAGE_FLY_HEIGHT_M, + }, + { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 } }, + ); + if (layerState._runNavigation) layerState._runNavigation(fly); + else fly(); + } + function _installClickHandler(viewer) { if (layerState._clickSubscription) return; @@ -149,6 +185,15 @@ export function createSelection({ // Clicking the selected highlight itself — ignore (don't deselect). if (hit.set === layerState._selectedSet?.id) return; + // A covered city's marker: fly down into it. + if (hit.set === layerState._coverageSet?.id) { + const city = coverageCityOf(hit.id); + if (city) { + flyIntoCity(city); + return; + } + } + // A station dot of this layer's own set if ( hit.set === layerState._stationSet?.id && @@ -183,5 +228,6 @@ export function createSelection({ _selectStation, _installClickHandler, _onKeyDown, + coverageCityOf, }; } diff --git a/src/layers/bikeshare/state.js b/src/layers/bikeshare/state.js index 075f67a43a..ab5c5aac67 100644 --- a/src/layers/bikeshare/state.js +++ b/src/layers/bikeshare/state.js @@ -27,6 +27,17 @@ export function createState({ services }) { layerState._stationSet = null; + /** + * Draw set of the covered cities' markers, shown above the activation + * height so the globe says where bike share is, or null. + */ + + layerState._coverageSet = null; + + /** The shell's camera action for a marker's flight (`attachShellServices`), or null. */ + + layerState._runNavigation = null; + /** Draw set of the selected station's highlight dot, or null. */ layerState._selectedSet = null; diff --git a/src/layers/bikeshare/viewport.js b/src/layers/bikeshare/viewport.js index 89acab7c6c..a7a843250d 100644 --- a/src/layers/bikeshare/viewport.js +++ b/src/layers/bikeshare/viewport.js @@ -115,6 +115,18 @@ export function createViewport({ state: layerState, services, parts, source }) { parts.rendering.removeCityPoints(cityId); } + /** + * Show the covered cities' markers, or hide them: shown while the layer is + * on and the camera is too high for stations. + * @param {boolean} shown + */ + function showCoverage(shown) { + const set = layerState._coverageSet; + if (!set || set.show === shown) return; + set.show = shown; + governorRequestRender('bikeshare-coverage'); + } + /** Repaint the row now: it follows the camera, the manager tick is 60 s. */ function refreshRow() { layerState._dataManager?.refreshLayerStats?.('bikeshare'); @@ -212,11 +224,13 @@ export function createViewport({ state: layerState, services, parts, source }) { const wasGateEnabled = layerState._altitudeGateEnabled; // Altitude gate: disable all cities when camera is too high if (!shouldActivateAtAltitude(altitude)) { + showCoverage(true); deactivateAllCities(); if (wasGateEnabled) refreshRow(); return; } + showCoverage(false); const center = getCameraCenterLatLon(layerState._viewer); if (!center) return; @@ -288,6 +302,7 @@ export function createViewport({ state: layerState, services, parts, source }) { activateCity, runProximityCheck, scheduleProximityCheck, + showCoverage, onCameraChanged, }; } diff --git a/src/layers/cctv/controls.js b/src/layers/cctv/controls.js index 1f83b7468a..5daa130e75 100644 --- a/src/layers/cctv/controls.js +++ b/src/layers/cctv/controls.js @@ -335,6 +335,25 @@ export function createControls({ state: layerState, services, parts, source }) { return nextId; }, + /** + * Selects the camera nearest a WGS84 point and optionally flies to it. + * @param {number} lat Latitude in degrees. + * @param {number} lon Longitude in degrees. + * @param {Object} [options={}] + * @param {boolean} [options.focus=true] Whether to fly after selection. + * @param {number} [options.durationSec] Fly-to duration in seconds. + * @returns {string|null} Camera ID, or null (invalid point, empty catalog). + */ + focusNearestToPoint(lat, lon, options = {}) { + const nearest = parts.navigation.nearestCameraIdToPoint(lat, lon); + if (!nearest) return null; + parts.selection.setActiveCamera(nearest); + if (options.focus !== false) { + parts.navigation.focusCamera(nearest, options.durationSec || 1.8); + } + return nearest; + }, + /** * Selects and flies to the camera nearest the current viewer position. * @param {Object} [options={}] diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index eaa9a888fc..6b2ba96aaf 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -9,14 +9,20 @@ export function createNavigation({ source, }) { /** - * Finds the camera closest to the viewer's current position. - * @returns {string|null} Camera ID of the nearest camera, or null. + * Nearest catalog camera to a WGS84 point. + * @param {number} lat Latitude in degrees. + * @param {number} lon Longitude in degrees. + * @returns {string|null} Camera ID, or null (invalid point, empty catalog). */ - - function nearestCameraIdToViewer() { - const pose = parts.model.eyePose(); - if (!pose || !layerState._records.length) return null; - const { lat, lon } = pose; + function nearestCameraIdToPoint(lat, lon) { + if ( + !Number.isFinite(lat) || + !Number.isFinite(lon) || + Math.abs(lat) > 90 || + Math.abs(lon) > 180 || + !layerState._records.length + ) + return null; let best = null; for (const record of layerState._records) { @@ -33,6 +39,16 @@ export function createNavigation({ return best?.id || null; } + /** + * Finds the camera closest to the viewer's current position. + * @returns {string|null} Camera ID of the nearest camera, or null. + */ + function nearestCameraIdToViewer() { + const pose = parts.model.eyePose(); + if (!pose) return null; + return nearestCameraIdToPoint(pose.lat, pose.lon); + } + /** * The camera the layer opens on when none is selected: the one nearest the * viewer, or the first record when the viewer has no position yet. @@ -175,6 +191,7 @@ export function createNavigation({ return (((Math.floor(currentIdx) + delta) % total) + total) % total; } return { + nearestCameraIdToPoint, nearestCameraIdToViewer, openingCameraId, reopenNearestCamera, diff --git a/src/layers/cctv/navigation.test.mjs b/src/layers/cctv/navigation.test.mjs new file mode 100644 index 0000000000..486f897843 --- /dev/null +++ b/src/layers/cctv/navigation.test.mjs @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createNavigation } from './navigation.js'; + +function fixture() { + const records = [ + { camera: { id: 'west', lat: 40, lon: -120 } }, + { camera: { id: 'east', lat: 40, lon: -100 } }, + ]; + const state = { _records: records }; + const parts = { + model: { + eyePose: () => ({ lat: 40, lon: -101 }), + haversineKm(lat1, lon1, lat2, lon2) { + return Math.hypot(lat1 - lat2, lon1 - lon2); + }, + }, + }; + const navigation = createNavigation({ + state, + services: {}, + parts, + source: {}, + }); + return { navigation }; +} + +test('nearest camera can be resolved from an explicit WGS84 target', () => { + const { navigation } = fixture(); + assert.equal(navigation.nearestCameraIdToPoint(40, -119), 'west'); + assert.equal(navigation.nearestCameraIdToPoint(40, -101), 'east'); +}); + +test('viewer-nearest delegates to the same target-point owner', () => { + const { navigation } = fixture(); + assert.equal(navigation.nearestCameraIdToViewer(), 'east'); +}); + +test('invalid target coordinates fail closed', () => { + const { navigation } = fixture(); + for (const [lat, lon] of [ + [NaN, 0], + [null, 0], + [0, Infinity], + [90.00001, 0], + [-90.00001, 0], + [0, 180.00001], + [0, -180.00001], + ]) { + assert.equal(navigation.nearestCameraIdToPoint(lat, lon), null); + } +}); diff --git a/src/layers/flights/clockFollow.js b/src/layers/flights/clockFollow.js index 7b9e8a2b73..114f28b6d3 100644 --- a/src/layers/flights/clockFollow.js +++ b/src/layers/flights/clockFollow.js @@ -27,6 +27,60 @@ export function createClockFollow({ flightState, services, parts }) { flightState._lastCamPoseSig = ''; } + /** + * The contacts drawn now that the first live snapshot after the clock came + * back to live lacks (the tracked one too): the snapshot judges them as a + * poll judges any absence (see the snapshot renderer). + * @param {{records: Array<{id: string}>}} snapshot + * @returns {Set} + */ + function absentAtHandover(snapshot) { + const present = new Set(snapshot.records.map((record) => record.id)); + const drawn = [...(flightState._icons?.ids() ?? [])]; + if (flightState._trackedIcao) drawn.push(flightState._trackedIcao); + return new Set(drawn.filter((id) => !present.has(id))); + } + + /** + * Back at live: forget how every contact moved, as at a jump, but keep the + * tracked trail, and keep the contacts `kept` (absentAtHandover) as they + * were: their record, fixes and course. Each was last seen at its newest + * fix, not when it was loaded, so absence judges how old it really is. + * @param {Set} kept + */ + function handOverMotion(kept) { + const held = []; + for (const id of kept) + held.push([ + id, + flightState.records.data.get(id), + flightState._positionHistory.get(id), + flightState._displayCourse.get(id), + ]); + forgetPlacedAircraft( + services?.placement, + [...flightState._positionHistory.keys()].filter((id) => !kept.has(id)), + ); + flightState.records.reset(); + flightState._positionHistory.clear(); + flightState._displayCourse.clear(); + flightState._groundSnap.clear(); + flightState._displayFloorState.clear(); + flightState._drReconcileValid = false; + flightState._cachedDRFrame = -1; + flightState._cachedDRPosition = null; + flightState._lastCamPoseSig = ''; + for (const [id, meta, history, course] of held) { + if (meta) + flightState.records.data.set(id, { + ...meta, + observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs, + }); + if (history) flightState._positionHistory.set(id, history); + if (course !== undefined) flightState._displayCourse.set(id, course); + } + } + /** Drop every contact: the time has none to show, or the clock went live. */ function clear() { if (flightState._trackedIcao) @@ -40,5 +94,5 @@ export function createClockFollow({ flightState, services, parts }) { flightState.feed._lastUpdate = null; } - return { resetMotion, clear }; + return { resetMotion, absentAtHandover, handOverMotion, clear }; } diff --git a/src/layers/flights/enrichment.js b/src/layers/flights/enrichment.js index 420811f89a..abfccd5629 100644 --- a/src/layers/flights/enrichment.js +++ b/src/layers/flights/enrichment.js @@ -156,7 +156,11 @@ export function createEnrichment({ (data) => { const meta = flightState.records.data.get(icao24); if (!meta) return; // evicted while the lookup was in flight - meta.typeCode = data.typeCode || meta.typeCode; + // A looked-up type outranks the feed's own from now on. + if (data.typeCode) { + meta.typeCode = data.typeCode; + meta.typeLookedUp = true; + } meta.typeName = data.typeName || meta.typeName; meta.registration = data.registration || meta.registration; if (meta.typeCode) { diff --git a/src/layers/flights/index.js b/src/layers/flights/index.js index 3c5de40506..e5cc42600e 100644 --- a/src/layers/flights/index.js +++ b/src/layers/flights/index.js @@ -12,7 +12,10 @@ import { createEvidence } from './evidence.js'; import { createTesting } from './testing.js'; import { createQueries } from './queries.js'; import { createClockFollow } from './clockFollow.js'; -import { createSnapshotTimeline } from '../../time/snapshotTimeline.js'; +import { + createSnapshotTimeline, + snapshotAnswer, +} from '../../time/snapshotTimeline.js'; import { worldClock } from '../../time/worldClock.js'; /** Compose one civil-flight layer with application-owned scene services. */ export function createCivilFlightLayer({ @@ -53,10 +56,19 @@ export function createCivilFlightLayer({ getQuery: (viewer) => parts.controller._flightQuery(viewer || flightState._viewer), applySnapshot: (snapshot, viewer, options) => { + // At another time the snapshot takes the place of every contact: how + // each moved belongs to the time the clock left. Back at live too, but + // the contacts it lacks are kept as they were for it to judge. if (options?.replace) parts.clockFollow.resetMotion(); + if (options?.handover) { + parts.clockFollow.handOverMotion( + parts.clockFollow.absentAtHandover(snapshot), + ); + } return applySnapshot(snapshot, viewer, options); }, followsClock: () => flightState.timeline.active(), + timedAnswer: snapshotAnswer, setSourceLabel: (source) => { layer.source = source; }, @@ -72,9 +84,7 @@ export function createCivilFlightLayer({ load: (atMs, { signal, replace }) => parts.ingestion.methods.loadAt(atMs, { signal, replace }), clear: () => parts.clockFollow.clear(), - resumeLive: () => { - layer.update(flightState._viewer).catch(() => {}); - }, + resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer), }); Object.assign( diff --git a/src/layers/flights/ingestion.js b/src/layers/flights/ingestion.js index 5558c7b6f0..b758457a3d 100644 --- a/src/layers/flights/ingestion.js +++ b/src/layers/flights/ingestion.js @@ -12,6 +12,7 @@ export function createIngestion({ setSourceLabel, applyPendingTrackingRestore, followsClock = () => false, + timedAnswer = () => true, }) { const methods = { async update(viewer, { signal = null } = {}) { @@ -21,13 +22,27 @@ export function createIngestion({ await acquire(viewer, { signal }); }, + /** + * Back at live from another time: poll at once, and let this live + * snapshot stand in for every contact. Those it has keep their + * icon and model and move on from where they are drawn; those it lacks + * go. Resolves true once it is applied, else false (nothing to poll yet, + * or the poll failed); rejects with an AbortError when it was dropped. + * @param {object} [viewer] + * @returns {Promise} + */ + async resumeLive(viewer) { + return (await acquire(viewer, { handover: true })) === true; + }, + /** * Apply the source's snapshot at world time `atMs` (its timeline says it * can answer one), in place of every contact when `replace`. Resolves - * whether it was applied. + * whether it was applied: `{ reachMs }`, the newest fix its records + * carry, when they carry fixes; else true, or false when it was not. * @param {number} atMs * @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options] - * @returns {Promise} + * @returns {Promise} */ async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) { // Whatever polls or loads for another time no longer applies. @@ -38,7 +53,10 @@ export function createIngestion({ }, }; - async function acquire(viewer, { signal = null, atMs, replace = false }) { + async function acquire( + viewer, + { signal = null, atMs, replace = false, handover = false }, + ) { const nowMs = Date.now(); const timed = atMs !== undefined; const trackingRefreshEpoch = ++feed._trackingRefreshEpoch; @@ -85,7 +103,9 @@ export function createIngestion({ setSourceLabel(feed._lastSource); const accepted = timed ? applySnapshot(snapshot, viewer, { replace }) - : applySnapshot(snapshot, viewer); + : handover + ? applySnapshot(snapshot, viewer, { handover: true }) + : applySnapshot(snapshot, viewer); feed._count = accepted.count; // Freshness belongs to the source snapshot, not the moment this browser // received a cached 200 response. @@ -99,7 +119,8 @@ export function createIngestion({ }; console.log(`[Data:Flights] Updated: ${feed._count} aircraft`); applyPendingTrackingRestore(); - return true; + // At a time, what the clock's follower is told of it. + return timed ? timedAnswer(snapshot) : true; } catch (e) { if (updateSignal.aborted || e?.name === 'AbortError') { throw new DOMException('Flights update aborted', 'AbortError'); diff --git a/src/layers/flights/liveHandover.test.mjs b/src/layers/flights/liveHandover.test.mjs new file mode 100644 index 0000000000..6ba2f1d8c1 --- /dev/null +++ b/src/layers/flights/liveHandover.test.mjs @@ -0,0 +1,266 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createFlightSnapshotRenderer } from './snapshotRenderer.js'; +import { createMotion } from './motion.js'; +import { createFlightState } from './state.js'; +import { createFlightFeed, createIngestion } from './ingestion.js'; +import { createClockFollow } from './clockFollow.js'; + +// Back at live from another time, the first live snapshot stands in for +// every contact: those it has keep their icon and ease on from where they +// are drawn, and only those it lacks go (src/time/snapshotTimeline.js). + +/** Any property is a no-op function unless given. */ +function stub(overrides = {}) { + return new Proxy(overrides, { + get: (target, key) => (key in target ? target[key] : () => undefined), + }); +} + +function harness() { + const iconIds = new Set(); + const calls = []; + const landed = new Set(); + const groundFloor = stub({ + cachedGroundFloor: () => null, + floorAltitudeM: (altitude) => altitude, + GROUND_FLOOR_LIFT_M: 0.5, + }); + const services = stub({ + geoid: { geoidHeight: () => 0 }, + camera: stub(), + focus: stub(), + groundFloor, + meshFloor: stub(), + groundSnap: stub({ createGroundSnap: () => stub() }), + placement: null, + }); + const flightState = createFlightState({ + services, + source: { label: 'Fixture aircraft' }, + }); + flightState._icons = { + has: (id) => iconIds.has(id), + ids: () => [...iconIds], + get count() { + return iconIds.size; + }, + }; + const parts = { + rendering: stub({ _modelOwnsVisual: () => false }), + icons: stub({ + _addIcon: (id) => { + calls.push(['add', id]); + iconIds.add(id); + }, + _forgetContact: (id) => { + calls.push(['forget', id]); + iconIds.delete(id); + }, + _planIcon: (id, options) => calls.push(['plan', id, options]), + }), + tracking: stub({ + _militaryLayerSuppresses: () => false, + _appendTrailFix: () => calls.push(['trail-append']), + _startTrail: (id) => calls.push(['trail-start', id]), + _clearTrail: () => calls.push(['trail-clear']), + }), + }; + parts.motion = createMotion({ flightState, services, parts, layer: {} }); + const apply = createFlightSnapshotRenderer({ + flightState, + records: flightState.records, + militaryRegistry: stub({ isMilitaryIcao: () => false }), + groundFloor, + rendering: parts.rendering, + tracking: parts.tracking, + motion: parts.motion, + icons: parts.icons, + enrichment: stub(), + queries: stub({ _likelyLanded: (id) => landed.has(id) }), + }); + const clockFollow = createClockFollow({ flightState, services, parts }); + return { + calls, + iconIds, + flightState, + clockFollow, + landed, + // `ids`: an id, or [id, fix age ms, on the ground]. + snapshot: (ids, fields = {}) => ({ + observedAtMs: Date.now(), + records: ids.map((entry, k) => { + const [id, ageMs = 5_000, onGround = false] = [entry].flat(); + return { + id, + reference: id, + longitude: -115 + k, + latitude: 36, + callsign: 'TEST1', + baroAltitudeM: onGround ? 0 : 9_000, + onGround, + speedMps: onGround ? 5 : 220, + courseDeg: 90, + positionTimeMs: Date.now() - ageMs, + }; + }), + complete: true, + ...fields, + }), + apply(ids, options, fields) { + calls.length = 0; + return apply(this.snapshot(ids, fields), null, options); + }, + // Back at live, as the layer applies its first live snapshot. + handOver(ids, fields) { + calls.length = 0; + const snapshot = this.snapshot(ids, fields); + clockFollow.handOverMotion(clockFollow.absentAtHandover(snapshot)); + return apply(snapshot, null, { handover: true }); + }, + }; +} + +test('the first live snapshot keeps the icons of contacts it has and drops only those it lacks', () => { + const h = harness(); + h.apply(['a00001', 'a00002']); + assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']); + + const accepted = h.handOver(['a00001', 'a00003']); + assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00003']); + assert.equal(accepted.count, 2); + // The contact it has keeps its icon: no remove and add, and its motion is + // planned as a handover, easing from where it is drawn. + assert.equal( + h.calls.some( + ([kind, id]) => id === 'a00001' && (kind === 'add' || kind === 'forget'), + ), + false, + ); + assert.deepEqual( + h.calls.find(([kind, id]) => kind === 'plan' && id === 'a00001'), + ['plan', 'a00001', { handover: true }], + ); + assert.ok(h.calls.some(([kind, id]) => kind === 'forget' && id === 'a00002')); + assert.ok(h.calls.some(([kind, id]) => kind === 'add' && id === 'a00003')); +}); + +test('a plain live poll keeps a missing contact as its absence rules say', () => { + const h = harness(); + h.apply(['a00001', 'a00002']); + h.apply(['a00001']); + assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']); + assert.deepEqual( + h.calls.find(([kind]) => kind === 'plan'), + ['plan', 'a00001', undefined], + ); +}); + +test('back at live, only the first live snapshot applied takes over; a failed poll says so', async () => { + const applied = []; + let fail = false; + const feed = createFlightFeed({ + async getSnapshot() { + if (fail) throw new Error('down'); + return { records: [], observedAtMs: Date.now(), freshness: 'current' }; + }, + }); + const { methods } = createIngestion({ + feed, + getQuery: () => ({}), + applySnapshot: (_snapshot, _viewer, options) => { + applied.push(options); + return { count: 0, ids: new Set() }; + }, + setSourceLabel: () => {}, + applyPendingTrackingRestore: () => {}, + }); + assert.equal(await methods.resumeLive(null), true); + await methods.update(null); + assert.deepEqual(applied, [{ handover: true }, undefined]); + + fail = true; + const warn = console.warn; + console.warn = () => {}; + try { + assert.equal(await methods.resumeLive(null), false); + } finally { + console.warn = warn; + } +}); + +test('back at live, the tracked contact and those the snapshot retains stay, stale, and a partial snapshot drops none', () => { + const h = harness(); + h.apply(['a00001', 'a00002', 'a00003', 'a00004']); + h.flightState._trackedIcao = 'a00001'; + const history = [{ epochMs: Date.now() - 60_000 }]; + h.flightState._positionHistory.set('a00001', history); + h.handOver(['a00004'], { retainIds: new Set(['a00002']) }); + assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002', 'a00004']); + assert.equal( + h.flightState._positionHistory.get('a00001'), + history, + 'the tracked contact keeps its fixes for the next poll to judge', + ); + assert.ok(h.flightState.records.data.has('a00001')); + assert.equal( + h.calls.some(([kind]) => kind === 'trail-clear' || kind === 'trail-start'), + false, + 'its trail goes on', + ); + + const partial = harness(); + partial.apply(['a00001', 'a00002']); + partial.handOver(['a00003'], { complete: false }); + assert.deepEqual([...partial.iconIds].sort(), ['a00001', 'a00002', 'a00003']); +}); + +test('back at live, the tracked contact the snapshot has goes on adding to its trail', () => { + const h = harness(); + h.apply(['a00001']); + h.flightState._trackedIcao = 'a00001'; + h.handOver(['a00001']); + assert.deepEqual( + h.calls.filter(([kind]) => kind.startsWith('trail')), + [['trail-append']], + ); +}); + +const HOURS_3 = 3 * 3_600_000; + +test('back at live, a partial snapshot keeps only contacts whose newest fix is recent, by the real absence rules', () => { + const h = harness(); + // Shown from a time three hours back, and one from a minute ago. + h.apply([ + ['a00001', HOURS_3], + ['a00002', 60_000], + ]); + h.handOver(['a00003'], { complete: false }); + assert.deepEqual( + [...h.iconIds].sort(), + ['a00002', 'a00003'], + 'the three-hour-old contact is no ghost', + ); +}); + +test('back at live, a tracked aircraft is kept only while its newest fix is recent and it has not landed', () => { + for (const [label, setUp, kept] of [ + ['recent', (h) => h.apply([['a00001', 60_000]]), true], + ['three hours old', (h) => h.apply([['a00001', HOURS_3]]), false], + [ + 'landed', + (h) => { + h.apply([['a00001', 120_000]]); + h.apply([['a00001', 60_000, true]]); + h.landed.add('a00001'); + }, + false, + ], + ]) { + const h = harness(); + setUp(h); + h.flightState._trackedIcao = 'a00001'; + h.handOver(['a00002']); + assert.equal(h.iconIds.has('a00001'), kept, label); + } +}); diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 538c123e7f..a429d0237e 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -42,7 +42,6 @@ import { limitCourseStep, corridorPathLatLon, } from '../../data/motionModel.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { placeLiveAircraft } from './placed.js'; import { modelVisualAnchor, @@ -50,7 +49,6 @@ import { } from '../../data/modelVisualAnchor.js'; import { FOCUS_EVIDENCE_DEV, - MODEL_MIN_PX, TRACKED_BILLBOARD_SCALE_BY_DISTANCE, DR_CORRECTION_MS, COURSE_SLEW_DT_MAX_SEC, @@ -415,19 +413,17 @@ export function createMotion({ const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24), ); - // Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX. + // Drawn as the fleet draws it: at its true size. const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = (2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM; - return Math.max(MODEL_MIN_PX, projectedDiameterPx); + return projectedDiameterPx; } const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; const width = sprite?.width ?? 28; const height = sprite?.height ?? 28; - const scale = - sprite?.scale ?? - (CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1); + const scale = sprite?.scale ?? 1; const scaleByDistance = sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE; const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM); @@ -456,6 +452,8 @@ export function createMotion({ const sameTrack = flightState._drReconcileValid && flightState._drReconcileIcao === icao24; const raw = _deadReckon(icao24, flightState._scratchDrRaw); + flightState._cachedDRPlaced = + Boolean(raw) && flightState._drSpeedPlaced === true; flightState._cachedDRCourse = flightState._drCourseDeg; flightState._cachedDRSpeedMps = flightState._drSpeedMps; flightState._cachedDRHold = flightState._drCourseHold; @@ -601,6 +599,16 @@ export function createMotion({ * against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when * there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */ + /** Whether a host-supplied placement placed the tracked aircraft where + * `_trackedDisplayCached` holds it this frame, rather than this layer's + * own motion at its display delay. */ + + function _trackedPlaced() { + return ( + _trackedDisplayCached() !== null && flightState._cachedDRPlaced === true + ); + } + function _trackedDisplayCached() { return flightState._drReconcileValid && flightState._drReconcileIcao === flightState._trackedIcao @@ -645,9 +653,8 @@ export function createMotion({ /** Trail endpoint for the rendered tracked owner. Brackets/readouts stay on * the visual centre; only the trail moves to the model's lower-centre hardpoint. */ /** The tracked model's rendered bounding radius (m), or 0 when no model of this - * contact is drawing. Carries the scale it is drawn at, which may be - * above `scale` to satisfy its pixel floor — the trail head has to be judged - * against the size the operator SEES, not the nominal one. */ + * contact is drawing, at the scale it is drawn at — the trail head has to + * be judged against the size the operator SEES. */ /** World-space origin of the tracked model, or null when no model of this * contact is drawing. This is the centre the rendered bounding sphere is * measured from, so the trail clip and the envelope agree on one frame. */ @@ -1222,6 +1229,7 @@ export function createMotion({ _trackedFocusSizePx, _trackedDisplayPosition, _trackedDisplayCached, + _trackedPlaced, _trackedVisualCached, _trackedModelCenterWorld, _trackedModelEnvelopeM, diff --git a/src/layers/flights/motion.test.mjs b/src/layers/flights/motion.test.mjs index 3a26c120a9..3fd23d7f15 100644 --- a/src/layers/flights/motion.test.mjs +++ b/src/layers/flights/motion.test.mjs @@ -4,6 +4,8 @@ import * as Cesium from 'cesium'; import { createMotion } from './motion.js'; import { arcOffsetEnu } from '../../data/motionModel.js'; import { createMotion as createMilitaryMotion } from '../military/motion.js'; +import { createQueries } from './queries.js'; +import { createQueries as createMilitaryQueries } from '../military/queries.js'; import { layerPlacement } from '../../data/placementProvider.js'; import { observeLiveAircraft } from './placed.js'; @@ -248,18 +250,77 @@ const declining = (asked) => ); // Each kind's record carries only its own kinematics fields. -for (const [name, create, record] of [ +for (const [name, create, record, queriesOf] of [ [ 'civil', createMotion, { velocity: 100, true_track: 90, renderAltitudeM: 1234 }, + createQueries, ], [ 'military', createMilitaryMotion, { speedMps: 100, track: 90, renderAltitudeM: 1234 }, + createMilitaryQueries, ], ]) { + test(`${name} aircraft waiting where a placement holds them still show their reported speed`, () => { + // Drawn standing (speed 0) while its fixes catch up: the aircraft has + // not stopped, and the panels say what it reports. + const placement = layerPlacement( + { + layer: () => ({ + place: () => ({ + lat: 30.5, + lon: -96.5, + altitudeM: 2000, + courseDeg: 90, + speedMps: 0, + extrapolating: false, + }), + }), + }, + 'aircraft', + ); + const { flightState, motion, start } = placedScenario( + create, + placement, + record, + ); + flightState.now = () => start + 2000; + flightState.feed = {}; + flightState.records.missingPolls = new Map(); + const describe = (kinematics) => { + flightState.records.data.set('abc123', { ...record, ...kinematics }); + return queriesOf({ + flightState, + services: { + aircraftPresentation: { + tr3bTypeLabel: (_, label) => label, + tr3bAircraftClass: () => null, + }, + labels: { formatFlightLevel: String }, + militaryRegistry: {}, + focus: {}, + recession: {}, + }, + parts: { + motion, + icons: { _iconPosition: () => null }, + tracking: { _routeIsPlausible: () => false }, + testing: {}, + }, + })._describeFlight('abc123'); + }; + const waiting = describe({}); + assert.equal(flightState._drSpeedMps, 0); + assert.equal(waiting.velocityMps, 100); + // Nothing reported: the speed it is drawn at. + const unreported = + name === 'civil' ? { velocity: undefined } : { speedMps: undefined }; + assert.equal(describe(unreported).velocityMps, 0); + }); + test(`${name} aircraft move as before without a placement or with one that places nothing`, () => { const own = placedScenario(create, null, record).drawn; const asked = []; @@ -338,14 +399,20 @@ test('an aircraft fix is told to the placement live, with its drawn height', () 'aircraft', ); const state = { timeline: { active: () => false } }; - const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false }; + const meta = { + rawLat: 1, + rawLon: 2, + renderAltitudeM: 300, + groundM: 1656, + onGround: false, + }; observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270); observeLiveAircraft( state, placement, 'abc123', 6000, - { ...meta, renderAltitudeInvented: true, onGround: true }, + { ...meta, renderAltitudeInvented: true, groundM: null, onGround: true }, null, undefined, ); @@ -360,12 +427,15 @@ test('an aircraft fix is told to the placement live, with its drawn height', () lat: 1, lon: 2, altitudeM: 300, + groundM: 1656, speedMps: 80, courseDeg: 270, headingDeg: NaN, onGround: false, }, ]); + // Where the layer does not know the ground, it says so. + assert.ok(Number.isNaN(told[1][1].groundM)); assert.ok(Number.isNaN(told[1][1].altitudeM)); assert.ok(Number.isNaN(told[1][1].speedMps)); assert.ok(Number.isNaN(told[1][1].courseDeg)); diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs index 3947a6999f..6fa9f9d511 100644 --- a/src/layers/flights/ownership.test.mjs +++ b/src/layers/flights/ownership.test.mjs @@ -608,3 +608,75 @@ test('a route answer for a callsign the plane no longer flies is dropped', async assert.equal(meta.routeCallsign, 'UAL10'); flightState.lifetime.abort(); }); + +test("a type lookup overrides the feed's type and fills the type name", async () => { + const queries = []; + const source = { + getEnrichment(query) { + queries.push(query); + return Promise.resolve({ + found: true, + typeCode: 'B738', + typeName: 'Boeing 737-800', + registration: 'N123AB', + }); + }, + }; + const flightState = createFlightState({ source, services: services() }); + const view = { + viewerLatDeg: null, + viewerLonDeg: null, + trackedId: null, + floorWarmPoints: [], + }; + const { meta } = flightState.records.receive( + { + id: 'abc123', + reference: 'abc123', + longitude: -77, + latitude: 39, + callsign: 'TEST1', + baroAltitudeM: 1000, + typeCode: 'EC45', + }, + view, + ); + assert.equal(meta.klass, 'helicopter', 'classed by the feed type at once'); + const restyled = []; + const synced = []; + const enrichment = createEnrichment({ + flightState, + services: enrichServices(), + parts: { + icons: { _applyIconPresentation: (id) => restyled.push(id) }, + rendering: { _syncModelToClass: (id) => synced.push(id) }, + }, + }); + // A present feed type does not skip the lookup. + enrichment._requestTypeEnrichment('abc123', true); + await new Promise((done) => setImmediate(done)); + assert.deepEqual(queries, [{ kind: 'type', id: 'abc123' }]); + const looked = flightState.records.data.get('abc123'); + assert.equal(looked.typeCode, 'B738'); + assert.equal(looked.typeName, 'Boeing 737-800'); + assert.equal(looked.registration, 'N123AB'); + assert.equal(looked.klass, 'airliner'); + assert.deepEqual(restyled, ['abc123']); + assert.deepEqual(synced, ['abc123']); + // The next poll's feed type no longer wins. + const next = flightState.records.receive( + { + id: 'abc123', + reference: 'abc123', + longitude: -77, + latitude: 39, + callsign: 'TEST1', + baroAltitudeM: 1000, + typeCode: 'EC45', + }, + view, + ).meta; + assert.equal(next.typeCode, 'B738'); + assert.equal(next.klass, 'airliner'); + flightState.lifetime.abort(); +}); diff --git a/src/layers/flights/placed.js b/src/layers/flights/placed.js index 69949087db..b17afb678c 100644 --- a/src/layers/flights/placed.js +++ b/src/layers/flights/placed.js @@ -61,6 +61,7 @@ export function placeLiveAircraft( history, out, ) { + flightState._drSpeedPlaced = false; if (!placement || followsClock(flightState)) return false; const placed = placeAircraftAt( placement, @@ -73,6 +74,7 @@ export function placeLiveAircraft( if (!placed) return false; flightState._drCourseDeg = placed.courseDeg; flightState._drSpeedMps = placed.speedMps; + flightState._drSpeedPlaced = true; flightState._drCourseHold = placed.speedMps < COURSE_HOLD_SPEED_MPS; flightState._drExtrapolating = placed.extrapolating; return true; @@ -93,13 +95,15 @@ export function forgetPlacedAircraft(placement, ids) { * Tell the host-supplied placement an aircraft's fix as the layer took it * (nothing while the layer follows the world clock): its own time, its * position, the height the layer draws it at (NaN when that height is - * invented), and its reported speed, course and ground state. + * invented), the ground under it in that height's reference (NaN where the + * layer does not know it), and its reported speed, course and ground state. * @param {object} flightState * @param {object|null|undefined} placement * @param {string} icao24 * @param {number} fixEpochMs * @param {{rawLat: number, rawLon: number, renderAltitudeM: number, - * renderAltitudeInvented?: boolean, onGround?: boolean}} meta + * renderAltitudeInvented?: boolean, groundM?: number|null, + * onGround?: boolean}} meta * @param {number|null|undefined} speedMps * @param {number|null|undefined} courseDeg */ @@ -119,6 +123,7 @@ export function observeLiveAircraft( lon: meta.rawLon, altitudeM: meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM, + groundM: Number.isFinite(meta.groundM) ? meta.groundM : NaN, speedMps: Number.isFinite(speedMps) ? speedMps : NaN, courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN, headingDeg: NaN, diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index 839be56fef..a82faa5c55 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -1,5 +1,6 @@ import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js'; import { cssColor } from '../../render/color.js'; +import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js'; /** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */ const rgba = (css, alpha) => @@ -13,6 +14,10 @@ export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true; export const MIL_TINT = rgba('#FFB800'); +/** Amber tint for airport vehicles (type ZVEH, emitter C1/C2), apart from aircraft. */ + +export const VEHICLE_TINT = rgba(VEHICLE_TINT_CSS); + /** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */ export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS); @@ -39,18 +44,27 @@ export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS); export const GROUND_SCALE = 0.8; // --- 3D model rendering (B3) --------------------------------------------------------- -// When enabled, aircraft render as 3D glTF models once the camera is below MODEL_ALT_CEIL_M -// (zoomed in); higher up they stay flat billboards. Eligibility is FRUSTUM-based (on-screen), and -// the slots go to either the nearest planes ('proximity') or every in-view plane ('all'), each -// backed by a hard cap so a draw-call explosion can't tank the frame (no instancing yet). +// When enabled, an aircraft draws as its 3D glTF model only within MODEL_ADD_M of the camera +// (eye to aircraft); farther away it stays its icon. Models are drawn at their true size, with no +// minimum pixel size, so a model never balloons past its real extent. Eligibility is distance-based +// with on-screen priority, and the slots go to either the nearest planes ('proximity') or every +// in-range plane ('all'): the two modes share the radius and differ by their caps, each a hard +// bound on the frame cost (every model is its own draw call). -export const MODEL_ALT_CEIL_M = 800000; -// m: below this camera altitude, draw 3D models (raised so it's easy to trigger) +export const MODEL_ADD_M = 3000; +// model NEW planes within 3 km of the camera -export const MODEL_MIN_PX = 24; -// floor so distant models stay visible WITHOUT ballooning into a giant -// min-pixel blob (was 54 — far planes at the All radius became white -// star-bursts); ~matches the 2D icon size so the model↔billboard read is consistent +export const MODEL_KEEP_M = 3600; +// KEEP modeled planes out to 3.6 km: the hysteresis band (KEEP > ADD) stops a plane on the edge +// from releasing and reloading its model as the camera moves (the zoom/pan flicker) + +export const MODEL_HIGHEST_CONTACT_M = 30000; +// m above the ellipsoid: no aircraft the layers draw flies higher (airliners cruise near 12 km, +// the highest-flying aircraft near 21 km) + +export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M; +// m: above this camera altitude no contact can be within MODEL_KEEP_M, so no model is +// considered at all (the eligibility pass is skipped) // Per-mode caps. Each model is its own draw call (no instancing yet), so these bound the frame cost. @@ -58,29 +72,22 @@ export const MODEL_MAX = 150; // 'proximity' cap (the planes immediately around you) export const MODEL_MAX_ALL = 350; -// 'all' cap (everything out to ~the horizon) -// Per-mode ADD / KEEP radii. The two modes differ by RADIUS, not just cap — otherwise they look -// IDENTICAL whenever fewer than a cap's worth of planes are in range (field bug: Proximity and All -// rendered the same). 'proximity' = a tight ring; 'all' = roughly to the horizon (state-scale). Each -// band has hysteresis (KEEP > ADD) so a plane doesn't release+reload its model when it straddles the -// add edge (the zoom/pan flicker). Beyond ADD a model would force-clamp to minimumPixelSize into a -// giant floating blob (the old 422 km airport-cluster bug), so far planes stay 2D dots; the cap + -// on-screen priority then spend the model slots on planes you can actually see. - -export const MODEL_PROX_ADD_M = 150000; -// proximity: model NEW planes within 150 km - -export const MODEL_PROX_KEEP_M = 185000; -// proximity: KEEP modeled planes out to 185 km +// 'all' cap (every plane in range) export const COCKPIT_MODEL_MAX = 60; // max concurrent GLBs in cockpit (never raises the map cap) -export const MODEL_ALL_ADD_M = 400000; -// all: model NEW planes within 400 km (~to the horizon) +// Cockpit's AIR band: contacts within it draw as aircraft silhouettes, beyond +// it as compact dots. Independent of the 3D model radius; per 3D mode, each +// with its keep hysteresis. -export const MODEL_ALL_KEEP_M = 450000; -// all: KEEP modeled planes out to 450 km +export const COCKPIT_AIR_PROX_ADD_M = 150000; + +export const COCKPIT_AIR_PROX_KEEP_M = 185000; + +export const COCKPIT_AIR_ALL_ADD_M = 400000; + +export const COCKPIT_AIR_ALL_KEEP_M = 450000; export const MODEL_HEADING_OFFSET_DEG = 180; // every fleet model is nose -X: opposite the renderer's heading 0 @@ -88,9 +95,6 @@ export const MODEL_HEADING_OFFSET_DEG = 180; /** A model's colour where it draws its mesh's own (`aircraftModelBlend`). */ export const MODEL_WHITE = rgba('#FFFFFF'); -/** The tracked contact's tint, and its billboard once a model takes over. */ -export const TRACKED_CYAN = rgba('#00FFFF'); -export const CYAN_TRANSPARENT = rgba('#00FFFF', 0); /** An ordinary fleet contact's tint. */ export const FLEET_TINT = rgba('#FFFFFF'); @@ -201,18 +205,15 @@ export const FLEET_DR_INTERVAL_MS = 80; /** * The icon-to-model rules the aircraft layers follow, as the Vessels, Transit * and Rail layers take them (`createFleetModelLayer`): the same altitude - * ceiling, minimum pixel size, proximity/all caps, add/keep radii and - * eligibility cadence, so every layer turns icons into models at one distance. + * ceiling, proximity/all caps, add/keep radii and eligibility cadence, so + * every layer turns icons into models at one distance, drawn at true size. */ export const FLEET_MODEL_POLICY = Object.freeze({ altitudeCeilingM: MODEL_ALT_CEIL_M, - minimumPixelSize: MODEL_MIN_PX, cap: MODEL_MAX, capAll: MODEL_MAX_ALL, - addM: MODEL_PROX_ADD_M, - addAllM: MODEL_ALL_ADD_M, - keepM: MODEL_PROX_KEEP_M, - keepAllM: MODEL_ALL_KEEP_M, + addM: MODEL_ADD_M, + keepM: MODEL_KEEP_M, intervalMs: FLEET_DR_INTERVAL_MS, }); diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 365af11db6..a696165b9a 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -145,6 +145,7 @@ export function createQueries({ derivedSpeedMps: flightState._drSpeedMps, derivedTrackDeg: flightState._drCourseDeg, reportedSpeedMps: info?.velocity, + derivedFromPlacement: flightState._drSpeedPlaced === true, reportedTrackDeg: info?.true_track, }); const carto = toLonLatH(basePos); @@ -345,11 +346,11 @@ export function createQueries({ /** * Live layer params. - * `models3d` toggles 3D glTF model rendering for the FLEET (altitude-gated): when on, - * surrounding aircraft become 3D models once the camera is zoomed in past MODEL_ALT_CEIL_M. + * `models3d` toggles 3D glTF model rendering for the FLEET: when on, aircraft within + * MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true size. * The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), so selecting * a contact never turns its icon into a model or its model into an icon. - * `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane). + * `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius. * @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedFlightsTrackingId?: string|null}} params */ setParams(params = {}, { origin = 'programmatic' } = {}) { diff --git a/src/layers/flights/records.js b/src/layers/flights/records.js index 9dbe08de6d..9b4653330c 100644 --- a/src/layers/flights/records.js +++ b/src/layers/flights/records.js @@ -92,11 +92,11 @@ export class FlightRecords { originCountry: origin_country, longitude: lon, latitude: lat, - baroAltitudeM: baro_alt, + baroAltitudeM: reportedBaroAlt, onGround: on_ground, speedMps: velocity, courseDeg: true_track, - ellipsoidAltitudeM: geo_alt, + ellipsoidAltitudeM: reportedGeoAlt, category, verticalRateMps: vertical_rate, } = observation; @@ -110,11 +110,12 @@ export class FlightRecords { // The airframe's facts: this record's, or those kept across a reset. const airframe = prevMeta ?? this.airframes.get(icao24); this.airframes.delete(icao24); - // A ground vehicle or ground station (a feed's ZVEH or GRND: a model - // built standing, catalog category `other`) takes the feed's own type, - // which no airframe lookup knows; every other aircraft keeps waiting for - // its looked-up type. With no altitude at all it stands on the ground, - // where it is, instead of at the airborne default. + // The feed's own ICAO type classes the contact and picks its model from + // the first fix; a looked-up type outranks it once one has answered. + // A ground vehicle or ground station (a feed's ZVEH or GRND) is known + // from its feed type alone, which no airframe lookup knows. With no + // altitude at all, a contact drawn with a model built standing is on the + // ground, where it is, instead of at the airborne default. const groundModel = (typeCode) => drawnAsGroundModel( this.fleetModels(), @@ -122,12 +123,33 @@ export class FlightRecords { category, stickyText(callsign, prevMeta?.callsign), ); - const feedType = observation.typeCode || null; - const typeCode = - airframe?.typeCode ?? - (feedType && groundModel(feedType) ? feedType : null); + const feedType = cleanType(observation.typeCode); + // A surface category keeps only a feed's ground type: a C1 contact whose + // feed names an airliner type stays a vehicle. + // A feed's ground type holds only for a contact that behaves as one: an + // airport vehicle reported airborne, or faster than a vehicle drives (a + // test transponder, a drone), is classed as any other aircraft. + const driving = + !(Number.isFinite(velocity) && velocity > VEHICLE_MAX_SPEED_MPS) && + (on_ground === true || + (!Number.isFinite(reportedBaroAlt) && + !Number.isFinite(reportedGeoAlt))); + const keepFeedType = + Boolean(feedType) && + (feedType !== 'ZVEH' || driving) && + (!groundCategory(category) || GROUND_FEED_TYPES.has(feedType)); + // A ground station is fixed: it stands on the ground whatever height its + // reports carry, as if they carried none. + const station = keepFeedType && feedType === 'GRND'; + const baro_alt = station ? null : reportedBaroAlt; + const geo_alt = station ? null : reportedGeoAlt; + const typeLookedUp = airframe?.typeLookedUp === true; + const typeCode = typeLookedUp + ? airframe.typeCode + : ((keepFeedType ? feedType : null) ?? airframe?.typeCode ?? null); const onGround = on_ground === true || + station || (!Number.isFinite(baro_alt) && !Number.isFinite(geo_alt) && groundModel(typeCode)); @@ -261,6 +283,10 @@ export class FlightRecords { // within GROUND_FLOOR_CLAMP_RADIUS_KM of the viewer — the only ones // whose burial is visible. Cells warm in one batch after the loop. // Airborne only (grounded planes keep the surface-cache path above). + // The ground under the contact in its render height's reference, where + // the warm cache knows it: the surface it stands on, or the floor under a + // low contact near the view. A landing is judged above it. + let groundM = onGround ? surfaceM : null; if ( !onGround && renderAltitudeM < GROUND_FLOOR_WARM_MAX_ALT_M && @@ -269,10 +295,8 @@ export class FlightRecords { approxDistanceKm(viewerLatDeg, viewerLonDeg, lat, lon) <= GROUND_FLOOR_CLAMP_RADIUS_KM)) ) { - renderAltitudeM = floorAltitudeM( - renderAltitudeM, - cachedGroundFloor(lat, lon), - ); + groundM = cachedGroundFloor(lat, lon); + renderAltitudeM = floorAltitudeM(renderAltitudeM, groundM); floorWarmPoints.push({ lat, lon }); } @@ -280,7 +304,8 @@ export class FlightRecords { const groundFlipped = !!prevMeta && (prevMeta.onGround === true) !== onGround; // Store flight metadata for click-to-track labels - const cat = stickyNumber(category, prevMeta?.category, null); + // OpenSky's integer category, or a feed's ADS-B emitter category ("C1"). + const cat = stickyCategory(category, prevMeta?.category); const nextCallsign = stickyText(callsign, prevMeta?.callsign); // A route (and its airline) belongs to the callsign it was looked up for; // a new callsign drops it, so an old flight's route never shows under it. @@ -311,6 +336,7 @@ export class FlightRecords { geoAltitudeM, renderAltitudeM, renderAltitudeInvented, + groundM: Number.isFinite(groundM) ? groundM : null, onGround, // Round 7: sticky airborne history — the landed fast-cull only // applies to contacts that actually flew this session. @@ -325,11 +351,9 @@ export class FlightRecords { ), courseAnchor: course.anchor, category: cat, - // An adsbdb-enriched type code outranks the coarse OpenSky category. - klass: classifyAircraft({ - typeCode: airframe?.typeCode ?? null, - category: cat, - }), + // A type code (the feed's, or a looked-up one) outranks the coarse + // emitter category, from the first fix. + klass: classifyAircraft({ typeCode, category: cat }), turnRateDps: prevMeta?.turnRateDps || 0, verticalRate: stickyNumber(vertical_rate, prevMeta?.verticalRate, null), // Analyst seam: OpenSky origin_country (state[2]) — additive, sticky @@ -362,8 +386,9 @@ export class FlightRecords { null, ), // adsbdb enrichment — written by the enrichment callbacks, carried - // across polls; a ground vehicle's or station's from the feed: + // across polls; the type is the feed's own until a lookup answers: typeCode, + typeLookedUp, typeName: airframe?.typeName ?? null, registration: airframe?.registration ?? null, airline: routeHeld ? (airframe.airline ?? null) : null, @@ -428,6 +453,7 @@ export class FlightRecords { for (const [id, meta] of this.data) { this.airframes.set(id, { typeCode: meta.typeCode, + typeLookedUp: meta.typeLookedUp, typeName: meta.typeName, registration: meta.registration, airline: meta.airline, @@ -452,13 +478,54 @@ export class FlightRecords { } } +/** An ADS-B emitter category as a feed gives it ("A3", "C1"). */ +const EMITTER_CATEGORY = /^[A-D][0-7]$/; + +/** + * A contact's category, kept across polls that omit it: OpenSky's integer + * category or an ADS-B emitter category string, else the last one, else null. + * @param {*} next + * @param {*} prev + * @returns {number|string|null} + */ +function stickyCategory(next, prev) { + if (Number.isFinite(next)) return next; + const text = typeof next === 'string' ? next.trim().toUpperCase() : ''; + if (EMITTER_CATEGORY.test(text)) return text; + return prev ?? null; +} + +/** A feed's ICAO type designator, upper case, or null. */ +function cleanType(value) { + const text = typeof value === 'string' ? value.trim().toUpperCase() : ''; + return text || null; +} + +/** The types a feed gives airport vehicles (ZVEH) and ground stations (GRND). */ +const GROUND_FEED_TYPES = new Set(['ZVEH', 'GRND']); +/** The fastest an airport vehicle drives, m/s (144 km/h); faster, it is no vehicle. */ +const VEHICLE_MAX_SPEED_MPS = 40; + /** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */ const groundModelCaches = new WeakMap(); +/** + * Whether an emitter category is a surface one: a vehicle or an obstacle + * (ADS-B C1 to C5, OpenSky 16 to 20). + * @param {string|number|null} category + * @returns {boolean} + */ +function groundCategory(category) { + if (Number.isInteger(category)) return category >= 16 && category <= 20; + return typeof category === 'string' && /^C[1-5]$/i.test(category.trim()); +} + /** * Whether an aircraft of this type, emitter category and callsign is drawn * with a model built standing on the ground (catalog category `other`: an - * airport vehicle, a ground station's mast). False before the set loads. + * airport vehicle, a ground station's mast). A surface emitter category + * (C1 to C5, OpenSky 16 to 20) always is. Otherwise, before the set loads, + * whether the type is one a feed gives ground vehicles and stations. * Answered once per type, category and callsign rule matched. * @param {object|null} set The loaded fleet model set. * @param {string|null} typeCode @@ -467,7 +534,11 @@ const groundModelCaches = new WeakMap(); * @returns {boolean} */ function drawnAsGroundModel(set, typeCode, category, callsign) { - if (!set || !typeCode) return false; + if (groundCategory(category)) return true; + if (!typeCode) return false; + // Before the set loads, the feed's own ground types: an airport vehicle + // must not be drawn as an aircraft until the set says what it is. + if (!set) return GROUND_FEED_TYPES.has(typeCode.trim().toUpperCase()); let cache = groundModelCaches.get(set); if (!cache) groundModelCaches.set(set, (cache = new Map())); const rule = aircraftCallsignRule(set.types, typeCode, callsign); diff --git a/src/layers/flights/records.test.mjs b/src/layers/flights/records.test.mjs index 1aaddcf5b4..9ec4b74679 100644 --- a/src/layers/flights/records.test.mjs +++ b/src/layers/flights/records.test.mjs @@ -283,6 +283,7 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc observation({ id: 'v1', typeCode: 'ZVEH', + speedMps: 8, callsign: 'FIRE 2', ...noAltitude, }), @@ -298,26 +299,175 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc assert.equal(mast.onGround, true); assert.equal(mast.typeCode, 'GRND'); // An airliner with no altitude keeps the airborne default, and its feed - // type still waits for the airframe lookup. + // type from the first fix. const plane = store.receive( observation({ id: 'p1', typeCode: 'A320', ...noAltitude }), view(), ).meta; assert.equal(plane.onGround, false); assert.equal(plane.altitude, 10000); - assert.equal(plane.typeCode, null); - // A vehicle reporting an altitude is placed by it. + assert.equal(plane.typeCode, 'A320'); + // An "airport vehicle" reported airborne is no vehicle (a drone, a test + // transponder): it is placed by its altitude and classed as an aircraft. const reported = store.receive( - observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }), + observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 762 }), view(), ).meta; assert.equal(reported.onGround, false); - // Before the model set loads nothing is grounded by its model. - const unloaded = records().receive( - observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }), + assert.equal(reported.typeCode, null); + assert.notEqual(reported.klass, 'vehicle'); + // Nor is one on the ground faster than a vehicle drives. + const fast = store.receive( + observation({ + id: 'v4', + typeCode: 'ZVEH', + onGround: true, + speedMps: 77, + ...noAltitude, + }), view(), ).meta; - assert.equal(unloaded.onGround, false); + assert.notEqual(fast.klass, 'vehicle'); + // A ground station stands on the ground whatever height it reports. + const high = store.receive( + observation({ id: 'm2', typeCode: 'GRND', baroAltitudeM: 11880 }), + view(), + ).meta; + assert.equal(high.onGround, true); + assert.equal(high.klass, 'station'); + assert.equal(high.altitude, 0); + assert.ok( + !(high.renderAltitudeM > 1000), + `drawn at ${high.renderAltitudeM} m`, + ); + // Before the model set loads, the feed's ground types already count: an + // airport vehicle is never drawn as an aircraft first. + const early = records(); + const unloaded = early.receive( + observation({ id: 'v3', typeCode: 'ZVEH', speedMps: 8, ...noAltitude }), + view(), + ).meta; + assert.equal(unloaded.onGround, true); + assert.equal(unloaded.typeCode, 'ZVEH'); + const earlyPlane = early.receive( + observation({ id: 'p2', typeCode: 'A320', ...noAltitude }), + view(), + ).meta; + assert.equal(earlyPlane.onGround, false); + assert.equal(earlyPlane.typeCode, 'A320'); +}); + +test('airport vehicles and ground stations take their class from the first fix', () => { + // Before the model set loads, and after. + for (const store of [records(), records(() => fleetSet)]) { + const klass = (fields) => + store.receive(observation({ callsign: '', ...fields }), view()).meta + .klass; + // An airport vehicle reports itself on the ground, at a vehicle's speed. + const driving = { onGround: true, speedMps: 8 }; + assert.equal(klass({ id: 'v1', typeCode: 'ZVEH', ...driving }), 'vehicle'); + assert.equal( + klass({ id: 'v2', typeCode: 'ZVEH', callsign: 'FIRE 2', ...driving }), + 'vehicle', + ); + assert.equal(klass({ id: 'v3', category: 'C1' }), 'vehicle'); + assert.equal(klass({ id: 'v4', category: 'C2' }), 'vehicle'); + assert.equal(klass({ id: 'm1', typeCode: 'GRND' }), 'station'); + assert.equal(klass({ id: 'm2', category: 'C4' }), 'station'); + // An aircraft's feed type outranks its emitter category. + assert.equal( + klass({ id: 'p1', typeCode: 'A320', category: 'A7' }), + 'airliner', + ); + } +}); + +test("an aircraft's feed type classes it from the first fix, until a lookup answers", () => { + for (const store of [records(), records(() => fleetSet)]) { + // A helicopter whose feed names its type, with an airliner-like category. + const first = store.receive( + observation({ + id: 'h1', + callsign: 'NHC47', + typeCode: 'ec45', + category: 'A3', + }), + view(), + ).meta; + assert.equal(first.typeCode, 'EC45'); + assert.equal(first.klass, 'helicopter'); + assert.equal(first.typeLookedUp, false); + // A later row without the type keeps it. + const quiet = store.receive( + observation({ id: 'h1', callsign: 'NHC47', category: 'A3' }), + view(), + ).meta; + assert.equal(quiet.klass, 'helicopter'); + assert.equal(quiet.typeCode, 'EC45'); + // A looked-up type outranks the feed's on every later poll and reset. + quiet.typeCode = 'EC35'; + quiet.typeLookedUp = true; + quiet.typeName = 'Airbus Helicopters H135'; + const after = store.receive( + observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }), + view(), + ).meta; + assert.equal(after.typeCode, 'EC35'); + assert.equal(after.typeName, 'Airbus Helicopters H135'); + assert.equal(after.klass, 'helicopter'); + store.reset(); + const again = store.receive( + observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }), + view(), + ).meta; + assert.equal(again.typeCode, 'EC35'); + // No type anywhere: the emitter category classes it. + const bare = store.receive( + observation({ id: 'h2', category: 'A7' }), + view(), + ).meta; + assert.equal(bare.typeCode, null); + assert.equal(bare.klass, 'helicopter'); + } +}); + +test('a surface emitter category stands on the ground, before and after the model set loads', () => { + const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null }; + for (const store of [records(), records(() => fleetSet)]) { + for (const [id, category] of [ + ['c1', 'C1'], + ['c2', 'C2'], + ['c3', 'C3'], + ['c5', 'C5'], + ['o16', 16], + ['o20', 20], + ]) { + const meta = store.receive( + observation({ id, category, callsign: '', ...noAltitude }), + view(), + ).meta; + assert.equal(meta.onGround, true, `${id} stands on the ground`); + assert.equal(meta.altitude, 0, id); + } + // An aircraft category with no altitude keeps the airborne default. + const plane = store.receive( + observation({ id: 'a3', category: 'A3', ...noAltitude }), + view(), + ).meta; + assert.equal(plane.onGround, false); + // A feed's aircraft type on a surface category does not make it an aircraft. + const odd = store.receive( + observation({ + id: 'c9', + category: 'C1', + typeCode: 'A320', + ...noAltitude, + }), + view(), + ).meta; + assert.equal(odd.klass, 'vehicle'); + assert.equal(odd.onGround, true); + } }); test('a contact reported with no course faces the way its newer fixes went', () => { @@ -365,3 +515,38 @@ test('a contact reported with no course faces the way its newer fixes went', () taxi(30.188, 20); assert.equal(course(), 0); }); + +test('a low contact near the view carries the ground under it; others carry none', () => { + const store = new FlightRecords({ + geoidHeight: () => 40, + cachedGroundFloor: () => 1656, + floorAltitudeM: (altitude, ground) => + Math.max(altitude, ground ?? -Infinity), + fleetModels: () => null, + }); + const denver = { latitude: 39.85, longitude: -104.67 }; + const near = { ...view(), viewerLatDeg: 39.8, viewerLonDeg: -104.7 }; + // Landing at Denver: 1,900 m above the ellipsoid over 1,656 m ground. + const landing = store.receive( + observation({ id: 'l1', ...denver, ellipsoidAltitudeM: 1900 }), + near, + ).meta; + assert.equal(landing.groundM, 1656); + // At cruise the ground is not read. + const cruise = store.receive( + observation({ + id: 'c1', + ...denver, + ellipsoidAltitudeM: 11000, + baroAltitudeM: 11000, + }), + near, + ).meta; + assert.equal(cruise.groundM, null); + // Nor without a view to be near. + const away = store.receive( + observation({ id: 'a1', ...denver, ellipsoidAltitudeM: 1900 }), + view(), + ).meta; + assert.equal(away.groundM, null); +}); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index c5364600fe..50ce7de051 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -2,13 +2,12 @@ import { aircraftLayerModelSpec, aircraftModelSpecCacheKey, } from './modelSpec.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { isEmergency } from '../../data/aircraftEmergency.js'; import { MIL_TINT, EMERGENCY_TINT, + VEHICLE_TINT, FLEET_TINT, - TRACKED_CYAN, GROUND_SCALE, COCKPIT_CIVILIAN_COLOR, } from './policy.js'; @@ -32,14 +31,16 @@ export function createRendering({ } /** Fleet (untracked) billboard tint: red while broadcasting an emergency, - * amber for known-military, white otherwise. - * Ground traffic gets NO special tint (owner verdict 2026-07-03 field test). */ + * orange amber for an airport vehicle, amber for known-military, white + * otherwise. Grounded aircraft get NO special tint (owner verdict + * 2026-07-03 field test). */ function _fleetBillboardColor( icao24, info = flightState.records.data.get(icao24), ) { if (_isEmergency(icao24, info)) return EMERGENCY_TINT; + if (info?.klass === 'vehicle') return VEHICLE_TINT; return isMilitaryIcao(icao24) ? MIL_TINT : FLEET_TINT; } @@ -53,13 +54,10 @@ export function createRendering({ return isMilitaryIcao(icao24) ? MIL_TINT : COCKPIT_CIVILIAN_COLOR; } - /** Fleet billboard scale: per-class scale, ×GROUND_SCALE while grounded. */ + /** Fleet billboard scale: one size for every class, ×GROUND_SCALE while grounded. */ - function _fleetBillboardScale(icao24, klass) { - return ( - (CLASS_SCALE_2D[klass] || 1) * - (flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1) - ); + function _fleetBillboardScale(icao24) { + return flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1; } /** The fleet model an aircraft draws with, by its type and emitter category. */ @@ -82,11 +80,10 @@ export function createRendering({ const _iconKind = (icao24, klass) => tr3bIconKind(icao24, klass, { hot: flightState._irBoost }); - /** Model colour: the mesh's own (white), tinted cyan while tracked and red - * while broadcasting an emergency. */ + /** Model colour: the mesh's own (white), tinted red while broadcasting an + * emergency. Tracking never recolours it. */ function _modelColor(icao24) { - if (icao24 === flightState._trackedIcao) return TRACKED_CYAN; return _isEmergency(icao24) ? EMERGENCY_TINT : policy.MODEL_WHITE; } diff --git a/src/layers/flights/rendering.test.mjs b/src/layers/flights/rendering.test.mjs new file mode 100644 index 0000000000..396a1964f4 --- /dev/null +++ b/src/layers/flights/rendering.test.mjs @@ -0,0 +1,43 @@ +// src/layers/flights/rendering.test.mjs +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { createRendering as createFlightsRendering } from './rendering.js'; +import { createRendering as createMilitaryRendering } from '../military/rendering.js'; + +function rendering(create) { + const data = new Map([ + ['light', { klass: 'light' }], + ['quadjet', { klass: 'quadjet' }], + ['vehicle', { klass: 'vehicle' }], + ['parked', { klass: 'quadjet', onGround: true }], + ]); + return create({ + flightState: { records: { data } }, + services: { + militaryRegistry: { isMilitaryIcao: () => false }, + aircraftPresentation: { tr3bIconKind: () => null }, + focus: { focusNowMs: () => 0, getFocusTarget: () => null }, + }, + parts: {}, + layer: {}, + resolveAsset: (url) => url, + }); +} + +test('Flights draws every class at one size, smaller on the ground', () => { + const r = rendering(createFlightsRendering); + for (const id of ['light', 'quadjet', 'vehicle']) { + assert.equal(r._fleetBillboardScale(id), 1, id); + } + assert.equal(r._fleetBillboardScale('parked'), 0.8); +}); + +test('Military draws every class at its one size, smaller on the ground', () => { + const r = rendering(createMilitaryRendering); + const size = r._fleetBillboardScale('light'); + for (const id of ['quadjet', 'vehicle']) { + assert.equal(r._fleetBillboardScale(id), size, id); + } + assert.ok(Math.abs(r._fleetBillboardScale('parked') - size * 0.8) < 1e-12); +}); diff --git a/src/layers/flights/snapshotRenderer.js b/src/layers/flights/snapshotRenderer.js index 87ef958060..228e2d3624 100644 --- a/src/layers/flights/snapshotRenderer.js +++ b/src/layers/flights/snapshotRenderer.js @@ -56,8 +56,16 @@ export function createFlightSnapshotRenderer({ /** * `replace`: the snapshot is the world at another time (the world clock * jumped), so it stands in for every contact: one it lacks is gone at once. + * `handover`: the first live snapshot after the clock came back to live: it + * stands in for every contact too, and those it has keep their icon and + * model and ease on from where they are drawn; of those it lacks, only + * those absence keeps (judged by their newest fix) stay. */ - return function applySnapshot(snapshot, viewer, { replace = false } = {}) { + return function applySnapshot( + snapshot, + viewer, + { replace = false, handover = false } = {}, + ) { // Before init (or after destroy) there is no icon set to draw into. if (!flightState._icons) return { count: 0, ids: new Set() }; const currentIcaos = new Set(); @@ -254,7 +262,7 @@ export function createFlightSnapshotRenderer({ // freshness change and the cockpit contract all land on the row's // style; motion re-plans from the updated history. icons._applyIconPresentation(icao24); - icons._planIcon(icao24); + icons._planIcon(icao24, handover ? { handover } : undefined); // Poll-path type or category change: same model resync rule as the // enrichment path — the fleet model or its scale may have changed. if ( @@ -294,6 +302,23 @@ export function createFlightSnapshotRenderer({ // EXCEPTION: likely-landed planes (last fix low + slow) get only // LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a // feed gap, and the full grace left phantom planes parked at airports. + // Back at live, a contact it lacks is from the time the clock left: it + // goes at once, unless absence keeps it as any poll would (a partial or + // retaining snapshot, the tracked aircraft), judged by its newest fix. + // No missed-poll grace, and a landed tracked aircraft is not kept. + const absenceAtHandover = (icao24) => { + const likelyLanded = queries._likelyLanded(icao24); + const judged = records.absence(icao24, { + complete: snapshot.complete, + retainIds: snapshot.retainIds, + likelyLanded, + tracked: icao24 === flightState._trackedIcao && !likelyLanded, + nowMs: flightState.now?.(), + }); + return judged === 'stale' && icao24 !== flightState._trackedIcao + ? 'remove' + : judged; + }; const absentIds = []; for (const icao24 of flightState._icons.ids()) { if (!currentIcaos.has(icao24)) absentIds.push(icao24); @@ -301,13 +326,15 @@ export function createFlightSnapshotRenderer({ for (const icao24 of absentIds) { const absence = replace ? 'remove' - : records.absence(icao24, { - complete: snapshot.complete, - retainIds: snapshot.retainIds, - likelyLanded: queries._likelyLanded(icao24), - tracked: icao24 === flightState._trackedIcao, - nowMs: flightState.now?.(), - }); + : handover + ? absenceAtHandover(icao24) + : records.absence(icao24, { + complete: snapshot.complete, + retainIds: snapshot.retainIds, + likelyLanded: queries._likelyLanded(icao24), + tracked: icao24 === flightState._trackedIcao, + nowMs: flightState.now?.(), + }); if (absence === 'retain') continue; if (absence === 'stale') { icons._applyIconPresentation(icao24); // the faded freshness alpha @@ -334,7 +361,8 @@ export function createFlightSnapshotRenderer({ icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak) } - // The tracked contact at the new time: its trail starts there. + // The tracked contact at the new time: its trail starts there. Back at + // live its trail goes on. if ( replace && flightState._trackedIcao && diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index dee00cc4d2..c0e23de720 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -266,6 +266,18 @@ export function createFlightState({ source, services }) { flightState._drSpeedMps = null; + /** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's, + * the speed it is drawn at (0 while it waits for its fixes), for motion + * only; panels show the reported ground speed (`displayedKinematics`). */ + + flightState._drSpeedPlaced = false; + + /** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed + * it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail + * ends where it is drawn rather than at the layer's display delay. */ + + flightState._cachedDRPlaced = false; + flightState._drCourseHold = false; /** Sibling scratch: whether the position `_deadReckon` just returned came from diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index bf2362a52b..a50c002390 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -1,4 +1,4 @@ -import { CYAN_TRANSPARENT, TRACKED_CYAN } from './policy.js'; +import { trackedIconColor } from '../../data/trackedAircraftIcon.js'; import { createModelRecord } from '../../data/modelRecord.js'; import { aircraftIconTestSeams, @@ -217,9 +217,11 @@ export function createTesting({ /** Evaluate the production tracked-billboard handoff colour for focused tests. */ function _trackedBillboardColorForTest() { - return parts.rendering._modelOwnsVisual(flightState._trackedIcao) - ? CYAN_TRANSPARENT - : TRACKED_CYAN; + const icao24 = flightState._trackedIcao; + const color = parts.rendering._fleetBillboardColor(icao24); + return parts.rendering._modelOwnsVisual(icao24) + ? trackedIconColor(color, 0) + : color; } /** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */ @@ -254,15 +256,20 @@ export function createTesting({ } /** How the tracked billboard is drawn (`_trackedBillboardLook`, - * `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */ + * `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet + * icon is (`_fleetLook`, `_fleetBillboardColor`). */ function _trackedIconLookForTest(icao24) { return { tracked: { ...parts.tracking._trackedBillboardLook(), sprite: parts.tracking._trackedSprite(icao24), + color: parts.tracking._trackedIconColor(), + }, + fleet: { + ...parts.icons._fleetLook(icao24), + color: parts.rendering._fleetBillboardColor(icao24), }, - fleet: parts.icons._fleetLook(icao24), }; } diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 8017e05170..b995b8a3a1 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -15,6 +15,7 @@ import { createTrackedAircraftIcon, isOtherTrackedIconSet, trackedContactHolder, + trackedIconColor, } from '../../data/trackedAircraftIcon.js'; import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; import { julianToEpochMs } from '../../geo/julian.js'; @@ -28,10 +29,12 @@ import { } from '../../data/trackingClickGesture.js'; import { inputFor } from '../../input/dispatcher.js'; import { + COCKPIT_AIR_ALL_ADD_M, + COCKPIT_AIR_ALL_KEEP_M, + COCKPIT_AIR_PROX_ADD_M, + COCKPIT_AIR_PROX_KEEP_M, TRAIL_MAX_POINTS, TRAIL_COLOR, - CYAN_TRANSPARENT, - TRACKED_CYAN, STALE_ALPHA, displayDelayMs, followsClock, @@ -46,6 +49,7 @@ import { trailBodySegments, trailHeadCurvePoints, trailHeadStartFix, + trailTimeAt, } from '../../data/trailContinuity.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord } from '../../data/entityRecords.js'; @@ -61,8 +65,6 @@ function aircraftPickId(hit) { return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id; } -const STALE_CYAN = Object.freeze([...TRACKED_CYAN.slice(0, 3), STALE_ALPHA]); - export function createTracking({ flightState, services, @@ -222,11 +224,13 @@ export function createTracking({ ); distancesSquared.push([icao24, distanceSquared(eye, position)]); } + // The AIR band follows the 3D mode, not the 3D model radius. + const all = flightState._models3dMode === 'all'; const next = nextCockpitNearContacts( previous, distancesSquared, - parts.rendering._modelAddDistM(), - parts.rendering._modelKeepDistM(), + all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M, + all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M, ); flightState._cockpitNearContacts = next; for (const icao24 of previous) @@ -390,12 +394,46 @@ export function createTracking({ ); } - /** Reports at or before the time the aircraft is drawn (now − the display delay). */ + /** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */ function _trailBodyCountNow() { - return trailBodyCount( + return trailBodyCount(flightState._trailFixes, _trailDisplayMs()); + } + + /** + * The time on its trail at which a host-supplied placement draws the + * aircraft, read off the trail where it is drawn (`trailTimeAt`): such a + * placement draws at a delay of its own, not this layer's. NaN when this + * layer's own motion draws it, or the trail has no pair to read. + * @returns {number} Epoch ms or NaN. + */ + function _placedTrailMs() { + if (!parts.motion._trackedPlaced?.()) return NaN; + return trailTimeAt( flightState._trailFixes, - flightState.now() - displayDelayMs(flightState), + parts.motion._trackedDisplayCached(), + ); + } + + /** + * The time the trail runs up to: the time the aircraft is drawn at, now − + * the display delay, or where a placement draws it. Otherwise the trail + * ends short of a placed aircraft, or runs on ahead of it. + * @returns {number} Epoch ms. + */ + function _trailDisplayMs() { + const placedMs = _placedTrailMs(); + return Number.isFinite(placedMs) + ? placedMs + : flightState.now() - displayDelayMs(flightState); + } + + /** Whether the trail holds no report behind the aircraft yet: this + * layer's own motion draws it before its oldest fix. Never for an + * aircraft a placement draws: its trail is read where it is drawn. */ + function _trailWarmingUp() { + return ( + !Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp() ); } @@ -412,7 +450,7 @@ export function createTracking({ if ( !flightState._trackedIcao || !flightState._trailFixes.length || - parts.motion._isTrackWarmingUp() + _trailWarmingUp() ) return []; const head = @@ -435,7 +473,7 @@ export function createTracking({ trailHeadCurvePoints( flightState._trailFixes, flightState._trailBodyCount, - flightState.now() - displayDelayMs(flightState), + _trailDisplayMs(), ), head, parts.motion._trackedModelCenterWorld(), @@ -697,10 +735,11 @@ export function createTracking({ // Hand the contact back to its icon only now: settling floors a grounded // contact, and while it still read as tracked its tracked model owned the // visual, so the floor would have stepped aside. - if (flightState._icons?.has(clearedIcao)) { - flightState._icons.setShown(clearedIcao, true); + // Its fleet model, kept loaded while it was selected, takes it back in + // this frame; the icon shows only when there is no loaded one. + parts.rendering._handBackDeselected(clearedIcao); + if (flightState._icons?.has(clearedIcao)) parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg }); - } parts.icons._applyIconPresentation(clearedIcao); clearTrackedSubjectContext('flights'); _emitAwarenessEvent('gev:awareness-subject-cleared', { @@ -813,14 +852,18 @@ export function createTracking({ return { text: '', dimmed: false }; } - /** The tracked billboard's colour: cyan, faded while stale, clear while the 3D model is the visual. */ + /** The tracked billboard's colour: the contact's own fleet colour (tracking + * never recolours it), faded while stale, clear while the 3D model is the + * visual. */ function _trackedIconColor() { - if (parts.rendering._modelOwnsVisual(flightState._trackedIcao)) - return CYAN_TRANSPARENT; - return _trackedStaleCue(flightState._trackedIcao).dimmed - ? STALE_CYAN - : TRACKED_CYAN; + const icao24 = flightState._trackedIcao; + const color = parts.rendering._fleetBillboardColor(icao24); + if (parts.rendering._modelOwnsVisual(icao24)) + return trackedIconColor(color, 0); + return _trackedStaleCue(icao24).dimmed + ? trackedIconColor(color, STALE_ALPHA) + : color; } /** @@ -912,10 +955,7 @@ export function createTracking({ width: look.size[0], height: look.size[1], get scale() { - return parts.rendering._fleetBillboardScale( - icao24, - flightState.records.data.get(icao24)?.klass, - ); + return parts.rendering._fleetBillboardScale(icao24); }, scaleByDistance: look.scaleByDistance, }; @@ -1078,13 +1118,13 @@ export function createTracking({ imageLod: _trackedBillboardLook().imageLod, sprite, position: getTrackedPosition, - // Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off, + // Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off, // or model still loading); transparent once the tracked model is actually up. color: _trackedIconColor, // Screen-projected rotation, evaluated per frame on the camera's own // axes, so it stays exact through a tracked orbit. The tracked target // must never vanish into tile geometry — tracking a taxiing plane at - // street level would otherwise bury the cyan icon inside the runway + // street level would otherwise bury the icon inside the runway // skin, so it draws over depth like the fleet icon set; its // shared-host tracked card is top-composited separately. rotation: () => { @@ -1092,6 +1132,8 @@ export function createTracking({ const pos = getTrackedPosition(); if (!tracked || !pos || !flightState._viewer) return flightState._lastTrackedRotation; + // A ground station's mast stands upright. + if (tracked.klass === 'station') return 0; const projected = courseScreenRotation( _pose(), pos, diff --git a/src/layers/flights/trail.test.mjs b/src/layers/flights/trail.test.mjs index ad3cf8e46a..d091431024 100644 --- a/src/layers/flights/trail.test.mjs +++ b/src/layers/flights/trail.test.mjs @@ -4,7 +4,12 @@ import * as Cesium from 'cesium'; import { createFlightState } from './state.js'; import { createTracking } from './tracking.js'; import { TRAIL_MAX_POINTS } from './policy.js'; -import { trailHeadJoins, trailPairBreaks } from '../../data/trailContinuity.js'; +import { + insertTrailFix, + trailHeadJoins, + trailPairBreaks, + trailTimeAt, +} from '../../data/trailContinuity.js'; const MINUTE = 60_000; const HOUR = 60 * MINUTE; @@ -92,6 +97,8 @@ function trackedHarness({ nowMs, floor, head = null, + placed = false, + warmingUp = false, } = {}) { const trail = recordingTrail(); const svc = services({ trails: trail, floor }); @@ -122,7 +129,9 @@ function trackedHarness({ services: svc, parts: { motion: { - _isTrackWarmingUp: () => false, + _isTrackWarmingUp: () => warmingUp, + _trackedPlaced: () => placed, + _trackedDisplayCached: () => head, _trackedTrailCached: () => head, _trackedDisplayPosition: () => head, _trackedModelCenterWorld: () => null, @@ -410,3 +419,136 @@ test('every waypoint of a 24 h history survives, and the trail stays within TRAI // The oldest go first: the newest live fix is still the last point. assert.equal(fixes[fixes.length - 1].timeMs, liveStart); }); + +/** A trail of `count` reports one minute apart flying east from (50, 1). */ +function eastTrail(t0, count) { + const fixes = []; + for (let i = 0; i < count; i++) + insertTrailFix( + fixes, + Cesium.Cartesian3.fromDegrees(1 + i * 0.12, 50, 10_000), + t0 + i * MINUTE, + TRAIL_MAX_POINTS, + ); + return fixes; +} + +test('the time on the trail is read where the aircraft is drawn', () => { + const t0 = Date.UTC(2026, 10, 8, 0, 0); + const fixes = eastTrail(t0, 4); + const at = (lon) => + trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(lon, 50, 10_000)); + // Halfway between the second and third reports. + assert.ok(Math.abs(at(1.18) - (t0 + 1.5 * MINUTE)) < 2_000); + // On a report. + assert.ok(Math.abs(at(1.24) - (t0 + 2 * MINUTE)) < 2_000); + // Past the newest report the time runs on; before the oldest it runs back. + assert.ok(Math.abs(at(1.42) - (t0 + 3.5 * MINUTE)) < 2_000); + assert.ok(Math.abs(at(0.94) - (t0 - 0.5 * MINUTE)) < 2_000); + // Nothing to read without a pair of reports, or without a position. + assert.ok(Number.isNaN(trailTimeAt(fixes.slice(0, 1), fixes[0].position))); + assert.ok(Number.isNaN(trailTimeAt(fixes, null))); +}); + +test('the time on the trail is never read across a break', () => { + const t0 = Date.UTC(2026, 10, 8, 0, 0); + const fixes = eastTrail(t0, 2); + // An hour later, far on: a new segment. + insertTrailFix( + fixes, + Cesium.Cartesian3.fromDegrees(20, 50, 10_000), + t0 + HOUR, + TRAIL_MAX_POINTS, + ); + insertTrailFix( + fixes, + Cesium.Cartesian3.fromDegrees(20.12, 50, 10_000), + t0 + HOUR + MINUTE, + TRAIL_MAX_POINTS, + ); + assert.equal(fixes[2].breakBefore, true); + // Halfway along the gap is not on the trail: it is read on the newest pair. + const at = trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(10, 50, 10_000)); + assert.ok(at <= t0 + HOUR, `read ${at - t0} ms in, across the break`); +}); + +test('a placed aircraft drawn ahead of the display delay keeps its trail joined to it', () => { + const t0 = Date.UTC(2026, 10, 8, 0, 0); + const liveFixes = [0, 1, 2, 3].map((i) => ({ + timeMs: t0 + i * MINUTE, + lat: 50, + lon: 1 + i * 0.12, + })); + // The layer's own delay puts the aircraft before its first fix (warming + // up), but the placement draws it between the third and fourth reports. + const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 10_000); + const placed = trackedHarness({ + liveFixes, + nowMs: t0 + 3.5 * MINUTE, + head: near, + placed: true, + warmingUp: true, + }); + placed.flightState._displayDelay = { currentMs: 10 * MINUTE }; + placed.tracking._startTrail('abc123'); + // The body runs to the last report behind the aircraft, none ahead of it. + assert.deepEqual( + placed.trail.last().map((segment) => segment.length > 0), + [true], + ); + const body = placed.trail.last()[0]; + assert.ok( + Cesium.Cartesian3.distance( + body[body.length - 1], + Cesium.Cartesian3.fromDegrees(1.24, 50, 10_000), + ) < 1, + ); + // The head joins it to the aircraft. + const drawn = headPositions(placed); + assert.ok(drawn.length >= 2); + assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1); + assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1e-6); + + // The layer's own motion, warming up, draws no head and no body. + const own = trackedHarness({ + liveFixes, + nowMs: t0 + 3.5 * MINUTE, + head: near, + warmingUp: true, + }); + own.flightState._displayDelay = { currentMs: 10 * MINUTE }; + own.tracking._startTrail('abc123'); + assert.deepEqual(own.trail.last(), []); + assert.deepEqual(headPositions(own), []); +}); + +test('a placed aircraft drawn behind the display delay has no trail ahead of it', () => { + const t0 = Date.UTC(2026, 10, 8, 0, 0); + const liveFixes = [0, 1, 2, 3].map((i) => ({ + timeMs: t0 + i * MINUTE, + lat: 50, + lon: 1 + i * 0.12, + })); + // The layer's delay would draw every report; the placement holds the + // aircraft between the first and second. + const behind = Cesium.Cartesian3.fromDegrees(1.06, 50, 10_000); + const { trail, tracking, flightState } = trackedHarness({ + liveFixes, + nowMs: t0 + 4 * MINUTE, + head: behind, + placed: true, + }); + flightState._displayDelay = { currentMs: 0 }; + tracking._startTrail('abc123'); + // One report behind it: no line yet, and nothing ahead of the aircraft. + assert.deepEqual(trail.last(), []); + const drawn = headPositions({ tracking }); + assert.equal(drawn.length, 2); + assert.ok( + Cesium.Cartesian3.distance( + drawn[0], + Cesium.Cartesian3.fromDegrees(1, 50, 10_000), + ) < 1, + ); + assert.ok(Cesium.Cartesian3.distance(drawn[1], behind) < 1e-6); +}); diff --git a/src/layers/flights/trailRecord.test.mjs b/src/layers/flights/trailRecord.test.mjs index a97c2a1797..68c2683d4e 100644 --- a/src/layers/flights/trailRecord.test.mjs +++ b/src/layers/flights/trailRecord.test.mjs @@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js'; import { createMotion } from './motion.js'; import { createFlightState } from './state.js'; import { createTracking } from './tracking.js'; -import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js'; +import { FLEET_TINT, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js'; // A tracked trail is the aircraft's reports joined along the curve the icon // is drawn along between them, so the icon always sits on its trail and a @@ -116,7 +116,11 @@ function harness({ flightState.now = () => clock; flightState._positionHistory.set(ICAO, fixes); const parts = { - rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) }, + rendering: { + _modelOwnsVisual: () => false, + _modelSpec: () => ({}), + _fleetBillboardColor: () => FLEET_TINT, + }, queries: { _contactLabel: (id, info) => info?.callsign || id }, }; parts.motion = createMotion({ flightState, services: svc, parts }); @@ -797,6 +801,11 @@ test('a stalled feed dims the tracked plane as STALE', () => { dimmed: true, }); assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA); + assert.deepEqual( + h.tracking._trackedIconColor().slice(0, 3), + FLEET_TINT.slice(0, 3), + 'faded in its own colour, never recoloured', + ); assert.equal(h.flightState.records.missingPolls.has(ICAO), false); } finally { h.restore(); diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js index 9332622411..df94883845 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -857,9 +857,12 @@ export function createGhostMapsLayer({ title: days === null ? t('Show markers of every age') - : t('Maximum event age: {days}d; undated markers are kept', { - days: formatNumber(days), - }), + : tn( + days, + 'Maximum event age: {days}d; undated markers are kept', + 'Maximum event age: {days}d; undated markers are kept', + { days: formatNumber(days) }, + ), active: days === _ageDays, onClick: () => setAgeDays(days), })), @@ -894,7 +897,7 @@ export function createGhostMapsLayer({ }; }), legend: [], - info: `${_ageDays === null ? t('All markers') : t('Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`, + info: `${_ageDays === null ? t('All markers') : tn(_ageDays, 'Event age: {days}d · undated kept', 'Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`, infoTitle: t( 'S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.', ), diff --git a/src/layers/ghostMaps/lifecycle.test.mjs b/src/layers/ghostMaps/lifecycle.test.mjs index 7bba31645d..675bdefa24 100644 --- a/src/layers/ghostMaps/lifecycle.test.mjs +++ b/src/layers/ghostMaps/lifecycle.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { setLocale } from '../../i18n/index.js'; import { createGhostMapsLayer } from './index.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js'; @@ -310,6 +311,35 @@ test('age controls default to seven days and widening restores filtered and expi assert.equal(ageChip(layer, null).active, true); }); +test('the event age agrees with its number of days', async (t) => { + t.after(() => setLocale('en')); + const { layer, viewer } = fixture(t, { reports: [{ name: 'Undated' }] }); + await layer.update(viewer); + const info = () => + layer.getRowControls().info.split(' · ').slice(0, 2).join(' · '); + assert.equal( + ageChip(layer, 1).title, + 'Maximum event age: 1d; undated markers are kept', + ); + setLocale('de'); + assert.equal( + ageChip(layer, 1).title, + 'Maximales Ereignisalter: 1 Tag; undatierte Markierungen bleiben erhalten', + ); + assert.equal( + ageChip(layer, 7).title, + 'Maximales Ereignisalter: 7 Tage; undatierte Markierungen bleiben erhalten', + ); + assert.equal(info(), 'Ereignisalter: 7 Tage · undatierte bleiben'); + await ageChip(layer, 1).onClick(); + assert.equal(info(), 'Ereignisalter: 1 Tag · undatierte bleiben'); + setLocale('es'); + assert.equal( + info(), + 'Antigüedad: 1 día · se conservan los marcadores sin fecha', + ); +}); + test('age preferences persist independently of product choices and reject invalid storage', async (t) => { const values = new Map([['gev.ghostmaps.products', '["cip"]']]); const storage = { diff --git a/src/layers/installations/controls.js b/src/layers/installations/controls.js index 762afe98a3..8c8d729cbe 100644 --- a/src/layers/installations/controls.js +++ b/src/layers/installations/controls.js @@ -1,41 +1,15 @@ -import { describeInstallationFeedback } from '../../data/installationFeedback.js'; +import { installationFeedback } from '../../data/installationFeedback.js'; import { LAYER_ID, DISTANCE_PREFILTER_MARGIN_M, ANCHOR_REFRESH_M, } from './policy.js'; -import { formatNumber, t, tn } from '../../i18n/index.js'; +import { t } from '../../i18n/index.js'; import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js'; import { surfaceDistance } from '../../geo/geodesic.js'; import { toDegrees, toRadians } from '../../geo/vector.js'; import { cameraOf } from '../../render/rendererOf.js'; -// installationFeedback.js is shared with the HUD (src/loadingFeedback.js) and -// hands back msg()-marked English plus values; getStats translates them here. -function localizeInstallationFeedback(feedback) { - if (feedback.text !== undefined) { - const values = {}; - if (feedback.reason !== undefined) values.reason = t(feedback.reason); - if (feedback.seconds !== undefined) values.seconds = feedback.seconds; - return t(feedback.text, values); - } - const { count, km } = feedback; - if (km) { - const kmText = formatNumber(km); - return count === 0 - ? t('No mapped sites within {km} km of the contact', { km: kmText }) - : tn( - count, - '{count} mapped site within {km} km of the contact', - '{count} mapped sites within {km} km of the contact', - { km: kmText }, - ); - } - return count === 0 - ? t('No mapped sites in view') - : tn(count, '{count} mapped site in view', '{count} mapped sites in view'); -} - export function createControls({ state: layerState, services, parts, source }) { const methods = { id: LAYER_ID, @@ -285,13 +259,12 @@ export function createControls({ state: layerState, services, parts, source }) { retryAt: layerState.retryAt, retrying: layerState.loading && Boolean(layerState.failureReason), failureReason: layerState.failureReason, - statusMessage: localizeInstallationFeedback( - describeInstallationFeedback({ - ...layerState, - count: layerState.lastUpdate ? mappedCount : undefined, - retrying: layerState.loading && Boolean(layerState.failureReason), - }), - ), + // English: the analyst reads it as is; displays translate it. + statusMessage: installationFeedback({ + ...layerState, + count: layerState.lastUpdate ? mappedCount : undefined, + retrying: layerState.loading && Boolean(layerState.failureReason), + }), loadingLabel: layerState.loading ? t('loading mapped installation context') : '', diff --git a/src/layers/installations/installationFeedbackLocale.test.mjs b/src/layers/installations/installationFeedbackLocale.test.mjs index cf4e758a33..c74c0ee477 100644 --- a/src/layers/installations/installationFeedbackLocale.test.mjs +++ b/src/layers/installations/installationFeedbackLocale.test.mjs @@ -1,6 +1,8 @@ +// statusMessage stays English (the analyst's empty note); displays translate it. import test from 'node:test'; import assert from 'node:assert/strict'; -import { setLocale, translateKnown } from '../../i18n/index.js'; +import { setLocale, t, tn } from '../../i18n/index.js'; +import { translateStatusMessage } from '../../ui/statusText.js'; import { createControls } from './controls.js'; function stats(state) { @@ -13,67 +15,113 @@ function stats(state) { }).methods.getStats(); } -for (const locale of ['es', 'ru']) { - test(`${locale}: installation feedback is in the UI language`, () => { - setLocale(locale); - const empty = stats({ status: 'empty', lastUpdate: 1 }).statusMessage; - assert.notEqual(empty, 'No mapped sites in view'); - const found = stats({ +function inLocale(locale, run) { + setLocale(locale); + try { + run(); + } finally { + setLocale('en'); + } +} + +// A retry a minute out reads "60s" (rounded up). +const cases = [ + [ + { status: 'empty', lastUpdate: 1 }, + 'No mapped sites in view', + () => t('No mapped sites in view'), + ], + [ + { status: 'ready', lastUpdate: 1, records: [{ kind: 'installation' }] }, + '1 mapped site in view', + () => tn(1, '{count} mapped site in view', '{count} mapped sites in view'), + ], + [ + { status: 'ready', lastUpdate: 1, records: [{ kind: 'installation' }, { kind: 'installation' }], - }).statusMessage; - assert.notEqual(found, '2 mapped sites in view'); - const tiles = stats({ - status: 'unavailable', - failureReason: 'tiles_unavailable', - }).statusMessage; - assert.notEqual(tiles, 'Map tiles temporarily unavailable'); - const retry = stats({ + }, + '2 mapped sites in view', + () => tn(2, '{count} mapped site in view', '{count} mapped sites in view'), + ], + [ + { + status: 'empty', + lastUpdate: 1, + wide: true, + coverage: { kind: 'subject', radiusM: 25000 }, + }, + 'No mapped sites within 25 km of the contact', + () => t('No mapped sites within {km} km of the contact', { km: '25' }), + ], + [ + { + status: 'ready', + lastUpdate: 1, + wide: true, + coverage: { kind: 'subject', radiusM: 25000 }, + records: [{ kind: 'installation' }], + }, + '1 mapped site within 25 km of the contact', + () => + tn( + 1, + '{count} mapped site within {km} km of the contact', + '{count} mapped sites within {km} km of the contact', + { km: '25' }, + ), + ], + [ + { status: 'unavailable', failureReason: 'tiles_unavailable' }, + 'Map tiles temporarily unavailable', + () => t('Map tiles temporarily unavailable'), + ], + [ + { status: 'unavailable', failureReason: 'names_unavailable', - retryAt: Date.now() + 5000, - }).statusMessage; - assert.doesNotMatch(retry, /^Mapped names temporarily unavailable/); - for (const text of [ - 'Too many mapped sites in view to list them all', - 'Installation context unavailable', - ]) { - assert.notEqual(translateKnown(text), text); - } + get retryAt() { + return Date.now() + 60_000; + }, + }, + 'Mapped names temporarily unavailable — retrying in 60s', + () => + t('{reason} — retrying in {seconds}s', { + reason: t('Mapped names temporarily unavailable'), + seconds: 60, + }), + ], + [ + { status: 'zoom-in' }, + 'Zoom in to search mapped installations', + () => t('Zoom in to search mapped installations'), + ], +]; + +for (const locale of ['es', 'ru']) { + test(`${locale}: installation statusMessage stays English data`, () => { + inLocale(locale, () => { + for (const [state, english] of cases) + assert.equal(stats(state).statusMessage, english); + }); + }); + + test(`${locale}: installation statusMessage is shown in the UI language`, () => { + inLocale(locale, () => { + for (const [state, english, shown] of cases) { + const shownText = translateStatusMessage(stats(state).statusMessage); + assert.notEqual(shownText, english); + assert.equal(shownText, shown()); + } + }); }); } test('en: installation feedback keeps its English wording', () => { setLocale('en'); - assert.equal( - stats({ status: 'empty', lastUpdate: 1 }).statusMessage, - 'No mapped sites in view', - ); - assert.equal( - stats({ - status: 'ready', - lastUpdate: 1, - records: [{ kind: 'installation' }], - }).statusMessage, - '1 mapped site in view', - ); - assert.equal( - stats({ - status: 'ready', - lastUpdate: 1, - wide: true, - coverage: { kind: 'subject', radiusM: 25000 }, - records: [{ kind: 'installation' }, { kind: 'installation' }], - }).statusMessage, - '2 mapped sites within 25 km of the contact', - ); - assert.equal( - stats({ - status: 'unavailable', - failureReason: 'names_unavailable', - retryAt: Date.now() + 5000, - }).statusMessage, - 'Mapped names temporarily unavailable — retrying in 5s', - ); + for (const [state, english] of cases) { + assert.equal(stats(state).statusMessage, english); + assert.equal(translateStatusMessage(english), english); + } }); diff --git a/src/layers/launches/missionStatus.i18n.test.mjs b/src/layers/launches/missionStatus.i18n.test.mjs index 8826d0d36e..7d3b2e572b 100644 --- a/src/layers/launches/missionStatus.i18n.test.mjs +++ b/src/layers/launches/missionStatus.i18n.test.mjs @@ -69,3 +69,38 @@ test('the mission panel translates only the fallback status', (t) => { assert.equal(shownStatus(UNKNOWN_LAUNCH_STATUS), 'Desconocido'); assert.equal(shownStatus('Launch Successful'), 'Launch Successful'); }); + +test('a confirmed landing position is worded apart from the CONFIRMED sightings chip', (t) => { + t.after(() => setLocale('en')); + const position = () => + createPanel({ + state: { + _selectedLaunchId: 'mission-1', + _launches: [ + { + id: 'mission-1', + name: 'Example', + status: 'Launch Successful', + payloads: [], + recoveryStages: [ + { + name: 'B1080', + endpoint: { lat: 28.41, lon: -80.6, accuracy: 'CONFIRMED' }, + }, + ], + }, + ], + _replayTracks: new Map(), + }, + parts: { + overlays: { shortMissionLabel: (name) => name }, + policyHelpers: { missionPathPresentation: () => ({}) }, + replay: { presentReplay: () => ({}) }, + }, + }).presentMission().stages[0].position; + assert.match(position(), / · CONFIRMED$/); + // One landing, singular: sv BEKRÄFTAD, where the sightings chip says + // BEKRÄFTADE. + setLocale('sv'); + assert.match(position(), / · BEKRÄFTAD$/); +}); diff --git a/src/layers/localAdsb/enrichment.js b/src/layers/localAdsb/enrichment.js index 4fb4673a8d..575c9262bb 100644 --- a/src/layers/localAdsb/enrichment.js +++ b/src/layers/localAdsb/enrichment.js @@ -24,7 +24,8 @@ export function localAdsbClass(record, meta = null) { const category = record?.category || null; return { klass: classifyAircraft({ typeCode, category }), - evidence: Boolean(typeCode) || /^(?:A[1-7]|B1)$/.test(category || ''), + evidence: + Boolean(typeCode) || /^(?:A[1-7]|B1|C[1-5])$/.test(category || ''), }; } diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index 22cd4a12f4..4d550bd08a 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -1,5 +1,7 @@ -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; +import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js'; import { aircraftIcon } from '../../data/aircraftIcons.js'; +import { rotorFrame } from '../../data/rotorFrames.js'; +import { KNOT_MPS } from '../../data/units.js'; import { courseScreenRotation, stabilizeScreenRotation, @@ -133,6 +135,8 @@ export function createLocalAdsbLayer({ } = services.context; const { registerPickOwner, unregisterPickOwner } = services.picking; const color = hexColor(LOCAL_ADSB_COLOR); + // An airport vehicle's tint, as in the Flights layer. + const vehicleColor = hexColor(VEHICLE_TINT_CSS); const uatRingColor = hexColor(LOCAL_ADSB_UAT_RING_COLOR); let viewer = null; @@ -265,9 +269,7 @@ export function createLocalAdsbLayer({ } function billboardScale(marker) { - return ( - (CLASS_SCALE_2D[marker.klass] || 1) * (marker.onGround ? GROUND_SCALE : 1) - ); + return marker.onGround ? GROUND_SCALE : 1; } /** Class silhouette and per-class scale (×0.8 on the ground), magenta. */ @@ -350,18 +352,34 @@ export function createLocalAdsbLayer({ }; } - /** A marker's icon, where and how it now draws. */ - function markerItem(marker, basis) { + /** + * A marker's icon, where and how it now draws: a helicopter's rotor frame + * at `at` (still on the ground), an airport vehicle in its own tint, a + * ground station's mast upright. + */ + function markerItem(marker, basis, at) { + const kind = marker.iconKind ?? 'airliner'; return { id: marker.id, pos: marker.position, - image: aircraftIcon(marker.iconKind ?? 'airliner'), + image: aircraftIcon( + kind, + undefined, + kind === 'helicopter' + ? rotorFrame(marker.id, at, { + onGround: marker.onGround, + speedMps: Number.isFinite(marker.record?.groundSpeedKt) + ? marker.record.groundSpeedKt * KNOT_MPS + : null, + }) + : undefined, + ), size: [MARKER_SPRITE.width, MARKER_SPRITE.height], scale: marker.iconScale ?? 1, - color, + color: kind === 'vehicle' ? vehicleColor : color, scaleByDistance: MARKER_SPRITE.scaleByDistance, rotationMode: 'screen', - rotation: markerRotation(marker, basis), + rotation: kind === 'station' ? 0 : markerRotation(marker, basis), // The 3D model, once loaded and placed, is the visual instead. show: !marker.modelOwnsVisual, disableDepthTest: Number.POSITIVE_INFINITY, @@ -390,11 +408,12 @@ export function createLocalAdsbLayer({ function drawMarkers() { if (!sets) return; const basis = cameraBasis(); + const at = now(); const icons = []; const rings = []; for (const marker of markers.values()) { if (!marker.position) continue; - icons.push(markerItem(marker, basis)); + icons.push(markerItem(marker, basis, at)); if (marker.uat) rings.push(ringItem(marker)); } if (icons.length) sets.markers.upsert(icons); diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 5b29e91a2f..3e53c9bbeb 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -2,9 +2,10 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import * as Cesium from 'cesium'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; +import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js'; import { layerFeedState } from '../../data/feedState.js'; import { aircraftIcon } from '../../data/aircraftIcons.js'; +import { ROTOR_STILL_FRAME, rotorFrame } from '../../data/rotorFrames.js'; import { createLocalAdsbLayer, HEARD_BY_RECEIVER, @@ -196,13 +197,14 @@ function fakeFeeds(initial = {}) { }; } -/** A viewer whose camera looks down on (0°, 0°) from 50 km. */ +/** A viewer whose camera looks down on (0°, 0°) from 2 km: within the 3 km + * model radius of an aircraft there on the ground or at 10,000 ft. */ function modelViewer() { return fakeViewer( { scene: {} }, { - height: 50_000, - position: { x: 6_378_137 + 50_000, y: 0, z: 0 }, + height: 2_000, + position: { x: 6_378_137 + 2_000, y: 0, z: 0 }, direction: { x: -1, y: 0, z: 0 }, }, ); @@ -238,7 +240,7 @@ test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves ); }); -test('local aircraft use their class silhouette and scale in magenta', async (t) => { +test('local aircraft use their class silhouette at one size in magenta', async (t) => { const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; const { layer, draw, calls } = await enabledLayer(receiver, clock); @@ -265,8 +267,17 @@ test('local aircraft use their class silhouette and scale in magenta', async (t) assert.equal(typeof readEntityRecord(carrier)?.displayPosition, 'function'); const heli = () => iconOf(draw, 'local-adsb:a0b702'); - assert.equal(heli().image, aircraftIcon('helicopter')); - assert.equal(heli().scale, CLASS_SCALE_2D.helicopter); + // Airborne, its rotor turns: the frame of its own phase at the layer's time. + assert.equal( + heli().image, + aircraftIcon( + 'helicopter', + undefined, + rotorFrame('local-adsb:a0b702', clock.now), + ), + ); + assert.equal(heli().scale, 1, 'every class draws at one size'); + assert.equal(icon.scale, heli().scale); assert.deepEqual( heli().color, MAGENTA, @@ -285,18 +296,48 @@ test('local aircraft use their class silhouette and scale in magenta', async (t) icao: 'a0b702', category: 'A7', onGround: true, + groundSpeedKt: 0, lastPositionAt: 100_500, }), ], }); await layer.update(); - assert.equal(heli().scale, CLASS_SCALE_2D.helicopter * 0.8); + assert.equal(heli().scale, 0.8); + // Parked on the ground its rotor holds still. + assert.equal( + heli().image, + aircraftIcon('helicopter', undefined, ROTOR_STILL_FRAME), + ); const [detectable] = layer.getDetectableObjects(); assert.equal(detectable.sourceId, 'a0b702'); assert.equal(detectable.type, 'AIR'); }); +test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => { + const receiver = fakeReceiver({ mode: 'adsb', connected: true }); + const clock = { now: 100_000 }; + const { layer, draw } = await enabledLayer(receiver, clock); + t.after(() => layer.destroy()); + receiver.set({ + aircraft: [ + record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }), + record({ icao: 'a0c002', category: 'C2', trackDeg: 90 }), + record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }), + ], + }); + await layer.update(); + for (const id of ['a0c001', 'a0c002']) { + const icon = iconOf(draw, `local-adsb:${id}`); + assert.equal(icon.image, aircraftIcon('vehicle'), id); + assert.deepEqual(icon.color, hexColor(VEHICLE_TINT_CSS), id); + } + const mast = iconOf(draw, 'local-adsb:a0c003'); + assert.equal(mast.image, aircraftIcon('station')); + assert.deepEqual(mast.color, MAGENTA); + assert.equal(mast.rotation, 0, 'upright whatever its track'); +}); + test('the heading slews toward a new track instead of snapping', async (t) => { const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; diff --git a/src/layers/localAdsb/models.js b/src/layers/localAdsb/models.js index 6875ef8c46..e4279cf7bb 100644 --- a/src/layers/localAdsb/models.js +++ b/src/layers/localAdsb/models.js @@ -8,18 +8,21 @@ import { sub, } from '../../geo/vector.js'; import { aircraftLayerModelSpec } from '../flights/modelSpec.js'; -import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js'; +import { + fleetModelSet, + fleetPartTable, + loadFleetModelSet, +} from '../../data/fleetModels.js'; +import { aircraftLayerPartState } from '../../data/modelPartDrivers.js'; +import { KNOT_MPS } from '../../data/units.js'; import { FLEET_DR_INTERVAL_MS, - MODEL_ALL_ADD_M, - MODEL_ALL_KEEP_M, + MODEL_ADD_M, MODEL_ALT_CEIL_M, MODEL_HEADING_OFFSET_DEG, + MODEL_KEEP_M, MODEL_MAX, MODEL_MAX_ALL, - MODEL_MIN_PX, - MODEL_PROX_ADD_M, - MODEL_PROX_KEEP_M, } from '../flights/policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, @@ -165,6 +168,36 @@ export function createLocalAdsbModels({ } } + /** + * The moving parts an aircraft's model is posed with, from its record + * (`aircraftLayerPartState`). The receiver knows no ground height, so its gear + * follows the approach rule by its reported altitude, climb and speed. An + * airport vehicle is a road vehicle (`groundVehiclePartState`): its wheels + * roll with its speed. + */ + function partsOf(marker, spec) { + const table = fleetPartTable(fleetModelSet(), spec.model); + if (!table) return undefined; + const record = marker.record ?? {}; + const finite = (v) => (Number.isFinite(v) ? v : null); + const speedMps = + finite(record.groundSpeedKt) === null + ? null + : record.groundSpeedKt * KNOT_MPS; + return aircraftLayerPartState(table, { + klass: marker.klass, + onGround: marker.onGround === true, + heightAboveGroundM: null, + altitudeM: + finite(record.altitudeFt) === null ? null : record.altitudeFt * 0.3048, + verticalRateMps: + finite(record.verticalRateFpm) === null + ? null + : (record.verticalRateFpm * 0.3048) / 60, + speedMps, + }); + } + function regime(preferences, pose) { if (!preferences?.models3d) return false; return pose.height < MODEL_ALT_CEIL_M; @@ -173,19 +206,17 @@ export function createLocalAdsbModels({ function refreshEligibility(markers, preferences, pose) { const all = preferences.models3dMode === 'all'; const cap = all ? MODEL_MAX_ALL : MODEL_MAX; - const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M; - const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M; const candidates = []; for (const [id, marker] of markers) { if (!marker.position) continue; const distanceSq = distanceSquared(pose.position, marker.position); - if (distanceSq > keepM * keepM) continue; + if (distanceSq > MODEL_KEEP_M * MODEL_KEEP_M) continue; candidates.push([id, distanceSq, inView(pose, marker.position)]); } candidates.sort((a, b) => a[1] - b[1]); eligible = selectModelEligible(candidates, { cap, - addDistSq: addM * addM, + addDistSq: MODEL_ADD_M * MODEL_ADD_M, isModeled: (id) => models.has(id), }); release([...models.keys()].filter((id) => !eligible.has(id))); @@ -246,6 +277,7 @@ export function createLocalAdsbModels({ const gltf = fleetModelSet()?.bytes?.get(spec.model); noteAsset(record, url, spec.bellyM); const position = placement(id, marker); + const parts = partsOf(marker, spec); const shown = Boolean(position) && horizon.isPointVisible(marker.position); items.push({ @@ -263,11 +295,11 @@ export function createLocalAdsbModels({ roll: 0, }, scale: spec.scale, - minPixelSize: MODEL_MIN_PX, // The mesh's own colours (white, multiplied). tint: WHITE, colorBlend: aircraftModelBlend(false), environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + ...(parts ? { parts } : {}), show: shown, }); if (shown && record.ready) marker.modelOwnsVisual = true; diff --git a/src/layers/military/clockFollow.js b/src/layers/military/clockFollow.js index f5c12bf97c..d8d44e9078 100644 --- a/src/layers/military/clockFollow.js +++ b/src/layers/military/clockFollow.js @@ -26,6 +26,59 @@ export function createClockFollow({ flightState, services, parts }) { flightState._lastCamPoseSig = ''; } + /** + * The contacts drawn now that the first live snapshot after the clock came + * back to live lacks (the tracked one too): the snapshot judges them as a + * poll judges any absence (see the snapshot renderer). + * @param {{records: Array<{id: string}>}} snapshot + * @returns {Set} + */ + function absentAtHandover(snapshot) { + const present = new Set(snapshot.records.map((record) => record.id)); + const drawn = [...(flightState._icons?.ids() ?? [])]; + if (flightState._trackedIcao) drawn.push(flightState._trackedIcao); + return new Set(drawn.filter((id) => !present.has(id))); + } + + /** + * Back at live: forget how every contact moved, as at a jump, but keep the + * tracked trail, and keep the contacts `kept` (absentAtHandover) as they + * were: their record, fixes and course. Each was last seen at its newest + * fix, not when it was loaded, so absence judges how old it really is. + * @param {Set} kept + */ + function handOverMotion(kept) { + const held = []; + for (const id of kept) + held.push([ + id, + flightState.records.data.get(id), + flightState._positionHistory.get(id), + flightState._displayCourse.get(id), + ]); + forgetPlacedAircraft( + services?.placement, + [...flightState._positionHistory.keys()].filter((id) => !kept.has(id)), + ); + flightState.records.reset(); + flightState._positionHistory.clear(); + flightState._displayCourse.clear(); + flightState._groundSnap.clear(); + flightState._drReconcileValid = false; + flightState._cachedDRFrame = -1; + flightState._cachedDRPosition = null; + flightState._lastCamPoseSig = ''; + for (const [id, meta, history, course] of held) { + if (meta) + flightState.records.data.set(id, { + ...meta, + observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs, + }); + if (history) flightState._positionHistory.set(id, history); + if (course !== undefined) flightState._displayCourse.set(id, course); + } + } + /** Drop every contact: the time has none to show, or the clock went live. */ function clear() { if (flightState._trackedIcao) @@ -39,5 +92,5 @@ export function createClockFollow({ flightState, services, parts }) { flightState.feed._lastUpdate = null; } - return { resetMotion, clear }; + return { resetMotion, absentAtHandover, handOverMotion, clear }; } diff --git a/src/layers/military/index.js b/src/layers/military/index.js index 0f30a391c2..94b36adcd2 100644 --- a/src/layers/military/index.js +++ b/src/layers/military/index.js @@ -10,7 +10,10 @@ import { createLifecycle } from './lifecycle.js'; import { createTesting } from './testing.js'; import { createQueries } from './queries.js'; import { createClockFollow } from './clockFollow.js'; -import { createSnapshotTimeline } from '../../time/snapshotTimeline.js'; +import { + createSnapshotTimeline, + snapshotAnswer, +} from '../../time/snapshotTimeline.js'; import { worldClock } from '../../time/worldClock.js'; /** Compose one military-flight layer with application-owned scene services. */ export function createMilitaryFlightLayer({ @@ -46,10 +49,19 @@ export function createMilitaryFlightLayer({ parts.ingestion = createIngestion({ feed: flightState.feed, applySnapshot: (snapshot, viewer, options) => { + // At another time the snapshot takes the place of every contact: how + // each moved belongs to the time the clock left. Back at live too, but + // the contacts it lacks are kept as they were for it to judge. if (options?.replace) parts.clockFollow.resetMotion(); + if (options?.handover) { + parts.clockFollow.handOverMotion( + parts.clockFollow.absentAtHandover(snapshot), + ); + } return applySnapshot(snapshot, viewer, options); }, followsClock: () => flightState.timeline.active(), + timedAnswer: snapshotAnswer, setSourceLabel: (source) => { layer.source = source; }, @@ -65,9 +77,7 @@ export function createMilitaryFlightLayer({ load: (atMs, { signal, replace }) => parts.ingestion.methods.loadAt(atMs, { signal, replace }), clear: () => parts.clockFollow.clear(), - resumeLive: () => { - layer.update(flightState._viewer).catch(() => {}); - }, + resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer), }); Object.assign( diff --git a/src/layers/military/ingestion.js b/src/layers/military/ingestion.js index af4697db2f..86580185c2 100644 --- a/src/layers/military/ingestion.js +++ b/src/layers/military/ingestion.js @@ -11,6 +11,7 @@ export function createIngestion({ setSourceLabel, applyPendingTrackingRestore, followsClock = () => false, + timedAnswer = () => true, }) { const methods = { async update(viewer, { signal = null } = {}) { @@ -20,13 +21,27 @@ export function createIngestion({ await acquire(viewer, { signal }); }, + /** + * Back at live from another time: poll at once, and let this live + * snapshot stand in for every contact. Those it has keep their + * icon and model and move on from where they are drawn; those it lacks + * go. Resolves true once it is applied, else false (nothing to poll yet, + * or the poll failed); rejects with an AbortError when it was dropped. + * @param {object} [viewer] + * @returns {Promise} + */ + async resumeLive(viewer) { + return (await acquire(viewer, { handover: true })) === true; + }, + /** * Apply the source's snapshot at world time `atMs` (its timeline says it * can answer one), in place of every contact when `replace`. Resolves - * whether it was applied. + * whether it was applied: `{ reachMs }`, the newest fix its records + * carry, when they carry fixes; else true, or false when it was not. * @param {number} atMs * @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options] - * @returns {Promise} + * @returns {Promise} */ async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) { // Whatever polls or loads for another time no longer applies. @@ -37,7 +52,10 @@ export function createIngestion({ }, }; - async function acquire(viewer, { signal = null, atMs, replace = false }) { + async function acquire( + viewer, + { signal = null, atMs, replace = false, handover = false }, + ) { const nowMs = Date.now(); const timed = atMs !== undefined; const trackingRefreshEpoch = ++feed._trackingRefreshEpoch; @@ -77,7 +95,9 @@ export function createIngestion({ : null); const accepted = timed ? applySnapshot(snapshot, viewer, { replace }) - : applySnapshot(snapshot, viewer); + : handover + ? applySnapshot(snapshot, viewer, { handover: true }) + : applySnapshot(snapshot, viewer); feed._count = accepted.count; feed._lastUpdate = snapshot.observedAtMs; feed._lastTrackingRefreshOutcome = { @@ -88,7 +108,8 @@ export function createIngestion({ }; console.log(`[Data:Military] Updated: ${feed._count} aircraft`); applyPendingTrackingRestore(); - return true; + // At a time, what the clock's follower is told of it. + return timed ? timedAnswer(snapshot) : true; } catch (e) { if (updateSignal.aborted || e?.name === 'AbortError') { throw new DOMException('Military update aborted', 'AbortError'); diff --git a/src/layers/military/liveHandover.test.mjs b/src/layers/military/liveHandover.test.mjs new file mode 100644 index 0000000000..25e25d2d07 --- /dev/null +++ b/src/layers/military/liveHandover.test.mjs @@ -0,0 +1,180 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createMilitarySnapshotRenderer } from './snapshotRenderer.js'; +import { createMotion } from './motion.js'; +import { createIngestion, createMilitaryFeed } from './ingestion.js'; +import { MilitaryFlightRecords } from './records.js'; +import { createClockFollow } from './clockFollow.js'; + +// Back at live from another time, the first live snapshot stands in for +// every military contact: those it has keep their icon, and only those it +// lacks go (src/time/snapshotTimeline.js). + +function harness() { + const iconIds = new Set(); + const calls = []; + const flightState = { + _viewer: null, + _icons: { + has: (id) => iconIds.has(id), + ids: () => [...iconIds], + get count() { + return iconIds.size; + }, + }, + _positionHistory: new Map(), + _groundSnap: { forget() {} }, + _models: new Map(), + _trackedModel: null, + _trackedIcao: null, + records: { data: new Map() }, + }; + const parts = { + rendering: { + _modelOwnsVisual: () => false, + _syncModelToClass() {}, + _groundSampleExclusions: () => ({ sets: [] }), + }, + icons: { + _addIcon: (id) => { + calls.push(['add', id]); + iconIds.add(id); + }, + _applyIconPresentation() {}, + _planIcon: (id, options) => calls.push(['plan', id, options]), + _forgetContact: (id) => { + calls.push(['forget', id]); + iconIds.delete(id); + }, + }, + }; + const services = { + camera: { trackedModelScaleForPixelCap: () => 1 }, + focus: {}, + groundFloor: { cachedGroundFloor: () => null, GROUND_FLOOR_LIFT_M: 0.5 }, + meshFloor: { sampleMeshFloorCells() {} }, + }; + parts.motion = createMotion({ flightState, services, parts, layer: {} }); + const records = new MilitaryFlightRecords({ + geoidHeight: () => 0, + cachedGroundFloor: () => null, + floorAltitudeM: (altitude) => altitude, + now: () => Date.now(), + }); + flightState.records = records; + flightState.now = () => Date.now(); + flightState._displayCourse = new Map(); + flightState._groundSnap.clear = () => {}; + const apply = createMilitarySnapshotRenderer({ + flightState, + records, + groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null }, + militaryRegistry: { registerMilitaryIcaos() {} }, + rendering: parts.rendering, + tracking: {}, + motion: parts.motion, + icons: parts.icons, + queries: { _likelyLanded: () => false }, + }); + const clockFollow = createClockFollow({ + flightState, + services: { placement: null }, + parts: { tracking: { _clearTrail() {} } }, + }); + // `ids`: an id, or [id, fix age ms]. + const snapshot = (ids, fields) => ({ + observedAtMs: Date.now(), + records: ids.map((entry, k) => { + const [id, ageMs = 5_000] = [entry].flat(); + return { + id, + reference: id, + longitude: -97 + k, + latitude: 30, + baroAltitudeM: 3_000, + onGround: false, + speedMps: 200, + courseDeg: 90, + positionTimeMs: Date.now() - ageMs, + }; + }), + complete: true, + ...fields, + }); + return { + calls, + iconIds, + apply(ids, options, fields) { + calls.length = 0; + return apply(snapshot(ids, fields), null, options); + }, + // Back at live, as the layer applies its first live snapshot. + handOver(ids, fields) { + calls.length = 0; + const live = snapshot(ids, fields); + clockFollow.handOverMotion(clockFollow.absentAtHandover(live)); + return apply(live, null, { handover: true }); + }, + }; +} + +test('the first live military snapshot keeps the icons of contacts it has and drops only those it lacks', () => { + const h = harness(); + h.apply(['ae0001', 'ae0002']); + h.handOver(['ae0001', 'ae0003']); + assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']); + assert.equal( + h.calls.some( + ([kind, id]) => id === 'ae0001' && (kind === 'add' || kind === 'forget'), + ), + false, + ); + assert.deepEqual( + h.calls.find(([kind, id]) => kind === 'plan' && id === 'ae0001'), + ['plan', 'ae0001', { handover: true }], + ); + // A plain poll keeps a missing contact as its absence rules say. + h.apply(['ae0001']); + assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']); +}); + +test('back at live, only the first live military snapshot applied takes over; a failed poll says so', async () => { + const applied = []; + let fail = false; + const feed = createMilitaryFeed({ + async getSnapshot() { + if (fail) throw new Error('down'); + return { records: [], observedAtMs: Date.now(), freshness: 'current' }; + }, + }); + const { methods } = createIngestion({ + feed, + applySnapshot: (_snapshot, _viewer, options) => { + applied.push(options); + return { count: 0, ids: new Set() }; + }, + setSourceLabel: () => {}, + applyPendingTrackingRestore: () => {}, + }); + assert.equal(await methods.resumeLive(null), true); + await methods.update(null); + assert.deepEqual(applied, [{ handover: true }, undefined]); + fail = true; + const warn = console.warn; + console.warn = () => {}; + try { + assert.equal(await methods.resumeLive(null), false); + } finally { + console.warn = warn; + } +}); + +test('back at live, a partial military snapshot keeps only contacts whose newest fix is recent', () => { + const h = harness(); + h.apply([ + ['ae0001', 3 * 3_600_000], + ['ae0002', 60_000], + ]); + h.handOver(['ae0003'], { complete: false }); + assert.deepEqual([...h.iconIds].sort(), ['ae0002', 'ae0003']); +}); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 2b1ffe24f0..170d7e4db2 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -35,7 +35,6 @@ import { recoveryMs, limitCourseStep, } from '../../data/motionModel.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { placeLiveAircraft } from '../flights/placed.js'; import { modelVisualAnchor, @@ -44,7 +43,6 @@ import { import { displayDelayMs, followsClock, - MODEL_MIN_PX, BILLBOARD_SCALE, TRACKED_BILLBOARD_SCALE_BY_DISTANCE, DR_CORRECTION_MS, @@ -312,20 +310,17 @@ export function createMotion({ const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24), ); - // Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX. + // Drawn as the fleet draws it: at its true size. const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = (2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM; - return Math.max(MODEL_MIN_PX, projectedDiameterPx); + return projectedDiameterPx; } const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; const width = sprite?.width ?? 28; const height = sprite?.height ?? 28; - const scale = - sprite?.scale ?? - BILLBOARD_SCALE * - (CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1); + const scale = sprite?.scale ?? BILLBOARD_SCALE; const scaleByDistance = sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE; const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM); @@ -354,6 +349,8 @@ export function createMotion({ const sameTrack = flightState._drReconcileValid && flightState._drReconcileIcao === icao24; const raw = _deadReckon(icao24, flightState._scratchDrRaw); + flightState._cachedDRPlaced = + Boolean(raw) && flightState._drSpeedPlaced === true; flightState._cachedDRCourse = flightState._drCourseDeg; flightState._cachedDRSpeedMps = flightState._drSpeedMps; flightState._cachedDRHold = flightState._drCourseHold; @@ -480,6 +477,16 @@ export function createMotion({ * later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the * now-stable plane. Null when no valid fix (callers fall back to the icon position). */ + /** Whether a host-supplied placement placed the tracked aircraft where + * `_trackedDisplayCached` holds it this frame, rather than this layer's + * own motion at its display delay. */ + + function _trackedPlaced() { + return ( + _trackedDisplayCached() !== null && flightState._cachedDRPlaced === true + ); + } + function _trackedDisplayCached() { return flightState._drReconcileValid && flightState._drReconcileIcao === flightState._trackedIcao @@ -515,9 +522,8 @@ export function createMotion({ } /** The tracked model's rendered bounding radius (m), or 0 when no model of this - * contact is drawing. Carries the scale it is drawn at, which may be - * above `scale` to satisfy its pixel floor — the trail head has to be judged - * against the size the operator SEES, not the nominal one. */ + * contact is drawing, at the scale it is drawn at — the trail head has to + * be judged against the size the operator SEES. */ /** World-space origin of the tracked model, or null when no model of this * contact is drawing. This is the centre the rendered bounding sphere is * measured from, so the trail clip and the envelope agree on one frame. */ @@ -703,6 +709,7 @@ export function createMotion({ _trackedFocusSizePx, _trackedDisplayPosition, _trackedDisplayCached, + _trackedPlaced, _trackedVisualCached, _trackedModelCenterWorld, _trackedModelEnvelopeM, diff --git a/src/layers/military/policy.js b/src/layers/military/policy.js index 512674deb4..c8ee6a5062 100644 --- a/src/layers/military/policy.js +++ b/src/layers/military/policy.js @@ -31,10 +31,6 @@ export const BILLBOARD_SCALE = 0.7; export const MIL_ICON_COLOR = rgba('#FFB800'); -/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */ - -export const TRACKED_ICON_COLOR = rgba('#FFD166'); - /** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */ export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS); @@ -61,21 +57,26 @@ export const MODEL_WHITE = rgba('#FFFFFF'); export const GROUND_SCALE = 0.8; // --- 3D model rendering (mirrors flights.js) ----------------------------------------- -// When enabled, military aircraft render as 3D glTF models once the camera is below -// MODEL_ALT_CEIL_M (zoomed in); higher up they stay flat billboards. Eligibility is -// FRUSTUM-based (on-screen), and the slots go to either the nearest planes ('proximity') -// or every in-view plane ('all'), each backed by a hard cap so a draw-call explosion -// can't tank the frame (no instancing yet). Each aircraft draws the fleet model of its -// type, as the flights layer does; the amber tint sets this layer apart. +// When enabled, a military aircraft draws as its 3D glTF model only within MODEL_ADD_M of the +// camera (eye to aircraft); farther away it stays its icon. Models are drawn at their true size, +// with no minimum pixel size. Eligibility is distance-based with on-screen priority, and the slots +// go to either the nearest planes ('proximity') or every in-range plane ('all'): the two modes share +// the radius and differ by their caps. Each aircraft draws the fleet model of its type, as the +// flights layer does; the amber tint sets this layer apart. -export const MODEL_ALT_CEIL_M = 800000; -// m: below this camera altitude, draw 3D models (raised so it's easy to trigger) +export const MODEL_ADD_M = 3000; +// model NEW planes within 3 km of the camera (mirror of flights.js) -export const MODEL_MIN_PX = 24; -// floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js) +export const MODEL_KEEP_M = 3600; +// KEEP modeled planes out to 3.6 km (hysteresis, mirror of flights.js) -// Per-mode caps + radii — mirror of flights.js. Modes differ by RADIUS (not just cap) so Proximity -// and All aren't identical when few planes are in range; on-screen planes win the cap (see flights.js). +export const MODEL_HIGHEST_CONTACT_M = 30000; +// m above the ellipsoid: no aircraft the layer draws flies higher (mirror of flights.js) + +export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M; +// m: above this camera altitude no contact can be within MODEL_KEEP_M (mirror of flights.js) + +// Per-mode caps — mirror of flights.js; on-screen planes win the cap (see flights.js). export const MODEL_MAX = 150; // 'proximity' cap @@ -83,32 +84,24 @@ export const MODEL_MAX = 150; export const MODEL_MAX_ALL = 350; // 'all' cap -export const MODEL_PROX_ADD_M = 150000; -// proximity: model NEW planes within 150 km - -export const MODEL_PROX_KEEP_M = 185000; -// proximity: KEEP modeled planes out to 185 km - -// Cockpit keeps the standard Display radii but lowers the GLB budget. Contacts -// inside the selected band remain AIR silhouettes when they cannot own a model; -// contacts outside the band use compact dots. - export const COCKPIT_MODEL_MAX = 60; // max concurrent GLBs in cockpit (never raises the map cap) -export const MODEL_ALL_ADD_M = 400000; -// all: model NEW planes within 400 km (~to the horizon) +// Cockpit's AIR band (mirror of flights.js): contacts inside it remain AIR +// silhouettes when they cannot own a model; contacts outside it use compact +// dots. Independent of the 3D model radius. -export const MODEL_ALL_KEEP_M = 450000; -// all: KEEP modeled planes out to 450 km +export const COCKPIT_AIR_PROX_ADD_M = 150000; + +export const COCKPIT_AIR_PROX_KEEP_M = 185000; + +export const COCKPIT_AIR_ALL_ADD_M = 400000; + +export const COCKPIT_AIR_ALL_KEEP_M = 450000; export const MODEL_HEADING_OFFSET_DEG = 180; // every fleet model is nose -X: opposite Cesium heading 0 -/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */ - -export const AMBER_TRANSPARENT = rgba('#FFB800', 0); - export const COCKPIT_CONTACT_SIZE_PX = 6; /** The tracked billboard's size by eye distance (the renderer's `NearFar`). */ diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index bd59490f24..52221f6d6e 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -109,6 +109,7 @@ export function createQueries({ derivedSpeedMps: flightState._drSpeedMps, derivedTrackDeg: flightState._drCourseDeg, reportedSpeedMps: info?.speedMps, + derivedFromPlacement: flightState._drSpeedPlaced === true, reportedTrackDeg: info?.track, }); const carto = toLonLatH(basePos); @@ -249,11 +250,11 @@ export function createQueries({ /** * Live layer params. - * `models3d` toggles 3D glTF jet-model rendering for the FLEET (altitude-gated): when on, - * surrounding military aircraft become 3D models once the camera is zoomed in past - * MODEL_ALT_CEIL_M. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), + * `models3d` toggles 3D glTF jet-model rendering for the FLEET: when on, military + * aircraft within MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true + * size. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), * so selecting a contact never turns its icon into a model or its model into an icon. - * `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane). + * `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius. * @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedMilitaryTrackingId?: string|null}} params */ setParams(params = {}, { origin = 'programmatic' } = {}) { diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index c8062e4c16..f53883753e 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -1,4 +1,3 @@ -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { aircraftLayerModelSpec, aircraftModelSpecCacheKey, @@ -9,7 +8,6 @@ import { BILLBOARD_SCALE, GROUND_SCALE, MIL_ICON_COLOR, - TRACKED_ICON_COLOR, EMERGENCY_ICON_COLOR, MODEL_WHITE, } from './policy.js'; @@ -41,15 +39,11 @@ export function createRendering({ return spec; } - /** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */ + /** Fleet icon scale: one size for every class, ×GROUND_SCALE while grounded. */ function _fleetBillboardScale(icao24) { const meta = flightState.records.data.get(icao24); - return ( - BILLBOARD_SCALE * - (CLASS_SCALE_2D[meta?.klass] || 1) * - (meta?.onGround ? GROUND_SCALE : 1) - ); + return BILLBOARD_SCALE * (meta?.onGround ? GROUND_SCALE : 1); } /** Sprite kind for one contact's icon. Identity for every aircraft except @@ -61,11 +55,10 @@ export function createRendering({ const _iconKind = (icao24, klass) => tr3bIconKind(icao24, klass, { hot: flightState._irBoost }); - /** Model colour: the mesh's own (white), tinted amber while tracked and red - * while broadcasting an emergency. */ + /** Model colour: the mesh's own (white), tinted red while broadcasting an + * emergency. Tracking never recolours it. */ function _modelColor(icao24) { - if (icao24 === flightState._trackedIcao) return TRACKED_ICON_COLOR; const info = flightState.records.data.get(icao24); return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MODEL_WHITE; } diff --git a/src/layers/military/snapshotRenderer.js b/src/layers/military/snapshotRenderer.js index cc3f74d490..73188950f4 100644 --- a/src/layers/military/snapshotRenderer.js +++ b/src/layers/military/snapshotRenderer.js @@ -55,8 +55,16 @@ export function createMilitarySnapshotRenderer({ /** * `replace`: the snapshot is the world at another time (the world clock * jumped), so it stands in for every contact: one it lacks is gone at once. + * `handover`: the first live snapshot after the clock came back to live: it + * stands in for every contact too, and those it has keep their icon and + * model and ease on from where they are drawn; of those it lacks, only + * those absence keeps (judged by their newest fix) stay. */ - return function applySnapshot(snapshot, viewer, { replace = false } = {}) { + return function applySnapshot( + snapshot, + viewer, + { replace = false, handover = false } = {}, + ) { // Before init (or after destroy) there is no icon set to draw into. if (!flightState._icons) return { count: 0, ids: new Set() }; const currentIcaos = new Set(); @@ -223,7 +231,7 @@ export function createMilitarySnapshotRenderer({ // freshness change and the cockpit contract all land on the row's // style; motion re-plans from the updated history. icons._applyIconPresentation(icao24); - icons._planIcon(icao24); + icons._planIcon(icao24, handover ? { handover } : undefined); // Per-type fleet models: a type or category change can mean a // different model OR scale — resync the live model, any in-flight // load, and the tracked standalone (mirror of flights.js). @@ -279,6 +287,23 @@ export function createMilitarySnapshotRenderer({ // EXCEPTION: likely-landed planes (last fix low + slow) get only // LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a // feed gap, and the full grace left phantom planes parked at airports. + // Back at live, a contact it lacks is from the time the clock left: it + // goes at once, unless absence keeps it as any poll would (a partial or + // retaining snapshot, the tracked aircraft), judged by its newest fix. + // No missed-poll grace, and a landed tracked aircraft is not kept. + const absenceAtHandover = (icao24) => { + const likelyLanded = queries._likelyLanded(icao24); + const judged = records.absence(icao24, { + complete: snapshot.complete, + retainIds: snapshot.retainIds, + likelyLanded, + tracked: icao24 === flightState._trackedIcao && !likelyLanded, + nowMs: flightState.now?.(), + }); + return judged === 'stale' && icao24 !== flightState._trackedIcao + ? 'remove' + : judged; + }; const absentIds = []; for (const icao24 of flightState._icons.ids()) { if (!currentIcaos.has(icao24)) absentIds.push(icao24); @@ -286,13 +311,15 @@ export function createMilitarySnapshotRenderer({ for (const icao24 of absentIds) { const absence = replace ? 'remove' - : records.absence(icao24, { - complete: snapshot.complete, - retainIds: snapshot.retainIds, - likelyLanded: queries._likelyLanded(icao24), - tracked: icao24 === flightState._trackedIcao, - nowMs: flightState.now?.(), - }); + : handover + ? absenceAtHandover(icao24) + : records.absence(icao24, { + complete: snapshot.complete, + retainIds: snapshot.retainIds, + likelyLanded: queries._likelyLanded(icao24), + tracked: icao24 === flightState._trackedIcao, + nowMs: flightState.now?.(), + }); if (absence === 'retain') continue; if (absence === 'stale') { icons._applyIconPresentation(icao24); // the faded freshness alpha @@ -319,7 +346,8 @@ export function createMilitarySnapshotRenderer({ icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak) } - // The tracked contact at the new time: its trail starts there. + // The tracked contact at the new time: its trail starts there. Back at + // live its trail goes on. if ( replace && flightState._trackedIcao && diff --git a/src/layers/military/state.js b/src/layers/military/state.js index 88e707124d..d0c41c4ca1 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -230,6 +230,18 @@ export function createFlightState({ source, services }) { flightState._drSpeedMps = null; + /** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's, + * the speed it is drawn at (0 while it waits for its fixes), for motion + * only; panels show the reported ground speed (`displayedKinematics`). */ + + flightState._drSpeedPlaced = false; + + /** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed + * it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail + * ends where it is drawn rather than at the layer's display delay. */ + + flightState._cachedDRPlaced = false; + flightState._drCourseHold = false; /** Set by `_deadReckon`: following the clock, the time drawn is well diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index 642d1ca87e..74fc7e97a5 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -1,4 +1,4 @@ -import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js'; +import { trackedIconColor } from '../../data/trackedAircraftIcon.js'; import { createModelRecord } from '../../data/modelRecord.js'; import { aircraftIconTestSeams, @@ -170,9 +170,11 @@ export function createTesting({ /** Evaluate the production tracked-billboard handoff colour for focused tests. */ function _trackedBillboardColorForTest() { - return parts.rendering._modelOwnsVisual(flightState._trackedIcao) - ? AMBER_TRANSPARENT - : TRACKED_ICON_COLOR; + const icao24 = flightState._trackedIcao; + const color = parts.rendering._fleetBillboardColor(icao24); + return parts.rendering._modelOwnsVisual(icao24) + ? trackedIconColor(color, 0) + : color; } /** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */ @@ -194,15 +196,20 @@ export function createTesting({ } /** How the tracked billboard is drawn (`_trackedBillboardLook`, - * `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */ + * `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet + * icon is (`_fleetLook`, `_fleetBillboardColor`). */ function _trackedIconLookForTest(icao24) { return { tracked: { ...parts.tracking._trackedBillboardLook(), sprite: parts.tracking._trackedSprite(icao24), + color: parts.tracking._trackedIconColor(), + }, + fleet: { + ...parts.icons._fleetLook(icao24), + color: parts.rendering._fleetBillboardColor(icao24), }, - fleet: parts.icons._fleetLook(icao24), }; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index ef8e7d8673..9f26bd39dd 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -15,6 +15,7 @@ import { createTrackedAircraftIcon, isOtherTrackedIconSet, trackedContactHolder, + trackedIconColor, } from '../../data/trackedAircraftIcon.js'; import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; import { julianToEpochMs } from '../../geo/julian.js'; @@ -27,13 +28,15 @@ import { } from '../../data/trackingClickGesture.js'; import { inputFor } from '../../input/dispatcher.js'; import { + COCKPIT_AIR_ALL_ADD_M, + COCKPIT_AIR_ALL_KEEP_M, + COCKPIT_AIR_PROX_ADD_M, + COCKPIT_AIR_PROX_KEEP_M, TRAIL_MAX_POINTS, displayDelayMs, followsClock, STALE_ALPHA, TRAIL_COLOR, - AMBER_TRANSPARENT, - TRACKED_ICON_COLOR, } from './policy.js'; import { drawTrailSegments, @@ -45,6 +48,7 @@ import { trailBodySegments, trailHeadCurvePoints, trailHeadStartFix, + trailTimeAt, } from '../../data/trailContinuity.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord } from '../../data/entityRecords.js'; @@ -60,11 +64,6 @@ function aircraftPickId(hit) { return isOtherTrackedIconSet(hit.set, 'military') ? undefined : hit.id; } -const STALE_TRACKED_COLOR = Object.freeze([ - ...TRACKED_ICON_COLOR.slice(0, 3), - STALE_ALPHA, -]); - export function createTracking({ flightState, services, @@ -212,11 +211,13 @@ export function createTracking({ ); distancesSquared.push([icao24, distanceSquared(eye, position)]); } + // The AIR band follows the 3D mode, not the 3D model radius. + const all = flightState._models3dMode === 'all'; const next = nextCockpitNearContacts( previous, distancesSquared, - parts.rendering._modelAddDistM(), - parts.rendering._modelKeepDistM(), + all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M, + all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M, ); flightState._cockpitNearContacts = next; for (const icao24 of previous) @@ -306,14 +307,18 @@ export function createTracking({ return { text: '', dimmed: false }; } - /** The tracked billboard's colour: amber, faded while stale, clear while the 3D model is the visual. */ + /** The tracked billboard's colour: the contact's own fleet colour (tracking + * never recolours it), faded while stale, clear while the 3D model is the + * visual. */ function _trackedIconColor() { - if (parts.rendering._modelOwnsVisual(flightState._trackedIcao)) - return AMBER_TRANSPARENT; - return _trackedStaleCue(flightState._trackedIcao).dimmed - ? STALE_TRACKED_COLOR - : TRACKED_ICON_COLOR; + const icao24 = flightState._trackedIcao; + const color = parts.rendering._fleetBillboardColor(icao24); + if (parts.rendering._modelOwnsVisual(icao24)) + return trackedIconColor(color, 0); + return _trackedStaleCue(icao24).dimmed + ? trackedIconColor(color, STALE_ALPHA) + : color; } /** @@ -404,10 +409,7 @@ export function createTracking({ width: look.size[0], height: look.size[1], get scale() { - return parts.rendering._fleetBillboardScale( - icao24, - flightState.records.data.get(icao24)?.klass, - ); + return parts.rendering._fleetBillboardScale(icao24); }, scaleByDistance: look.scaleByDistance, }; @@ -611,12 +613,46 @@ export function createTracking({ ); } - /** Reports at or before the time the aircraft is drawn (now − the display delay). */ + /** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */ function _trailBodyCountNow() { - return trailBodyCount( + return trailBodyCount(flightState._trailFixes, _trailDisplayMs()); + } + + /** + * The time on its trail at which a host-supplied placement draws the + * aircraft, read off the trail where it is drawn (`trailTimeAt`): such a + * placement draws at a delay of its own, not this layer's. NaN when this + * layer's own motion draws it, or the trail has no pair to read. + * @returns {number} Epoch ms or NaN. + */ + function _placedTrailMs() { + if (!parts.motion._trackedPlaced?.()) return NaN; + return trailTimeAt( flightState._trailFixes, - flightState.now() - displayDelayMs(flightState), + parts.motion._trackedDisplayCached(), + ); + } + + /** + * The time the trail runs up to: the time the aircraft is drawn at, now − + * the display delay, or where a placement draws it. Otherwise the trail + * ends short of a placed aircraft, or runs on ahead of it. + * @returns {number} Epoch ms. + */ + function _trailDisplayMs() { + const placedMs = _placedTrailMs(); + return Number.isFinite(placedMs) + ? placedMs + : flightState.now() - displayDelayMs(flightState); + } + + /** Whether the trail holds no report behind the aircraft yet: this + * layer's own motion draws it before its oldest fix. Never for an + * aircraft a placement draws: its trail is read where it is drawn. */ + function _trailWarmingUp() { + return ( + !Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp() ); } @@ -633,7 +669,7 @@ export function createTracking({ if ( !flightState._trackedIcao || !flightState._trailFixes.length || - parts.motion._isTrackWarmingUp() + _trailWarmingUp() ) return []; const head = @@ -661,7 +697,7 @@ export function createTracking({ trailHeadCurvePoints( flightState._trailFixes, flightState._trailBodyCount, - flightState.now() - displayDelayMs(flightState), + _trailDisplayMs(), ), end, parts.motion._trackedModelCenterWorld(), @@ -926,10 +962,11 @@ export function createTracking({ flightState._trackedIcao = null; // Hand the contact back to its icon only now, once it no longer reads as // tracked (the settle plans it as a fleet contact). - if (flightState._icons?.has(clearedIcao)) { - flightState._icons.setShown(clearedIcao, true); + // Its fleet model, kept loaded while it was selected, takes it back in + // this frame; the icon shows only when there is no loaded one. + parts.rendering._handBackDeselected(clearedIcao); + if (flightState._icons?.has(clearedIcao)) parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg }); - } parts.icons._applyIconPresentation(clearedIcao); clearTrackedSubjectContext('military'); _emitAwarenessEvent('gev:awareness-subject-cleared', { @@ -1044,14 +1081,13 @@ export function createTracking({ imageLod: _trackedBillboardLook().imageLod, sprite, position: getTrackedPosition, - // Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading); - // transparent once the tracked model is actually up (ready + shown). - // Amber (faded while stale), transparent once the tracked model is the visual. + // Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off, + // or model still loading); transparent once the tracked model is actually up (ready + shown). color: _trackedIconColor, // Screen-projected rotation, evaluated per frame on the camera's own // axes, so it stays exact through a tracked orbit. The tracked target // must never vanish into tile geometry — tracking a taxiing plane at - // street level would otherwise bury the amber icon inside the runway + // street level would otherwise bury the icon inside the runway // skin, so it draws over depth like the fleet icon set; its // shared-host tracked card is top-composited separately. rotation: () => { @@ -1059,6 +1095,8 @@ export function createTracking({ const pos = getTrackedPosition(); if (!tracked || !pos || !flightState._viewer) return flightState._lastTrackedRotation; + // A ground station's mast stands upright. + if (tracked.klass === 'station') return 0; const projected = courseScreenRotation( _pose(), pos, diff --git a/src/layers/military/tracking.test.mjs b/src/layers/military/tracking.test.mjs new file mode 100644 index 0000000000..6daa094e21 --- /dev/null +++ b/src/layers/military/tracking.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const source = (layer) => + readFileSync(new URL(`../${layer}/tracking.js`, import.meta.url), 'utf8'); + +for (const layer of ['military', 'flights']) { + test(`${layer}: a tracked ground station's mast is never turned`, () => { + // The tracked billboard's rotation answers 0 for a station before any + // course is projected on screen. + const rotation = /rotation: \(\) => \{[\s\S]*?courseScreenRotation\(/.exec( + source(layer), + )?.[0]; + assert.ok(rotation, 'the tracked billboard turns by a rotation callback'); + assert.match( + rotation, + /if \(tracked\.klass === 'station'\) return 0;\s*const projected = courseScreenRotation\(/, + ); + }); +} diff --git a/src/layers/military/trail.test.mjs b/src/layers/military/trail.test.mjs index daa954ea9b..b4d97074f8 100644 --- a/src/layers/military/trail.test.mjs +++ b/src/layers/military/trail.test.mjs @@ -65,7 +65,15 @@ function recordingTrail() { }; } -function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) { +function trackedHarness({ + liveFixes = [], + trace = null, + nowMs, + floor, + head, + placed = false, + warmingUp = false, +}) { const trail = recordingTrail(); const svc = services({ trails: trail, floor }); const flightState = createFlightState({ @@ -104,7 +112,9 @@ function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) { services: svc, parts: { motion: { - _isTrackWarmingUp: () => false, + _isTrackWarmingUp: () => warmingUp, + _trackedPlaced: () => placed, + _trackedDisplayCached: () => head ?? null, _trackedTrailCached: () => head ?? null, _trackedDisplayPosition: () => head ?? null, _trackedModelCenterWorld: () => null, @@ -256,3 +266,36 @@ test('a full 24 h military trace fits within TRAIL_MAX_POINTS without thinning', assert.ok(TRAIL_MAX_POINTS >= day + 500); assert.equal(flightState._trailFixes.length, day + 1); }); + +test('a placed military aircraft drawn ahead of the display delay keeps its trail joined to it', () => { + const t0 = Date.UTC(2026, 10, 8, 0, 0); + const liveFixes = [0, 1, 2, 3].map((i) => ({ + timeMs: t0 + i * MINUTE, + lat: 50, + lon: 1 + i * 0.12, + })); + // Warming up by the layer's own delay; the placement draws it between the + // third and fourth reports. + const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 9_000); + const harness = trackedHarness({ + liveFixes, + nowMs: t0 + 3.5 * MINUTE, + head: near, + placed: true, + warmingUp: true, + }); + harness.flightState._displayDelay = { currentMs: 10 * MINUTE }; + harness.tracking._startTrail('ae0001'); + const body = harness.trail.last()[0]; + assert.equal(harness.trail.last().length, 1); + assert.ok( + Cesium.Cartesian3.distance( + body[body.length - 1], + Cesium.Cartesian3.fromDegrees(1.24, 50, 9_000), + ) < 1, + ); + const drawn = harness.headPositions(); + assert.ok(drawn.length >= 2); + assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1); + assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1); +}); diff --git a/src/layers/military/trailRecord.test.mjs b/src/layers/military/trailRecord.test.mjs index a35391be51..1fe139b2cb 100644 --- a/src/layers/military/trailRecord.test.mjs +++ b/src/layers/military/trailRecord.test.mjs @@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js'; import { createMotion } from './motion.js'; import { createFlightState } from './state.js'; import { createTracking } from './tracking.js'; -import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js'; +import { MIL_ICON_COLOR, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js'; // A tracked military contact's trail is its reports joined along the curve // the icon is drawn along between them, so the icon always sits on its trail @@ -104,7 +104,11 @@ function harness({ fixes, info, nowMs, ground = () => null }) { flightState.now = () => clock; flightState._positionHistory.set(ICAO, fixes); const parts = { - rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) }, + rendering: { + _modelOwnsVisual: () => false, + _modelSpec: () => ({}), + _fleetBillboardColor: () => MIL_ICON_COLOR, + }, queries: { _toCleanText: (value) => (typeof value === 'string' ? value.trim() : ''), _formatAltitude: (ft) => `${ft} ft`, @@ -649,6 +653,11 @@ test('military: a stalled feed dims the tracked plane as STALE', () => { dimmed: true, }); assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA); + assert.deepEqual( + h.tracking._trackedIconColor().slice(0, 3), + MIL_ICON_COLOR.slice(0, 3), + 'faded in its own colour, never recoloured', + ); assert.equal(h.flightState.records.missingPolls.has(ICAO), false); } finally { h.restore(); diff --git a/src/layers/rail/rendering.js b/src/layers/rail/rendering.js index b2c37b922e..f0fe05bc55 100644 --- a/src/layers/rail/rendering.js +++ b/src/layers/rail/rendering.js @@ -48,6 +48,7 @@ import { transitModelSpec, } from '../../data/fleetModels.js'; import { createFleetModelLayer } from '../../data/fleetModelInstances.js'; +import { groundVehiclePartState } from '../../data/modelPartDrivers.js'; /** How often the trains near enough for a model are gathered again (wall ms). */ const MODEL_CANDIDATES_MS = 500; @@ -924,6 +925,25 @@ export function createRendering({ state, services, parts }) { display: fleet.display, policy: fleet.policy, resolveAsset: fleet.resolveAsset, + partState: vehiclePartState, + }); + } + + /** + * Wheels rolling at the speed it is drawn moving at (else its reported + * one), doors open while it stands at a stop. + */ + function vehiclePartState(item, table) { + const entry = item.entry; + const drawn = entry?.sample?.segmentSpeedMps; + const reported = entry?.record?.speedMps; + return groundVehiclePartState(table, { + speedMps: Number.isFinite(drawn) + ? drawn + : Number.isFinite(reported) + ? reported + : null, + atStop: entry?.record?.status === 'STOPPED_AT', }); } @@ -978,11 +998,7 @@ export function createRendering({ state, services, parts }) { if (now - modelCandidatesAtMs >= MODEL_CANDIDATES_MS) { modelCandidatesAtMs = now; const eye = cameraPose()?.position; - const policy = services.fleet.policy; - const keepM = - services.fleet.display?.()?.models3dMode === 'all' - ? policy.keepAllM - : policy.keepM; + const keepM = services.fleet.policy.keepM; const limitSq = keepM * keepM * 1.44; if (eye) for (const entry of state._trains.values()) { diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 868a3b645a..ce3c97610d 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -574,12 +574,14 @@ export function createRecentImageryLayer({ const list = stripList(); if (!list.length) return; reconcileFocus(); - thumbnails.requestOrdered(list, _box, { - focusIndex: Math.max(0, focusIndexIn(list)), - firstVisible: _visible.first, - lastVisible: _visible.last, - extra: 2, - }); + const wanted = new Set( + thumbnails.requestOrdered(list, _box, { + focusIndex: Math.max(0, focusIndexIn(list)), + firstVisible: _visible.first, + lastVisible: _visible.last, + extra: 2, + }), + ); for (const key of new Set([ _assigned.a, _assigned.b, @@ -587,8 +589,11 @@ export function createRecentImageryLayer({ _followKey, ])) { const candidate = candidateFor(key); - if (sourceOn(candidate)) thumbnails.request(candidate, _box, 0); + if (!sourceOn(candidate)) continue; + thumbnails.request(candidate, _box, 0); + wanted.add(candidate.key); } + thumbnails.retain(wanted); } function resetCatalog() { @@ -821,7 +826,16 @@ export function createRecentImageryLayer({ // A probe can take a pinned day off the map or let a followed focus // preview; both change more than the cards, so a full notification // follows the thumbnail one. + const previousFollow = _followKey; + const previousPreview = _previewKey; const pruned = pruneEmpty(); + if ( + pruned && + (_followKey !== previousFollow || _previewKey !== previousPreview) + ) { + // The new automatic day's probe may have been cancelled off-screen. + requestThumbnails(); + } if (pruned) syncRender(); const followed = Boolean(_followKey) && diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 89fa68110a..7fd9b2f82d 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1105,6 +1105,10 @@ test('alpha, split and visible range notify without re-rendering the row', async f.layer.setSplit(0.25); f.layer.setVisibleRange(1, 3); assert.equal(f.thumbnails.calls.at(-1)[2].firstVisible, 1); + assert.ok( + f.thumbnails.retained.at(-1).includes(f.snap().focus.key), + 'the current focus remains in the retained refinement intent', + ); assert.equal(rowRenders, rows); assert.deepEqual(f.reasons.slice(-2), ['alpha', 'split']); f.layer.setAlpha('bad'); @@ -1193,6 +1197,48 @@ const dailyViirs = () => ), ); +test('empty auto VIIRS re-requests a cancelled successor', async () => { + const f = fixture(); + const days = dailyViirs(); + const newest = days[0].key; + const next = days[1].key; + f.layer.setSources({ hls: false }); + await f.ready(days); + + assert.equal(f.diag().following, newest); + assert.ok( + f.thumbnails.retained.at(-1).includes(next), + 'the next day was originally scheduled', + ); + + // Move the visible window away before either day answers: retention + // cancels the next day's probe but keeps the currently followed day. + f.layer.setVisibleRange(25, 29); + assert.equal( + f.thumbnails.retained.at(-1).includes(next), + false, + 'the next day is no longer retained', + ); + const before = f.thumbnails.requests.filter(([key]) => key === next).length; + + f.thumbnails.probe(newest, 'empty'); + assert.equal(f.diag().following, next); + assert.equal(f.snap().preview.pending, next); + assert.ok( + f.thumbnails.retained.at(-1).includes(next), + 'the new follow day is retained without scrolling again', + ); + assert.equal( + f.thumbnails.requests.filter(([key]) => key === next).length, + before + 1, + 'the cancelled successor is requested again', + ); + + f.thumbnails.probe(next, 'present'); + assert.equal(f.snap().preview.key, next); + assert.deepEqual(f.drapes(), { a: `${next}|none`, b: null }); +}); + test('restored pins outside the visible strip window are probed and swipe once present', async () => { const f = fixture(); const days = dailyViirs(); diff --git a/src/layers/recentImagery/testDoubles.mjs b/src/layers/recentImagery/testDoubles.mjs index 8997e9f1e0..75f660553c 100644 --- a/src/layers/recentImagery/testDoubles.mjs +++ b/src/layers/recentImagery/testDoubles.mjs @@ -258,6 +258,7 @@ export function fakeThumbnails() { const requested = []; /** Direct `request` calls: `[key, priority]`. */ const requests = []; + const retained = []; const ask = (key) => { if (!requested.includes(key)) requested.push(key); }; @@ -265,21 +266,28 @@ export function fakeThumbnails() { calls, requested, requests, + retained, requestOrdered(candidates, box, window) { calls.push(['ordered', candidates.map((c) => c.key), window]); const { focusIndex, firstVisible, lastVisible, extra } = window; - thumbnailOrder( + const order = thumbnailOrder( focusIndex, firstVisible, lastVisible, candidates.length, extra, - ).forEach((index) => ask(candidates[index].key)); + ); + const keys = order.map((index) => candidates[index].key); + keys.forEach(ask); + return keys; }, request(candidate, box, priority) { ask(candidate.key); requests.push([candidate.key, priority]); }, + retain(keys) { + retained.push([...keys]); + }, /** Settle every requested key still unknown, as the loader would. */ probeRequested(status = 'present') { for (const key of requested) diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 4aaec294bf..190836fefd 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -166,6 +166,19 @@ export function createThumbnailLoader({ const existing = entries.get(key); if (existing) { touch(existing); + if (existing.loading && existing.controller?.signal.aborted) { + // Wanted again before the abort settles: a fresh entry, so the old + // run cannot discard it. + const renewed = { + ...existing, + priority, + loading: false, + controller: null, + }; + entries.set(key, renewed); + enqueue(renewed); + return; + } if (existing.loading) return; if (existing.status === 'unknown') { existing.priority = priority; @@ -210,11 +223,33 @@ export function createThumbnailLoader({ candidates.length, extra, ); - order.forEach((index, priority) => { + return order.map((index, priority) => { this.request(candidates[index], box, priority); + return candidates[index].key; }); }, + /** + * Cancel queued and in-flight work for every key not in `keys`. Settled + * entries stay under the LRU; a cancelled re-fetch of a present day keeps + * its status. + * @param {Iterable} keys + */ + retain(keys) { + const wanted = new Set(keys); + for (let index = queue.length - 1; index >= 0; index -= 1) { + const entry = queue[index]; + if (wanted.has(entry.key)) continue; + queue.splice(index, 1); + if (entry.status === 'unknown') entries.delete(entry.key); + } + for (const entry of [...entries.values()]) { + if (!entry.loading || wanted.has(entry.key)) continue; + entry.controller?.abort(); + if (entry.status === 'unknown') entries.delete(entry.key); + } + }, + /** * Abort every fetch in flight and forget every unsettled request. A * known day whose image was being fetched again keeps what it knows. diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjs index ada857f9ae..a9df5e0861 100644 --- a/src/layers/recentImagery/thumbnails.test.mjs +++ b/src/layers/recentImagery/thumbnails.test.mjs @@ -336,3 +336,93 @@ test('injected thumbnail acquisition owns requests while the loader releases obj loader.destroy(); assert.deepEqual(revoked, ['blob:1']); }); + +test('retain aborts stale acquisition while allowing the current intent to start', async () => { + const { loader, fetch } = fixture({ maxInFlight: 1 }); + const stale = candidate('S30', '2026-09-10'); + const current = candidate('S30', '2026-09-11'); + + loader.request(stale, BOX, 0); + loader.request(current, BOX, 1); + assert.equal(fetch.calls.length, 1); + assert.match(fetch.calls[0].url, /TIME=2026-09-10/); + + loader.retain([current.key]); + assert.equal(fetch.calls[0].signal.aborted, true); + await settle(); + + assert.equal( + fetch.calls.length, + 2, + 'current intent starts after stale abort', + ); + assert.match(fetch.calls[1].url, /TIME=2026-09-11/); + assert.equal(loader.get(stale.key).status, 'unknown'); +}); + +test('a cancelled re-fetch of a known-present day keeps its status and is retryable', async () => { + const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 }); + const stale = candidate('S30', '2026-09-10'); + const newer = candidate('S30', '2026-09-11'); + + loader.request(stale, BOX, 0); + fetch.respond(0); + await settle(); + const acquisitionTime = loader.get(stale.key).acquisitionTime; + + loader.request(newer, BOX, 0); + fetch.respond(1); + await settle(); + assert.equal(loader.get(stale.key).status, 'present'); + assert.equal(loader.get(stale.key).objectUrl, null); + + loader.request(stale, BOX, 0); + assert.equal(fetch.calls.length, 3, 'an evicted known day re-fetches'); + loader.retain([]); + assert.equal(fetch.calls[2].signal.aborted, true); + + await settle(); + assert.equal(loader.get(stale.key).status, 'present'); + assert.equal(loader.get(stale.key).acquisitionTime, acquisitionTime); + + loader.request(stale, BOX, 0); + assert.equal(fetch.calls.length, 4, 'a cancelled re-fetch is retryable'); + fetch.respond(3); + await settle(); + assert.equal(loader.get(stale.key).status, 'present'); +}); + +for (const cancelRenewed of [false, true]) { + test(`a known-present day requested during abort settlement ${cancelRenewed ? 'can be cancelled again' : 'restarts without another intent change'}`, async (t) => { + const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 }); + t.after(() => loader.destroy()); + const day = candidate('S30', '2026-09-10'); + const other = candidate('S30', '2026-09-11'); + loader.request(day, BOX); + fetch.respond(0); + await settle(); + const acquisitionTime = loader.get(day.key).acquisitionTime; + loader.request(other, BOX); + fetch.respond(1); + await settle(); + assert.equal(loader.get(day.key).objectUrl, null); + + loader.request(day, BOX); + loader.retain([]); + assert.equal(fetch.calls[2].signal.aborted, true); + // Deliberately do not await: the old run still owns its in-flight slot. + loader.request(day, BOX); + loader.retain(cancelRenewed ? [] : [day.key]); + assert.equal(fetch.calls.length, 3, 'renewal respects the concurrency cap'); + await settle(); + assert.equal(loader.get(day.key).acquisitionTime, acquisitionTime); + assert.equal(fetch.calls.length, cancelRenewed ? 3 : 4); + if (!cancelRenewed) { + assert.equal(fetch.calls[3].signal.aborted, false); + fetch.respond(3); + await settle(); + assert.ok(loader.get(day.key).objectUrl); + assert.equal(loader.get(day.key).loading, false); + } + }); +} diff --git a/src/layers/satellites/offCesium.test.mjs b/src/layers/satellites/offCesium.test.mjs index 5ffdd4575e..e13d0af971 100644 --- a/src/layers/satellites/offCesium.test.mjs +++ b/src/layers/satellites/offCesium.test.mjs @@ -271,13 +271,22 @@ test('the rendering part draws the dots, the tracked dot and the rings through t state._enabled = true; state._params = { showPoints: false, showOrbits: false }; let at = { x: 10, y: 20, z: 30 }; - const carrier = rendering._addTrackedEntity({ position: () => at }); + const issRed = [1, 0.27, 0.27, 1]; + const carrier = rendering._addTrackedEntity({ + position: () => at, + color: issRed, + }); assert.deepEqual(carrier, { noradId: 25544 }); const tracked = draw.set(points.replace(':points', ':tracked')); assert.equal(tracked.items.size, 0); rendering._preRenderTick({ frame: 3 }); assert.deepEqual(tracked.items.get('25544').pos, at); assert.equal(tracked.items.get('25544').pixelSize, 14); + assert.deepEqual( + tracked.items.get('25544').color, + issRed, + 'the satellite keeps its own colour', + ); assert.equal(tracked.items.get('25544').disableDepthTest, Infinity); at = { x: 11, y: 21, z: 31 }; rendering._preRenderTick({ frame: 4 }); diff --git a/src/layers/satellites/rendering.js b/src/layers/satellites/rendering.js index 491ce88606..9704dac7cf 100644 --- a/src/layers/satellites/rendering.js +++ b/src/layers/satellites/rendering.js @@ -34,12 +34,11 @@ const POINT_SCALE_BY_DISTANCE = Object.freeze({ }); /** - * The tracked satellite's dot: 14 px yellow with a white outline, drawn - * over everything. + * The tracked satellite's dot: 14 px in the satellite's own colour with a + * white outline, drawn over everything. Tracking never recolours it. */ const TRACKED_DOT = Object.freeze({ pixelSize: 14, - color: Object.freeze([1, 1, 0, 1]), outlineColor: Object.freeze([1, 1, 1, 1]), outlineWidth: 2, disableDepthTest: Number.POSITIVE_INFINITY, @@ -386,12 +385,13 @@ export function createRendering({ /** * Draw the tracked satellite's dot and make the carrier the follow target * and the tracked card read (its entity record holds the card). - * @param {{position: () => object, viewFrom: {x: number, y: number, - * z: number}}} options `position` is read as the follow camera reads - * it, once each frame before the tick moves the sample on. + * @param {{position: () => object, color: number[], viewFrom: {x: number, + * y: number, z: number}}} options `position` is read as the follow + * camera reads it, once each frame before the tick moves the sample on; + * `color` is the satellite's own dot colour. * @returns {object} The carrier. */ - function _addTrackedEntity({ position }) { + function _addTrackedEntity({ position, color }) { const noradId = layerState._trackedNorad; const carrier = { noradId }; trackedDot = { @@ -400,6 +400,7 @@ export function createRendering({ id: String(noradId), pos: { x: 0, y: 0, z: 0 }, ...TRACKED_DOT, + color, meta: { noradId }, }, drawn: false, diff --git a/src/layers/satellites/tracking.js b/src/layers/satellites/tracking.js index 7eb21cf6c4..8d80fd6c4c 100644 --- a/src/layers/satellites/tracking.js +++ b/src/layers/satellites/tracking.js @@ -445,6 +445,8 @@ export function createTracking({ state: layerState, services, parts, source }) { layerState._trackedEntity = parts.rendering._addTrackedEntity({ position: trackedPosition, + // Its own dot's colour: tracking never recolours a satellite. + color: parts.controls._pointStyleFor(noradId, sat.group).color, viewFrom, }); entityRecord(layerState._trackedEntity).selectionOrigin = origin; diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 49a3e7f17a..18760b5f5d 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -4181,6 +4181,7 @@ test('the actual Transit lifecycle keeps exactly its own camera listener in ever onCameraChanged: noop, runProximityCheck: noop, deactivateAllCities: noop, + showCoverage: noop, }, ingestion: { abortAllInFlight: noop }, }, diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 194d042a3e..f6c22ebc81 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -43,6 +43,7 @@ import { transitModelSpec, } from '../../data/fleetModels.js'; import { createFleetModelLayer } from '../../data/fleetModelInstances.js'; +import { groundVehiclePartState } from '../../data/modelPartDrivers.js'; /** Layers built so far, so each one's draw sets have ids of their own. */ let instances = 0; @@ -944,6 +945,25 @@ export function createRendering({ state, services, parts }) { display: fleet.display, policy: fleet.policy, resolveAsset: fleet.resolveAsset, + partState: vehiclePartState, + }); + } + + /** + * Wheels rolling at the speed it is drawn moving at (else its reported + * one), doors open while it stands at a stop. + */ + function vehiclePartState(item, table) { + const entry = item.entry; + const drawn = entry?.sample?.segmentSpeedMps; + const reported = entry?.record?.speedMps; + return groundVehiclePartState(table, { + speedMps: Number.isFinite(drawn) + ? drawn + : Number.isFinite(reported) + ? reported + : null, + atStop: entry?.record?.status === 'STOPPED_AT', }); } diff --git a/src/layers/vessels/clockFollow.test.mjs b/src/layers/vessels/clockFollow.test.mjs index e208f6ef41..9053684f25 100644 --- a/src/layers/vessels/clockFollow.test.mjs +++ b/src/layers/vessels/clockFollow.test.mjs @@ -216,3 +216,87 @@ test('back at live, the live poll goes out at once even while a snapshot at a ti assert.equal(Object.hasOwn(queries[1], 'atMs'), false); assert.equal(probe.applied.at(-1).rows.length, 1); }); + +test('back at live, only the first live vessel rows applied take over; a poll that fails or brings none says so', async () => { + let answer = 'rows'; + const probe = ingestion({ + async getSnapshot() { + if (answer === 'fail') throw new Error('down'); + return { + records: + answer === 'rows' + ? [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }] + : [], + observedAtMs: 5, + freshness: 'current', + complete: true, + transportStatus: 'live', + }; + }, + }); + assert.equal(await probe.resumeLive({}), true); + await probe.methods.update(); + assert.deepEqual( + probe.applied.map(({ options }) => options), + [{ complete: true, handover: true }, { complete: true }], + ); + answer = 'none'; + assert.equal(await probe.resumeLive({}), false); + answer = 'fail'; + const warn = console.warn; + console.warn = () => {}; + try { + assert.equal(await probe.resumeLive({}), false); + } finally { + console.warn = warn; + } +}); + +test('back at live while a live poll is already out, that poll takes over and its answer is awaited', async () => { + let answer; + const probe = ingestion({ + getSnapshot: () => + new Promise((resolve) => { + answer = () => + resolve({ + records: [ + { id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }, + ], + observedAtMs: 5, + freshness: 'current', + complete: true, + transportStatus: 'live', + }); + }), + }); + const poll = probe.methods.update(); + const resumed = probe.resumeLive({}); + answer(); + assert.equal(await resumed, true); + await poll; + assert.deepEqual( + probe.applied.map(({ options }) => options), + [{ complete: true, handover: true }], + ); +}); + +test('without AbortSignal.any a vessel request still gives up after its timeout', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const any = AbortSignal.any; + AbortSignal.any = undefined; + try { + const probe = ingestion({ + getSnapshot: (_query, { signal }) => + new Promise((_, reject) => + signal.addEventListener('abort', () => reject(signal.reason)), + ), + }); + const resumed = probe.resumeLive({}); + await Promise.resolve(); + t.mock.timers.tick(10_000); + assert.equal(await resumed, false); + assert.equal(probe.feed.loading, false); + } finally { + AbortSignal.any = any; + } +}); diff --git a/src/layers/vessels/index.js b/src/layers/vessels/index.js index 57c3e2dc13..1fcdc2885a 100644 --- a/src/layers/vessels/index.js +++ b/src/layers/vessels/index.js @@ -12,7 +12,10 @@ import { createTesting } from './testing.js'; import { createEvidence } from './evidence.js'; import { createQueries } from './queries.js'; import { followsClock } from './policy.js'; -import { createSnapshotTimeline } from '../../time/snapshotTimeline.js'; +import { + createSnapshotTimeline, + snapshotAnswer, +} from '../../time/snapshotTimeline.js'; import { worldClock } from '../../time/worldClock.js'; /** Compose one vessel layer with application-owned scene services. */ export function createVesselLayer({ source, services, options = {} } = {}) { @@ -58,6 +61,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) { layer.source = source; }, followsClock: () => followsClock(vesselState), + timedAnswer: snapshotAnswer, reloadAtClock: () => vesselState.timeline.reload(), }); // Vessels follow the world clock while the source declares a timeline. @@ -77,9 +81,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) { state.feed.count = state.records.all.length; state.feed.lastUpdate = null; }, - resumeLive: () => { - void parts.ingestion.loadLivePositions(vesselState.state.viewer); - }, + resumeLive: () => parts.ingestion.resumeLive(vesselState.state.viewer), }); Object.assign( layer, diff --git a/src/layers/vessels/ingestion.js b/src/layers/vessels/ingestion.js index b70d1ee88b..ebc898d656 100644 --- a/src/layers/vessels/ingestion.js +++ b/src/layers/vessels/ingestion.js @@ -1,6 +1,9 @@ import { AIS_FIRST_CONNECT_LABEL } from './recordPolicy.js'; import { viewAreaMovedEnough } from './viewArea.js'; +/** Longest a vessel request may take before it is given up. */ +const REQUEST_TIMEOUT_MS = 10_000; + // A portable export (package.json): no i18n here. The text stays English data // and the layer panel shows it translated. const msg = (text) => text; @@ -23,14 +26,62 @@ export function createIngestion({ setSourceLabel, followsClock = () => false, reloadAtClock = () => {}, + timedAnswer = () => true, }) { + // The live load in flight: its result, and its request, whose `handover` + // may still be set while it loads (see resumeLive). + let liveLoad = null; + + /** + * Poll the live vessels (or take the live poll already out). Resolves + * when it is done, with nothing: a feed that fails is shown on the layer, + * and turning the layer on still succeeds. + * @param {object} viewer + * @returns {Promise} + */ async function loadLivePositions(viewer) { + await pollLive(viewer); + } + + /** + * The live poll: resolves what loadPositions answers (false when it could + * not be had), or that of the live poll already out. + */ + async function pollLive(viewer, { handover = false } = {}) { // Following the world clock, the layer shows the snapshots loadAt applies. - if (followsClock()) return; + if (followsClock()) return false; // Back at live, a snapshot at a time still loading no longer applies: // it would hold the live poll back until the next refresh. if (feed.loading && feed.loadingAtTime) dropLoad(); - await loadPositions(viewer); + // A live load already out answers this one too. + if (feed.loading && liveLoad) { + if (handover) liveLoad.request.handover = true; + return liveLoad.promise; + } + const request = { handover }; + const promise = loadPositions(viewer, { request }); + const load = { request, promise }; + liveLoad = load; + try { + return await promise; + } finally { + if (liveLoad === load) liveLoad = null; + } + } + + /** + * Back at live from another time: poll at once (or take the live poll + * already out), and let its snapshot stand in for every vessel. Those it has keep their + * icon and model and move on from where they are; those it lacks go. + * Resolves true once it is applied, else false (it could not be had). + * @param {object} [viewer] + * @returns {Promise} + */ + async function resumeLive(viewer) { + const applied = await pollLive(viewer || readViewer(), { + handover: true, + }); + return applied === true; } /** Let go of the load in flight, so another can start now. */ @@ -44,10 +95,11 @@ export function createIngestion({ /** * Apply the source's snapshot at world time `atMs` (its timeline says it * can answer one), in place of every vessel when `replace`. Resolves - * whether it was applied. + * whether it was applied: `{ reachMs }`, the newest fix its records carry, + * when they carry fixes; else true, or false when it was not. * @param {number} atMs * @param {{signal?: AbortSignal|null, replace?: boolean}} [options] - * @returns {Promise} + * @returns {Promise} */ async function loadAt(atMs, { signal = null, replace = false } = {}) { // Whatever polls or loads for another time no longer applies: the @@ -56,7 +108,10 @@ export function createIngestion({ return loadPositions(readViewer(), { atMs, replace, signal }); } - async function loadPositions(viewer, { atMs, replace = false, signal } = {}) { + async function loadPositions( + viewer, + { atMs, replace = false, signal, request = null } = {}, + ) { const timed = atMs !== undefined; if (!viewer || feed.loading) return false; feed.loading = true; @@ -65,18 +120,35 @@ export function createIngestion({ const requestController = new AbortController(); const requestSessionId = feed.sessionId; feed.abort = requestController; + let timeout = null; try { // Combine the layer's teardown-abort with a hard timeout so a hung upstream // can't wedge the poll indefinitely (parity with the track fetch + flights). - const requestSignal = - typeof AbortSignal.any === 'function' - ? AbortSignal.any([ - requestController.signal, - AbortSignal.timeout(10000), - ...(signal ? [signal] : []), - ]) - : requestController.signal; + let requestSignal; + if (typeof AbortSignal.any === 'function') + requestSignal = AbortSignal.any([ + requestController.signal, + AbortSignal.timeout(REQUEST_TIMEOUT_MS), + ...(signal ? [signal] : []), + ]); + else { + // Without it, the request's own controller takes the timeout and + // the caller's abort. + timeout = setTimeout( + () => + requestController.abort( + new DOMException('Vessel request timed out', 'TimeoutError'), + ), + REQUEST_TIMEOUT_MS, + ); + signal?.addEventListener( + 'abort', + () => requestController.abort(signal.reason), + { once: true }, + ); + requestSignal = requestController.signal; + } // Ask for the vessels in view; a wide view asks for every vessel. const area = readArea(viewer); feed.lastArea = area; @@ -92,9 +164,10 @@ export function createIngestion({ if (signal?.aborted) return false; // The clock left the live edge while this poll was out. if (!timed && followsClock()) return false; + const takesOver = !timed && request?.handover === true; setSourceLabel(snapshot.source); // Map observations into the existing display store; source fields stop here. - applyAisFeedSnapshot(viewer, { + const applied = applyAisFeedSnapshot(viewer, { rows: snapshot.records.map(vesselDisplayRow), observedAtMs: snapshot.observedAtMs, freshness: snapshot.freshness, @@ -112,8 +185,12 @@ export function createIngestion({ silentForMs: snapshot.silentForMs, reconnectAttempt: snapshot.reconnectAttempt, ...(replace && { replace }), + ...(takesOver && { handover: true }), }); - return true; + // Back at live, a snapshot that placed no vessel could not take over. + if (takesOver) return applied.reconciled; + // At a time, what the clock's follower is told of it. + return timed ? timedAnswer(snapshot) : true; } catch (error) { // A snapshot at a time the source dropped for a newer one is no failure. if (timed && error?.name === 'AbortError') throw error; @@ -130,6 +207,7 @@ export function createIngestion({ } return false; } finally { + if (timeout !== null) clearTimeout(timeout); if ( feed.abort === requestController && feed.sessionId === requestSessionId @@ -197,6 +275,7 @@ export function createIngestion({ applyRows(viewer, snapshot.acceptedRows, { complete: payload?.complete !== false, ...(payload?.replace && { replace: true }), + ...(payload?.handover && { handover: true }), }); feed.count = readCount(); feed.stale = @@ -266,6 +345,7 @@ export function createIngestion({ return { loadLivePositions, + resumeLive, loadAt, refreshIfMoved, ownsAisRequest, diff --git a/src/layers/vessels/ownership.test.mjs b/src/layers/vessels/ownership.test.mjs index b4b8772eda..cf8c71f23d 100644 --- a/src/layers/vessels/ownership.test.mjs +++ b/src/layers/vessels/ownership.test.mjs @@ -7,6 +7,10 @@ import { createVesselIconBook } from './iconBook.js'; import { liftedForHorizon } from '../../geo/horizon.js'; import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { aidSprite, vesselSprite } from '../../data/vesselSprites.js'; +import { VESSEL_KIND_STYLES } from '../../data/vesselTypes.js'; +import { AID_TO_NAVIGATION_STYLE } from '../../data/vesselLabels.js'; +import { cssColor } from '../../render/color.js'; /** A query port with nothing on screen: the viewer doubles have no scene. */ const offscreen = { @@ -90,7 +94,7 @@ const snapshot = (records, extra = {}) => ({ ...extra, }); -test('vessel construction is inert and each instance owns its records, icon cache and clock', () => { +test('vessel construction is inert and each instance owns its records and clock', () => { let requested = 0; const source = { getSnapshot() { @@ -99,8 +103,7 @@ test('vessel construction is inert and each instance owns its records, icon cach }; const one = createVesselState({ source, services: services() }); const two = createVesselState({ source, services: services() }); - for (const key of ['state', 'shipIconCache']) - assert.notEqual(one[key], two[key]); + assert.notEqual(one.state, two.state); assert.notEqual(one.state.records.byId, two.state.records.byId); assert.notEqual(one.state.feed, two.state.feed); assert.notEqual(one.state.records.all, two.state.records.all); @@ -557,7 +560,7 @@ test('AIS feed rows stay keyed by their MMSI', async () => { ); }); -test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => { +test('an aid to navigation is drawn as the upright buoy, a vessel as its kind’s hull turned with course', async () => { const aid = { ...observation('993672001'), mmsi: '993672001', @@ -565,26 +568,62 @@ test('an aid to navigation is drawn as a disc, a vessel as its chevron', async ( speedMps: 0, }; const ship = { ...observation('366999002'), type: 'Cargo' }; + const sailing = { ...observation('366999003'), type: '36' }; + const { layer, icons } = setup({ + async getSnapshot() { + return snapshot([aid, ship, sailing]); + }, + }); + await layer.update(); + const itemOf = (id) => { + assert.ok(icons.has(id), id); + return icons.item(id); + }; + const buoy = itemOf('993672001'); + assert.equal(buoy.image, aidSprite()); + assert.equal(buoy.rotationMode, 'screen', 'upright'); + assert.equal(buoy.rotation, 0, 'never turned'); + assert.deepEqual(buoy.color, cssColor(AID_TO_NAVIGATION_STYLE.css)); + // The source's virtual flag reaches the layer's record. + const recordOf = (id) => layer.testing._vesselRecordForTest(id); + assert.equal(recordOf('993672001').virtual, false); + assert.equal(recordOf('366999002').virtual, false); + const cargo = itemOf('366999002'); + assert.equal(cargo.image, vesselSprite('cargo')); + assert.equal(cargo.rotationMode, 'course'); + assert.deepEqual(cargo.color, cssColor(VESSEL_KIND_STYLES.cargo.css)); + const sail = itemOf('366999003'); + assert.equal(sail.image, vesselSprite('sailing')); + assert.deepEqual(sail.color, cssColor(VESSEL_KIND_STYLES.sailing.css)); + // Every vessel and aid draws the same size before its speed scale. + assert.deepEqual(cargo.size, buoy.size); + assert.deepEqual(sail.size, buoy.size); +}); + +test('selecting a vessel or an aid never changes its colour', async () => { + const aid = { + ...observation('993672002'), + mmsi: '993672002', + type: 'Port Hand Mark', + speedMps: 0, + }; + const ship = { ...observation('366999004'), type: 'Cargo' }; const { layer, icons } = setup({ async getSnapshot() { return snapshot([aid, ship]); }, }); await layer.update(); - const svgOf = (id) => { - assert.ok(icons.has(id), id); - return atob(icons.item(id).image.split(',')[1]); - }; - assert.match(svgOf('993672001'), / layer.testing._vesselRecordForTest(id); - assert.equal(recordOf('993672001').virtual, false); - assert.equal(recordOf('366999002').virtual, false); - assert.doesNotMatch(svgOf('993672001'), / { +test('a virtual aid to navigation keeps its buoy and its virtual flag', async () => { const aid = { ...observation('993672009'), mmsi: '993672009', @@ -599,7 +638,7 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async () await layer.update(); assert.ok(icons.has('993672009')); assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true); - assert.match(atob(icons.item('993672009').image.split(',')[1]), / { diff --git a/src/layers/vessels/placement.test.mjs b/src/layers/vessels/placement.test.mjs index c13b196809..d868c22dbe 100644 --- a/src/layers/vessels/placement.test.mjs +++ b/src/layers/vessels/placement.test.mjs @@ -20,6 +20,7 @@ function harness({ placement = null, following = false } = {}) { const visuals = []; const state = { selectedRecord: null, trailId: null }; const records = new VesselRecords({ now: () => 5_000_000 }); + const primitives = []; const rendering = { ensureCollections() {}, makeOccluder: () => null, @@ -28,8 +29,12 @@ function harness({ placement = null, following = false } = {}) { visuals.push(record.id); return { billboard: null }; }, - addRecordPrimitives() {}, - removeRecordPrimitives() {}, + addRecordPrimitives(record) { + primitives.push(['add', record.id]); + }, + removeRecordPrimitives(record) { + primitives.push(['remove', record.id]); + }, shipIcon: () => 'icon', shipScale: () => 1, syncRecordIcon() {}, @@ -41,12 +46,15 @@ function harness({ placement = null, following = false } = {}) { records, rendering, tracking: {}, - selection: {}, - cards: {}, + selection: { clearVesselInspection() {} }, + cards: { updateSelectedVesselHud() {} }, followsClock: () => following, }); return { visuals, + primitives, + state, + records, reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options), }; } @@ -105,3 +113,61 @@ test('following the world clock, or rows at another time, tell the placement not harness({ placement }).reconcile([row('a')], { replace: true }); assert.deepEqual(told, []); }); + +test('back at live, the first live vessel rows keep the vessels they have, drop the rest, and are told to the placement', () => { + const { told, forgotten, placement } = recording(); + const probe = harness({ placement }); + probe.reconcile([row('a'), row('b')]); + probe.primitives.length = 0; + told.length = 0; + probe.reconcile( + [row('a', { lat: 52, last_position_epoch: 1_060 }), row('c')], + { handover: true }, + ); + // The vessel it has keeps its icon; the one it lacks goes; a new one is + // added. + assert.deepEqual(probe.primitives, [ + ['add', 'c'], + ['remove', 'b'], + ]); + assert.deepEqual(forgotten, ['b']); + assert.deepEqual( + told.map(([id]) => id), + ['a', 'c'], + 'live fixes, told to the placement', + ); +}); + +test('back at live, partial vessel rows keep the vessels they lack whose newest fix is recent; complete rows pin the selected one', () => { + const probe = harness(); + // The records' clock reads 5 000 s: 'recent' was fixed 100 s before it, + // 'old' and 'picked' over an hour before. + probe.reconcile([ + row('recent', { last_position_epoch: 4_900 }), + row('old'), + row('picked'), + ]); + probe.state.selectedRecord = probe.records.byId.get('picked'); + probe.primitives.length = 0; + probe.reconcile([row('c', { last_position_epoch: 4_990 })], { + complete: false, + handover: true, + }); + // Partial rows prove no absence for a recent fix; an old one is gone. + assert.ok(probe.records.byId.has('recent')); + assert.equal(probe.records.byId.get('recent').motion, null); + assert.equal(probe.records.byId.has('old'), false); + + const complete = harness(); + complete.reconcile([ + row('recent', { last_position_epoch: 4_900 }), + row('picked'), + ]); + complete.state.selectedRecord = complete.records.byId.get('picked'); + complete.reconcile([row('c', { last_position_epoch: 4_990 })], { + handover: true, + }); + // Complete rows judge as a refresh does: the selected vessel is pinned for + // a few refreshes, the rest go. + assert.deepEqual([...complete.records.byId.keys()].sort(), ['c', 'picked']); +}); diff --git a/src/layers/vessels/records.js b/src/layers/vessels/records.js index bda5267b53..e2af0cd21c 100644 --- a/src/layers/vessels/records.js +++ b/src/layers/vessels/records.js @@ -103,7 +103,12 @@ export class VesselRecords { * between the two (see motion.js). `replace`: the rows are the world at * another time (the clock jumped), so they stand in for every vessel: one * they lack is gone at once, selected or not, and none moves from where it - * was at the time the clock left. + * was at the time the clock left. `handover`: the first live rows after the + * clock came back to live: a vessel they have moves to its live fix, not + * from where it was at the time the clock left; one they lack is judged + * as any live refresh judges it (a partial refresh, the selected vessel), + * by how old its newest fix is rather than when it was loaded, and holds + * at its last position meanwhile. */ reconcile( rows, @@ -112,6 +117,7 @@ export class VesselRecords { selectedRecord = null, cap = Infinity, replace = false, + handover = false, follow = false, }, effects, @@ -152,7 +158,7 @@ export class VesselRecords { record.fixReceivedAtMs = next.fixReceivedAtMs; record.fixFeedEpoch = next.fixFeedEpoch; } - if (replace) { + if (replace || handover) { record.motion = null; record.fixes = next.fixes; } else if (follow) { @@ -195,6 +201,13 @@ export class VesselRecords { } for (const [id, record] of this.byId) { if (seen.has(id)) continue; + if (handover) { + record.motion = null; + record.fixes = null; + // Loaded for another time: last seen at its newest fix. + const fixMs = finiteNumber(record.lastPositionEpoch); + if (fixMs !== null) record.receivedAtMs = fixMs * 1000; + } if (replace) { effects.remove(record, record === selectedRecord); this.byId.delete(id); diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index 221306c835..c4083c4ebd 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -43,7 +43,11 @@ import { vesselModelSpec, } from '../../data/fleetModels.js'; import { createFleetModelLayer } from '../../data/fleetModelInstances.js'; -import { isAidToNavigation } from '../../data/vesselTypes.js'; +import { vesselPartState } from '../../data/modelPartDrivers.js'; +import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js'; +import { aidSprite, vesselSprite } from '../../data/vesselSprites.js'; +import { cssColor } from '../../render/color.js'; +import { KNOT_MPS } from '../../data/units.js'; /** A moving vessel's next frame is asked for once it would move this far on * screen (pixels), so it glides when it moves visibly and the scene idles @@ -55,11 +59,14 @@ const PLACEMENT_FRAME_MS = 1000; * ms), so one that comes into view is judged where it is. */ const HIDDEN_FOLLOW_MS = 250; -/** The ship artwork's own raster size (px). */ +/** A vessel or aid sprite's drawn size before its scale (CSS px). */ const SHIP_ICON_PX = 32; let instances = 0; +/** Tint by CSS colour: a handful of type colours. */ +const tints = new Map(); + /** How often the vessels near enough for a model are gathered again (wall ms). */ const MODEL_CANDIDATES_MS = 500; @@ -404,7 +411,7 @@ export function createRendering({ /** The icon item a record draws, as it now is. */ function iconItem(record, visual) { - const selected = record === state.selectedRecord; + const aid = isAidToNavigation(record); const courseDeg = vesselCourseDeg(record); // Following the clock, not there yet at the time drawn. visual.seen = seenYet(record); @@ -418,11 +425,14 @@ export function createRendering({ // is not there yet. show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen, pos: plan?.pos ?? visual.position, - image: shipIcon(record, selected), + image: shipIcon(record), size: [SHIP_ICON_PX, SHIP_ICON_PX], - // Selection changes the colour only, never the size. + // Tinted by type; selection changes neither the colour nor the size. + color: shipTint(record), scale: shipScale(record), - rotationMode: 'course', + // An aid's buoy stands upright on screen; a vessel turns with course. + rotationMode: aid ? 'screen' : 'course', + rotation: 0, // Held on course, or along its track on the renderer's clock; // `course` for renderers without motion segments. course: courseDeg, @@ -519,40 +529,33 @@ export function createRendering({ } /** - * Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel. - * The shape points north (up) so the row's course maps directly to heading. - * An aid to navigation, which has no heading, is a ringed disc instead. - * One icon is generated per color+variant and shares one atlas slot. - * @param {Object} record - Vessel record (drives per-type tint). - * @param {boolean} selected - True for the white/brighter selected variant. + * The sprite a vessel is drawn as: the white hull of its kind + * (`vesselKind`), bow up so the row's course turns it to its heading, or + * for an aid to navigation the buoy. The layer tints it + * (`shipTint`), so each shape takes one icon-atlas slot. + * @param {Object} record - Vessel record. * @returns {string} SVG data URL. */ - function shipIcon(record, selected) { - const aid = isAidToNavigation(record); - const cssColor = selected - ? '#ffffff' - : aid - ? AID_TO_NAVIGATION_STYLE.css - : vesselTypeCss(record.type); - const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`; - if (vesselState.shipIconCache.has(key)) - return vesselState.shipIconCache.get(key); + function shipIcon(record) { + return isAidToNavigation(record) + ? aidSprite() + : vesselSprite(vesselKind(record.type)); + } - const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)'; - const strokeWidth = selected ? 1.1 : 0.7; - const shape = aid - ? ` - ` - : ``; - const svg = ` - - ${shape} - - `; - const icon = 'data:image/svg+xml;base64,' + btoa(svg); - vesselState.shipIconCache.set(key, icon); - return icon; + /** + * A vessel's tint, `[r, g, b, a]`: its type's colour (vesselLabels.js, + * shared with its card), an aid's bone white. + * @param {Object} record - Vessel record. + */ + + function shipTint(record) { + const css = isAidToNavigation(record) + ? AID_TO_NAVIGATION_STYLE.css + : vesselTypeCss(record.type); + let tint = tints.get(css); + if (!tint) tints.set(css, (tint = Object.freeze(cssColor(css)))); + return tint; } // Under the DISPLAY rail's 3D toggle, vessels near the camera are drawn as @@ -578,6 +581,13 @@ export function createRendering({ resolveAsset: fleet.resolveAsset, // A hull below the waterline would show through a plain globe. waterline: true, + // Its radar sweeps while it is under way (speed in knots). + partState: (item, table) => + vesselPartState(table, { + speedMps: Number.isFinite(item.record?.speed) + ? item.record.speed * KNOT_MPS + : null, + }), }); } @@ -614,11 +624,7 @@ export function createRendering({ ? findCamera(state.viewer)?.pose()?.position : null; if (!eye) return; - const policy = services.fleet.policy; - const keepM = - services.fleet.display?.()?.models3dMode === 'all' - ? policy.keepAllM - : policy.keepM; + const keepM = services.fleet.policy.keepM; const limitSq = keepM * keepM * 1.44; for (const record of state.records.all) { const waterline = getVisual(record).waterline; diff --git a/src/layers/vessels/snapshotRenderer.js b/src/layers/vessels/snapshotRenderer.js index 54e683a739..8af886c970 100644 --- a/src/layers/vessels/snapshotRenderer.js +++ b/src/layers/vessels/snapshotRenderer.js @@ -1,4 +1,5 @@ -const KNOT_MPS = 1852 / 3600; +import { KNOT_MPS } from '../../data/units.js'; + const finiteOrNaN = (value) => typeof value === 'number' && Number.isFinite(value) ? value : NaN; @@ -34,11 +35,15 @@ export function createVesselSnapshotRenderer({ cards, followsClock = () => false, }) { - /** `replace`: the rows are the world at another time (see VesselRecords). */ + /** + * `replace`: the rows are the world at another time (see VesselRecords). + * `handover`: the first live rows after the clock came back to live (see + * VesselRecords); they are live fixes. + */ function reconcileVessels( viewer, rows, - { complete = true, replace = false } = {}, + { complete = true, replace = false, handover = false } = {}, ) { rendering.ensureCollections(viewer); const occluder = rendering.makeOccluder(); @@ -57,6 +62,7 @@ export function createVesselSnapshotRenderer({ selectedRecord: state.selectedRecord, cap: rendering.renderRowLimit(), ...(replace && { replace }), + ...(handover && { handover }), ...(follow && { follow }), }, { diff --git a/src/layers/vessels/state.js b/src/layers/vessels/state.js index 35224a3231..e973306b27 100644 --- a/src/layers/vessels/state.js +++ b/src/layers/vessels/state.js @@ -53,10 +53,6 @@ export function createVesselState({ source, services }) { vesselState._geoidReady = false; - /** @type {Map} `${cssColor}:${variant}` -> chevron SVG data URL */ - - vesselState.shipIconCache = new Map(); - /** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */ vesselState._unkeyedIconSequence = 0; diff --git a/src/layers/wildlifeSightings/acquisition.test.mjs b/src/layers/wildlifeSightings/acquisition.test.mjs index 3cb5cd4f73..daad1f53c4 100644 --- a/src/layers/wildlifeSightings/acquisition.test.mjs +++ b/src/layers/wildlifeSightings/acquisition.test.mjs @@ -544,7 +544,7 @@ test('retention never revives an incumbent card after the observation window exp test('all heights and the sampled fallback use the same sightings-in-view count label', () => { const h = harness(); h.state.renderedRows = [sighting]; - assert.equal(h.layer.getStats().countLabel, '1 sightings in view'); + assert.equal(h.layer.getStats().countLabel, '1 sighting in view'); h.state.sightingCount = 2000; assert.equal(h.layer.getStats().count, 2000); assert.equal( @@ -562,6 +562,32 @@ test('all heights and the sampled fallback use the same sightings-in-view count } }); +test('the sightings count takes the plural form of its number', (t) => { + t.after(() => setLocale('en')); + const h = harness(); + const label = (count) => { + h.state.sightingCount = count; + return h.layer.getStats().countLabel; + }; + setLocale('ru'); + assert.equal(label(1), '1 наблюдение в кадре'); + assert.equal(label(3), '3 наблюдения в кадре'); + assert.equal(label(5), '5 наблюдений в кадре'); + setLocale('de'); + assert.equal(label(1), '1 Beobachtung im Bild'); + assert.equal(label(2000), '2.000 Beobachtungen im Bild'); +}); + +test('the CONFIRMED chip names the sightings, apart from a confirmed launch landing', (t) => { + t.after(() => setLocale('en')); + const h = harness(); + assert.equal(h.chip('quality-confirmed').label, 'CONFIRMED'); + setLocale('sv'); + assert.equal(h.chip('quality-confirmed').label, 'BEKRÄFTADE'); + setLocale('es'); + assert.equal(h.chip('quality-confirmed').label, 'CONFIRMADOS'); +}); + test('a stale fallback with a failed-refresh deadline remains DEGRADED, retryable and dated to the cached data', async () => { const h = harness({ getSnapshotDetail: async () => ({ diff --git a/src/layers/wildlifeSightings/controls.js b/src/layers/wildlifeSightings/controls.js index 84b8b862ae..b0499931a8 100644 --- a/src/layers/wildlifeSightings/controls.js +++ b/src/layers/wildlifeSightings/controls.js @@ -1,4 +1,4 @@ -import { t, formatNumber, translateKnown } from '../../i18n/index.js'; +import { t, tn, formatNumber, translateKnown } from '../../i18n/index.js'; import { msg } from '../../i18n/marker.js'; import { translateFeedError } from '../../ui/statusText.js'; import { wildlifeIconicGroup } from './model.js'; @@ -138,7 +138,8 @@ export function createControls({ state, services, parts }) { const chips = [ chip({ id: WILDLIFE_CONFIRMED_CHIP_ID, - label: t('CONFIRMED'), + // The sightings, plural; a launch landing is CONFIRMED alone. + label: t('CONFIRMED', { context: 'sightings filter' }), title: t('Show only community-confirmed (research-grade) sightings'), params: { confirmed: confirmedFailed ? state.confirmed : !state.confirmed, @@ -215,9 +216,12 @@ export function createControls({ state, services, parts }) { stale: state.stale, loading, refreshing, - countLabel: t('{count} sightings in view', { - count: formatNumber(count), - }), + countLabel: tn( + count, + '{count} sighting in view', + '{count} sightings in view', + { count: formatNumber(count) }, + ), loadingLabel: loading ? t('loading...') : refreshing diff --git a/src/layers/wildlifeSightings/ownership.test.mjs b/src/layers/wildlifeSightings/ownership.test.mjs index 057c805196..c7ab130a0f 100644 --- a/src/layers/wildlifeSightings/ownership.test.mjs +++ b/src/layers/wildlifeSightings/ownership.test.mjs @@ -1936,7 +1936,7 @@ test('unavailable grids fail closed to visible sampled sprites without a global assert.equal(h.clicks.collection.values[0].id, 'wildlife:inat:1'); assert.ok(h.clicks.collection.values[0].size[0] * 0.5 >= 8); assert.equal(h.layer.getStats().count, 1); - assert.match(h.layer.getStats().countLabel, /sightings in view/); + assert.equal(h.layer.getStats().countLabel, '1 sighting in view'); assert.equal(h.layer.getStats().partial, undefined); assert.equal(layerFeedState(h.layer.getStats()), 'degraded'); assert.match(h.layer.getStats().error, /Malformed iNaturalist grid response/); @@ -1973,7 +1973,7 @@ test('an oversized view coarsens to a complete grid within the six-tile cap', as await h.update(); assert.equal(h.clicks.collection.values.length, 1); assert.equal(h.clicks.collection.values[0].id, 'wildlife:inat:1'); - assert.match(h.layer.getStats().countLabel, /sightings in view/); + assert.match(h.layer.getStats().countLabel, /sightings? in view/); assert.equal(layerFeedState(h.layer.getStats()), 'nominal'); h.layer.destroy(); }); diff --git a/src/library/controller.js b/src/library/controller.js index 200bbd07e2..762961d8bc 100644 --- a/src/library/controller.js +++ b/src/library/controller.js @@ -25,6 +25,10 @@ import { } from './layers.js'; import { isExplicitLayerStateOrigin } from '../data/layerState.js'; +/** A required catalog that did not answer is asked again after this, doubling. */ +const CATALOG_RETRY_MS = 30_000; +const CATALOG_RETRY_MAX_MS = 10 * 60_000; + function safeLocalStorage() { try { return globalThis.localStorage ?? null; @@ -44,6 +48,14 @@ function safeLocalStorage() { * @param {(reason: string) => void} [options.requestRender] * @param {(extent: object) => boolean} [options.zoomTo] Fly to an extent * through the shell's navigation authority; false when refused. + * @param {Function} [options.fetchTile] A tiles entry's tile fetch in place + * of the renderer's (`createLibrarySource`). + * @param {Function} [options.fetchData] A proxied dataset's fetch + * (`createLibrarySource`). + * @param {boolean} [options.requireCatalog] Offer only what the server's + * catalog names, nothing while it does not answer; it is asked again later. + * @param {typeof fetch} [options.fetchImpl] Asks the library server (its + * catalog) in place of the page's fetch (`createLibrarySource`). */ export function createDataLibrary({ entries = LIBRARY_ENTRIES, @@ -57,7 +69,21 @@ export function createDataLibrary({ requestRender = () => {}, zoomTo = null, storage = safeLocalStorage(), - source = createLibrarySource({ entries }), + fetchTile = null, + fetchData = null, + requireCatalog = false, + fetchImpl = undefined, + source = createLibrarySource({ + entries, + storage, + fetchImpl, + fetchTile, + fetchData, + requireCatalog, + }), + retryMs = CATALOG_RETRY_MS, + setTimer = (run, ms) => setTimeout(run, ms), + clearTimer = (timer) => clearTimeout(timer), }) { if (!dataManager?.registerLibraryLayer) throw new TypeError('A sealed layer manager is required'); @@ -80,6 +106,8 @@ export function createDataLibrary({ let destroyed = false; const listeners = new Set(); const pending = new Map(); + let retryTimer = null; + let retryDelay = retryMs; const notify = () => { for (const listener of [...listeners]) { @@ -315,6 +343,7 @@ export function createDataLibrary({ if (destroyed) return; availability = answer.availability; serverPresent = answer.server; + if (answer.retry) scheduleRetry(signal); const stored = readStoredLibrarySelection(storage, switchable); savedOn = stored.on; // A share opened in this tab while availability loaded wins over the @@ -342,6 +371,37 @@ export function createDataLibrary({ applySelection(next, linked ? 'share-restore' : 'local-restore'); } + /** + * Ask a required catalog again until it answers, then restore what the + * library holds as start-up would have. + */ + function scheduleRetry(signal) { + if (destroyed || retryTimer !== null || signal?.aborted) return; + retryTimer = setTimer(async () => { + retryTimer = null; + let answer; + try { + answer = await source.getAvailability({ signal }); + } catch { + return; + } + if (destroyed) return; + availability = answer.availability; + serverPresent = answer.server; + if (answer.retry) { + retryDelay = Math.min(retryDelay * 2, CATALOG_RETRY_MAX_MS); + scheduleRetry(signal); + notify(); + return; + } + for (const id of selection.added) { + const entry = byId.get(id); + if (entry && addable(id)) register(entry); + } + applySelection(selection, 'local-restore'); + }, retryDelay); + } + /** * Add an entry to the panel and switch it on. * @param {string} id @@ -460,7 +520,13 @@ export function createDataLibrary({ * @returns {Array<{ entry: object, available: boolean, reason: string|null, added: boolean, on: boolean, busy: boolean }>} */ function list() { - return entries.map((entry) => { + // A required catalog shows nothing until it answers, and an entry this + // instance's server does not list is not shown at all. + if (source.requireCatalog && !loaded) return []; + const shown = entries.filter( + (entry) => availability.get(entry.id)?.listed !== false, + ); + return shown.map((entry) => { const state = availability.get(entry.id) || { available: false, reason: started ? 'server-unavailable' : null, @@ -538,6 +604,8 @@ export function createDataLibrary({ destroy() { if (destroyed) return; destroyed = true; + if (retryTimer !== null) clearTimer(retryTimer); + retryTimer = null; unsubscribeManager?.(); shareLink?.setLibraryParamsEncoder?.(null); shareLink?.setLibraryShareListener?.(null); diff --git a/src/library/controller.test.mjs b/src/library/controller.test.mjs index 970d6c54ce..ece7445007 100644 --- a/src/library/controller.test.mjs +++ b/src/library/controller.test.mjs @@ -5,6 +5,8 @@ import { createDataLibrary } from './controller.js'; import { LIBRARY_ENTRIES, LIBRARY_LEDGER } from './catalog.js'; import { validateLibraryCatalog } from './manifest.js'; import { LIBRARY_STORAGE_KEY } from './selection.js'; +import { createLibrarySource } from './source.js'; +import { libraryLayerId } from '../data/libraryLayerIds.js'; const base = { family: 'imagery', @@ -502,7 +504,10 @@ test('entries this instance cannot serve still show as added and can be removed' assert.equal(row.added, true); assert.equal(library.summary().added, 1); assert.equal(await library.remove('night-lights'), true); - assert.deepEqual(JSON.parse(storage.store.get(LIBRARY_STORAGE_KEY)).added, []); + assert.deepEqual( + JSON.parse(storage.store.get(LIBRARY_STORAGE_KEY)).added, + [], + ); library.destroy(); }); @@ -530,10 +535,9 @@ test('a layer that fails to tear down stays in the library', async (t) => { assert.equal(await library.remove('night-lights'), false); assert.equal(await library.reset(), 0); assert.equal(manager.layers.has('lib-night-lights'), true); - assert.deepEqual( - JSON.parse(storage.store.get(LIBRARY_STORAGE_KEY)).added, - ['night-lights'], - ); + assert.deepEqual(JSON.parse(storage.store.get(LIBRARY_STORAGE_KEY)).added, [ + 'night-lights', + ]); assert.equal( library.list().find((row) => row.entry.id === 'night-lights').added, true, @@ -772,3 +776,117 @@ test('every shipped entry kind registers, view-bounded datasets included', async assert.equal(module.getDiagnostics().tooHigh, true); assert.equal(await library.add('nasa-black-marble'), true); }); + +test('an entry the server does not list is neither shown nor added', async (t) => { + const manager = sealedManager(t); + const library = createDataLibrary({ + entries, + ledger, + dataManager: manager, + services: {}, + storage: memoryStorage(), + initialHash: '', + source: source({ + 'sea-marks': { + available: false, + reason: 'operator-disabled', + listed: false, + }, + }), + }); + await library.start(); + assert.deepEqual( + library.list().map(({ entry }) => entry.id), + ['night-lights', 'fixture-pack'], + ); + assert.equal(library.summary().entries, 2); + assert.equal(await library.add('sea-marks'), false); +}); + +test('a required catalog that does not answer offers nothing and is asked again later', async (t) => { + const manager = sealedManager(t); + const calls = []; + let catalog = new Response('busy', { status: 503 }); + const timers = []; + const library = createDataLibrary({ + entries, + ledger, + dataManager: manager, + services: {}, + storage: memoryStorage( + JSON.stringify({ added: ['night-lights'], on: ['night-lights'] }), + ), + initialHash: '', + requireCatalog: true, + source: createLibrarySource({ + entries, + storage: null, + requireCatalog: true, + fetchImpl: async (url) => { + calls.push(String(url)); + return String(url).endsWith('/catalog') + ? catalog + : new Response('', { status: 500 }); + }, + }), + setTimer: (run, ms) => timers.push({ run, ms }), + clearTimer: () => {}, + }); + await library.start(); + assert.deepEqual(library.list(), []); + assert.equal(library.summary().entries, 0); + assert.equal(await library.add('night-lights'), false); + assert.deepEqual(calls, ['/api/library/catalog']); + assert.equal(timers.length, 1); + assert.equal(timers[0].ms, 30_000); + + // Still failing: asked again, later still. + catalog = new Response('', { status: 429 }); + await timers[0].run(); + assert.equal(timers.length, 2); + assert.equal(timers[1].ms, 60_000); + assert.deepEqual(library.list(), []); + + // Answered: what it names is offered, and the stored selection returns. + catalog = Response.json({ + entries: [{ id: 'night-lights', available: true, reason: null }], + }); + await timers[1].run(); + assert.equal(timers.length, 2); + assert.deepEqual( + library.list().map(({ entry }) => entry.id), + ['night-lights'], + ); + assert.ok(manager.layers.has(libraryLayerId('night-lights'))); + // No publisher was ever asked. + assert.ok(calls.every((url) => url === '/api/library/catalog')); + library.destroy(); +}); + +test("the library asks its catalog with the application's own fetch", async (t) => { + const manager = sealedManager(t); + const calls = []; + const library = createDataLibrary({ + entries, + ledger, + dataManager: manager, + services: {}, + storage: memoryStorage(null), + initialHash: '', + requireCatalog: true, + fetchImpl: async (url) => { + calls.push(String(url)); + return Response.json({ + entries: [{ id: 'night-lights', available: true, reason: null }], + }); + }, + setTimer: () => {}, + clearTimer: () => {}, + }); + await library.start(); + assert.deepEqual(calls, ['/api/library/catalog']); + assert.deepEqual( + library.list().map(({ entry }) => entry.id), + ['night-lights'], + ); +}); diff --git a/src/library/layers.js b/src/library/layers.js index 4fd95cd453..c2928b9a27 100644 --- a/src/library/layers.js +++ b/src/library/layers.js @@ -410,9 +410,11 @@ export const LIBRARY_AERIAL_Z = 10; * The globe port imagery spec for a tiles entry. * @param {object} entry Validated tiles entry. * @param {string} url Tile URL template. + * @param {import('../render/contract/globe').ImagerySpec['fetchTile']|null} [fetchTile] + * Fetches each tile in place of the renderer (`source.tileFetch`). * @returns {import('../render/contract/globe').ImagerySpec} */ -export function libraryImagerySpec(entry, url) { +export function libraryImagerySpec(entry, url, fetchTile = null) { const bbox = entry.source.bounded ? entry.coverage.bbox : null; const minZoom = entry.source.minZoom ?? 0; // A dense entry (`minimumTerrainLevelFor`) is hidden where the view is @@ -442,6 +444,7 @@ export function libraryImagerySpec(entry, url) { : {}), ...(entry.display.aerial ? { zOrder: LIBRARY_AERIAL_Z } : {}), ...(tileTransform ? { tileTransform } : {}), + ...(fetchTile ? { fetchTile } : {}), }; } @@ -563,7 +566,11 @@ export function createLibraryTileLayer( if (host.kind === 'tileset') markBaseTileset(tileset); try { imagery = globe.imagery.add( - libraryImagerySpec(entry, source.tileTemplate(entry)), + libraryImagerySpec( + entry, + source.tileTemplate(entry), + source.tileFetch?.(entry) ?? null, + ), ); } catch (error) { // A renderer without tile hooks cannot draw relief or clear the diff --git a/src/library/manifest.js b/src/library/manifest.js index 8b4595c85f..cd4b56c555 100644 --- a/src/library/manifest.js +++ b/src/library/manifest.js @@ -67,6 +67,55 @@ export function libraryTileUrl(template, z, x, y) { .replaceAll('{y}', String(y)); } +/** The finest and coarsest grid a proxied view box snaps to, in degrees. */ +const VIEW_GRID_MIN_DEG = 2 ** -10; +const VIEW_GRID_MAX_DEG = 1; + +/** + * The box a view-bounded entry asks a proxy for: the camera's box snapped + * out to a grid of two cells a side, the cell the smallest power of two + * (degrees) at least as large as the box. Nearby views name the same box, + * so a proxy and the caches in front of it see few distinct requests, and + * each box always holds the box it came from. + * @param {number[]} box `[west, south, east, north]` in degrees. + * @returns {number[]|null} The snapped box, or null for one too large. + */ +export function libraryViewBox([west, south, east, north]) { + const span = Math.max(east - west, north - south); + if (!(span > 0)) return null; + let cell = VIEW_GRID_MIN_DEG; + while (cell < span) cell *= 2; + if (cell > VIEW_GRID_MAX_DEG) return null; + const left = Math.floor(west / cell) * cell; + const bottom = Math.floor(south / cell) * cell; + return [left, bottom, left + 2 * cell, bottom + 2 * cell]; +} + +/** + * Parse a proxied view box (`west,south,east,north`) as + * {@link libraryViewBox} writes it: two grid cells a side, on the grid, and + * written exactly as `String` writes its numbers, so every box has one + * spelling. + * @param {string|null} text + * @returns {number[]|null} + */ +export function parseLibraryViewBox(text) { + if (typeof text !== 'string' || text.length > 128) return null; + const box = text.split(',').map(Number); + if (box.length !== 4 || !box.every(Number.isFinite)) return null; + if (box.join(',') !== text) return null; + const [west, south, east, north] = box; + const cell = (east - west) / 2; + if (north - south !== 2 * cell) return null; + if (!(cell >= VIEW_GRID_MIN_DEG && cell <= VIEW_GRID_MAX_DEG)) return null; + if (2 ** Math.round(Math.log2(cell)) !== cell) return null; + if (!Number.isInteger(west / cell) || !Number.isInteger(south / cell)) + return null; + if (west < -180 - 2 * cell || east > 180 + 2 * cell) return null; + if (south < -90 - 2 * cell || north > 90 + 2 * cell) return null; + return box; +} + /** How the browser reaches the upstream. */ export const FETCH_MODES = Object.freeze(['browser-direct', 'proxied']); @@ -338,7 +387,8 @@ function checkSource(entry, errors) { `source.view needs maxAltitudeM (${MIN_VIEW_ALTITUDE_M}–${MAX_VIEW_ALTITUDE_M}) and an optional sample bbox`, ); // View-bounded loading queries the camera's box; this build does that - // for ArcGIS layers and partitioned GeoParquet, fetched by the browser. + // for ArcGIS layers and partitioned GeoParquet, fetched by the browser + // (or, when a server routes the entry, by its proxy). if ( !['arcgis', 'geoparquet'].includes(source.format) || source.fetch !== 'browser-direct' diff --git a/src/library/proxy.js b/src/library/proxy.js new file mode 100644 index 0000000000..88cc315d72 --- /dev/null +++ b/src/library/proxy.js @@ -0,0 +1,533 @@ +/** + * The Data Library's server side as a fetch handler: a `Request` in, a + * `Response` out, so any server (Node, a Worker, a test) can answer the + * library routes the browser asks for. + * + * GET /catalog what this server offers, per entry + * GET /data/[?bbox=w,s,e,n] a dataset's features + * GET /tile//// one tile's image + * GET /index/ a partitioned GeoParquet's index + * + * The browser names an entry id, never a URL: every upstream request is built + * from that entry's manifest and stays on its host, so the allowlist is + * exactly the catalog. Redirects are refused, bodies are capped while + * streaming, keys come from the server's environment and upstream error text + * is never returned. + * + * A server may hide entries (`listed`: never offered, never served) and route + * browser-direct entries through itself (`proxied`); the catalog route tells + * the browser both. Same-site gates and rate limits belong to the server + * that mounts the handler. + */ +import { LIBRARY_ENTRIES } from './catalog.js'; +import { loadLibraryDataset } from './formats.js'; +import { buildPartitionIndex } from './parquet.js'; +import { + libraryTileUrl, + libraryUpstreamUrl, + parseLibraryIdList, + parseLibraryViewBox, +} from './manifest.js'; +import { createLibrarySource } from './source.js'; +import { KEY_SETUP_KEYS } from '../keySetupCore.mjs'; +import { + coalesceProxyRequest, + readResponseBytesCapped, + readResponseTextCapped, +} from '../sources/httpBody.js'; + +/** The catalog and its view grid, for a server that decides what it serves. */ +export { LIBRARY_ENTRIES } from './catalog.js'; +export { libraryViewBox, parseLibraryViewBox } from './manifest.js'; + +const DATASET_TIMEOUT_MS = 30_000; +const TILE_TIMEOUT_MS = 10_000; +/** Each listing page or footer read while building a partition index. */ +const INDEX_TIMEOUT_MS = 20_000; +/** How long an incomplete partition index is served before a rebuild. */ +const PARTIAL_INDEX_MS = 5 * 60_000; +const TILE_MAX_BYTES = 2 * 1024 * 1024; +const TILE_CACHE_LIMIT = 512; +const VIEW_CACHE_LIMIT = 64; +const IN_FLIGHT_LIMIT = 64; +const TILE_TYPES = /^image\/(png|jpeg|webp)$/; + +/** The configured value for a manifest key, through the key registry. */ +export function libraryKeyValue(key, env) { + const registered = KEY_SETUP_KEYS.find(({ id }) => id === key?.id); + for (const name of registered?.envVars || []) { + const value = String(env[name] || '').trim(); + if (value) return value; + } + return null; +} + +/** + * Availability of every entry on this instance, decided by the operator's + * environment alone: `GEV_LIBRARY_DISABLE` removes entries, opt-in entries + * need `GEV_LIBRARY_ENABLE` (or, for a pack, its host's own switch), and a + * keyed entry needs its key. The answer names a reason, never a secret. + * @param {object[]} entries + * @param {Record} env + * @returns {Map} + */ +export function libraryAvailability(entries, env) { + const enabled = parseLibraryIdList(env.GEV_LIBRARY_ENABLE); + const disabled = parseLibraryIdList(env.GEV_LIBRARY_DISABLE); + const result = new Map(); + for (const entry of entries) { + let reason = null; + if (disabled.has(entry.id)) reason = 'operator-disabled'; + else if (entry.kind === 'pack') { + if (String(env[entry.pack.env] || '').trim() !== '1') + reason = 'operator-opt-in'; + } else if (entry.licence.operatorOptIn && !enabled.has(entry.id)) + reason = 'operator-opt-in'; + else if (entry.source.key && !libraryKeyValue(entry.source.key, env)) + reason = 'key-missing'; + result.set(entry.id, { available: reason === null, reason }); + } + return result; +} + +/** + * Parse `////` against a tiles entry's zoom range. + * @returns {{ z: number, x: number, y: number } | null} + */ +export function parseLibraryTilePath(parts, source) { + if ( + parts.length !== 3 || + !parts.every((part) => /^(0|[1-9]\d{0,7})$/.test(part)) + ) + return null; + const [z, x, y] = parts.map(Number); + const minZoom = source.minZoom ?? 0; + const maxZoom = source.maxZoom ?? 22; + if (z < minZoom || z > maxZoom) return null; + const span = 2 ** z; + if (x >= span || y >= span) return null; + return { z, x, y }; +} + +function withKey(url, key, env, headers) { + if (!key) return url; + const value = libraryKeyValue(key, env); + if (!value) throw Object.assign(new Error('key_missing'), { status: 503 }); + if (key.in === 'header') { + headers[key.name] = value; + return url; + } + const keyed = new URL(url); + keyed.searchParams.set(key.name, value); + return keyed.href; +} + +/** A timeout that also ends with the caller's signal, when there is one. */ +function timeoutSignal(timeoutMs, signal) { + const timeout = AbortSignal.timeout(timeoutMs); + return signal && typeof AbortSignal.any === 'function' + ? AbortSignal.any([timeout, signal]) + : timeout; +} + +function json(status, value, headers = {}) { + return new Response(JSON.stringify(value), { + status, + headers: { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + ...(status === 405 ? { Allow: 'GET' } : {}), + ...(status === 429 ? { 'Retry-After': '60' } : {}), + ...headers, + }, + }); +} + +/** + * How long a browser or shared cache may keep an entry's answer: its + * `cacheSeconds`, shared unless a key fetched it (a keyed answer is the + * operator's, kept by the browser alone). + */ +function cacheControl(entry) { + const scope = entry.source.key ? 'private' : 'public'; + return `${scope}, max-age=${entry.source.cacheSeconds}`; +} + +/** + * @param {object} [options] + * @param {object[]} [options.entries] The catalog. + * @param {Record} [options.env] Keys and the + * `GEV_LIBRARY_*` switches (`libraryAvailability`). + * @param {typeof fetch} [options.fetchImpl] + * @param {() => number} [options.now] + * @param {string} [options.base] Path the routes are mounted under. + * @param {(entry: object) => boolean} [options.listed] False hides an entry: + * the catalog leaves it out of the browser's list and no route serves it. + * @param {(entry: object) => boolean} [options.proxied] True routes a + * browser-direct entry through this handler. + * @param {boolean} [options.keep] Keep answers in this process's memory for + * `cacheSeconds` (and serve a stale dataset when a refresh fails). A server + * with a shared cache in front turns it off. + * @param {Map} [options.partitionCache] Decoded GeoParquet + * partitions, shared by every request this map is given to; at most four + * are kept (pass one map per process to cap them there). + * @param {(entry: object, init: { signal?: AbortSignal }) => Promise} [options.fetchIndex] + * Fetches a partitioned entry's index, e.g. this handler's own `/index/` + * through a shared cache. By default the index route is answered in + * process. A dataset request never builds an index itself. + * @param {number} [options.subrequestLimit] Most upstream requests one + * dataset or tile request may make (a host's per-request subrequest + * limit); a request that would need more is refused with 503 + * `subrequest_limit` before passing it. + * @returns {(request: Request) => Promise} + */ +export function createLibraryHandler({ + entries = LIBRARY_ENTRIES, + env = {}, + fetchImpl = (...args) => globalThis.fetch(...args), + now = () => Date.now(), + base = '/api/library', + listed = () => true, + proxied = () => false, + keep = true, + partitionCache = new Map(), + fetchIndex = null, + subrequestLimit = Infinity, +} = {}) { + const shown = entries.filter((entry) => listed(entry)); + const byId = new Map(shown.map((entry) => [entry.id, entry])); + const datasets = new Map(); + const views = new Map(); + const tiles = new Map(); + const indexes = new Map(); + const partialIndexes = new Map(); + const inFlight = new Map(); + + const routed = (entry) => + entry.kind !== 'pack' && + (entry.source.fetch === 'proxied' || proxied(entry) === true); + + /** The upstream request for `url`, on the manifest's host only. */ + async function upstream(entry, url, { timeoutMs, signal, headers = {} }) { + // Defense in depth: every derived request stays on the manifest's host. + const target = libraryUpstreamUrl(url); + const declared = libraryUpstreamUrl(entry.source.url); + if (!target || !declared || target.host !== declared.host) + throw Object.assign(new Error('off_manifest_host'), { status: 502 }); + const keyHeaders = {}; + const keyed = withKey(url, entry.source.key, env, keyHeaders); + const timed = timeoutSignal(timeoutMs, signal); + const response = await fetchImpl(keyed, { + signal: timed, + redirect: 'error', + headers: { Accept: '*/*', ...headers, ...keyHeaders }, + }); + return { response, signal: timed }; + } + + async function okUpstream(entry, url, options) { + const result = await upstream(entry, url, options); + if (!result.response.ok) { + await result.response.body?.cancel?.().catch?.(() => {}); + throw Object.assign(new Error('upstream_unavailable'), { status: 502 }); + } + return result; + } + + /** Counts one request's upstream fetches against `subrequestLimit`. */ + function subrequests() { + let used = 0; + return () => { + used += 1; + if (used > subrequestLimit) + throw Object.assign(new Error('subrequest_limit'), { status: 503 }); + }; + } + + /** + * A GeoParquet entry's reader for one request: the browser's own, fetching + * upstream from here, with its index fetched (never built) and decoded + * partitions shared through `partitionCache`. + */ + function readerFor(entry, count) { + const direct = { + ...entry, + source: { ...entry.source, fetch: 'browser-direct' }, + }; + const source = createLibrarySource({ + entries: [direct], + base: null, + storage: null, + now, + partitionCache, + buildIndex: false, + fetchIndex: async (_entry, init) => { + count(); + return fetchIndex ? fetchIndex(entry, init) : index(entry); + }, + fetchImpl: async (url, init = {}) => { + count(); + const range = new Headers(init.headers).get('range'); + const { response } = await upstream(entry, String(url), { + timeoutMs: DATASET_TIMEOUT_MS, + signal: init.signal, + headers: range ? { Range: range } : {}, + }); + return response; + }, + }); + return { entry: direct, source }; + } + + async function fetchDataset(entry, bbox) { + const count = subrequests(); + if (entry.source.format === 'geoparquet') { + const reader = readerFor(entry, count); + const result = await reader.source.loadDataset(reader.entry, { bbox }); + return { ...result, fetchedAt: now() }; + } + const collection = await loadLibraryDataset( + entry, + async (url, budget) => { + count(); + const { response, signal } = await okUpstream(entry, url, { + timeoutMs: DATASET_TIMEOUT_MS, + }); + const text = await readResponseTextCapped( + response, + budget.remainingBytes, + signal, + ); + budget.remainingBytes -= new TextEncoder().encode(text).byteLength; + return text; + }, + { bbox }, + ); + return { ...collection, fetchedAt: now() }; + } + + async function cached(store, key, ttlMs, load, limit = Infinity) { + const previous = keep ? store.get(key) : undefined; + if (previous && now() - previous.savedAt < ttlMs) + return { value: previous.value, stale: false }; + if (!inFlight.has(key) && inFlight.size >= IN_FLIGHT_LIMIT) + throw Object.assign(new Error('busy'), { status: 429 }); + try { + const { promise } = coalesceProxyRequest(inFlight, key, async () => { + const value = await load(); + if (keep) { + store.delete(key); + store.set(key, { value, savedAt: now() }); + while (store.size > limit) store.delete(store.keys().next().value); + } + return value; + }); + return { value: await promise, stale: false }; + } catch (error) { + if (previous) return { value: previous.value, stale: true }; + throw error; + } + } + + function failure(error) { + if (error?.status === 429) return json(429, { error: 'rate_limited' }); + if (error?.status === 503) + return json(503, { + error: ['subrequest_limit', 'index_unavailable'].includes(error.message) + ? error.message + : 'key_missing', + }); + return json(502, { error: 'library_upstream_unavailable' }); + } + + async function index(entry) { + // Only a complete index is kept for cacheSeconds. An incomplete one + // (footers that kept failing) is served as `complete: false` and kept + // for PARTIAL_INDEX_MS only, so the next request soon rebuilds it; a + // complete index from before keeps being served while rebuilds fail. + const key = `index:${entry.id}`; + const partial = partialIndexes.get(key); + if (partial && now() - partial.savedAt < PARTIAL_INDEX_MS) { + const previous = indexes.get(key); + return json(200, previous?.value ?? partial.value); + } + try { + const { value } = await cached( + indexes, + key, + entry.source.cacheSeconds * 1000, + async () => { + const count = subrequests(); + const built = await buildPartitionIndex(entry, { + fetchImpl: async (url, options = {}) => { + count(); + const range = new Headers(options.headers).get('range'); + const { response } = await upstream(entry, String(url), { + timeoutMs: INDEX_TIMEOUT_MS, + signal: options.signal, + headers: range ? { Range: range } : {}, + }); + return response; + }, + }); + const value = { + partitions: built.partitions, + complete: built.complete, + builtAt: now(), + }; + if (!built.complete) { + // Recorded here too: with an earlier complete index, cached() + // serves that one and swallows this error, and the rebuild + // still waits PARTIAL_INDEX_MS. + partialIndexes.set(key, { value, savedAt: now() }); + throw Object.assign(new Error('index_incomplete'), { + partialIndex: value, + }); + } + partialIndexes.delete(key); + return value; + }, + ); + return json(200, value, { 'Cache-Control': cacheControl(entry) }); + } catch (error) { + if (error?.partialIndex) return json(200, error.partialIndex); + return error?.status === 429 + ? json(429, { error: 'rate_limited' }) + : json(502, { error: 'library_upstream_unavailable' }); + } + } + + async function data(entry, params) { + const view = Boolean(entry.source.view); + const bboxText = params.get('bbox'); + const bbox = view ? parseLibraryViewBox(bboxText) : null; + if (view && !bbox) return json(400, { error: 'invalid_bbox' }); + if (!view && bboxText !== null) return json(400, { error: 'invalid_bbox' }); + try { + const { value, stale } = await cached( + view ? views : datasets, + view ? `view:${entry.id}:${bboxText}` : `data:${entry.id}`, + entry.source.cacheSeconds * 1000, + () => fetchDataset(entry, bbox), + view ? VIEW_CACHE_LIMIT : Infinity, + ); + return stale + ? json(200, { ...value, stale: true }, { 'X-Data-Stale': 'true' }) + : json(200, value, { 'Cache-Control': cacheControl(entry) }); + } catch (error) { + return failure(error); + } + } + + async function tile(entry, parts) { + const at = parseLibraryTilePath(parts, entry.source); + if (!at) return json(400, { error: 'invalid_tile' }); + try { + const { value } = await cached( + tiles, + `tile:${entry.id}:${at.z}/${at.x}/${at.y}`, + entry.source.cacheSeconds * 1000, + async () => { + const { response, signal } = await okUpstream( + entry, + libraryTileUrl(entry.source.url, at.z, at.x, at.y), + { timeoutMs: TILE_TIMEOUT_MS }, + ); + const type = String(response.headers.get('content-type') || '') + .split(';')[0] + .trim() + .toLowerCase(); + if (!TILE_TYPES.test(type)) { + await response.body?.cancel?.().catch?.(() => {}); + throw Object.assign(new Error('not_an_image'), { status: 502 }); + } + const bytes = await readResponseBytesCapped( + response, + TILE_MAX_BYTES, + signal, + ); + return { type, bytes }; + }, + TILE_CACHE_LIMIT, + ); + return new Response(value.bytes, { + status: 200, + headers: { + 'Content-Type': value.type, + 'Cache-Control': cacheControl(entry), + 'X-Content-Type-Options': 'nosniff', + }, + }); + } catch (error) { + return failure(error); + } + } + + return async function handle(request) { + if (request.method !== 'GET') + return json(405, { error: 'method_not_allowed' }); + const url = new URL(request.url); + const path = url.pathname.startsWith(base) + ? url.pathname.slice(base.length) + : url.pathname; + // One spelling per resource, so a cache keyed on the path holds each + // tile or answer once: no empty segments, no trailing slash. + const parts = path.replace(/^\//, '').split('/'); + if (parts.some((part) => part === '')) + return json(404, { error: 'unknown_entry' }); + const availability = libraryAvailability(shown, env); + + if (parts.length === 1 && parts[0] === 'catalog') { + return json(200, { + entries: [ + ...shown.map(({ id }) => { + const entry = byId.get(id); + return { + id, + ...availability.get(id), + ...(entry.kind !== 'pack' && + entry.source.fetch !== 'proxied' && + routed(entry) + ? { fetch: 'proxied' } + : {}), + }; + }), + ...entries + .filter((entry) => !byId.has(entry.id)) + .map(({ id }) => ({ + id, + available: false, + reason: 'operator-disabled', + listed: false, + })), + ], + }); + } + + const [route, id, ...rest] = parts; + const entry = byId.get(id); + if (!entry || !['data', 'tile', 'index'].includes(route)) + return json(404, { error: 'unknown_entry' }); + + if (route === 'index') { + if (rest.length || !entry.source?.partitions) + return json(404, { error: 'not_partitioned' }); + const { available, reason } = availability.get(id); + if (!available) return json(403, { error: reason }); + return index(entry); + } + + const isDataset = route === 'data' && rest.length === 0; + const isTile = route === 'tile'; + if ( + !routed(entry) || + (isDataset && entry.kind !== 'dataset') || + (isTile && entry.kind !== 'tiles') || + (!isDataset && !isTile) + ) + return json(404, { error: 'not_proxied' }); + const { available, reason } = availability.get(id); + if (!available) return json(403, { error: reason }); + return isDataset ? data(entry, url.searchParams) : tile(entry, rest); + }; +} diff --git a/src/library/proxy.test.mjs b/src/library/proxy.test.mjs new file mode 100644 index 0000000000..96a96217cb --- /dev/null +++ b/src/library/proxy.test.mjs @@ -0,0 +1,256 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createLibraryHandler } from './proxy.js'; +import { libraryEntry } from './catalog.js'; +import { + libraryViewBox, + parseLibraryViewBox, + validateLibraryCatalog, +} from './manifest.js'; + +const base = { + family: 'imagery', + provider: 'Fixture', + description: 'Fixture entry.', + maintainer: 'test', + coverage: { global: true }, + licence: { name: 'Public domain', url: 'https://example.org/licence' }, + attribution: { text: 'Fixture' }, + status: 'community', +}; +const { entries, errors } = validateLibraryCatalog([ + { + ...base, + id: 'direct-tiles', + kind: 'tiles', + title: 'Direct tiles', + source: { + format: 'bbox', + url: 'https://maps.example.org/export?bbox={bbox-epsg-3857}&f=image', + fetch: 'browser-direct', + cacheSeconds: 900, + }, + }, + { + ...base, + id: 'hidden-tiles', + kind: 'tiles', + title: 'Hidden tiles', + source: { + format: 'xyz', + url: 'https://tiles.example.org/{z}/{x}/{y}.png', + fetch: 'browser-direct', + }, + }, + { + ...base, + id: 'direct-points', + kind: 'dataset', + family: 'events', + title: 'Direct points', + source: { + format: 'geojson', + url: 'https://data.example.org/points.json', + fetch: 'browser-direct', + }, + }, +]); +assert.deepEqual(errors, []); +const view = libraryEntry('fema-usa-structures'); + +const png = () => + new Response(new Uint8Array([137, 80, 78, 71]), { + headers: { 'content-type': 'image/png' }, + }); +const get = (handle, path) => + handle(new Request(`https://app.example/api/library${path}`)); + +test('a hidden entry is listed as not offered and no route serves it', async () => { + let calls = 0; + const handle = createLibraryHandler({ + entries, + listed: (entry) => entry.id !== 'hidden-tiles', + proxied: () => true, + fetchImpl: async () => { + calls++; + return png(); + }, + }); + const catalog = await (await get(handle, '/catalog')).json(); + assert.deepEqual( + catalog.entries.find(({ id }) => id === 'hidden-tiles'), + { + id: 'hidden-tiles', + available: false, + reason: 'operator-disabled', + listed: false, + }, + ); + assert.equal((await get(handle, '/tile/hidden-tiles/1/0/0')).status, 404); + assert.equal(calls, 0); +}); + +test('a routed browser-direct entry is served from its manifest and cacheable for cacheSeconds', async () => { + const calls = []; + const handle = createLibraryHandler({ + entries, + proxied: (entry) => entry.id === 'direct-tiles', + keep: false, + fetchImpl: async (url, options) => { + calls.push({ url, options }); + return png(); + }, + }); + const catalog = await (await get(handle, '/catalog')).json(); + assert.equal( + catalog.entries.find(({ id }) => id === 'direct-tiles').fetch, + 'proxied', + ); + assert.equal( + catalog.entries.find(({ id }) => id === 'direct-points').fetch, + undefined, + ); + const tile = await get(handle, '/tile/direct-tiles/1/1/0?url=https://evil'); + assert.equal(tile.status, 200); + assert.equal(tile.headers.get('content-type'), 'image/png'); + assert.equal(tile.headers.get('cache-control'), 'public, max-age=900'); + assert.equal(calls.length, 1); + assert.match( + calls[0].url, + /^https:\/\/maps\.example\.org\/export\?bbox=0\.000,0\.000,20037508\.343,20037508\.343&f=image$/, + ); + assert.equal(calls[0].options.redirect, 'error'); + // Not kept in memory: a shared cache in front holds it. + await get(handle, '/tile/direct-tiles/1/1/0'); + assert.equal(calls.length, 2); + // An entry the server does not route stays the browser's to fetch. + assert.equal((await get(handle, '/data/direct-points')).status, 404); +}); + +test('a routed view-bounded entry needs a snapped box and queries only it', async () => { + const calls = []; + const handle = createLibraryHandler({ + entries: [view], + proxied: () => true, + fetchImpl: async (url) => { + calls.push(new URL(url)); + return new Response( + JSON.stringify({ type: 'FeatureCollection', features: [] }), + ); + }, + }); + assert.equal((await get(handle, '/data/fema-usa-structures')).status, 400); + assert.equal( + (await get(handle, '/data/fema-usa-structures?bbox=-77.03,38.89,-77,38.9')) + .status, + 400, + ); + assert.equal(calls.length, 0); + const box = libraryViewBox([-77.031, 38.889, -77.02, 38.9]); + const ok = await get(handle, `/data/fema-usa-structures?bbox=${box}`); + assert.equal(ok.status, 200); + assert.equal( + ok.headers.get('cache-control'), + `public, max-age=${view.source.cacheSeconds}`, + ); + assert.equal(calls.length, 1); + assert.equal( + calls[0].searchParams.get('geometry'), + box.map((value) => value.toFixed(6)).join(','), + ); +}); + +test('a view box snaps out to two grid cells a side, with one spelling', () => { + const asked = [-77.031, 38.889, -77.02, 38.9]; + const box = libraryViewBox(asked); + assert.ok(box[0] <= asked[0] && box[1] <= asked[1]); + assert.ok(box[2] >= asked[2] && box[3] >= asked[3]); + assert.equal(box[2] - box[0], box[3] - box[1]); + // Nearby views name the same box. + assert.deepEqual(libraryViewBox([-77.0305, 38.8895, -77.0205, 38.8995]), box); + assert.deepEqual(parseLibraryViewBox(box.join(',')), box); + assert.equal( + parseLibraryViewBox(box.map((v) => v.toFixed(8)).join(',')), + null, + ); + assert.equal(parseLibraryViewBox('-77,38,-76,39.5'), null); + assert.equal(parseLibraryViewBox('0,0,4,4'), null); + assert.equal(libraryViewBox([0, 0, 3, 3]), null); +}); + +test('a tile path has one spelling: no leading zeros, no empty segments, inside the grid', async () => { + const calls = []; + const xyz = entries.find(({ id }) => id === 'hidden-tiles'); + const handle = createLibraryHandler({ + entries: [xyz], + proxied: () => true, + keep: false, + fetchImpl: async (url) => { + calls.push(url); + return png(); + }, + }); + for (const path of [ + '/tile/hidden-tiles/02/1/1', + '/tile/hidden-tiles/2/01/1', + '/tile/hidden-tiles/2/1/4', + '/tile/hidden-tiles/2/1/1.5', + '/tile/hidden-tiles/23/1/1', + ]) + assert.equal((await get(handle, path)).status, 400, path); + for (const path of [ + '/tile/hidden-tiles//2/1/1', + '/tile/hidden-tiles/2/1/1/', + '//tile/hidden-tiles/2/1/1', + ]) + assert.equal((await get(handle, path)).status, 404, path); + assert.equal(calls.length, 0); + assert.equal((await get(handle, '/tile/hidden-tiles/2/1/3')).status, 200); + assert.equal(calls.length, 1); +}); + +test('a partitioned dataset reads its index from the given fetch, never builds one, and stays under the subrequest limit', async () => { + const epc = libraryEntry('epc-england-wales'); + const box = libraryViewBox(epc.source.view.sample); + const upstream = []; + const indexes = []; + const handler = (fetchIndex, subrequestLimit = Infinity) => + createLibraryHandler({ + entries: [epc], + proxied: () => true, + keep: false, + fetchIndex, + subrequestLimit, + fetchImpl: async (url) => { + upstream.push(String(url)); + return new Response('', { status: 500 }); + }, + }); + + // No index to be had: refused clearly, the publisher never asked. + const missing = await get( + handler(async (entry) => { + indexes.push(entry.id); + return new Response('', { status: 404 }); + }), + `/data/epc-england-wales?bbox=${box}`, + ); + assert.equal(missing.status, 503); + assert.deepEqual(await missing.json(), { error: 'index_unavailable' }); + assert.deepEqual(indexes, ['epc-england-wales']); + assert.deepEqual(upstream, []); + + // An index naming partitions in view: reading them would pass the limit. + const partitions = Array.from({ length: 8 }, (_, i) => ({ + url: `${epc.source.partitions.keyBase}addresscloud/epc/geoparquet-local-authority/p${i}.parquet`, + bbox: box, + })); + const over = await get( + handler(async () => Response.json({ partitions, complete: true }), 3), + `/data/epc-england-wales?bbox=${box}`, + ); + assert.equal(over.status, 503); + assert.deepEqual(await over.json(), { error: 'subrequest_limit' }); + // The index fetch and two upstream reads; the third read was refused. + assert.equal(upstream.length, 2); +}); diff --git a/src/library/source.js b/src/library/source.js index 1c6f544a69..7aae814fb2 100644 --- a/src/library/source.js +++ b/src/library/source.js @@ -4,12 +4,13 @@ * * Browser-direct entries are fetched from their upstream without cookies or * a referrer; proxied entries go through `/api/library`, which names entries - * by id only. A static build with no server still serves every browser-direct - * entry that is not operator opt-in. + * by id only. A server may hide entries and route browser-direct ones through + * itself; its catalog route says which. A static build with no server still + * serves every browser-direct entry that is not operator opt-in. */ import { loadLibraryDataset, boundLibraryFeatures } from './formats.js'; import { readResponseTextCapped } from '../sources/httpBody.js'; -import { BBOX_TOKEN } from './manifest.js'; +import { BBOX_TOKEN, libraryViewBox } from './manifest.js'; /** Partitions read per view before giving up, in parallel batches. */ const MAX_PARTITION_READS_PER_VIEW = 8; @@ -150,26 +151,66 @@ export function staticLibraryAvailability(entries) { ); } +/** Every entry unavailable and left out of the list. */ +function unlisted(entries) { + return new Map( + entries.map(({ id }) => [ + id, + { available: false, reason: 'server-unavailable', listed: false }, + ]), + ); +} + /** - * @param {{ entries: object[], fetchImpl?: typeof fetch, base?: string }} options + * @param {object} options + * @param {object[]} options.entries + * @param {typeof fetch} [options.fetchImpl] + * @param {string|null} [options.base] The library server's path; null for + * none (a server reading upstream itself). + * @param {Storage|null} [options.storage] Where partition indexes and + * learned extents are kept between visits (the page's localStorage); none + * by default. + * @param {(request: { entry: object, tile: object, url: string, signal: AbortSignal }) => Promise} [options.fetchTile] + * Fetches a tiles entry's tile in place of the renderer (the imagery + * spec's `fetchTile`): for a host that keeps tiles in its own cache. + * @param {(request: { entry: object, url: string, signal?: AbortSignal }) => Promise} [options.fetchData] + * Fetches a proxied dataset's answer from the library server in place of + * `fetchImpl`. + * @param {boolean} [options.requireCatalog] Offer only what the server's + * catalog names: while it does not answer, nothing is offered (and + * `getAvailability` says `retry`), rather than every browser-direct entry. + * @param {Map} [options.partitionCache] Decoded GeoParquet + * partitions, most recent last, shared by sources given the same map; at + * most four are kept. + * @param {(entry: object, init: { signal?: AbortSignal }) => Promise} [options.fetchIndex] + * Fetches a partitioned entry's index (`{ partitions, complete }`) in + * place of the library server's `/index/`. + * @param {boolean} [options.buildIndex] Build a partition index here when + * no complete one can be fetched; false uses an incomplete one or fails. */ export function createLibrarySource({ entries, fetchImpl = (...args) => globalThis.fetch(...args), base = LIBRARY_API_BASE, - storage = (() => { - try { - return globalThis.localStorage ?? null; - } catch { - return null; - } - })(), + fetchTile = null, + fetchData = null, + requireCatalog = false, + partitionCache = new Map(), + fetchIndex = null, + buildIndex = true, + storage = null, now = () => Date.now(), loadParquet = () => import('./parquet.js'), }) { const known = new Set(entries.map(({ id }) => id)); + /** Entries the library server routes through itself (its catalog says). */ + const routed = new Set(); + // What the last catalog answer offered; with `requireCatalog`, nothing + // else is ever loaded. + const offered = new Set(); + const isProxied = (entry) => + entry.source.fetch === 'proxied' || routed.has(entry.id); const indexes = new Map(); - const partitionCache = new Map(); /** * A partitioned entry's index: from this app's server (built once and @@ -209,11 +250,14 @@ export function createLibrarySource({ : null; let partial = null; try { - const response = await fetchImpl( - `${base}/index/${encodeURIComponent(entry.id)}`, - { headers: { Accept: 'application/json' } }, - ); - if (response.ok) { + const response = fetchIndex + ? await fetchIndex(entry, {}) + : base + ? await fetchImpl(`${base}/index/${encodeURIComponent(entry.id)}`, { + headers: { Accept: 'application/json' }, + }) + : null; + if (response?.ok) { const body = await response.json(); if (Array.isArray(body?.partitions)) { if (body.complete !== false) @@ -229,6 +273,10 @@ export function createLibrarySource({ now() - storedComplete.savedAt < entry.source.cacheSeconds * 1000 ) return { partitions: storedComplete.partitions, complete: true }; + if (!buildIndex) { + if (partial) return { partitions: partial, complete: false }; + throw Object.assign(new Error('index_unavailable'), { status: 503 }); + } // The server's index is incomplete, or there is no server: build here. const { buildPartitionIndex } = await loadParquet(); const built = await buildPartitionIndex(entry, { fetchImpl }); @@ -366,6 +414,11 @@ export function createLibrarySource({ * @returns {Promise<{ server: boolean, availability: Map }>} */ async function getAvailability({ signal } = {}) { + if (!base) + return { + server: false, + availability: staticLibraryAvailability(entries), + }; try { const response = await fetchImpl(`${base}/catalog`, { signal, @@ -373,21 +426,42 @@ export function createLibrarySource({ }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const body = await response.json(); - const availability = staticLibraryAvailability(entries); - for (const row of Array.isArray(body?.entries) ? body.entries : []) { + if (!Array.isArray(body?.entries)) throw new Error('no catalog'); + // A required catalog is an allowlist: what it does not name is not + // offered. + const availability = requireCatalog + ? unlisted(entries) + : staticLibraryAvailability(entries); + routed.clear(); + offered.clear(); + for (const row of body.entries) { if (!known.has(row?.id)) continue; + // An entry the server does not list is not offered at all. + const listed = row.listed !== false; + const available = listed && row.available === true; availability.set(row.id, { - available: row.available === true, - reason: row.available === true ? null : String(row.reason || ''), + available, + reason: available + ? null + : String(row.reason || (listed ? '' : 'operator-disabled')), + ...(listed ? {} : { listed: false }), }); + if (listed && row.fetch === 'proxied') routed.add(row.id); + if (available) offered.add(row.id); } return { server: true, availability }; } catch (error) { if (signal?.aborted) throw error; - return { - server: false, - availability: staticLibraryAvailability(entries), - }; + // Without the server's word, a required catalog offers nothing (the + // caller asks again later); otherwise the static rule applies. + routed.clear(); + offered.clear(); + return requireCatalog + ? { server: false, availability: unlisted(entries), retry: true } + : { + server: false, + availability: staticLibraryAvailability(entries), + }; } } @@ -399,6 +473,37 @@ export function createLibrarySource({ * @returns {Promise<{ features: object[], truncated: boolean }>} */ async function loadDataset(entry, { signal, bbox = null } = {}) { + if (requireCatalog && !offered.has(entry.id)) + throw new Error(`${entry.id} is not offered by the library server`); + if (isProxied(entry)) { + // A view-bounded entry asks for its snapped box (`libraryViewBox`), + // so nearby views share one answer. + let query = ''; + if (entry.source.view) { + const box = bbox && libraryViewBox(bbox); + if (!box) return { features: [], truncated: false }; + query = `?bbox=${box.join(',')}`; + } + const url = `${base}/data/${encodeURIComponent(entry.id)}${query}`; + const response = fetchData + ? await fetchData({ entry, url, signal }) + : await fetchImpl(url, { + signal, + headers: { Accept: 'application/json' }, + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const body = await response.json(); + // The server already bounded the set; bound again so a page never + // trusts more than its manifest allows. + const bounded = boundLibraryFeatures(body?.features || [], { + maxFeatures: entry.source.maxFeatures, + display: entry.display, + }); + return { + features: bounded.features, + truncated: Boolean(body?.truncated) || bounded.truncated, + }; + } if (entry.source.format === 'geoparquet') { if (entry.source.partitions) { if (!bbox) return { features: [], truncated: false }; @@ -417,24 +522,6 @@ export function createLibrarySource({ ); return { features: bounded.features, truncated: bounded.truncated }; } - if (entry.source.fetch === 'proxied') { - const response = await fetchImpl( - `${base}/data/${encodeURIComponent(entry.id)}`, - { signal, headers: { Accept: 'application/json' } }, - ); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - const body = await response.json(); - // The server already bounded the set; bound again so a page never - // trusts more than its manifest allows. - const bounded = boundLibraryFeatures(body?.features || [], { - maxFeatures: entry.source.maxFeatures, - display: entry.display, - }); - return { - features: bounded.features, - truncated: Boolean(body?.truncated) || bounded.truncated, - }; - } const collection = await loadLibraryDataset( entry, async (url, budget) => { @@ -461,7 +548,7 @@ export function createLibrarySource({ /** The tile URL template the imagery provider requests. */ function tileTemplate(entry) { - if (entry.source.fetch === 'proxied') + if (isProxied(entry)) return `${base}/tile/${encodeURIComponent(entry.id)}/{z}/{x}/{y}`; // Cesium fills a tile's projected corners itself. return entry.source.url.replaceAll( @@ -470,5 +557,20 @@ export function createLibrarySource({ ); } - return { getAvailability, loadDataset, tileTemplate }; + /** + * The imagery spec's `fetchTile` for a tiles entry: the host's, told which + * entry asks; null to let the renderer fetch. + */ + function tileFetch(entry) { + if (typeof fetchTile !== 'function') return null; + return (request) => fetchTile({ ...request, entry }); + } + + return { + getAvailability, + loadDataset, + tileTemplate, + tileFetch, + requireCatalog, + }; } diff --git a/src/library/source.test.mjs b/src/library/source.test.mjs new file mode 100644 index 0000000000..479ab38052 --- /dev/null +++ b/src/library/source.test.mjs @@ -0,0 +1,110 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createLibrarySource } from './source.js'; +import { libraryEntry } from './catalog.js'; +import { libraryViewBox } from './manifest.js'; +import { libraryImagerySpec } from './layers.js'; + +const tiles = libraryEntry('usgs-topo'); +const view = libraryEntry('fema-usa-structures'); +const entries = [tiles, view]; + +function serverSaying(rows, calls = []) { + return async (url, options) => { + calls.push({ url: String(url), options }); + if (String(url).endsWith('/catalog')) + return Response.json({ entries: rows }); + return Response.json({ features: [], truncated: false }); + }; +} + +test('the server can hide an entry and route a browser-direct one through itself', async () => { + const source = createLibrarySource({ + entries, + storage: null, + fetchImpl: serverSaying([ + { id: tiles.id, available: true, reason: null, fetch: 'proxied' }, + { + id: view.id, + available: false, + reason: 'operator-disabled', + listed: false, + }, + ]), + }); + assert.equal(source.tileTemplate(tiles), tiles.source.url); + const { availability } = await source.getAvailability(); + assert.deepEqual(availability.get(view.id), { + available: false, + reason: 'operator-disabled', + listed: false, + }); + assert.equal(availability.get(tiles.id).available, true); + assert.equal( + source.tileTemplate(tiles), + `/api/library/tile/${tiles.id}/{z}/{x}/{y}`, + ); +}); + +test('a routed view-bounded dataset asks the server for its snapped box, through the host fetch', async () => { + const calls = []; + const asked = []; + const source = createLibrarySource({ + entries, + storage: null, + fetchImpl: serverSaying( + [{ id: view.id, available: true, reason: null, fetch: 'proxied' }], + calls, + ), + fetchData: async ({ entry, url }) => { + asked.push({ entry: entry.id, url }); + return Response.json({ features: [], truncated: true }); + }, + }); + await source.getAvailability(); + const bbox = [-77.031, 38.889, -77.02, 38.9]; + const result = await source.loadDataset(view, { bbox }); + assert.equal(result.truncated, true); + assert.deepEqual(asked, [ + { + entry: view.id, + url: `/api/library/data/${view.id}?bbox=${libraryViewBox(bbox).join(',')}`, + }, + ]); + // No box, nothing asked. + assert.deepEqual(await source.loadDataset(view), { + features: [], + truncated: false, + }); + assert.equal(asked.length, 1); + assert.equal(calls.length, 1); +}); + +test("a host's tile fetch reaches the imagery spec, told the entry", async () => { + const seen = []; + const source = createLibrarySource({ + entries, + storage: null, + fetchTile: async ({ entry, url }) => { + seen.push([entry.id, url]); + return { missing: true }; + }, + }); + const spec = libraryImagerySpec( + tiles, + source.tileTemplate(tiles), + source.tileFetch(tiles), + ); + assert.deepEqual(await spec.fetchTile({ tile: {}, url: 'u' }), { + missing: true, + }); + assert.deepEqual(seen, [[tiles.id, 'u']]); + assert.equal( + 'fetchTile' in libraryImagerySpec(tiles, tiles.source.url), + false, + ); + assert.equal( + createLibrarySource({ entries, storage: null }).tileFetch(tiles), + null, + ); +}); diff --git a/src/locationReadouts.test.mjs b/src/locationReadouts.test.mjs index b36a615b78..3b1e7edd30 100644 --- a/src/locationReadouts.test.mjs +++ b/src/locationReadouts.test.mjs @@ -73,7 +73,7 @@ test('any other camera destination clears the search label too', () => { assert.match(shellMethod('_stampNavigation').toString(), /if \(clearSearchedLocation\) this\.clearLocation\(\);/); // The shared funnel is what the reset and voice seams actually reach. - for (const seam of ['resetToGlobeView() {', 'beginLocationNavigation() {', '_runExplicitNavigation(']) { + for (const seam of ['resetToGlobeView({ view = null } = {}) {', 'beginLocationNavigation() {', '_runExplicitNavigation(']) { const at = ui.indexOf(seam); assert.ok(at > 0, `missing navigation seam "${seam}"`); assert.match(shellMethod(seam.match(/^(\w+)/)[1]).toString(), /_stampNavigation\(/, `"${seam}" must stamp navigation`); diff --git a/src/locations.js b/src/locations.js index 3e390433ae..c241175d9b 100644 --- a/src/locations.js +++ b/src/locations.js @@ -32,21 +32,31 @@ export const GLOBE_VIEW = Object.freeze({ /** * Fly straight out to the full-earth globe view, keeping the current sub-camera - * point centered so the user's continent stays in front of them. + * point centered so the user's continent stays in front of them. With `view` + * (`{ lon, lat, height, heading?, pitch? }`, angles in degrees, as the start + * view is given), fly to that view instead. * @param {object} viewer - * @param {{duration?: number, onComplete?: Function, onCancel?: Function}} options + * @param {{duration?: number, onComplete?: Function, onCancel?: Function, + * view?: {lon: number, lat: number, height: number, heading?: number, + * pitch?: number}}} options * @returns {{latitude: number, longitude: number, heightM: number}} */ export function flyToGlobeView(viewer, options = {}) { const camera = cameraOf(viewer); - const { lon: longitude, lat: latitude } = camera.pose(); + const here = camera.pose(); + const view = options.view ?? { + lon: here.lon, + lat: here.lat, + height: GLOBE_VIEW.heightM, + }; + const { lon: longitude, lat: latitude, height: heightM } = view; camera.cancelFlight(); camera.flyTo( - { lon: longitude, lat: latitude, height: GLOBE_VIEW.heightM }, + { lon: longitude, lat: latitude, height: heightM }, { orientation: { - heading: 0, - pitch: toRadians(GLOBE_VIEW.pitchDeg), + heading: toRadians(view.heading ?? 0), + pitch: toRadians(view.pitch ?? GLOBE_VIEW.pitchDeg), roll: 0, }, durationS: finitePositive(options.duration) || GLOBE_VIEW.durationS, @@ -55,7 +65,7 @@ export function flyToGlobeView(viewer, options = {}) { onCancel: options.onCancel, }, ); - return { latitude, longitude, heightM: GLOBE_VIEW.heightM }; + return { latitude, longitude, heightM }; } /** diff --git a/src/locations.test.mjs b/src/locations.test.mjs index 20040a2266..049e763c60 100644 --- a/src/locations.test.mjs +++ b/src/locations.test.mjs @@ -631,6 +631,21 @@ test('a globe flight without callbacks still flies (both hooks are optional)', ( viewer.flights[0].complete(); }); +test('a globe flight to a given view flies there, not out over the current spot', () => { + const viewer = stubViewer(); + const target = flyToGlobeView(viewer, { + view: { lon: -82.5, lat: 35, height: 23000000 }, + }); + assert.deepEqual(target, { latitude: 35, longitude: -82.5, heightM: 23000000 }); + const flight = viewer.flights[0]; + const end = Cesium.Cartographic.fromCartesian(flight.destination); + assert.ok(Math.abs(Cesium.Math.toDegrees(end.longitude) + 82.5) < 1e-6); + assert.ok(Math.abs(Cesium.Math.toDegrees(end.latitude) - 35) < 1e-6); + assert.ok(Math.abs(end.height - 23000000) < 1); + assert.equal(flight.orientation.heading, 0); + assert.ok(Math.abs(flight.orientation.pitch + Math.PI / 2) < 1e-9); +}); + test('geocoded Location branches forward the resolved-navigation ownership hook', () => { const source = fs.readFileSync(new URL('./locations.js', import.meta.url), 'utf8'); const searchStart = source.indexOf('export async function searchAndFlyTo'); diff --git a/src/navigationPolicy.js b/src/navigationPolicy.js index b2826745f5..781161d137 100644 --- a/src/navigationPolicy.js +++ b/src/navigationPolicy.js @@ -38,6 +38,8 @@ const COCKPIT_REFUSALS = Object.freeze({ cyclone: msg('Exit cockpit to fly to a cyclone'), // The News panel's cards and the news layer's hotspots fly to the event. news: msg('Exit cockpit to fly to a news report'), + // A covered city's marker on Bike Share flies down into the city. + 'bike share': msg('Exit cockpit to fly to a bike share city'), // Voice track_entity (TRACKABLE_FAMILIES kinds in gevActions.js) and // frame_overhead, which frames the contacts around the current view. aircraft: msg('Exit cockpit to fly to an aircraft'), diff --git a/src/render/applicationHooks.js b/src/render/applicationHooks.js index c989d4801f..450b47eddd 100644 --- a/src/render/applicationHooks.js +++ b/src/render/applicationHooks.js @@ -14,6 +14,11 @@ * - `viewerDrawsEntity(entity)`: whether an entity is one the renderer draws * itself (Cockpit asks whether the aircraft it flies still draws). * - `qaHandles`: values QA scripts read from `window.__godsEyeView`. + * - `engine`: the renderer's own engine, for an application that draws with + * it directly beside the contract: `kind` names it (`'cesium'`, with + * `viewer`, Cesium's `Viewer`). An application draws only with engines + * whose kind it knows; what it draws there is its own to add, update and + * remove. * - `ownCreditDisplay`: true when the renderer shows its credits in a * display of its own; otherwise the application shows what its credits * port lists (`src/ui/creditsView.js`). diff --git a/src/render/cesium/appRenderer.js b/src/render/cesium/appRenderer.js index a3a51375d7..6e649d8345 100644 --- a/src/render/cesium/appRenderer.js +++ b/src/render/cesium/appRenderer.js @@ -218,6 +218,8 @@ export function createCesiumRendererPlugin({ // Whether an entity is one of the viewer's own (Cockpit asks whether // the aircraft it flies still draws). viewerDrawsEntity: (entity) => viewer.entities.contains(entity), + // An application drawing with Cesium itself beside the contract. + engine: Object.freeze({ kind: 'cesium', viewer }), // QA scripts drive and read the viewer itself. qaHandles: { viewer, diff --git a/src/render/cesium/appRenderer.test.mjs b/src/render/cesium/appRenderer.test.mjs index dccc1ff3e7..a9c16aff37 100644 --- a/src/render/cesium/appRenderer.test.mjs +++ b/src/render/cesium/appRenderer.test.mjs @@ -156,6 +156,8 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async ); assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits'); assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer'); + assert.equal(hooks.engine.kind, 'cesium', 'the engine says what it is'); + assert.equal(hooks.engine.viewer, viewer, 'an application may draw with it'); assert.equal(hooks.viewerDrawsEntity({ own: true }), true); assert.equal(hooks.viewerDrawsEntity({}), false); assert.equal(typeof hooks.trimStaleCommands, 'function'); diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 5cfdb0e7d0..9c55c72d00 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -5312,10 +5312,14 @@ export function createCesiumDraw({ replaceHost, horizonNow, requestRender, + parts: capabilities.has('modelParts'), + now, }); const buildModels = (record) => modelSets.build(record); // Whether shapes pulsed in the last frame, which draws on in the next. let pulsing = false; + // Whether a shown model's parts spun in the last frame, likewise. + let spinning = false; const lineWidth = (px) => typeof scene.clampLineWidth === 'function' ? scene.clampLineWidth(px) @@ -5452,7 +5456,7 @@ export function createCesiumDraw({ turnInertial(record); record.drapeInertial?.(); } - modelSets.beforeRender(sets.values()); + spinning = modelSets.beforeRender(sets.values()); quadSets.beforeRender(sets.values()); }, /** Each frame, after it drew: clamp state, and ground swaps. */ @@ -5483,7 +5487,8 @@ export function createCesiumDraw({ // Rows moving on a live clock, and flowing lines, draw on in the // frames that follow. const playing = quadSets.afterRender(sets.values()); - if (anySet(animating) || flowing() || pulsing || playing) requestRender(); + if (anySet(animating) || flowing() || pulsing || spinning || playing) + requestRender(); }, /** * Let go of the sets; with `removeHosts`, take what they draw out of @@ -5494,6 +5499,8 @@ export function createCesiumDraw({ clampListeners.clear(); // Fields go with the port, and their frame listeners with them. fieldPart.dispose(); + // Part shaders and their textures go with it too. + modelSets.dispose(); // Late model loads find no host and destroy themselves. for (const record of sets.values()) { if (removeHosts && !scene.isDestroyed?.()) { @@ -5538,7 +5545,7 @@ provideUnboundDraw((viewer) => { const part = createCesiumDraw({ scene, report: uncaught, - capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields']), + capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']), }); unboundParts.set(part.port, part); const offs = [ diff --git a/src/render/cesium/drawModels.js b/src/render/cesium/drawModels.js index 41dbb62c13..08c03ccc9c 100644 --- a/src/render/cesium/drawModels.js +++ b/src/render/cesium/drawModels.js @@ -26,6 +26,20 @@ * `shading: 'thermal'` draws the model unlit and white-hot (its texture * left out), then tinted as asked: a hot target, as the thermal views draw * them. Heights are absolute: models clamp nothing. + * + * An item's `parts` (with `modelParts`) poses the moving parts of a model + * whose mesh carries `_PART` and whose root node carries a part table + * (`render/modelParts.js`): its model then draws with a custom shader of + * its own whose vertex stage moves each vertex by its part's matrix, read + * from a small float texture (`PARTS_VERTEX` says its layout), with the + * item's mask, unlit or thermal look in the same shader; a moved part's + * material normal turns with it. The texture is written again in place + * when the part state changes, and each frame while a part of a model in + * view spins (frames are asked for while one does). Spins keep their angle + * across a change of rate. A model at rest, or without a part table, draws + * exactly as it would without `parts`, on the shared shaders above. Cesium + * culls and picks a model by its bounds as its file draws it, so a part + * moved outside them is drawn only while those bounds are in view. */ import * as Cesium from 'cesium'; import { @@ -34,6 +48,15 @@ import { recedeParams, recededAlpha, } from '../recession.js'; +import { customShaderTexture } from './internals.js'; +import { + glbJson, + gltfMeshMatrix, + gltfPartTable, + partMatrices, + PART_HIGHLIGHT, + asksHighlight, +} from '../modelParts.js'; const BLEND_MODES = { highlight: Cesium.ColorBlendMode.HIGHLIGHT, @@ -144,6 +167,366 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { return undefined; } +/** The colour a part with `highlight: true` is drawn in. */ +const PART_HIGHLIGHT_COLOR = '#ffc400'; + +/** How much of a highlighted part's colour the highlight replaces. */ +const PART_HIGHLIGHT_MIX = 0.6; + +/** Texels in a part's row of its texture. */ +const PART_TEXELS = 8; +/** Floats in a part's row: `PART_TEXELS` RGBA texels. */ +const PART_FLOATS = PART_TEXELS * 4; + +/** A texel's centre across a part's row, as a texture coordinate. */ +const texelAt = (i) => ((i + 0.5) / PART_TEXELS).toFixed(4); + +/** + * The vertex stage of a posed model. A part's row of the texture holds the + * three rows of its matrix in the mesh's own frame (texels 0..2), the three + * rows of that matrix's inverse transpose (3..5; texel 3's alpha is 1 where + * the part is moved, 0 where it is at rest), and its highlight colour (6, + * alpha 0 for none). Each vertex is moved by its part's matrix; the normal + * turn is passed on in eye space, for the fragment stage to turn the + * material's own normal (normal maps and back-face flips kept) by it. + * Positions are the mesh's own (before its node's transform), as are the + * matrices written for it, and as `czm_normal` takes them to eye space. + */ +const PARTS_VERTEX = ` +void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { + float row = (floor(vsInput.attributes.part + 0.5) + 0.5) / u_partRows; + vec4 r0 = texture(u_partMatrices, vec2(${texelAt(0)}, row)); + vec4 r1 = texture(u_partMatrices, vec2(${texelAt(1)}, row)); + vec4 r2 = texture(u_partMatrices, vec2(${texelAt(2)}, row)); + vec4 n0 = texture(u_partMatrices, vec2(${texelAt(3)}, row)); + v_partHighlight = texture(u_partMatrices, vec2(${texelAt(6)}, row)); + vec4 p = vec4(vsOutput.positionMC, 1.0); + vsOutput.positionMC = vec3(dot(r0, p), dot(r1, p), dot(r2, p)); + v_partMoved = n0.a; + if (n0.a > 0.5) { + vec4 n1 = texture(u_partMatrices, vec2(${texelAt(4)}, row)); + vec4 n2 = texture(u_partMatrices, vec2(${texelAt(5)}, row)); + mat3 turn = transpose(mat3(n0.xyz, n1.xyz, n2.xyz)); + v_partNormalEC = czm_normal * turn * inverse(czm_normal); + } else { + v_partNormalEC = mat3(1.0); + } +}`; + +/** + * A posed model's custom shader: its parts moved (`PARTS_VERTEX`), drawn in + * `shading` with `mask` painted where `_TINT` marks the model (not under + * `thermal`), and its highlighted parts in their colour. Lit, a moved + * part's material normal is turned with it; the body and parts at rest keep + * theirs as the material made them. `data` is the part texture's first + * contents, `rows` its parts. + */ +function partShaderOf(shading, mask, data, rows) { + const lit = shading !== 'unlit' && shading !== 'thermal'; + const masked = Boolean(mask) && shading !== 'thermal'; + return new Cesium.CustomShader({ + mode: Cesium.CustomShaderMode.MODIFY_MATERIAL, + ...(lit ? {} : { lightingModel: Cesium.LightingModel.UNLIT }), + uniforms: { + u_partMatrices: { + type: Cesium.UniformType.SAMPLER_2D, + value: partTexture(data, rows), + }, + u_partRows: { type: Cesium.UniformType.FLOAT, value: rows }, + ...(masked + ? { + u_maskColor: { + type: Cesium.UniformType.VEC3, + value: new Cesium.Cartesian3(mask.red, mask.green, mask.blue), + }, + } + : {}), + }, + varyings: { + v_partNormalEC: Cesium.VaryingType.MAT3, + v_partMoved: Cesium.VaryingType.FLOAT, + v_partHighlight: Cesium.VaryingType.VEC4, + }, + vertexShaderText: PARTS_VERTEX, + fragmentShaderText: ` +void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { +${ + lit + ? ` if (v_partMoved > 0.5) + material.normalEC = normalize(v_partNormalEC * material.normalEC);` + : '' +} +${shading === 'thermal' ? ' material.diffuse = vec3(1.0);' : ''} +${ + masked + ? ` vec3 mask = czm_srgbToLinear(u_maskColor); + material.diffuse *= mix(vec3(1.0), mask, fsInput.attributes.tint);` + : '' +} + if (v_partHighlight.a > 0.0) { + vec3 highlight = czm_srgbToLinear(v_partHighlight.rgb); + material.diffuse = mix(material.diffuse, highlight, ${PART_HIGHLIGHT_MIX.toFixed(2)}); + material.emissive = max(material.emissive, highlight * 0.5); + } +}`, + }); +} + +/** A part texture's contents as a texture uniform: `PART_TEXELS` float texels a row, read unfiltered. */ +function partTexture(data, rows) { + return new Cesium.TextureUniform({ + typedArray: data, + width: PART_TEXELS, + height: rows, + pixelFormat: Cesium.PixelFormat.RGBA, + pixelDatatype: Cesium.PixelDatatype.FLOAT, + repeat: false, + minificationFilter: Cesium.TextureMinificationFilter.NEAREST, + magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST, + }); +} + +/** An affine column-major 4×4's inverse. */ +function inverseAffine(m) { + const [a, b, c] = [m[0], m[1], m[2]]; + const [d, e, f] = [m[4], m[5], m[6]]; + const [g, h, i] = [m[8], m[9], m[10]]; + const A = e * i - f * h; + const B = -(b * i - c * h); + const C = b * f - c * e; + const det = a * A + d * B + g * C; + if (!(Math.abs(det) > 1e-30)) return null; + const r = 1 / det; + const out = [ + A * r, + B * r, + C * r, + 0, + -(d * i - f * g) * r, + (a * i - c * g) * r, + -(a * f - c * d) * r, + 0, + (d * h - e * g) * r, + -(a * h - b * g) * r, + (a * e - b * d) * r, + 0, + 0, + 0, + 0, + 1, + ]; + for (let row = 0; row < 3; row++) + out[12 + row] = -( + out[row] * m[12] + + out[4 + row] * m[13] + + out[8 + row] * m[14] + ); + return out; +} + +/** What a glTF document (or GLB) says of its parts: its table and mesh frame; null without a table. */ +const partInfos = new WeakMap(); + +/** `source`'s part table and mesh frame, read once; null for a model without moving parts. */ +function partInfoOf(source) { + if (partInfos.has(source)) return partInfos.get(source); + let info = null; + try { + const json = source instanceof Uint8Array ? glbJson(source) : source; + const table = gltfPartTable(json); + const mesh = table && gltfMeshMatrix(json); + const meshInverse = mesh && inverseAffine(mesh); + if (table && table.parts.length > 1 && meshInverse) + info = { table, mesh, meshInverse }; + } catch { + // A malformed table: the model draws whole. + info = null; + } + partInfos.set(source, info); + return info; +} + +/** Whether a part state asks for anything. */ +const asksParts = (state) => + Boolean(state) && + typeof state === 'object' && + ['spin', 'deploy', 'poses'].some( + (key) => state[key] && Object.keys(state[key]).length > 0, + ); + +/** Scratch for one model's part matrices and flags, and one matrix's rows. */ +let scratchParts = new Float64Array(16 * 32); +let scratchFlags = new Uint8Array(32); +const scratchRow = new Float64Array(4); +const scratchL = new Float64Array(12); + +/** How far from the identity a part's matrix may be and still be at rest. */ +const AT_REST_EPSILON = 1e-9; + +/** Highlight colours by what was asked, read once (a few at most). */ +const highlightColors = new Map(); + +/** + * The colour a part's `highlight` asks for, read once: `true` the + * renderer's own, a colour that parses as itself; null for anything else + * (drawn without a highlight). + */ +export function partHighlightColor(value) { + if (!asksHighlight(value)) return null; + const key = value === true ? PART_HIGHLIGHT_COLOR : String(value); + let color = highlightColors.get(key); + if (color === undefined) { + if (value === true || typeof value === 'string') + color = Cesium.Color.fromCssColorString(key.trim()) ?? null; + else color = new Cesium.Color(value[0], value[1], value[2], 1); + if (highlightColors.size >= 256) highlightColors.clear(); + highlightColors.set(key, color); + } + return color; +} + +/** + * Write a model's part texture into `data` (`PART_FLOATS` a part, the + * layout `PARTS_VERTEX` reads) for `state` at `timeS`: for each part the + * rows of its matrix in the mesh's own frame, L = meshInverse · X · mesh, + * then the rows of L's inverse transpose (normals turn by it, exact under a + * stretch or a mesh frame that is not a rotation) with whether the part is + * moved, then its highlight colour. Whether any part is not at rest. + */ +export function writePartTexture(info, state, timeS, scale, data) { + const { table, mesh, meshInverse } = info; + const n = table.parts.length; + if (scratchParts.length < n * 16) { + scratchParts = new Float64Array(n * 16); + scratchFlags = new Uint8Array(n); + } + const posed = partMatrices(table, state, timeS, scratchParts, { + flags: scratchFlags, + scale, + }); + const poses = state?.poses; + const x = scratchParts; + const ix = scratchRow; + const L = scratchL; + for (let k = 0; k < n; k++) { + const o = k * 16; + const d = k * PART_FLOATS; + let moved = false; + for (let row = 0; row < 3; row++) { + // (meshInverse · X) row `row`, as four column entries. + for (let col = 0; col < 4; col++) { + let sum = 0; + for (let j = 0; j < 4; j++) + sum += meshInverse[j * 4 + row] * x[o + col * 4 + j]; + ix[col] = sum; + } + for (let col = 0; col < 4; col++) { + let sum = 0; + for (let j = 0; j < 4; j++) sum += ix[j] * mesh[col * 4 + j]; + L[row * 4 + col] = sum; + data[d + row * 4 + col] = sum; + if (Math.abs(sum - (row === col ? 1 : 0)) > AT_REST_EPSILON) + moved = true; + } + } + // The inverse transpose of L's 3×3: its cofactors over its determinant. + const a = L[0]; + const b = L[1]; + const c = L[2]; + const e = L[4]; + const f = L[5]; + const g = L[6]; + const h = L[8]; + const i = L[9]; + const j = L[10]; + const c00 = f * j - g * i; + const c01 = -(e * j - g * h); + const c02 = e * i - f * h; + const c10 = -(b * j - c * i); + const c11 = a * j - c * h; + const c12 = -(a * i - b * h); + const c20 = b * g - c * f; + const c21 = -(a * g - c * e); + const c22 = a * f - b * e; + const det = a * c00 + b * c01 + c * c02; + const nd = d + 12; + // At rest, or hidden (collapsed to a point): normals as they are. + const turned = moved && Math.abs(det) > 1e-12; + const r = turned ? 1 / det : 0; + data[nd] = turned ? c00 * r : 1; + data[nd + 1] = turned ? c01 * r : 0; + data[nd + 2] = turned ? c02 * r : 0; + data[nd + 3] = turned ? 1 : 0; + data[nd + 4] = turned ? c10 * r : 0; + data[nd + 5] = turned ? c11 * r : 1; + data[nd + 6] = turned ? c12 * r : 0; + data[nd + 7] = 0; + data[nd + 8] = turned ? c20 * r : 0; + data[nd + 9] = turned ? c21 * r : 0; + data[nd + 10] = turned ? c22 * r : 1; + data[nd + 11] = 0; + const color = + scratchFlags[k] & PART_HIGHLIGHT + ? partHighlightColor(poses?.[table.parts[k].name]?.highlight) + : null; + const hd = d + 24; + data[hd] = color ? color.red : 0; + data[hd + 1] = color ? color.green : 0; + data[hd + 2] = color ? color.blue : 0; + data[hd + 3] = color ? 1 : 0; + } + return posed; +} + +/** + * A posed model's spins, turned on to `timeS` (seconds): each spinning + * part's angle moves on at its rate since it last did, so a change of rate + * never makes a part jump. A part that stops spinning keeps its angle. + */ +export function advanceSpins(spins, timeS) { + const dt = timeS - spins.at; + spins.at = timeS; + if (!(dt > 0)) return; + for (const [name, rate] of spins.rates) + spins.angles[name] = (spins.angles[name] + rate * dt) % 360; +} + +/** + * Spins at `state`'s rates from `timeS` on, carrying the angles reached; a + * part starting to spin starts at an angle of `startAngle`'s (by default a + * random one, so a fleet posed at once does not turn in step). + */ +export function respin( + spins, + table, + state, + timeS, + startAngle = () => Math.random() * 360, +) { + advanceSpins(spins, timeS); + spins.rates.clear(); + for (const [name, rate] of Object.entries(state?.spin ?? {})) { + const index = table.byName.get(name); + if ( + index === undefined || + !table.parts[index].axis || + typeof rate !== 'number' || + !Number.isFinite(rate) || + rate === 0 + ) + continue; + spins.rates.set(name, rate); + if (!(name in spins.angles)) spins.angles[name] = startAngle(); + } +} + +/** New spins: none yet, at `timeS`. */ +export const newSpins = (timeS) => ({ + rates: new Map(), + angles: {}, + at: timeS, +}); + /** A contract distance curve's value at `distance`: linear, clamped. */ export function nearFarValue(curve, distance) { if (!curve) return 1; @@ -228,8 +611,11 @@ const focusOf = (item) => * The models part of a Cesium draw port. * @param {{scene: object, toColor: Function, pickId: Function, * replaceHost: Function, horizonNow: () => object|null, - * requestRender: () => void}} options From the draw port: its colour - * conversion, pick ids, host swap, horizon and render request. + * requestRender: () => void, parts?: boolean, + * now?: () => number}} options From the draw port: its colour + * conversion, pick ids, host swap, horizon and render request; whether it + * poses models' parts (`modelParts`), and the clock (milliseconds) spins + * are turned by. */ export function createModelSets({ scene, @@ -238,7 +624,238 @@ export function createModelSets({ replaceHost, horizonNow, requestRender, + parts: posesParts = false, + now = () => performance.now(), }) { + /** Each Cesium model drawn posed: its part shader, texture and spins. */ + const posings = new Map(); + /** The GLB bytes each model was built from, where it was. */ + const modelBytes = new WeakMap(); + /** Part shaders let go, destroyed once no draw uses them. */ + const retired = []; + // Float textures carry the part matrices, and WebGL 2's shading language + // turns the normals: without them models draw whole. + const canPose = () => + scene.context?.floatingPointTexture !== false && + scene.context?.webgl2 !== false; + + /** A model's part table and mesh frame, or null. */ + function partInfoOfModel(model) { + const bytes = modelBytes.get(model); + if (bytes) return partInfoOf(bytes); + const json = model.loader?.gltfJson; + return json ? partInfoOf(json) : null; + } + + /** Let go of a model's posing: its shader goes once no draw uses it. */ + function unpose(model) { + const posing = posings.get(model); + if (!posing) return; + posings.delete(model); + retired.push({ shader: posing.shader, frames: 0 }); + } + + /** Write a posing's texture where its shader reads it. */ + function upload(posing) { + const texture = customShaderTexture(posing.shader, 'u_partMatrices'); + if ( + texture && + !texture.isDestroyed?.() && + texture.width === PART_TEXELS && + texture.height === posing.rows + ) + texture.copyFrom({ + source: { + arrayBufferView: posing.data, + width: PART_TEXELS, + height: posing.rows, + }, + }); + else + posing.shader.setUniform( + 'u_partMatrices', + partTexture(posing.data, posing.rows), + ); + } + + /** + * The state a posing's texture is written for: its item's deploys and + * poses, its spins as the angles they have reached (written at a time of + * 1 s, each angle given as a rate). + */ + function spunState(posing) { + const drawn = posing.drawn; + drawn.deploy = posing.state.deploy; + drawn.poses = posing.state.poses; + drawn.spin = posing.spins.angles; + return drawn; + } + + /** Write a posing's texture for now. Whether any part is not at rest. */ + function writePosing(posing, timeS) { + advanceSpins(posing.spins, timeS); + return writePartTexture( + posing.info, + spunState(posing), + 1, + posing.scale, + posing.data, + ); + } + + /** + * The shader `model` draws its entry's item's `parts` with, its texture + * written for them now; undefined when the model draws whole (no `parts`, + * no part table, or every part at rest), its posing let go. + */ + function posedShader(entry, model) { + const item = entry.item; + const state = posesParts ? item.parts : undefined; + const posing = posings.get(model); + const info = asksParts(state) && canPose() ? partInfoOfModel(model) : null; + if (!info) { + unpose(model); + return undefined; + } + const axes = item.axisScale; + const scale = + axes && (axes[0] !== 1 || axes[1] !== 1 || axes[2] !== 1) + ? axes + : undefined; + const key = JSON.stringify(state); + const scaleKey = scale ? scale.join(',') : ''; + const shading = item.shading; + const sameLook = + posing?.info === info && + posing.shading === shading && + posing.mask === entry.mask; + // A fleet re-poses every frame with the same parts: written when they + // change (a spin turns in the frame pass). + if (sameLook && posing.key === key && posing.scaleKey === scaleKey) + return posing.shader; + const timeS = now() / 1000; + // Spins go on from where they were, whatever else changed. + const spins = posing?.info === info ? posing.spins : newSpins(timeS); + respin(spins, info.table, state, timeS); + const spinning = spins.rates.size > 0; + const rows = info.table.parts.length; + const next = { + info, + shader: sameLook ? posing.shader : null, + shading, + mask: entry.mask, + data: sameLook ? posing.data : new Float32Array(rows * PART_FLOATS), + rows, + key, + scaleKey, + scale, + spinning, + state, + spins, + drawn: posing?.drawn ?? {}, + }; + const posed = writePosing(next, timeS); + if (!posed && !spinning) { + unpose(model); + return undefined; + } + if (sameLook) { + Object.assign(posing, next); + upload(posing); + return posing.shader; + } + unpose(model); + next.shader = partShaderOf(shading, entry.mask, next.data, rows); + posings.set(model, next); + return next.shader; + } + + /** Pixels across a model's bounds under which its spins are not turned. */ + const MIN_SPIN_PIXELS = 4; + const scratchSpinSphere = new Cesium.BoundingSphere(); + + /** + * Whether a model is worth turning this frame: shown, in the view, and + * at least `MIN_SPIN_PIXELS` across. + */ + function seen(model, culling, width, height) { + if (!model.show || !model.ready) return false; + const sphere = model.boundingSphere; + if (!sphere || !(sphere.radius > 0)) return false; + if ( + culling && + culling.computeVisibility(sphere) === Cesium.Intersect.OUTSIDE + ) + return false; + if (!(width > 0 && height > 0)) return true; + Cesium.BoundingSphere.clone(sphere, scratchSpinSphere); + scratchSpinSphere.radius = 0; + const metresPerPixel = scene.camera.getPixelSize( + scratchSpinSphere, + width, + height, + ); + return ( + !(metresPerPixel > 0) || + !Number.isFinite(metresPerPixel) || + (2 * sphere.radius) / metresPerPixel >= MIN_SPIN_PIXELS + ); + } + + /** + * Before a frame: turn the spinning parts of each model in view to now, + * sweep the posings of models gone, and destroy part shaders no draw + * uses any more. Whether any model in view spins (frames go on being + * asked for; one out of view or too small to see asks for none). + */ + function turnParts() { + for (let i = retired.length - 1; i >= 0; i--) + if ((retired[i].frames += 1) > 2) { + const [{ shader }] = retired.splice(i, 1); + shader.destroy?.(); + } + if (!posings.size) return false; + const timeS = now() / 1000; + const camera = scene.camera; + const culling = + camera?.frustum?.computeCullingVolume && camera.positionWC + ? camera.frustum.computeCullingVolume( + camera.positionWC, + camera.directionWC, + camera.upWC, + ) + : null; + const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0; + const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0; + let spinning = false; + for (const [model, posing] of posings) { + if (model.isDestroyed?.()) { + unpose(model); + continue; + } + if (!posing.spinning || !seen(model, culling, width, height)) continue; + spinning = true; + writePosing(posing, timeS); + upload(posing); + } + return spinning; + } + + /** + * Let go of every posing and part shader now, their textures with them: + * the port is done, and no frame comes to retire them. A model still + * drawn is left drawing whole. + */ + function dispose() { + for (const [model, posing] of posings) { + if (!model.isDestroyed?.() && model.customShader === posing.shader) + model.customShader = undefined; + posing.shader.destroy?.(); + } + posings.clear(); + for (const { shader } of retired.splice(0)) shader.destroy?.(); + } + /** The set's host, made once: its models are changed where they are. */ function hostOf(record) { if (record.host && !record.host.isDestroyed?.()) return record.host; @@ -337,6 +954,7 @@ export function createModelSets({ settle(false); return model.destroy(); } + if (item.gltf) modelBytes.set(model, item.gltf); entry.next = model; entry.styled = null; style(record, entry, model, true); @@ -413,7 +1031,7 @@ export function createModelSets({ if (model.minimumPixelSize !== minimum) model.minimumPixelSize = minimum; if (model.maximumScale !== item.maxScale) model.maximumScale = item.maxScale; - const shader = entryShader(entry); + const shader = posedShader(entry, model) ?? entryShader(entry); if (model.customShader !== shader) model.customShader = shader; const clip = item.clip === 'belowOrigin'; if (Boolean(model.clippingPlanes) !== clip) @@ -583,10 +1201,14 @@ export function createModelSets({ notePickIds(record); } - /** Each frame, before it draws: distance curves, pixel caps and the cull. */ + /** + * Each frame, before it draws: distance curves, pixel caps, the cull and + * spinning parts. Whether any shown model spins. + */ function beforeRender(sets) { + const spinning = turnParts(); const eye = scene.camera?.positionWC; - if (!eye) return; + if (!eye) return spinning; const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0; const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0; let horizon; @@ -677,6 +1299,7 @@ export function createModelSets({ if (m) apply(entry, m, frame, hidden); } } + return spinning; } /** @@ -701,5 +1324,5 @@ export function createModelSets({ } } - return { build, upsert, beforeRender, restyle }; + return { build, upsert, beforeRender, restyle, dispose }; } diff --git a/src/render/cesium/drawModels.test.mjs b/src/render/cesium/drawModels.test.mjs new file mode 100644 index 0000000000..3239328416 --- /dev/null +++ b/src/render/cesium/drawModels.test.mjs @@ -0,0 +1,180 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + advanceSpins, + newSpins, + partHighlightColor, + respin, + writePartTexture, +} from './drawModels.js'; +import { partsModelGlb } from '../conformance/partsModel.js'; +import { glbJson, gltfMeshMatrix, gltfPartTable } from '../modelParts.js'; + +/** Floats a part's row of the texture holds. */ +const ROW = 32; + +/** The part info `drawModels.js` reads from a model's GLB. */ +function infoOf(glb) { + const json = glbJson(glb); + const mesh = gltfMeshMatrix(json); + // The test models' node transforms are rotations, uniform scales and moves. + const s = Math.hypot(mesh[0], mesh[1], mesh[2]); + const r = (i, j) => mesh[j * 4 + i] / s; + const t = [mesh[12], mesh[13], mesh[14]]; + const inv = new Array(16).fill(0); + for (let i = 0; i < 3; i++) + for (let j = 0; j < 3; j++) inv[j * 4 + i] = r(j, i) / s; + for (let i = 0; i < 3; i++) + inv[12 + i] = -(inv[i] * t[0] + inv[4 + i] * t[1] + inv[8 + i] * t[2]); + inv[15] = 1; + return { table: gltfPartTable(json), mesh, meshInverse: inv }; +} + +const row = (data, k, texel) => + Array.from(data.slice(k * ROW + texel * 4, k * ROW + texel * 4 + 4)); + +/** A part's matrix in the mesh frame, as rows of 4. */ +const matrixOf = (data, k) => [0, 1, 2].map((t) => row(data, k, t)); +/** Its normal matrix, as rows of 3, and whether it is moved. */ +const normalsOf = (data, k) => ({ + rows: [3, 4, 5].map((t) => row(data, k, t).slice(0, 3)), + moved: row(data, k, 3)[3], +}); + +const near = (a, b, eps = 1e-5) => a.every((v, i) => Math.abs(v - b[i]) < eps); + +test('a part moved writes its matrix in the mesh’s own frame, the rest identity', () => { + for (const node of [{}, { scale: 4, turnDeg: 90, translation: [3, 2, -1] }]) { + const info = infoOf(partsModelGlb(node)); + const data = new Float32Array(4 * ROW); + const posed = writePartTexture( + info, + { poses: { body: { offsetM: [15, 0, 0] } } }, + 0, + undefined, + data, + ); + assert.equal(posed, true); + // The body's vertex at model (10, −10, −10) lands 15 m to its right + // (−Z): back in the model frame through the node's transform. + const m = info.mesh; + const inv = info.meshInverse; + const toMesh = (p) => + [0, 1, 2].map( + (i) => + inv[i] * p[0] + inv[4 + i] * p[1] + inv[8 + i] * p[2] + inv[12 + i], + ); + const toModel = (p) => + [0, 1, 2].map( + (i) => m[i] * p[0] + m[4 + i] * p[1] + m[8 + i] * p[2] + m[12 + i], + ); + const L = matrixOf(data, 0); + const v = [...toMesh([10, -10, -10]), 1]; + const moved = toModel(L.map((r) => r.reduce((s, x, i) => s + x * v[i], 0))); + assert.ok(near(moved, [10, -10, -25], 1e-4), JSON.stringify(moved)); + // A move turns no normal, but the part is marked moved. + const n = normalsOf(data, 0); + assert.equal(n.moved, 1); + assert.ok(near(n.rows.flat(), [1, 0, 0, 0, 1, 0, 0, 0, 1])); + } +}); + +test('normals turn by the inverse transpose, exact under a stretch', () => { + const info = infoOf(partsModelGlb()); + const data = new Float32Array(4 * ROW); + writePartTexture( + info, + { poses: { pod: { yawDeg: 30 } } }, + 0, + [2, 1, 1], + data, + ); + const L = matrixOf(data, 1).map((r) => r.slice(0, 3)); + const { rows: N, moved } = normalsOf(data, 1); + assert.equal(moved, 1); + // N = L⁻ᵀ: Nᵀ · L is the identity. + for (let i = 0; i < 3; i++) + for (let j = 0; j < 3; j++) { + let sum = 0; + for (let k = 0; k < 3; k++) sum += N[k][i] * L[k][j]; + assert.ok(Math.abs(sum - (i === j ? 1 : 0)) < 1e-4, `${i},${j}: ${sum}`); + } + // A stretched turn is not a rotation: its own 3×3 would turn normals wrong. + assert.ok(!near(N.flat(), L.flat(), 1e-3)); + // The body, at rest, is left as it is. + assert.equal(normalsOf(data, 0).moved, 0); +}); + +test('a highlight that is not true or a colour draws none, and never throws', () => { + const info = infoOf(partsModelGlb()); + const data = new Float32Array(4 * ROW); + for (const highlight of ['', 'not a colour', 0, [1, 'x', 0], {}]) { + writePartTexture( + info, + { poses: { pod: { highlight } } }, + 0, + undefined, + data, + ); + assert.deepEqual(row(data, 1, 6), [0, 0, 0, 0], String(highlight)); + } + writePartTexture( + info, + { poses: { pod: { highlight: true } } }, + 0, + undefined, + data, + ); + assert.equal(row(data, 1, 6)[3], 1); + writePartTexture( + info, + { poses: { pod: { highlight: [0, 1, 0] } } }, + 0, + undefined, + data, + ); + assert.deepEqual(row(data, 1, 6), [0, 1, 0, 1]); + assert.equal(partHighlightColor('#00f').blue, 1); + assert.equal(partHighlightColor('nope'), null); + assert.equal(partHighlightColor(false), null); +}); + +test('a hidden part collapses, its normals left alone', () => { + const info = infoOf(partsModelGlb()); + const data = new Float32Array(4 * ROW); + writePartTexture( + info, + { poses: { pod: { hidden: true } } }, + 0, + undefined, + data, + ); + assert.ok( + matrixOf(data, 1) + .flat() + .every((v) => v === 0), + ); + assert.equal(normalsOf(data, 1).moved, 0); + assert.ok(data.every(Number.isFinite)); +}); + +test('spins keep their angle when their rate changes, and stop where they are', () => { + const { table } = infoOf(partsModelGlb()); + const spins = newSpins(0); + respin(spins, table, { spin: { pod: 90 } }, 0, () => 10); + assert.equal(spins.angles.pod, 10); + advanceSpins(spins, 1); + assert.equal(spins.angles.pod, 100); + // Twice as fast from here: no jump at the change. + respin(spins, table, { spin: { pod: 180 } }, 1.5); + assert.equal(spins.angles.pod, 145); + advanceSpins(spins, 2); + assert.equal(spins.angles.pod, 235); + // Stopped: the angle stays; a name without an axis or a rate of 0 spins nothing. + respin(spins, table, { spin: { body: 50, missing: 5, pod: 0 } }, 3); + assert.equal(spins.angles.pod, (235 + 180) % 360); + assert.equal(spins.rates.size, 0); + advanceSpins(spins, 10); + assert.equal(spins.angles.pod, (235 + 180) % 360); +}); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 62f06cf0fc..7e5704910a 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -84,7 +84,9 @@ export const CESIUM_CHECKS = new Set([ 'draw.models.loadFailed', 'draw.models.tint', 'draw.models.blend', + 'draw.models.paint', 'draw.models.update', + 'draw.models.parts', 'draw.motion', 'draw.motion.arc', 'draw.motion.climb', diff --git a/src/render/cesium/internals.js b/src/render/cesium/internals.js index ac5b386015..086a53df7f 100644 --- a/src/render/cesium/internals.js +++ b/src/render/cesium/internals.js @@ -300,3 +300,17 @@ export function creditDisplayContents(display) { export function materialTexture(material, uniform) { return material?._textures?.[uniform]; } + +/** + * The texture a custom shader holds for a texture uniform, once it has made + * it. A custom shader takes a new texture uniform only as a texture it makes + * (and the old one it destroys) on its next update; `drawModels.js` writes a + * posed model's part matrices into this texture in place instead, each frame + * a part spins. + * @param {object} shader Cesium CustomShader. + * @param {string} uniform The uniform's name. + * @returns {object|undefined} Cesium Texture. + */ +export function customShaderTexture(shader, uniform) { + return shader?._textureManager?.getTexture?.(uniform); +} diff --git a/src/render/cesium/internals.test.mjs b/src/render/cesium/internals.test.mjs index 0bf1e7bed2..f6dd582ae8 100644 --- a/src/render/cesium/internals.test.mjs +++ b/src/render/cesium/internals.test.mjs @@ -12,6 +12,7 @@ import { closeRenderLoopLatch, commandExtents, creditDisplayContents, + customShaderTexture, defaultView, globeTilesDrawn, lastRenderTime, @@ -70,6 +71,7 @@ test('every private field the app reaches is still declared by the installed Ces [ENGINE, 'Scene/CreditDisplay.js', '_currentFrameCredits'], [ENGINE, 'Scene/CreditDisplay.js', '_currentCesiumCredit'], [ENGINE, 'Scene/Material.js', '_textures'], + [ENGINE, 'Scene/Model/CustomShader.js', '_textureManager'], ]; const missing = fields.filter( ([root, file, field]) => @@ -281,6 +283,18 @@ test('private Cesium fields are reached only through internals.js', () => { assert.deepEqual([...new Set(offenders)], []); }); +test('customShaderTexture reads the texture a custom shader made for a uniform', () => { + const texture = {}; + const shader = { + _textureManager: { + getTexture: (name) => (name === 'u_a' ? texture : undefined), + }, + }; + assert.equal(customShaderTexture(shader, 'u_a'), texture); + assert.equal(customShaderTexture(shader, 'u_b'), undefined); + assert.equal(customShaderTexture(undefined, 'u_a'), undefined); +}); + test('trimGlobeTiles empties the globe cache of what the frame did not draw', () => { const trims = []; trimGlobeTiles({ diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index e368983307..5f73daa482 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -70,6 +70,8 @@ const GLOBE_CAPABILITIES = [ export function cesiumCapabilities(scene, only) { const all = [ 'models', + // Moving parts posed in a custom shader per posed model (`drawModels.js`). + 'modelParts', // Cesium scatters drawn models through the atmosphere wherever the // scene draws fog (its models' atmosphere stage). 'modelAtmosphere', diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 04ef937fd1..fc0e40bff2 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -33,7 +33,14 @@ test('capabilities follow what the scene supports', () => { 'vectorBase', ]; const globe = { show: true }; - const draw = ['models', 'modelAtmosphere', 'quads', 'meshes', 'fields']; + const draw = [ + 'models', + 'modelParts', + 'modelAtmosphere', + 'quads', + 'meshes', + 'fields', + ]; assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]); // A scene with a globe reads its visibility back. assert.deepEqual(cesiumCapabilities({ globe }), [ diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index faf4a8468e..9d2409d9e2 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -14,6 +14,7 @@ import { AUSTIN, SCRIPT_VIEWPORT } from '../cameraScripts.js'; import { deepEqual, equal, near, nearVec, ok, throws } from '../expect.js'; import { iconPosition } from '../../motion/iconMotion.js'; import { encodeVectorTile } from '../../vectorBase/encode.js'; +import { partsModelGlb } from '../partsModel.js'; /** 1 × 1 PNGs (red, green, blue), so imagery checks load nothing from the network. */ const PIXEL_PNGS = [ @@ -4048,6 +4049,93 @@ export function portChecks() { }, { capability: 'models', bareSky: true }, ), + check( + 'draw.models.paint', + 'a lit model draws its vertex paint (`COLOR_0`) under the sun, stays readable with the sun below the horizon, and a tint mixed in keeps the paint', + async (h, r) => { + if (h.pixels === false) + return { skip: 'this harness reads no drawn pixels' }; + // Austin at 13:00 local (sun about 80° up) and at 03:00 (about 32° below). + const DAY = Date.parse('2026-06-21T18:00:00Z'); + const NIGHT = Date.parse('2026-06-21T08:00:00Z'); + r.frame.setTime(DAY); + await overAustin(h, r, 200); + const set = r.draw.models({ id: 'conf:models.paint' }); + const ready = []; + set.on('ready', (id) => ready.push(id)); + const pos = h.toEcef({ ...AUSTIN, height: 0 }); + const model = (extra = {}) => ({ + id: 'm', + pos, + url: 'conformance:painted-model.glb', + // Red paint, as a fleet model's livery: a white material, its + // colour per vertex. + gltf: partsModelGlb({ paint: [0.8, 0.05, 0.05] }), + orientation: { heading: 0, pitch: 0, roll: 0 }, + environmentMap: false, + tint: '#ffffff', + colorBlend: { mode: 'highlight' }, + ...extra, + }); + try { + set.set([model()]); + for (let i = 0; i < 600 && !ready.length; i++) await drawn(h, r, 1); + deepEqual(ready, ['m'], 'ready'); + const s = r.query.project(pos); + ok(s, 'the model projects'); + // The mean colour of a patch on the model's top, seen from above. + const mean = async (time) => { + r.frame.setTime(time); + await drawn(h, r, 3); + await settled(r); + r.frame.setTime(time); + r.frame.renderNow(); + const image = r.readPixels({ + crop: { + x: Math.round(s.x) - 4, + y: Math.round(s.y) - 4, + width: 9, + height: 9, + }, + }); + const sum = [0, 0, 0]; + for (let i = 0; i < image.data.length; i += 4) + for (let c = 0; c < 3; c++) sum[c] += image.data[i + c]; + return sum.map((v) => Math.round(v / (image.data.length / 4))); + }; + const day = await mean(DAY); + ok( + day[0] > 100 && day[0] > 2 * day[1] && day[0] > 2 * day[2], + `in daylight, its red paint: ${day}`, + ); + const night = await mean(NIGHT); + ok( + night[0] >= 30 && night[0] > 2 * night[1], + `with the sun below the horizon, still its paint, not black: ${night}`, + ); + ok( + night[0] < day[0], + `darker at night than by day: ${night}, ${day}`, + ); + // A tint with no red, as a tracked cyan: mixed in, the paint shows. + set.upsert([ + model({ + tint: '#00ffff', + colorBlend: { mode: 'mix', amount: 0.3 }, + }), + ]); + const tinted = await mean(DAY); + ok( + tinted[0] > 60 && tinted[1] > day[1] + 30, + `a cyan tint mixed in at 0.3 keeps the red paint and adds its colour: ${tinted}`, + ); + deepEqual(ready, ['m'], 'never loaded again'); + } finally { + set.dispose(); + } + }, + { capability: 'models', bareSky: true }, + ), check( 'draw.models.bytes', 'a model given its bytes is drawn from them, its url never fetched', @@ -4123,6 +4211,186 @@ export function portChecks() { }, { capability: 'models' }, ), + check( + 'draw.models.parts', + 'a model’s parts are moved, hidden, clamped and spun live, without loading again', + async (h, r) => { + await overAustin(h, r, 200); + const set = r.draw.models({ id: 'conf:models.parts' }); + const ready = []; + const failed = []; + set.on('ready', (id) => ready.push(id)); + set.on('loadFailed', (id) => failed.push(id)); + // `partsModel.js`: a body, a pod on it, a ram on that, an arm ahead. + const models = { + m: partsModelGlb(), + // The same model, its mesh node turned, scaled and moved. + n: partsModelGlb({ scale: 4, turnDeg: 90, translation: [3, 2, -1] }), + }; + const pos = h.toEcef({ ...AUSTIN, height: 0 }); + const model = (id, parts, extra = {}) => ({ + id, + pos, + url: `conformance:parts-model-${id}.glb`, + gltf: models[id], + orientation: { heading: 0, pitch: 0, roll: 0 }, + environmentMap: false, + meta: { n: 1 }, + ...extra, + ...(parts ? { parts } : {}), + }); + const metresPerLon = 111320 * Math.cos((AUSTIN.lat * Math.PI) / 180); + /** The point `east`, `north` metres from the model, `up` above it. */ + const at = ([east, north], metres, up = 0) => + h.toEcef({ + lon: AUSTIN.lon + (east * metres) / metresPerLon, + lat: AUSTIN.lat + (north * metres) / 110574, + height: up, + }); + const pickedAt = (p) => { + const s = r.query.project(p); + return ( + s !== null && + r.query.drillPick(s.x, s.y).some((hit) => hit.set === set.id) + ); + }; + // The compass, clockwise seen from above. + const COMPASS = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; + const clockwise = ([e, n]) => [n, -e]; + const same = (a, b) => a[0] === b[0] && a[1] === b[1]; + /** The compass points 15 m off at which the model is picked. */ + const pickedAround = (up = 0) => + COMPASS.filter((d) => pickedAt(at(d, 15, up))); + const picks = h.pixels !== false; + const look = async () => { + await drawn(h, r, 3); + await settled(r); + }; + const show = async (item) => { + set.upsert([item]); + await look(); + }; + set.set([model('m')]); + for (let i = 0; i < 600 && !ready.length && !failed.length; i++) + await drawn(h, r, 1); + deepEqual(ready, ['m'], 'ready'); + await look(); + if (picks) ok(pickedAt(pos), 'drawn whole, at rest'); + + await show(model('m', { poses: { pod: { hidden: true } } })); + if (picks) ok(pickedAt(pos), 'the pod hidden, the body drawn'); + await show(model('m', { poses: { body: { hidden: true } } })); + if (picks) ok(!pickedAt(pos), 'the body hidden, and all riding it'); + + // Moves go where they say: forward, then right of that. + await show(model('m', { poses: { body: { offsetM: [0, 15, 0] } } })); + const ahead = picks ? pickedAround() : []; + if (picks) equal(ahead.length, 1, 'moved forward, drawn 15 m one way'); + await show(model('m', { poses: { body: { offsetM: [15, 0, 0] } } })); + if (picks) { + ok(!pickedAt(pos), 'moved right, gone from its place'); + const right = pickedAround(); + equal(right.length, 1, 'moved right, drawn 15 m one way'); + ok( + ahead.length === 1 && + right.length === 1 && + same(right[0], clockwise(ahead[0])), + 'its right is a quarter turn clockwise of its forward', + ); + } + const forward = ahead[0] ?? COMPASS[0]; + const rightward = clockwise(forward); + const back = clockwise(clockwise(forward)); + + // A mesh node turned, scaled and moved: parts move in the model's + // frame all the same. + set.set([model('n')]); + for (let i = 0; i < 600 && ready.length < 2 && !failed.length; i++) + await drawn(h, r, 1); + deepEqual(ready, ['m', 'n'], 'the turned-node model ready'); + await show(model('n', { poses: { body: { offsetM: [15, 0, 0] } } })); + if (picks) { + ok( + !pickedAt(pos), + 'its node turned: moved right, gone from its place', + ); + ok(pickedAt(at(rightward, 15)), 'and drawn 15 m to its right'); + } + set.set([model('m')]); + for (let i = 0; i < 600 && ready.length < 3 && !failed.length; i++) + await drawn(h, r, 1); + await look(); + + // Stretched twice its length: a move along it stretches with it. + const stretched = { axisScale: [2, 1, 1] }; + await show(model('m', undefined, stretched)); + if (picks) ok(!pickedAt(at(back, 30)), 'stretched, it ends 20 m back'); + await show( + model('m', { poses: { body: { offsetM: [0, -7.5, 0] } } }, stretched), + ); + if (picks) + ok( + pickedAt(at(back, 30)), + 'moved 7.5 m back stretched, drawn 15 m back', + ); + + // A slide's travel stays within its limits: the ram stops at 20 m. + const ramAhead = at(forward, 20, 23); + await show(model('m')); + if (picks) ok(!pickedAt(ramAhead), 'the ram at rest, on top'); + await show(model('m', { poses: { ram: { offsetM: [0, 40, 0] } } })); + if (picks) ok(pickedAt(ramAhead), 'pushed 40 m, the ram stops at 20 m'); + await show(model('m', { deploy: { ram: 1 } })); + if (picks) ok(pickedAt(ramAhead), 'deployed, the ram is out 20 m'); + + // A hinge's turn stays within its limits: the arm swings 45° left + // at most, and not at all to the right. + const left = clockwise(back); + const armAt = (d, m = 15) => at(d, m, 3); + const diagonal = (side) => + h.toEcef({ + lon: AUSTIN.lon + ((forward[0] + side[0]) * 10.6) / metresPerLon, + lat: AUSTIN.lat + ((forward[1] + side[1]) * 10.6) / 110574, + height: 3, + }); + if (picks) ok(pickedAt(armAt(forward)), 'the arm at rest, ahead'); + await show(model('m', { poses: { arm: { yawDeg: -90 } } })); + if (picks) { + ok(!pickedAt(armAt(forward)), 'turned left, the arm leaves'); + ok(!pickedAt(armAt(left)), 'and stops short of a quarter turn'); + ok(pickedAt(diagonal(left)), 'at 45° ahead and to the left'); + } + await show(model('m', { poses: { arm: { yawDeg: 90 } } })); + if (picks) { + ok(!pickedAt(armAt(rightward)), 'turned right, the arm does not'); + ok(pickedAt(armAt(forward)), 'and stays ahead'); + } + + // A spinning part asks for frames for as long as it spins, so the + // scene never settles; wait for frames to be drawn instead. + set.upsert([ + model('m', { + spin: { pod: 90 }, + deploy: { pod: 1, missing: 1 }, + poses: { pod: { highlight: true }, missing: { hidden: true } }, + }), + ]); + await drawn(h, r, 3); + if (picks) ok(pickedAt(pos), 'spinning and highlighted, where it is'); + await show(model('m')); + if (picks) ok(pickedAt(pos), 'back at rest'); + deepEqual(ready, ['m', 'n', 'm'], 'posed without loading again'); + deepEqual(failed, [], 'nothing failed'); + equal(set.size(), 1, 'one model'); + set.dispose(); + }, + { capability: ['models', 'modelParts'] }, + ), // --- Query ------------------------------------------------------------- check( diff --git a/src/render/conformance/partsModel.js b/src/render/conformance/partsModel.js new file mode 100644 index 0000000000..18abd759d5 --- /dev/null +++ b/src/render/conformance/partsModel.js @@ -0,0 +1,298 @@ +/** + * @module render/conformance/partsModel + * @description A glTF model with moving parts, built in code for the + * conformance checks (`PARTS_MODEL_TABLE` says what its parts are). One + * mesh whose vertices carry their part index (`_PART`), its node scaled + * (by ten unless told otherwise: the mesh is in tenths of the model's + * metres), and the part table in that node's `extras`. + */ + +/** Each cube face: its normal and two axes across it. */ +const FACES = [ + [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + ], + [ + [-1, 0, 0], + [0, 0, 1], + [0, 1, 0], + ], + [ + [0, 1, 0], + [0, 0, 1], + [1, 0, 0], + ], + [ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1], + ], + [ + [0, 0, 1], + [1, 0, 0], + [0, 1, 0], + ], + [ + [0, 0, -1], + [0, 1, 0], + [1, 0, 0], + ], +]; + +/** + * Append a cube of half size `half` centred at `centre` (the model's glTF + * frame, metres) as part `part`, its vertices and normals put into the + * mesh's own frame by `toMesh`. + */ +function cube(mesh, centre, half, part, toMesh) { + for (const [n, u, v] of FACES) { + const base = mesh.positions.length / 3; + for (const [su, sv] of [ + [-1, -1], + [1, -1], + [1, 1], + [-1, 1], + ]) { + const p = [0, 1, 2].map( + (i) => centre[i] + half * (n[i] + su * u[i] + sv * v[i]), + ); + mesh.positions.push(...toMesh.point(p)); + mesh.normals.push(...toMesh.direction(n)); + mesh.parts.push(part); + } + // Counter-clockwise seen from outside: u × v is the normal. + mesh.indices.push(base, base + 1, base + 2, base, base + 2, base + 3); + } +} + +/** + * The part table, in the model's glTF frame (forward −X, up +Y, right −Z): + * a 20 m cube (`body`) centred on the origin; a 10 m cube on top of it + * (`pod`) that spins about the vertical through its centre; a 6 m cube on + * top of that (`ram`) that slides forward up to 20 m; and a 6 m cube 15 m + * ahead of the body at its foot (`arm`), hinged about the vertical through + * the body's centre, turning up to 45° to the left. + */ +export const PARTS_MODEL_TABLE = Object.freeze([ + { name: 'body', kind: 'body' }, + { name: 'pod', kind: 'spin', pivot: [0, 15, 0], axis: [0, 1, 0] }, + { + name: 'ram', + kind: 'slide', + pivot: [0, 23, 0], + axis: [-1, 0, 0], + limits: [0, 20], + rest: 0, + }, + { + name: 'arm', + kind: 'hinge', + pivot: [0, 3, 0], + axis: [0, 1, 0], + limits: [0, 45], + rest: 0, + }, +]); + +/** Each part's cube: its centre (glTF frame, metres) and half size. */ +const CUBES = [ + [[0, 0, 0], 10], + [[0, 15, 0], 5], + [[0, 23, 0], 3], + [[-15, 3, 0], 3], +]; + +/** + * The model's GLB bytes. Its mesh node is scaled by `scale`, turned + * `turnDeg` about its vertical and moved by `translation`; the mesh is + * built in that node's own frame, so the model it draws is the same + * whatever the node's transform. `paint` (RGB, 0..1) is every vertex's + * colour (`COLOR_0`) over a white material, as the fleet models carry + * their paint; without it the model has no vertex colours. + * @param {{scale?: number, turnDeg?: number, + * translation?: [number, number, number], + * paint?: [number, number, number]}} [node] + * @returns {Uint8Array} + */ +export function partsModelGlb({ + scale = 10, + turnDeg = 0, + translation = [0, 0, 0], + paint, +} = {}) { + const a = (turnDeg * Math.PI) / 180; + const c = Math.cos(a); + const sn = Math.sin(a); + // The node's turn undone: about +Y by −turnDeg. + const unturn = ([x, y, z]) => [c * x - sn * z, y, sn * x + c * z]; + const toMesh = { + point: (p) => + unturn([0, 1, 2].map((i) => p[i] - translation[i])).map((v) => v / scale), + direction: unturn, + }; + const mesh = { positions: [], normals: [], parts: [], indices: [] }; + CUBES.forEach(([centre, half], part) => + cube(mesh, centre, half, part, toMesh), + ); + const count = mesh.parts.length; + const positions = new Float32Array(mesh.positions); + const normals = new Float32Array(mesh.normals); + // A vertex attribute's elements sit on 4-byte boundaries. + const parts = new Uint8Array(count * 4); + mesh.parts.forEach((part, i) => (parts[i * 4] = part)); + const indices = new Uint16Array(mesh.indices); + // Normalised bytes, RGBA: four to a vertex, on its 4-byte boundary. + const colors = paint ? new Uint8Array(count * 4) : null; + if (colors) + for (let i = 0; i < count; i++) + colors.set([...paint.map((c) => Math.round(c * 255)), 255], i * 4); + const chunks = [positions, normals, parts, indices]; + if (colors) chunks.push(colors); + const offsets = []; + let length = 0; + for (const chunk of chunks) { + offsets.push(length); + length += Math.ceil(chunk.byteLength / 4) * 4; + } + const bin = new Uint8Array(length); + chunks.forEach((chunk, i) => + bin.set( + new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), + offsets[i], + ), + ); + const min = [Infinity, Infinity, Infinity]; + const max = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i < positions.length; i++) { + min[i % 3] = Math.min(min[i % 3], positions[i]); + max[i % 3] = Math.max(max[i % 3], positions[i]); + } + const json = { + asset: { version: '2.0' }, + scene: 0, + scenes: [{ nodes: [0] }], + nodes: [ + { + name: 'parts', + mesh: 0, + scale: [scale, scale, scale], + rotation: [0, Math.sin(a / 2), 0, Math.cos(a / 2)], + translation, + extras: { parts: PARTS_MODEL_TABLE }, + }, + ], + meshes: [ + { + primitives: [ + { + attributes: { + POSITION: 0, + NORMAL: 1, + _PART: 2, + ...(colors ? { COLOR_0: 4 } : {}), + }, + indices: 3, + material: 0, + }, + ], + }, + ], + materials: [ + { + pbrMetallicRoughness: { + baseColorFactor: [1, 1, 1, 1], + metallicFactor: 0, + roughnessFactor: 1, + }, + }, + ], + buffers: [{ byteLength: length }], + bufferViews: [ + { + buffer: 0, + byteOffset: offsets[0], + byteLength: positions.byteLength, + target: 34962, + }, + { + buffer: 0, + byteOffset: offsets[1], + byteLength: normals.byteLength, + target: 34962, + }, + { + buffer: 0, + byteOffset: offsets[2], + byteLength: parts.byteLength, + byteStride: 4, + target: 34962, + }, + { + buffer: 0, + byteOffset: offsets[3], + byteLength: indices.byteLength, + target: 34963, + }, + ...(colors + ? [ + { + buffer: 0, + byteOffset: offsets[4], + byteLength: colors.byteLength, + byteStride: 4, + target: 34962, + }, + ] + : []), + ], + accessors: [ + { + bufferView: 0, + componentType: 5126, + count, + type: 'VEC3', + min, + max, + }, + { bufferView: 1, componentType: 5126, count, type: 'VEC3' }, + { bufferView: 2, componentType: 5121, count, type: 'SCALAR' }, + { + bufferView: 3, + componentType: 5123, + count: indices.length, + type: 'SCALAR', + }, + ...(colors + ? [ + { + bufferView: 4, + componentType: 5121, + normalized: true, + count, + type: 'VEC4', + }, + ] + : []), + ], + }; + let text = new TextEncoder().encode(JSON.stringify(json)); + const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20); + padded.set(text); + text = padded; + const total = 12 + 8 + text.length + 8 + bin.length; + const out = new Uint8Array(total); + const view = new DataView(out.buffer); + view.setUint32(0, 0x46546c67, true); + view.setUint32(4, 2, true); + view.setUint32(8, total, true); + view.setUint32(12, text.length, true); + view.setUint32(16, 0x4e4f534a, true); + out.set(text, 20); + const binAt = 20 + text.length; + view.setUint32(binAt, bin.length, true); + view.setUint32(binAt + 4, 0x004e4942, true); + out.set(bin, binAt + 8); + return out; +} diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts index 010498e7e9..df585c2484 100644 --- a/src/render/contract/common.d.ts +++ b/src/render/contract/common.d.ts @@ -191,6 +191,8 @@ export type Capability = | 'motionSegments' /** glTF models. */ | 'models' + /** Moving parts of glTF models posed as an item's `parts` says. */ + | 'modelParts' /** Image, video and canvas planes. */ | 'quads' /** Custom meshes in a local east-north-up frame. */ diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index a1a1558e73..11a69a433c 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -450,6 +450,65 @@ export interface ModelItem extends Placed { * change live. */ focus?: number; + /** + * `modelParts`: how the model's moving parts are posed. Applies to a + * model whose mesh carries a `_PART` vertex attribute (each vertex's part + * index) and whose root node's glTF `extras.parts` is its part table; + * ignored for any other. Omitted, or without the capability, the model is + * drawn whole, at rest, as its file draws it. Can change live, without + * loading the model again. + */ + parts?: ModelPartState; +} + +/** + * A model's part state (`ModelItem.parts`), each member by part name; a + * part not named is at rest, and a name the model's part table lacks is + * ignored. The maths is `render/modelParts`'s `partMatrices`: about each + * part's pivot, its deploy fraction first, then its spin, then its pose, + * then its parent part's whole motion. + */ +export interface ModelPartState { + /** + * Degrees a second about the part's axis, which the renderer advances + * itself on its own clock each frame: a turning rotor costs the + * application no write per frame. A change of rate goes on from the angle + * reached, without a jump; a part that stops spinning stays where it is. + */ + spin?: Record; + /** + * 0 (stowed, the table's first limit) to 1 (deployed, its second): a + * hinge or deploy part turned, a slide or separable part moved along its + * axis, that far between its limits. Clamped to 0..1. + */ + deploy?: Record; + /** Each part's pose, on top of its spin and deploy fraction. */ + poses?: Record; +} + +/** + * One part's pose about its pivot, in the model's own frame (in its glTF: + * forward −X, up +Y, right −Z). A hinge or deploy part's turn about its + * axis stays within its limits, as does a slide part's travel; the rest of + * every part's motion is free. A number that is not finite counts as 0. + */ +export interface PartPose { + /** Metres along the model's right, forward and up. */ + offsetM?: [right: number, forward: number, up: number]; + /** Degrees clockwise seen from above, as a heading. Applied first. */ + yawDeg?: number; + /** Degrees nose up. Applied after the yaw. */ + pitchDeg?: number; + /** Degrees clockwise looking forward. Applied last. */ + rollDeg?: number; + /** Not drawn, nor any part riding it. */ + hidden?: boolean; + /** + * Drawn in a highlight colour: `true` for the renderer's own, or a + * colour. Anything else, or a colour the renderer cannot read, draws no + * highlight. Not inherited by the parts riding it. + */ + highlight?: boolean | Color; } /** A plane showing an image, a video or a canvas. */ diff --git a/src/render/contract/index.js b/src/render/contract/index.js index d494467fab..2198b6226c 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -34,6 +34,7 @@ export const CAPABILITIES = Object.freeze([ 'columns', 'motionSegments', 'models', + 'modelParts', 'quads', 'meshes', 'fields', diff --git a/src/render/contract/renderer.d.ts b/src/render/contract/renderer.d.ts index 5d8da3c440..522228f386 100644 --- a/src/render/contract/renderer.d.ts +++ b/src/render/contract/renderer.d.ts @@ -58,6 +58,14 @@ export interface ApplicationHooks { viewerDrawsEntity?(entity: unknown): boolean; /** Values QA scripts read from the page's debug handle. */ qaHandles?: Readonly>; + /** + * The renderer's own engine, for an application that draws with it + * directly beside the contract: `kind` names the engine (`'cesium'` for + * Cesium, whose `Cesium.Viewer` is `viewer`) and the rest is that engine's + * own. An application draws only with engines whose kind it knows, and + * whatever it draws there is its own to add, update and remove. + */ + engine?: Readonly<{ kind: string; [key: string]: unknown }>; /** * Show a recoverable notice when the renderer stops drawing (an error, a * lost context), with Retry and, if `allowReload`, Reset, by publishing it diff --git a/src/render/modelParts.d.ts b/src/render/modelParts.d.ts new file mode 100644 index 0000000000..2f20ba91e4 --- /dev/null +++ b/src/render/modelParts.d.ts @@ -0,0 +1,86 @@ +/** + * A model's moving parts (`modelParts.js`): its part table and the maths + * that turns a model item's `parts` into one matrix per part, so a renderer + * that poses parts draws exactly those. + */ +import type { ModelPartState } from './contract/index'; + +/** What a part does: what live data drives and what is offered first. */ +export type PartKind = + 'body' | 'spin' | 'hinge' | 'slide' | 'deploy' | 'separable' | 'marker'; + +/** `[x, y, z]`. */ +export type PartVec3 = readonly [number, number, number]; + +/** One part of a model, as its table gives it (glTF frame, metres and degrees). */ +export interface ModelPart { + /** Its `_PART` index. */ + readonly index: number; + readonly name: string; + readonly kind: PartKind; + /** The part it rides, or null for the body. */ + readonly parent: string | null; + /** Its parent's index, or -1 for the body. */ + readonly parentIndex: number; + /** The point it turns about; the origin for the body. */ + readonly pivot: PartVec3; + /** Its axis of motion, unit length; null where the table gives none. */ + readonly axis: PartVec3 | null; + /** `[stowed, deployed]`: degrees for hinge and deploy, metres for slide and separable. */ + readonly limits: readonly [number, number] | null; + /** The value it is drawn at in the file; null without limits. */ + readonly rest: number | null; +} + +/** A model's part table: its parts in `_PART` index order, the body first. */ +export interface PartTable { + readonly parts: readonly ModelPart[]; + /** A part's index by its name. */ + readonly byName: ReadonlyMap; +} + +/** Where and how `partMatrices` writes. */ +export interface PartMatricesOptions { + /** Where in `out` the first matrix goes; 0 by default. */ + readonly offset?: number; + /** Gets each part's `PART_HIDDEN` and `PART_HIGHLIGHT`, from `flagsOffset`. */ + readonly flags?: Uint8Array; + readonly flagsOffset?: number; + /** The model's stretch along its glTF axes (`axisScale`): parts then turn rigidly in the stretched model. */ + readonly scale?: PartVec3 | null; +} + +export const PART_KINDS: readonly PartKind[]; +export const PART_HIDDEN: 1; +export const PART_HIGHLIGHT: 2; + +/** Whether a pose's `highlight` asks for one: true, or a colour (a non-empty string, or three or four finite numbers). */ +export function asksHighlight(value: unknown): boolean; + +/** The part table in a node's glTF `extras`; null when it has none. Throws on a malformed table. */ +export function partTableOf(extras: unknown): PartTable | null; + +/** The glTF JSON of a GLB. Throws when the bytes are not a GLB. */ +export function glbJson(glb: Uint8Array | ArrayBuffer): Record; + +/** The part table of a glTF document; null when no node has one. */ +export function gltfPartTable(gltf: Record): PartTable | null; + +/** The part table of a GLB's bytes; null for a model without one. */ +export function readPartTable(glb: Uint8Array | ArrayBuffer): PartTable | null; + +/** Where the scene's first mesh is drawn: its node's transform with its parents', column-major 4×4. */ +export function gltfMeshMatrix(gltf: Record): number[]; + +/** + * Each part's column-major 4×4 matrix for `state` at `timeS` seconds into + * `out`, in `_PART` order, in the model's glTF frame. Whether any part is + * not at rest. + */ +export function partMatrices( + table: PartTable, + state: ModelPartState | null | undefined, + timeS: number, + out: Float32Array | Float64Array, + options?: PartMatricesOptions, +): boolean; diff --git a/src/render/modelParts.js b/src/render/modelParts.js new file mode 100644 index 0000000000..5601e3131e --- /dev/null +++ b/src/render/modelParts.js @@ -0,0 +1,696 @@ +/** + * @module render/modelParts + * @description A model's moving parts: the part table a glTF model carries + * and the pure maths that turns a model item's `parts` (`ModelPartState`) + * into one matrix per part. Plain JavaScript: no fetch, no DOM, no engine. + * + * **The model.** One glTF mesh whose vertices carry a part index (`_PART`, an + * unsigned byte). The root node's glTF `extras.parts` lists the parts in + * `_PART` index order: `{name, kind, pivot, axis, limits, rest, parent}`, + * glTF Y-up, metres and degrees; index 0 is the body. A model that is only + * its body carries no table. + * + * **Frames.** The table, and the matrices {@link partMatrices} writes, are + * in the model's glTF frame (Y up, nose −X, so right is −Z), applied after + * the mesh node's own transform (a packed model's dequantization; + * {@link gltfMeshMatrix}). Poses are given in `[right, forward, up]` metres, + * with yaw (clockwise from above, as a heading), pitch (nose up) and roll + * (clockwise looking forward), applied yaw, then pitch, then roll. + * + * **A part's motion**, about its pivot, innermost first: its deploy + * fraction, then its spin, then its pose, then its parent part's whole + * motion, so a child rides its parent. A hinge or deploy part's turn about + * its axis is clamped to its limits, as is a slide part's travel along its + * axis; a part's other motion, and a spin, separable, marker or body part's, + * is free. + */ + +/** What a part does: what live data drives and what is offered first. */ +export const PART_KINDS = Object.freeze([ + 'body', + 'spin', + 'hinge', + 'slide', + 'deploy', + 'separable', + 'marker', +]); + +/** {@link partMatrices}'s flags per part: not drawn. */ +export const PART_HIDDEN = 1; +/** {@link partMatrices}'s flags per part: highlighted. */ +export const PART_HIGHLIGHT = 2; + +const isObject = (value) => + value !== null && typeof value === 'object' && !Array.isArray(value); + +function vec3(value, what) { + if ( + !Array.isArray(value) || + value.length !== 3 || + !value.every((n) => typeof n === 'number' && Number.isFinite(n)) + ) + throw new Error(`${what} is not three numbers`); + return [value[0], value[1], value[2]]; +} + +/** + * The part table in a node's glTF `extras` (`{parts: [...]}`); null when it + * has none (a model that is only its body). Throws on a table that is + * malformed: a missing or unknown kind, a repeated name, a parent that is + * not an earlier part, a malformed pivot, axis or limits. + * @param {unknown} extras + * @returns {import('./modelParts').PartTable|null} + */ +export function partTableOf(extras) { + if (!isObject(extras) || extras.parts === undefined) return null; + const list = extras.parts; + if (!Array.isArray(list) || list.length === 0) + throw new Error('parts is not a list of parts'); + if (list.length > 256) + throw new Error(`${list.length} parts: _PART is a byte`); + const byName = new Map(); + const parts = list.map((entry, index) => { + if (!isObject(entry)) throw new Error(`part ${index} is not an object`); + const { name, kind } = entry; + if (typeof name !== 'string' || name === '') + throw new Error(`part ${index} has no name`); + if (byName.has(name)) throw new Error(`part ${name} is named twice`); + if (typeof kind !== 'string' || !PART_KINDS.includes(kind)) + throw new Error(`part ${name} has kind ${String(kind)}`); + if ((index === 0) !== (kind === 'body')) + throw new Error(`part ${name}: the body, and only it, is part 0`); + const parentName = index === 0 ? null : (entry.parent ?? 'body'); + if (parentName !== null && typeof parentName !== 'string') + throw new Error(`part ${name} has parent ${String(parentName)}`); + const parentIndex = + parentName === null ? -1 : (byName.get(parentName) ?? -2); + if (parentIndex === -2) + throw new Error(`part ${name} rides ${parentName}, not an earlier part`); + const pivot = + entry.pivot === undefined ? [0, 0, 0] : vec3(entry.pivot, name); + let axis = null; + if (entry.axis !== undefined) { + const [x, y, z] = vec3(entry.axis, `${name} axis`); + const length = Math.hypot(x, y, z); + if (!(length > 0)) throw new Error(`part ${name} has a zero axis`); + axis = [x / length, y / length, z / length]; + } + let limits = null; + const given = entry.limits; + if (given !== undefined) { + if ( + !Array.isArray(given) || + given.length !== 2 || + !given.every((n) => typeof n === 'number' && Number.isFinite(n)) + ) + throw new Error(`part ${name} limits are not two numbers`); + limits = [given[0], given[1]]; + } + const restGiven = entry.rest; + if ( + restGiven !== undefined && + (typeof restGiven !== 'number' || !Number.isFinite(restGiven)) + ) + throw new Error(`part ${name} rest is not a number`); + const rest = limits === null ? null : (restGiven ?? limits[0]); + byName.set(name, index); + return { + index, + name, + kind, + parent: parentName, + parentIndex, + pivot, + axis, + limits, + rest, + }; + }); + return { parts, byName }; +} + +/** + * The glTF JSON of a GLB (its first chunk). Throws when the bytes are not a + * GLB. + * @param {Uint8Array|ArrayBuffer} glb + * @returns {object} + */ +export function glbJson(glb) { + const bytes = glb instanceof Uint8Array ? glb : new Uint8Array(glb); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67) + throw new Error('not a GLB'); + const length = view.getUint32(12, true); + if (view.getUint32(16, true) !== 0x4e4f534a || 20 + length > bytes.byteLength) + throw new Error('GLB has no JSON chunk'); + const json = JSON.parse( + new TextDecoder().decode(bytes.subarray(20, 20 + length)), + ); + if (!isObject(json)) throw new Error('GLB JSON is not an object'); + return json; +} + +/** The scene's root node indices, then every node's, in order. */ +function nodeOrder(gltf) { + const nodes = Array.isArray(gltf.nodes) ? gltf.nodes : []; + const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : []; + const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0]; + const roots = + isObject(scene) && Array.isArray(scene.nodes) ? scene.nodes : []; + return { nodes, order: [...roots, ...nodes.keys()] }; +} + +/** + * The part table of a glTF document: the first node with `extras.parts`, + * the scene's root nodes first. Null when no node has one. + * @param {object} gltf + * @returns {import('./modelParts').PartTable|null} + */ +export function gltfPartTable(gltf) { + const { nodes, order } = nodeOrder(gltf); + for (const index of order) { + const node = typeof index === 'number' ? nodes[index] : undefined; + if ( + isObject(node) && + isObject(node.extras) && + node.extras.parts !== undefined + ) + return partTableOf(node.extras); + } + return null; +} + +/** + * The part table of a GLB's bytes; null for a model without one. Throws on + * bytes that are not a GLB, or on a malformed table. + * @param {Uint8Array|ArrayBuffer} glb + * @returns {import('./modelParts').PartTable|null} + */ +export function readPartTable(glb) { + return gltfPartTable(glbJson(glb)); +} + +/** `a · b`, column-major 4×4, into a new array. */ +function multiply4(a, b) { + const out = new Array(16); + for (let col = 0; col < 4; col++) + for (let row = 0; row < 4; row++) { + let sum = 0; + for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k]; + out[col * 4 + row] = sum; + } + return out; +} + +/** A glTF node's local transform, column-major. */ +function nodeMatrix(node) { + if (Array.isArray(node.matrix) && node.matrix.length === 16) + return [...node.matrix]; + const [tx, ty, tz] = node.translation ?? [0, 0, 0]; + const [x, y, z, w] = node.rotation ?? [0, 0, 0, 1]; + const [sx, sy, sz] = node.scale ?? [1, 1, 1]; + return [ + (1 - 2 * (y * y + z * z)) * sx, + 2 * (x * y + z * w) * sx, + 2 * (x * z - y * w) * sx, + 0, + 2 * (x * y - z * w) * sy, + (1 - 2 * (x * x + z * z)) * sy, + 2 * (y * z + x * w) * sy, + 0, + 2 * (x * z + y * w) * sz, + 2 * (y * z - x * w) * sz, + (1 - 2 * (x * x + y * y)) * sz, + 0, + tx, + ty, + tz, + 1, + ]; +} + +/** + * Where the first mesh of a glTF document's scene is drawn: its node's + * transform with every parent's, column-major 4×4. A vertex of the mesh is + * at this matrix times its position in the model's glTF frame, where part + * matrices apply. The identity for a document without a mesh. + * @param {object} gltf + * @returns {number[]} + */ +export function gltfMeshMatrix(gltf) { + const { nodes } = nodeOrder(gltf); + const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : []; + const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0]; + const roots = + isObject(scene) && Array.isArray(scene.nodes) + ? scene.nodes + : [...nodes.keys()]; + const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + // Depth first, the scene's own order: the first node with a mesh. + const stack = roots + .slice() + .reverse() + .map((index) => [index, identity, 0]); + while (stack.length) { + const [index, parent, depth] = stack.pop(); + const node = nodes[index]; + if (!isObject(node) || depth > 64) continue; + const world = multiply4(parent, nodeMatrix(node)); + if (typeof node.mesh === 'number') return world; + const children = Array.isArray(node.children) ? node.children : []; + for (let i = children.length - 1; i >= 0; i--) + stack.push([children[i], world, depth + 1]); + } + return identity; +} + +// ---------------------------------------------------------------- the maths + +const DEG = Math.PI / 180; + +/** The `[right, forward, up]` axes in the glTF frame (nose −X, Y up, right −Z). */ +const RIGHT_G = [0, 0, -1]; +const FORWARD_G = [-1, 0, 0]; +const UP_G = [0, 1, 0]; + +/** Scratch quaternions `[x, y, z, w]` and vectors, reused between calls. */ +const _q = new Float64Array(4); +const _p = new Float64Array(4); +const _v = new Float64Array(3); +/** A part's axis in the scaled model, and the instance's scale. */ +const _a = new Float64Array(3); +const _s = new Float64Array(3); + +/** `out` = the rotation by `deg` about the unit `axis`, right-handed. */ +function axisAngle(out, axis, deg) { + const half = (deg * DEG) / 2; + const s = Math.sin(half); + out[0] = axis[0] * s; + out[1] = axis[1] * s; + out[2] = axis[2] * s; + out[3] = Math.cos(half); +} + +/** `a` = `a · b`. */ +function multiplyInto(a, b) { + const ax = a[0]; + const ay = a[1]; + const az = a[2]; + const aw = a[3]; + const bx = b[0]; + const by = b[1]; + const bz = b[2]; + const bw = b[3]; + a[0] = aw * bx + ax * bw + ay * bz - az * by; + a[1] = aw * by - ax * bz + ay * bw + az * bx; + a[2] = aw * bz + ax * by - ay * bx + az * bw; + a[3] = aw * bw - ax * bx - ay * by - az * bz; +} + +/** `v` turned by the unit quaternion `q`, in place. */ +function rotateInto(q, v) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + const tx = 2 * (y * v[2] - z * v[1]); + const ty = 2 * (z * v[0] - x * v[2]); + const tz = 2 * (x * v[1] - y * v[0]); + v[0] = v[0] + w * tx + (y * tz - z * ty); + v[1] = v[1] + w * ty + (z * tx - x * tz); + v[2] = v[2] + w * tz + (x * ty - y * tx); +} + +/** A pose's number, or 0 where it is missing or not finite. */ +const finite = (value) => + typeof value === 'number' && Number.isFinite(value) ? value : 0; + +/** Whether a pose turns or moves anything (a value not finite counts as 0). */ +function isPosed(pose) { + const o = pose.offsetM; + return ( + finite(pose.yawDeg) !== 0 || + finite(pose.pitchDeg) !== 0 || + finite(pose.rollDeg) !== 0 || + (Array.isArray(o) && + (finite(o[0]) !== 0 || finite(o[1]) !== 0 || finite(o[2]) !== 0)) + ); +} + +/** + * `q` = a pose's rotation in the glTF frame: yaw clockwise about up, then + * pitch about the new right, then roll about the new forward. `t` = its + * offset in the glTF frame. + */ +function poseInto(q, t, pose) { + axisAngle(q, UP_G, -finite(pose.yawDeg)); + axisAngle(_p, RIGHT_G, finite(pose.pitchDeg)); + multiplyInto(q, _p); + axisAngle(_p, FORWARD_G, finite(pose.rollDeg)); + multiplyInto(q, _p); + const o = pose.offsetM; + t[0] = 0; + t[1] = 0; + t[2] = 0; + if (!Array.isArray(o)) return; + t[0] = -finite(o[1]); + t[1] = finite(o[2]); + t[2] = -finite(o[0]); +} + +/** `angle` (degrees) as the value nearest `[lo, hi]` among its turns, clamped into it. */ +function clampAngle(angle, lo, hi) { + let best = angle; + let bestOut = Infinity; + for (const turn of [-360, 0, 360]) { + const a = angle + turn; + const out = a < lo ? lo - a : a > hi ? a - hi : 0; + if (out < bestOut) { + best = a; + bestOut = out; + } + } + return Math.min(hi, Math.max(lo, best)); +} + +/** + * Clamp the rotation `q`'s turn about the unit `axis` (its twist, degrees + * from rest) so that `rest` plus it stays within `limits`, leaving the rest + * of the rotation (its swing) as it is. + */ +function clampTwist(q, axis, rest, limits) { + const d = q[0] * axis[0] + q[1] * axis[1] + q[2] * axis[2]; + const w = q[3]; + if (Math.abs(d) < 1e-12 && Math.abs(w) < 1e-12) return; + let twist = (2 * Math.atan2(d, w)) / DEG; + if (twist > 180) twist -= 360; + else if (twist <= -180) twist += 360; + const lo = Math.min(limits[0], limits[1]) - rest; + const hi = Math.max(limits[0], limits[1]) - rest; + const clamped = clampAngle(twist, lo, hi); + if (Math.abs(clamped - twist) < 1e-9) return; + // q = swing · twist, so q' = q · twist⁻¹ · twist'. + axisAngle(_p, axis, clamped - twist); + multiplyInto(q, _p); +} + +/** The degrees or metres from rest a deploy fraction puts a part at. */ +function deployedBy(part, fraction) { + const limits = part.limits; + const f = Math.min(1, Math.max(0, fraction)); + return limits[0] + (limits[1] - limits[0]) * f - part.rest; +} + +/** + * World (model frame) rotation and translation per part, 12 numbers each (R + * row-major, then t), and whether each is hidden; reused between calls. + */ +let _world = new Float64Array(12 * 32); +let _hidden = new Uint8Array(32); +/** A pose's rotation, its translation, and one part's local affine, scratch. */ +const _r = new Float64Array(4); +const _t = new Float64Array(3); +const _local = new Float64Array(12); + +const IDENTITY = Float64Array.of( + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, +); + +const TURNS = new Set(['spin', 'hinge', 'deploy']); +const MOVES = new Set(['slide', 'separable']); + +/** Write the unit quaternion `q` and translation `t` as an affine (R row-major, then t) into `m` at `at`. */ +function affineInto(q, t, m, at) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + m[at] = 1 - 2 * (y * y + z * z); + m[at + 1] = 2 * (x * y - z * w); + m[at + 2] = 2 * (x * z + y * w); + m[at + 3] = 2 * (x * y + z * w); + m[at + 4] = 1 - 2 * (x * x + z * z); + m[at + 5] = 2 * (y * z - x * w); + m[at + 6] = 2 * (x * z - y * w); + m[at + 7] = 2 * (y * z + x * w); + m[at + 8] = 1 - 2 * (x * x + y * y); + m[at + 9] = t[0]; + m[at + 10] = t[1]; + m[at + 11] = t[2]; +} + +/** + * Whether a highlight asks for one: true, or a colour (a non-empty string, + * or three or four finite numbers). A renderer that cannot read the + * colour draws the part without one. + */ +export function asksHighlight(value) { + if (value === true) return true; + if (typeof value === 'string') return value.trim() !== ''; + return ( + Array.isArray(value) && + (value.length === 3 || value.length === 4) && + value.every((v) => typeof v === 'number' && Number.isFinite(v)) + ); +} + +/** + * Write each part's matrix (4×4, column-major) for a model whose item has + * `state` as its `parts`, at `timeS` seconds of the renderer's clock, into + * `out`: `table.parts.length` matrices, in `_PART` order, in the model's + * glTF frame. A vertex of part k is drawn at matrix k times its position + * (after the mesh node's transform). A hidden part's matrix, and every + * part's riding it, is all zeros. + * + * With `options.scale` S (the model drawn stretched along its glTF axes, + * `axisScale`), each matrix X is S⁻¹·Part_s·S, where Part_s is the part's + * motion worked out in the stretched model (its pivot, axis and moves scaled + * by S), so S·X·v = Part_s·S·v: a radar on a hull drawn twice its length + * turns without stretching. Limits stay in the model's own units. + * + * A spin turns its part `rate × timeS` degrees about its axis (any part with + * an axis); a deploy fraction puts a hinge or deploy part that far between + * its limits, and a slide or separable part as far along its axis. A spin, + * deploy or pose naming a part the table does not have is ignored. + * + * Returns whether any part is not at rest (moved, hidden or highlighted): + * false means every matrix written is the identity and every flag 0. + * @param {import('./modelParts').PartTable} table + * @param {import('./contract/draw').ModelPartState|null|undefined} state + * @param {number} timeS + * @param {Float32Array|Float64Array} out + * @param {import('./modelParts').PartMatricesOptions} [options] + * @returns {boolean} + */ +export function partMatrices(table, state, timeS, out, options = {}) { + const { offset = 0, flags, flagsOffset = 0, scale } = options; + let scaled = false; + if (scale !== undefined && scale !== null) { + _s[0] = scale[0]; + _s[1] = scale[1]; + _s[2] = scale[2]; + // A scale that is not positive along an axis cannot be undone: parts + // stay unscaled. + scaled = + (_s[0] !== 1 || _s[1] !== 1 || _s[2] !== 1) && + _s[0] > 0 && + _s[1] > 0 && + _s[2] > 0; + } + const parts = table.parts; + const n = parts.length; + if (_world.length < n * 12) { + _world = new Float64Array(n * 12); + _hidden = new Uint8Array(n); + } + const world = _world; + const posed = state?.poses; + const spin = state?.spin; + const deploy = state?.deploy; + if (posed == null && spin == null && deploy == null) { + // Every part at rest. + for (let k = 0; k < n; k++) out.set(IDENTITY, offset + k * 16); + flags?.fill(0, flagsOffset, flagsOffset + n); + return false; + } + let anyPosed = false; + for (let k = 0; k < n; k++) { + const part = parts[k]; + const name = part.name; + const pose = posed?.[name]; + const parentIndex = part.parentIndex; + const hidden = + pose?.hidden === true || (parentIndex >= 0 && _hidden[parentIndex] === 1); + const highlight = asksHighlight(pose?.highlight); + _hidden[k] = hidden ? 1 : 0; + if (flags !== undefined) + flags[flagsOffset + k] = + (hidden ? PART_HIDDEN : 0) | (highlight ? PART_HIGHLIGHT : 0); + if (hidden) { + out.fill(0, offset + k * 16, offset + k * 16 + 16); + anyPosed = true; + continue; + } + anyPosed ||= highlight; + // The local motion about the pivot, rotation `_q` and translation `_t`, + // in the (stretched) model: deploy, spin, then pose. `axis` is the + // part's axis there, `stretch` its length over the model's own. + let axis = part.axis; + let stretch = 1; + if (axis !== null && scaled) { + _a[0] = axis[0] * _s[0]; + _a[1] = axis[1] * _s[1]; + _a[2] = axis[2] * _s[2]; + stretch = Math.hypot(_a[0], _a[1], _a[2]); + _a[0] /= stretch; + _a[1] /= stretch; + _a[2] /= stretch; + axis = _a; + } + const rate = spin?.[name]; + const fraction = deploy?.[name]; + let moves = false; + _q.fill(0); + _q[3] = 1; + _t.fill(0); + if ( + axis !== null && + typeof rate === 'number' && + rate !== 0 && + Number.isFinite(rate * timeS) + ) { + // Reduced in doubles first: a rate times an epoch clock is a large + // number of degrees. + axisAngle(_q, axis, (rate * timeS) % 360); + moves = true; + } + if ( + axis !== null && + part.limits !== null && + typeof fraction === 'number' && + Number.isFinite(fraction) + ) { + const by = deployedBy(part, fraction); + if (by !== 0 && TURNS.has(part.kind)) { + axisAngle(_p, axis, by); + multiplyInto(_q, _p); + moves = true; + } else if (by !== 0 && MOVES.has(part.kind)) { + _t[0] = axis[0] * by * stretch; + _t[1] = axis[1] * by * stretch; + _t[2] = axis[2] * by * stretch; + moves = true; + } + } + if (pose !== undefined && pose !== null && isPosed(pose)) { + // Pose over the rest: R = Rpose · R, t = tpose + Rpose · t. + poseInto(_r, _v, pose); + if (scaled) for (let i = 0; i < 3; i++) _v[i] = _v[i] * _s[i]; + rotateInto(_r, _t); + _t[0] = _t[0] + _v[0]; + _t[1] = _t[1] + _v[1]; + _t[2] = _t[2] + _v[2]; + multiplyInto(_r, _q); + _q.set(_r); + moves = true; + } + if (moves && part.limits !== null && axis !== null) { + if (part.kind === 'hinge' || part.kind === 'deploy') + clampTwist(_q, axis, part.rest, part.limits); + else if (part.kind === 'slide') { + // Along the axis in the model's own metres, which its limits are in. + const along = + (_t[0] * axis[0] + _t[1] * axis[1] + _t[2] * axis[2]) / stretch; + const lo = Math.min(part.limits[0], part.limits[1]) - part.rest; + const hi = Math.max(part.limits[0], part.limits[1]) - part.rest; + const shift = (Math.min(hi, Math.max(lo, along)) - along) * stretch; + _t[0] = _t[0] + axis[0] * shift; + _t[1] = _t[1] + axis[1] * shift; + _t[2] = _t[2] + axis[2] * shift; + } + } + anyPosed ||= moves; + const w = k * 12; + if (moves) { + // Local L = R and p + t − R p, about the pivot. + let [px, py, pz] = part.pivot; + if (scaled) { + px *= _s[0]; + py *= _s[1]; + pz *= _s[2]; + } + _v[0] = px; + _v[1] = py; + _v[2] = pz; + rotateInto(_q, _v); + _t[0] = _t[0] + px - _v[0]; + _t[1] = _t[1] + py - _v[1]; + _t[2] = _t[2] + pz - _v[2]; + } + if (parentIndex < 0) affineInto(_q, _t, world, w); + else if (!moves) + world.copyWithin(w, parentIndex * 12, parentIndex * 12 + 12); + else { + // World = parent's world · local. + affineInto(_q, _t, _local, 0); + const b = parentIndex * 12; + for (let row = 0; row < 3; row++) { + const a0 = world[b + row * 3]; + const a1 = world[b + row * 3 + 1]; + const a2 = world[b + row * 3 + 2]; + world[w + row * 3] = a0 * _local[0] + a1 * _local[3] + a2 * _local[6]; + world[w + row * 3 + 1] = + a0 * _local[1] + a1 * _local[4] + a2 * _local[7]; + world[w + row * 3 + 2] = + a0 * _local[2] + a1 * _local[5] + a2 * _local[8]; + world[w + 9 + row] = + a0 * _local[9] + + a1 * _local[10] + + a2 * _local[11] + + world[b + 9 + row]; + } + } + if (!scaled) writeMatrix(world, w, out, offset + k * 16); + else { + // X = S⁻¹ · World · S. + for (let row = 0; row < 3; row++) { + for (let col = 0; col < 3; col++) + _local[row * 3 + col] = + (world[w + row * 3 + col] * _s[col]) / _s[row]; + _local[9 + row] = world[w + 9 + row] / _s[row]; + } + writeMatrix(_local, 0, out, offset + k * 16); + } + } + return anyPosed; +} + +/** Write the affine `m` (12 numbers from `at`: R row-major, then t) as a column-major 4×4 into `out` at `to`. */ +function writeMatrix(m, at, out, to) { + for (let col = 0; col < 3; col++) { + out[to + col * 4] = m[at + col]; + out[to + col * 4 + 1] = m[at + 3 + col]; + out[to + col * 4 + 2] = m[at + 6 + col]; + out[to + col * 4 + 3] = 0; + } + out[to + 12] = m[at + 9]; + out[to + 13] = m[at + 10]; + out[to + 14] = m[at + 11]; + out[to + 15] = 1; +} diff --git a/src/render/modelParts.test.mjs b/src/render/modelParts.test.mjs new file mode 100644 index 0000000000..75f379bd4d --- /dev/null +++ b/src/render/modelParts.test.mjs @@ -0,0 +1,573 @@ +import assert from 'node:assert/strict'; +import { describe, test } from 'node:test'; + +import { + gltfMeshMatrix, + PART_HIDDEN, + PART_HIGHLIGHT, + partMatrices, + partTableOf, + readPartTable, + asksHighlight, +} from './modelParts.js'; + +/** `m` (column-major 4×4 at `at`) times the point `p`. */ +function apply(m, at, p) { + const out = [0, 0, 0]; + for (let row = 0; row < 3; row++) + out[row] = + m[at + row] * p[0] + + m[at + 4 + row] * p[1] + + m[at + 8 + row] * p[2] + + m[at + 12 + row]; + return out; +} + +function close(actual, expected, digits = 6) { + assert.equal(actual.length, expected.length); + const tolerance = 10 ** -digits / 2; + actual.forEach((value, i) => + assert.ok( + Math.abs(value - expected[i]) <= tolerance, + `[${i}] ${value} is not ${expected[i]}`, + ), + ); +} + +const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + +/** A model in the glTF frame (nose −X, Y up, right −Z). */ +const TABLE = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + // Nose gear: stowed at 90, down at 0, turning about +Z through a point ahead and below. + { + name: 'gear_nose', + kind: 'hinge', + pivot: [-10, -1, 0], + axis: [0, 0, 1], + limits: [90, 0], + }, + // A flap about the right axis (−Z), 0 to 40 degrees, drawn at 0. + { + name: 'flap', + kind: 'hinge', + pivot: [2, 0, -3], + axis: [0, 0, -1], + limits: [0, 40], + }, + { name: 'engine', kind: 'marker', pivot: [0, -2, -5] }, + { + name: 'fan', + kind: 'spin', + parent: 'engine', + pivot: [-2, -2, -5], + axis: [1, 0, 0], + }, + { + name: 'stage_1', + kind: 'separable', + pivot: [0, 40, 0], + axis: [0, -1, 0], + limits: [0, 30], + }, + { + name: 'leg_1', + kind: 'hinge', + parent: 'stage_1', + pivot: [1, 1, 0], + axis: [0, 0, -1], + limits: [0, 110], + }, + { + name: 'door', + kind: 'slide', + pivot: [0, 0, 1], + axis: [2, 0, 0], + limits: [0, 1.5], + }, + { + name: 'panel', + kind: 'deploy', + pivot: [0, 0, 4], + axis: [1, 0, 0], + limits: [90, 0], + rest: 0, + }, + ], +}); + +function matrices(state, timeS = 0) { + const out = new Float64Array(TABLE.parts.length * 16); + const flags = new Uint8Array(TABLE.parts.length); + const posed = partMatrices(TABLE, state, timeS, out, { flags }); + const at = (name) => TABLE.byName.get(name) * 16; + return { out, flags, posed, at }; +} + +const slice = (out, at) => Array.from(out.subarray(at, at + 16)); + +describe('partTableOf', () => { + test('reads a table with its defaults', () => { + assert.deepEqual( + TABLE.parts.map((p) => p.name), + [ + 'body', + 'gear_nose', + 'flap', + 'engine', + 'fan', + 'stage_1', + 'leg_1', + 'door', + 'panel', + ], + ); + const body = TABLE.parts[0]; + assert.equal(body.kind, 'body'); + assert.equal(body.parent, null); + assert.equal(body.parentIndex, -1); + assert.deepEqual(body.pivot, [0, 0, 0]); + assert.equal(body.axis, null); + assert.equal(body.limits, null); + assert.equal(body.rest, null); + // `rest` is the stowed limit unless given; `parent` is the body unless given. + assert.equal(TABLE.parts[1].parent, 'body'); + assert.equal(TABLE.parts[1].parentIndex, 0); + assert.equal(TABLE.parts[1].rest, 90); + assert.deepEqual(TABLE.parts[8].limits, [90, 0]); + assert.equal(TABLE.parts[8].rest, 0); + assert.equal(TABLE.parts[4].parent, 'engine'); + assert.equal(TABLE.parts[4].parentIndex, 3); + assert.equal(TABLE.parts[4].rest, null); + // The axis is made unit length. + assert.deepEqual(TABLE.parts[7].axis, [1, 0, 0]); + assert.equal(TABLE.byName.get('leg_1'), 6); + }); + + test('a model without a table has none', () => { + assert.equal(partTableOf(undefined), null); + assert.equal(partTableOf({}), null); + assert.equal(partTableOf({ other: 1 }), null); + }); + + const body = { name: 'body', kind: 'body' }; + for (const [extras, message] of [ + [{ parts: [] }, /list of parts/], + [{ parts: [{ name: 'hull', kind: 'marker' }] }, /body/], + [{ parts: [body, { name: 'x', kind: 'wobble' }] }, /kind wobble/], + [{ parts: [body, { name: 'body', kind: 'marker' }] }, /twice/], + [ + { parts: [body, { name: 'a', kind: 'marker', parent: 'b' }] }, + /not an earlier part/, + ], + [{ parts: [body, { name: 'a', kind: 'spin', axis: [0, 0] }] }, /axis/], + [ + { parts: [body, { name: 'a', kind: 'spin', axis: [0, 0, 0] }] }, + /zero axis/, + ], + [{ parts: [body, { name: 'a', kind: 'hinge', limits: [0] }] }, /limits/], + ]) + test(`refuses a malformed table (${message})`, () => { + assert.throws(() => partTableOf(extras), message); + }); +}); + +/** A GLB of `json` and no binary chunk. */ +function glb(json) { + let text = new TextEncoder().encode(JSON.stringify(json)); + const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20); + padded.set(text); + text = padded; + const out = new Uint8Array(20 + text.length); + const view = new DataView(out.buffer); + view.setUint32(0, 0x46546c67, true); + view.setUint32(4, 2, true); + view.setUint32(8, out.length, true); + view.setUint32(12, text.length, true); + view.setUint32(16, 0x4e4f534a, true); + out.set(text, 20); + return out; +} + +describe('readPartTable', () => { + test('reads the table of the scene’s root node', () => { + const extras = { + parts: [ + { name: 'body', kind: 'body' }, + { name: 'radar', kind: 'spin' }, + ], + }; + const bytes = glb({ + scene: 0, + scenes: [{ nodes: [1] }], + nodes: [ + { extras: { parts: [{ name: 'body', kind: 'body' }] } }, + { mesh: 0, extras }, + ], + }); + assert.deepEqual( + readPartTable(bytes).parts.map((p) => p.name), + ['body', 'radar'], + ); + assert.equal(readPartTable(bytes.buffer).parts.length, 2); + }); + + test('a model that is only its body has none', () => { + assert.equal( + readPartTable(glb({ scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }] })), + null, + ); + }); + + test('refuses bytes that are not a GLB', () => { + assert.throws( + () => readPartTable(new TextEncoder().encode('glTF but not really')), + /GLB/, + ); + }); +}); + +describe('gltfMeshMatrix', () => { + test('the mesh node’s transform with its parents’', () => { + const m = gltfMeshMatrix({ + scenes: [{ nodes: [0] }], + nodes: [ + { translation: [1, 2, 3], children: [1] }, + // A packed model's dequantization: a scale and an offset. + { mesh: 0, translation: [0, 2, 0], scale: [10, 10, 10] }, + ], + }); + close(apply(m, 0, [1, 0, 0]), [11, 4, 3]); + close(apply(m, 0, [0, -1, 0]), [1, -6, 3]); + }); + + test('turned by a node’s rotation', () => { + // 90 degrees about +Y: +X turns to −Z. + const s = Math.SQRT1_2; + const m = gltfMeshMatrix({ + nodes: [{ mesh: 0, rotation: [0, s, 0, s] }], + }); + close(apply(m, 0, [1, 0, 0]), [0, 0, -1]); + }); + + test('the identity without a mesh', () => { + assert.deepEqual(gltfMeshMatrix({ nodes: [{}] }), IDENTITY); + }); +}); + +describe('partMatrices', () => { + test('no state, or an empty one, leaves every part at rest', () => { + for (const state of [null, {}, { poses: {}, spin: {}, deploy: {} }]) { + const { out, flags, posed } = matrices(state); + assert.equal(posed, false); + for (let k = 0; k < TABLE.parts.length; k++) + assert.deepEqual(slice(out, k * 16), IDENTITY); + assert.deepEqual( + Array.from(flags), + new Array(TABLE.parts.length).fill(0), + ); + } + }); + + test('a hinge turns about its pivot, off the origin', () => { + // Deployed: from 90 (as drawn) to 0, so −90 degrees about +Z through [-10, -1, 0]. + const { out, at, posed } = matrices({ deploy: { gear_nose: 1 } }); + assert.equal(posed, true); + close(apply(out, at('gear_nose'), [-10, -1, 0]), [-10, -1, 0]); + // 2 m along −Y from the pivot turns to 2 m along −X. + close(apply(out, at('gear_nose'), [-10, -3, 0]), [-12, -1, 0]); + // Halfway is 45 degrees. + const half = matrices({ deploy: { gear_nose: 0.5 } }); + const s = Math.SQRT1_2 * 2; + close(apply(half.out, half.at('gear_nose'), [-10, -3, 0]), [ + -10 - s, + -1 - s, + 0, + ]); + // Other parts stay at rest. + assert.deepEqual(slice(out, at('flap')), IDENTITY); + }); + + test('a hinge’s pose is clamped to its limits, its swing left free', () => { + // The flap's axis is the model's right, so pitch turns it: 0 to 40 degrees. + const tip = [3, 0, -3]; + const turned = (deg) => [ + 2 + Math.cos(deg * (Math.PI / 180)), + // Nose up: what is behind the hinge goes down. + -Math.sin(deg * (Math.PI / 180)), + -3, + ]; + for (const [pitch, expected] of [ + [25, 25], + [60, 40], + [-10, 0], + [400, 40], + ]) { + const { out, at } = matrices({ poses: { flap: { pitchDeg: pitch } } }); + close(apply(out, at('flap'), tip), turned(expected)); + } + // A roll is about the forward axis, not the hinge's: kept as posed. + const rolled = matrices({ poses: { flap: { rollDeg: 90 } } }); + close(apply(rolled.out, rolled.at('flap'), [2, 1, -3]), [2, 0, -4]); + }); + + test('the deploy fraction is clamped to 0..1, and a pose adds to it within limits', () => { + const over = matrices({ deploy: { gear_nose: 3 } }); + const full = matrices({ deploy: { gear_nose: 1 } }); + close(Array.from(over.out), Array.from(full.out)); + // The gear down (0) and pitched 30 more (−30 about its +Z axis): still + // 0, its limit; pitched the other way, it comes 30 back up. + const past = matrices({ + deploy: { gear_nose: 1 }, + poses: { gear_nose: { pitchDeg: 30 } }, + }); + close(Array.from(past.out), Array.from(full.out)); + const back = matrices({ + deploy: { gear_nose: 1 }, + poses: { gear_nose: { pitchDeg: -30 } }, + }); + const thirty = matrices({ deploy: { gear_nose: 1 - 30 / 90 } }); + close(Array.from(back.out), Array.from(thirty.out)); + // A deploy part drawn deployed (rest 0) stows to 90 about +X. + const stowed = matrices({ deploy: { panel: 0 } }); + close(apply(stowed.out, stowed.at('panel'), [0, 1, 4]), [0, 0, 5]); + }); + + test('a child part rides its parent', () => { + // The engine moved 1 m up: its fan, at rest about its own hub, moves with it. + const { out, at } = matrices({ poses: { engine: { offsetM: [0, 0, 1] } } }); + close(apply(out, at('engine'), [0, -2, -5]), [0, -1, -5]); + close(apply(out, at('fan'), [-2, -2, -5]), [-2, -1, -5]); + // Spinning too: the hub stays on the moved axis, a blade tip turns about it. + const spun = matrices( + { poses: { engine: { offsetM: [0, 0, 1] } }, spin: { fan: 90 } }, + 1, + ); + close(apply(spun.out, spun.at('fan'), [-2, -2, -5]), [-2, -1, -5]); + // +90 about +X: +Y turns to +Z. + close(apply(spun.out, spun.at('fan'), [-2, -1, -5]), [-2, -1, -4]); + }); + + test('a child hinge turns about its pivot as carried by its parent', () => { + const { out, at } = matrices({ deploy: { stage_1: 1, leg_1: 1 } }); + // The stage leaves 30 m along −Y; the leg's hinge goes with it and turns 110 about −Z there. + close(apply(out, at('leg_1'), [1, 1, 0]), [1, -29, 0]); + const deg = 110 * (Math.PI / 180); + close(apply(out, at('leg_1'), [1, 2, 0]), [ + 1 + Math.sin(deg), + -29 + Math.cos(deg), + 0, + ]); + }); + + test('a spin turns at its rate over time', () => { + const tip = [-2, -1, -5]; + const at = (timeS) => { + const m = matrices({ spin: { fan: 90 } }, timeS); + return apply(m.out, m.at('fan'), tip); + }; + close(at(0), tip); + close(at(1), [-2, -2, -4]); + close(at(2), [-2, -3, -5]); + close(at(4), tip); + // A rate times an epoch clock still lands where it should. + close(at(1_700_000_000), tip, 4); + close(at(1_700_000_001), [-2, -2, -4], 4); + // A spin driving a part with no axis does nothing. + assert.equal(matrices({ spin: { engine: 90 } }, 1).posed, false); + }); + + test('a separable part moves freely: its limits bound only the deploy fraction', () => { + const half = matrices({ deploy: { stage_1: 0.5 } }); + close(apply(half.out, half.at('stage_1'), [0, 40, 0]), [0, 25, 0]); + // Posed 500 m right and turned, past any limit (right is −Z). + const { out, at } = matrices({ + poses: { stage_1: { offsetM: [500, 0, -200], yawDeg: 30 } }, + }); + close(apply(out, at('stage_1'), [0, 40, 0]), [0, -160, -500]); + }); + + test('a slide is clamped along its axis, free across it', () => { + // The door slides along +X (the model's back) 0 to 1.5 m; offsetM is [right, forward, up]. + const back = (metres) => + matrices({ poses: { door: { offsetM: [0, -metres, 0] } } }); + close(apply(back(1).out, back(1).at('door'), [0, 0, 1]), [1, 0, 1]); + close(apply(back(9).out, back(9).at('door'), [0, 0, 1]), [1.5, 0, 1]); + close(apply(back(-2).out, back(-2).at('door'), [0, 0, 1]), [0, 0, 1]); + const up = matrices({ poses: { door: { offsetM: [0, -9, 2] } } }); + close(apply(up.out, up.at('door'), [0, 0, 1]), [1.5, 2, 1]); + }); + + test('hidden hides the part and every part riding it', () => { + const { out, flags, at, posed } = matrices({ + poses: { engine: { hidden: true } }, + }); + assert.equal(posed, true); + assert.deepEqual(slice(out, at('engine')), new Array(16).fill(0)); + assert.deepEqual(slice(out, at('fan')), new Array(16).fill(0)); + assert.equal(flags[TABLE.byName.get('engine')], PART_HIDDEN); + assert.equal(flags[TABLE.byName.get('fan')], PART_HIDDEN); + assert.equal(flags[TABLE.byName.get('flap')], 0); + assert.deepEqual(slice(out, at('flap')), IDENTITY); + }); + + test('highlight marks the part alone, and does not move it', () => { + const { out, flags, posed } = matrices({ + poses: { engine: { highlight: '#ff0' } }, + }); + assert.equal(posed, true); + assert.equal(flags[TABLE.byName.get('engine')], PART_HIGHLIGHT); + assert.equal(flags[TABLE.byName.get('fan')], 0); + for (let k = 0; k < TABLE.parts.length; k++) + assert.deepEqual(slice(out, k * 16), IDENTITY); + assert.equal( + matrices({ poses: { engine: { highlight: false } } }).posed, + false, + ); + }); + + test('a highlight is true or a colour; anything else asks for none', () => { + for (const value of [true, '#ff0', 'red', [1, 0.5, 0], [1, 0, 0, 0.5]]) + assert.equal(asksHighlight(value), true, String(value)); + for (const value of [ + false, + '', + ' ', + 0, + 1, + null, + undefined, + {}, + [1, 0], + [1, 'x', 0], + [NaN, 0, 0], + ]) + assert.equal(asksHighlight(value), false, String(value)); + assert.equal( + matrices({ poses: { engine: { highlight: '' } } }).posed, + false, + ); + assert.equal( + matrices({ poses: { engine: { highlight: 0 } } }).posed, + false, + ); + }); + + test('a pose value that is not finite counts as 0', () => { + const { out, posed } = matrices({ + poses: { + engine: { + yawDeg: NaN, + pitchDeg: Infinity, + rollDeg: -Infinity, + offsetM: [NaN, Infinity, undefined], + }, + }, + }); + assert.equal(posed, false); + for (let k = 0; k < TABLE.parts.length; k++) + assert.deepEqual(slice(out, k * 16), IDENTITY); + // Beside a finite one, it is still 0 and no NaN is written. + const mixed = matrices({ + poses: { engine: { yawDeg: 90, pitchDeg: NaN, offsetM: [NaN, 0, 1] } }, + }); + assert.equal(mixed.posed, true); + assert.ok(mixed.out.every(Number.isFinite)); + }); + + test('names the table does not have are ignored', () => { + const { posed } = matrices({ + poses: { rotor_main: { yawDeg: 30, hidden: true } }, + spin: { rotor_main: 100 }, + deploy: { gear_main: 1 }, + }); + assert.equal(posed, false); + }); + + test('writes from an offset, into float32', () => { + const out = new Float32Array(16 + TABLE.parts.length * 16).fill(7); + const flags = new Uint8Array(3 + TABLE.parts.length).fill(9); + partMatrices(TABLE, { poses: { flap: { hidden: true } } }, 0, out, { + offset: 16, + flags, + flagsOffset: 3, + }); + assert.deepEqual(Array.from(out.subarray(0, 16)), new Array(16).fill(7)); + assert.deepEqual(Array.from(out.subarray(16, 32)), IDENTITY); + assert.deepEqual(Array.from(flags.subarray(0, 3)), [9, 9, 9]); + assert.equal(flags[3 + TABLE.byName.get('flap')], PART_HIDDEN); + }); +}); + +describe('partMatrices on a stretched model', () => { + /** Where `p` is drawn by a model stretched `scale` whose part is `out`'s matrix at `at`: S · X · p. */ + const drawnAt = (out, at, scale, p) => { + const x = apply(out, at, p); + return [x[0] * scale[0], x[1] * scale[1], x[2] * scale[2]]; + }; + const RADAR = partTableOf({ + parts: [ + { name: 'body', kind: 'body' }, + { name: 'radar', kind: 'spin', pivot: [5, 3, 0], axis: [0, 1, 0] }, + ], + }); + const length = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + + test('a radar on a hull drawn twice its length keeps its length at every angle', () => { + const scale = [2, 1, 1]; + const hub = [5, 3, 0]; + const tip = [6, 3, 0]; + const state = { spin: { radar: 30 } }; + for (let timeS = 0; timeS < 12; timeS++) { + const out = new Float64Array(32); + partMatrices(RADAR, state, timeS, out, { scale }); + const h = drawnAt(out, 16, scale, hub); + const t = drawnAt(out, 16, scale, tip); + // The hub stays where the stretched hull draws it; the 1 m arm is drawn 2 m long. + close(h, [10, 3, 0]); + assert.ok(Math.abs(length(t, h) - 2) < 1e-9); + } + // Unscaled matrices under the same stretch distort it: 1 m long across the hull. + const naive = new Float64Array(32); + partMatrices(RADAR, state, 3, naive); + const h = drawnAt(naive, 16, scale, hub); + const t = drawnAt(naive, 16, scale, tip); + assert.ok(Math.abs(length(t, h) - 1) < 1e-9); + }); + + test('a hinge turns rigidly about its stretched pivot', () => { + const scale = [1, 3, 1]; + const out = new Float64Array(TABLE.parts.length * 16); + partMatrices(TABLE, { deploy: { gear_nose: 1 } }, 0, out, { scale }); + const at = TABLE.byName.get('gear_nose') * 16; + close(drawnAt(out, at, scale, [-10, -1, 0]), [-10, -3, 0]); + close(drawnAt(out, at, scale, [-10, -3, 0]), [-16, -3, 0]); + }); + + test('a slide keeps its limits in the model’s own metres', () => { + const scale = [2, 1, 1]; + const out = new Float64Array(TABLE.parts.length * 16); + // Offsets are stretched with the model: 9 m back asked, 1.5 m allowed, drawn 3 m. + partMatrices(TABLE, { poses: { door: { offsetM: [0, -9, 0] } } }, 0, out, { + scale, + }); + close( + drawnAt(out, TABLE.byName.get('door') * 16, scale, [0, 0, 1]), + [3, 0, 1], + ); + }); + + test('a scale of one, or none, writes the same matrices', () => { + const state = { + deploy: { gear_nose: 0.3, stage_1: 1, leg_1: 0.5 }, + spin: { fan: 33 }, + poses: { engine: { offsetM: [1, 2, 3], yawDeg: 10 } }, + }; + const a = new Float64Array(TABLE.parts.length * 16); + const b = new Float64Array(TABLE.parts.length * 16); + partMatrices(TABLE, state, 1.5, a); + partMatrices(TABLE, state, 1.5, b, { scale: [1, 1, 1] }); + assert.deepEqual(Array.from(b), Array.from(a)); + }); +}); diff --git a/src/render/neutralExports.test.mjs b/src/render/neutralExports.test.mjs index b81379d00c..17057a35ec 100644 --- a/src/render/neutralExports.test.mjs +++ b/src/render/neutralExports.test.mjs @@ -29,6 +29,7 @@ const NEUTRAL = [ './render/vectorBase', './render/iconSegment', './render/recession', + './render/modelParts', './render/windStreamlines', './render/weather', './weather/effects', diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index d09c74dada..d2da3f359d 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -30,6 +30,7 @@ test('the stub passes the conformance suite', async () => { 'draw.lines.split', 'draw.lines.outlineDraped', 'draw.models.blend', + 'draw.models.paint', 'globe.imagery.video', 'globe.weather.drawn', 'globe.weather.sceneTime', diff --git a/src/scenes/director.js b/src/scenes/director.js index 35387ecba7..4332d99362 100644 --- a/src/scenes/director.js +++ b/src/scenes/director.js @@ -492,6 +492,8 @@ export class SceneDirector { download: () => this.downloadLastRunMetadata(), load: (sceneId, shotId) => this.loadShot(sceneId, shotId), deleteShot: (sceneId, shotId) => this.deleteShot(sceneId, shotId), + moveShot: (sceneId, shotId, index) => + this.moveShot(sceneId, shotId, index), }, }); } @@ -1225,6 +1227,31 @@ export class SceneDirector { if (inStories) this._publish({ type: 'stories-changed' }); } + /** + * Move a shot to another place in its scene's playback order, the shots + * between shifting over (the shot list's up and down buttons swap it with + * its neighbour). Not while the scene plays. + * @param {string} sceneId + * @param {string} shotId + * @param {number} index Its new place, kept within the scene's shots. + * @returns {boolean} Whether it moved. + */ + moveShot(sceneId, shotId, index) { + if (this._running || !Number.isInteger(index)) return false; + const { scene, shot } = this._getShot(sceneId, shotId); + if (!scene || !shot) return false; + const from = scene.shots.indexOf(shot); + const to = Math.max(0, Math.min(scene.shots.length - 1, index)); + if (from === to) return false; + const shots = scene.shots.filter((item) => item !== shot); + shots.splice(to, 0, shot); + scene.shots = shots; + this._saveProject(); + this._shotOutcome('shot-moved', scene, shot, to); + if (scene.stories) this._publish({ type: 'stories-changed' }); + return true; + } + /** * Load a single shot: apply its visual state, enable/disable layers, and fly * the camera to the shot's position. Blocked while a scene run is active. diff --git a/src/scenes/director.test.mjs b/src/scenes/director.test.mjs index dd36ec3897..4e34dc5c56 100644 --- a/src/scenes/director.test.mjs +++ b/src/scenes/director.test.mjs @@ -1869,6 +1869,43 @@ test('Scene snapshots are immutable and editing outcomes retain the affected sho } finally { restore(); } }); +test('moveShot reorders a scene, saves it and publishes shot-moved; not past the ends, not while playing', async () => { + const { director, restore } = makeDirector(); + try { + director._activeRun = null; + const seen = []; + director.subscribe(({ change }) => { if (change) seen.push(change); }); + const order = () => director._project.scenes[0].shots.map(({ id }) => id); + const saved = () => + JSON.parse(localStorage.getItem('godsEyeView.sceneProject.v2')) + .scenes[0].shots.map(({ id }) => id); + + assert.equal(director.moveShot('scene-1', 'shot-b', 0), true); + assert.deepEqual(order(), ['shot-b', 'shot-a']); + assert.deepEqual(saved(), ['shot-b', 'shot-a']); + const moved = seen.find(({ type }) => type === 'shot-moved'); + assert.equal(moved.shot.id, 'shot-b'); + assert.equal(moved.index, 0); + + // The view's action is the same edit. + seen.length = 0; + director._controls.actions.moveShot('scene-1', 'shot-b', 1); + assert.deepEqual(order(), ['shot-a', 'shot-b']); + assert.deepEqual(seen.map(({ type }) => type), ['shot-moved']); + + // Past an end it stays at the end; at its place, unknown, or playing, nothing moves. + assert.equal(director.moveShot('scene-1', 'shot-b', 5), false); + assert.equal(director.moveShot('scene-1', 'shot-a', -1), false); + assert.equal(director.moveShot('scene-1', 'missing', 0), false); + assert.equal(director.moveShot('scene-1', 'shot-a', 0.5), false); + director._running = true; + assert.equal(director.moveShot('scene-1', 'shot-b', 0), false); + director._running = false; + assert.deepEqual(order(), ['shot-a', 'shot-b']); + await director.destroy(); + } finally { restore(); } +}); + test('Scene load outcomes exclude superseded and disposed completions', async () => { const { director, styleManager, restore } = makeDirector(); try { diff --git a/src/sources/live/aircraft.js b/src/sources/live/aircraft.js index 85b3acdc55..accc8672d8 100644 --- a/src/sources/live/aircraft.js +++ b/src/sources/live/aircraft.js @@ -109,6 +109,11 @@ export function openSkySnapshot( const statuses = payload?.emergencyByIcao; if (record && statuses && Object.hasOwn(statuses, record.id)) record.emergency = cleanText(statuses[record.id]).toLowerCase() || null; + // A state vector has no type field; a feed that knows the airframe's + // ICAO type designator sends it alongside, by ICAO address. + const types = payload?.typeByIcao; + if (record && types && Object.hasOwn(types, record.id)) + record.typeCode = cleanText(types[record.id]).toUpperCase() || null; return record; }, 'OpenSky', diff --git a/src/sources/live/contract.test.mjs b/src/sources/live/contract.test.mjs index 2c22012bf3..bc5c57a3c8 100644 --- a/src/sources/live/contract.test.mjs +++ b/src/sources/live/contract.test.mjs @@ -614,3 +614,18 @@ test('a vessel with no name is not named by its id; a ten-digit MMSI is an MMSI' ); assert.equal(named.name, 'EVER GIVEN'); }); + +test('a type sent alongside the state vectors becomes the record type code', () => { + const row = (id) => [id, 'TEST1', 'US', 1, 1, -77, 39, 1000, false, 100, 90]; + const snapshot = openSkySnapshot({ + time: 1, + states: [row('abc123'), row('def456')], + typeByIcao: { abc123: ' ec45 ', zzz999: 'B738' }, + }); + assert.equal(snapshot.records[0].typeCode, 'EC45'); + assert.equal(snapshot.records[1].typeCode, null); + assert.equal( + openSkySnapshot({ states: [row('abc123')] }).records[0].typeCode, + null, + ); +}); diff --git a/src/testSupport/fleetModelFakes.mjs b/src/testSupport/fleetModelFakes.mjs index daeb47e3cd..820ffb3f71 100644 --- a/src/testSupport/fleetModelFakes.mjs +++ b/src/testSupport/fleetModelFakes.mjs @@ -7,13 +7,10 @@ import { fetchPublicFile } from './fleetGlb.mjs'; /** A model policy whose eligibility is read again on every frame. */ export const FLEET_TEST_POLICY = Object.freeze({ altitudeCeilingM: 800_000, - minimumPixelSize: 16, cap: 4, capAll: 8, addM: 5_000, - addAllM: 20_000, keepM: 6_000, - keepAllM: 24_000, intervalMs: 0, }); diff --git a/src/time/snapshotTimeline.js b/src/time/snapshotTimeline.js index 98f360c971..880227ce7e 100644 --- a/src/time/snapshotTimeline.js +++ b/src/time/snapshotTimeline.js @@ -1,10 +1,33 @@ import { readSnapshotTimeline } from '../sources/live/contract.js'; -import { TIMELINE_HELD_MS } from './timelineFixes.js'; +import { fixesReachMs, TIMELINE_HELD_MS } from './timelineFixes.js'; /** The longest play waits on a snapshot before it goes on without it. */ export const SNAPSHOT_WAIT_MS = 8_000; /** How long a snapshot that failed to load waits before it is asked again. */ export const SNAPSHOT_RETRY_MS = 5_000; +/** + * How much play keeps of the loaded fixes after the newest snapshot: it holds + * this far short of their end (at most half of them), so a contact never + * reaches the end of its fixes while the next snapshot loads. + */ +export const SNAPSHOT_HOLD_MARGIN_MS = 60_000; +/** + * How far ahead, in real time at the clock's rate, play asks for snapshots: + * at a high rate it asks several steps before the time needs them. + */ +export const SNAPSHOT_PREFETCH_MS = 4_000; + +/** + * What a layer's `load` answers once it applied `snapshot`: `{ reachMs }`, + * how far its records' fixes reach (fixesReachMs), when they carry fixes; + * else true. + * @param {{records?: Array<{fixes?: unknown}>}} snapshot + * @returns {true|{reachMs: number}} + */ +export function snapshotAnswer(snapshot) { + const reachMs = fixesReachMs(snapshot?.records); + return reachMs === null ? true : { reachMs }; +} /** * Let a layer of live contacts (flights, military aircraft, vessels) follow @@ -26,7 +49,10 @@ export const SNAPSHOT_RETRY_MS = 5_000; * are applied as polls are (`replace: false`), so contacts move on smoothly. * - When the source's timeline declares `spanMs`, its records carry their * fixes from `spanMs` before a snapshot's time to `spanMs` after it, and - * the layer places each contact on them by the clock. A seek or a move + * the layer places each contact on them by the clock. Playing on, it asks + * for the next step SNAPSHOT_PREFETCH_MS of play ahead (at least a step), + * and play holds only SNAPSHOT_HOLD_MARGIN_MS short of the end of the + * newest snapshot's fixes, not at the step still loading. A seek or a move * back that stays within the fixes the loaded snapshots carry is then no * jump: nothing is cleared, play does not wait, and contacts move to the * time smoothly. A move to a step before the newest loaded asks for that @@ -36,17 +62,23 @@ export const SNAPSHOT_RETRY_MS = 5_000; * fixes after the newest asks for the snapshot there (`replace: false`). * - Outside the source's coverage the layer is `clear()`ed and nothing loads; * while the coverage is not known yet nothing loads and nothing is cleared. - * - Back at live, the layer is `clear()`ed and `resumeLive()` polls at once. + * - Back at live, `resumeLive()` polls at once and its snapshot takes the + * place of every contact: those it has move on from where they are drawn, + * and only those it lacks go. The contacts stay until it answers; when it + * answers anything but true (it could not be had), the layer is `clear()`ed. + * A rejection named AbortError (a newer poll took its place) clears nothing. * - * `load` resolves true once the snapshot is applied and false (or rejects) - * when it could not be; it must not apply anything once `signal` aborts. A + * `load` resolves true once the snapshot is applied, or `{ reachMs }` when its + * records carry fixes, the newest of them (`fixesReachMs`), and false (or + * rejects) when it could not be; it must not apply anything once `signal` aborts. A * rejection named AbortError is a request the source dropped for a newer * one: it is not a failure, and nothing is cleared. * * @param {{id: string, clock: ReturnType, * source: () => object|null, - * load: (atMs: number, options: {signal: AbortSignal, replace: boolean}) => Promise, - * clear: () => void, resumeLive: () => void, + * load: (atMs: number, options: {signal: AbortSignal, replace: boolean}) => + * Promise, + * clear: () => void, resumeLive: () => boolean|Promise, * now?: () => number, setTimeout?: typeof globalThis.setTimeout, * clearTimeout?: typeof globalThis.clearTimeout}} options `source` * returns the layer's current source; it is read when the layer starts. @@ -86,6 +118,10 @@ export function createSnapshotTimeline({ let gated; let failedUntil = -Infinity; let retryTimer = null; + // Each return to live; an answer to an older one is dropped. + let handovers = 0; + // How far the fixes of each snapshot applied since the last jump reach. + const reaches = new Map(); const span = () => { let covered; @@ -194,7 +230,7 @@ export function createSnapshotTimeline({ return; } inflight = null; - held(atMs, replace); + held(atMs, replace, applied?.reachMs); empty = false; capped = false; stopWaiting(); @@ -218,24 +254,27 @@ export function createSnapshotTimeline({ // afresh: the contacts have no fixes for the time between. The stretch is // kept to TIMELINE_HELD_MS, from the end just loaded, which every // contact's fixes still cover. - function held(atMs, replace) { + function held(atMs, replace, reachMs) { const reach = 2 * (timeline.spanMs || 0); scrubbed = null; - if ( - replace || - lead === null || - atMs > lead + reach || - atMs < base - reach - ) { + const afresh = + replace || lead === null || atMs > lead + reach || atMs < base - reach; + if (afresh) reaches.clear(); + if (Number.isFinite(reachMs)) reaches.set(atMs, reachMs); + else reaches.delete(atMs); + if (afresh) { lead = atMs; base = atMs; return; } lead = Math.max(lead, atMs); base = Math.min(base, atMs); - if (lead - base <= TIMELINE_HELD_MS) return; - if (atMs === lead) base = lead - TIMELINE_HELD_MS; - else lead = base + TIMELINE_HELD_MS; + if (lead - base > TIMELINE_HELD_MS) { + if (atMs === lead) base = lead - TIMELINE_HELD_MS; + else lead = base + TIMELINE_HELD_MS; + } + for (const at of reaches.keys()) + if (at < base || at > lead) reaches.delete(at); } // Ask again for what the time needs, after a failure or a dropped load: @@ -316,8 +355,12 @@ export function createSnapshotTimeline({ clearOnce(); return; } + const hold = lead === null ? null : holdAt(covered); if (inflight) { - if (playsOn(state) && timeMs >= inflight.atMs && !inflight.quiet) + // With fixes past the newest snapshot, play waits only at their end. + const waitsAt = + timeline.spanMs > 0 && hold !== null ? hold : inflight.atMs; + if (playsOn(state) && timeMs >= waitsAt && !inflight.quiet) startWaiting(); return; } @@ -331,8 +374,8 @@ export function createSnapshotTimeline({ return; } const step = timeline.stepMs; - if (lead - timeMs >= step) { - setGate(lead); + if (lead - timeMs >= prefetchMs(state)) { + setGate(hold); return; } const next = Math.min( @@ -343,13 +386,62 @@ export function createSnapshotTimeline({ setGate(null); return; } - setGate(capped ? null : next); + setGate(capped ? null : timeline.spanMs > 0 ? hold : next); // Past what the loaded fixes reach (play went on without waiting), the // contacts have no fixes for the time between: the step stands in for // them all. request(next, timeline.spanMs > 0 && next > lead + 2 * timeline.spanMs); } + // Where play holds while the next snapshot loads: the newest loaded, + // or, with fixes past it, SNAPSHOT_HOLD_MARGIN_MS short of where they + // end: as far as that snapshot's fixes reach, at most the declared span + // (never past the coverage). + function holdAt(covered) { + const reach = timeline.spanMs || 0; + if (reach <= 0) return lead; + const margin = Math.min(SNAPSHOT_HOLD_MARGIN_MS, reach / 2); + const carried = reaches.get(lead); + const end = Number.isFinite(carried) + ? Math.min(lead + reach, carried) + : lead + reach; + return Math.max(lead, Math.min(covered.end, end - margin)); + } + + // How far ahead of the time play asks for the next step: a step, or with + // fixes past each snapshot, SNAPSHOT_PREFETCH_MS of play at the clock's + // rate, up to where play holds. + function prefetchMs(state) { + const step = timeline.stepMs; + const reach = timeline.spanMs || 0; + if (reach <= 0) return step; + const rate = Number.isFinite(state.rate) ? Math.abs(state.rate) : 1; + const margin = Math.min(SNAPSHOT_HOLD_MARGIN_MS, reach / 2); + return Math.max( + step, + Math.min(reach - margin, rate * SNAPSHOT_PREFETCH_MS), + ); + } + + // Back at live: the first live snapshot takes the place of every contact, + // which stay drawn until it does; one that cannot be had clears them. + function handOver() { + const mine = ++handovers; + const current = () => mine === handovers && started && clock.isLive(); + Promise.resolve() + .then(() => resumeLive()) + .then( + (applied) => { + if (current() && applied !== true) clear(); + }, + (error) => { + if (!current() || error?.name === 'AbortError') return; + console.warn(`Live snapshot failed: ${id}`, error); + clear(); + }, + ); + } + function follow(state) { if (!started) return; if (state.live) { @@ -363,10 +455,11 @@ export function createSnapshotTimeline({ base = null; empty = false; failedUntil = -Infinity; - clear(); - resumeLive(); + handOver(); return; } + // Away from live, a return to it still answering no longer applies. + handovers += 1; const timeMs = state.timeMs; // Away from live already: a move may stay within the loaded fixes. const wasFollowing = wasActive; @@ -432,6 +525,7 @@ export function createSnapshotTimeline({ stop() { if (!started) return; started = false; + handovers += 1; cancel(); setGate(null); wasActive = false; diff --git a/src/time/snapshotTimeline.test.mjs b/src/time/snapshotTimeline.test.mjs index 026c174143..5027f2f6ef 100644 --- a/src/time/snapshotTimeline.test.mjs +++ b/src/time/snapshotTimeline.test.mjs @@ -3,14 +3,23 @@ import assert from 'node:assert/strict'; import { createWorldClock } from './worldClock.js'; import { createSnapshotTimeline, + SNAPSHOT_HOLD_MARGIN_MS, + SNAPSHOT_PREFETCH_MS, SNAPSHOT_RETRY_MS, SNAPSHOT_WAIT_MS, + snapshotAnswer, } from './snapshotTimeline.js'; const STEP = 10_000; const WALL = Date.UTC(2026, 10, 1, 12); -function harness({ timeline = true, coverage, spanMs } = {}) { +function harness({ + timeline = true, + coverage, + spanMs, + stepMs = STEP, + live = () => true, +} = {}) { const t = { wall: WALL, mono: 1_000, @@ -33,7 +42,7 @@ function harness({ timeline = true, coverage, spanMs } = {}) { ...(timeline && { timeline: { coverage: () => span, - stepMs: STEP, + stepMs, ...(spanMs && { spanMs }), subscribe(listener) { coverageListeners.add(listener); @@ -62,7 +71,10 @@ function harness({ timeline = true, coverage, spanMs } = {}) { pending.push({ atMs, replace, signal, resolve, reject }); }), clear: () => calls.push({ type: 'clear' }), - resumeLive: () => calls.push({ type: 'live' }), + resumeLive: () => { + calls.push({ type: 'live' }); + return live(); + }, now: () => t.mono, ...timers, }); @@ -248,7 +260,7 @@ test('outside coverage the layer is cleared and nothing loads; unknown coverage assert.equal(h.coverageListeners.size, 0); }); -test('back at live the layer is cleared and polls at once', async () => { +test('back at live the layer polls at once and keeps its contacts for the live snapshot', async () => { const h = harness(); h.follower.start(); h.clock.seek(WALL - 600_000); @@ -257,11 +269,72 @@ test('back at live the layer is cleared and polls at once', async () => { h.clock.goLive(); await flush(); assert.equal(inflight.signal.aborted, true); - assert.deepEqual(h.calls.slice(-2), [{ type: 'clear' }, { type: 'live' }]); + assert.deepEqual(h.calls.at(-1), { type: 'live' }); + assert.equal( + h.calls.some((call) => call.type === 'clear'), + false, + 'the live snapshot takes the place of the contacts; nothing is cleared', + ); assert.equal(h.follower.active(), false); h.follower.stop(); }); +test('back at live, a live snapshot that cannot be had clears the layer', async () => { + for (const answer of [ + () => false, + () => Promise.resolve(false), + () => Promise.reject(new Error('down')), + ]) { + const h = harness({ live: answer }); + h.follower.start(); + h.clock.seek(WALL - 600_000); + await flush(); + await h.answer(); + h.clock.goLive(); + await flush(); + assert.deepEqual(h.calls.slice(-2), [{ type: 'live' }, { type: 'clear' }]); + h.follower.stop(); + } +}); + +test('back at live, a live poll dropped for a newer one, or answered after leaving live, clears nothing', async () => { + const dropped = harness({ + live: () => + Promise.reject( + Object.assign(new Error('dropped'), { name: 'AbortError' }), + ), + }); + dropped.follower.start(); + dropped.clock.seek(WALL - 600_000); + await flush(); + await dropped.answer(); + dropped.clock.goLive(); + await flush(); + assert.deepEqual(dropped.calls.at(-1), { type: 'live' }); + dropped.follower.stop(); + + let fail; + const late = harness({ + live: () => new Promise((resolve) => (fail = () => resolve(false))), + }); + late.follower.start(); + late.clock.seek(WALL - 600_000); + await flush(); + await late.answer(); + late.clock.goLive(); + await flush(); + late.clock.seek(WALL - 1_200_000); + await flush(); + fail(); + await flush(); + assert.equal( + late.calls.some((call) => call.type === 'clear'), + false, + 'the time shown now is not cleared by the old live answer', + ); + late.follower.stop(); +}); + test('a load the source drops for a newer one is no failure: nothing clears, it is asked again', async () => { const h = harness(); h.follower.start(); @@ -450,8 +523,9 @@ test('a snapshot the loaded fixes do not reach starts the held stretch afresh', h.advance(100); h.clock.coverageChanged(); await flush(); - // The next step is slow: play goes on without it, far past the fixes. - h.advance(2 * STEP); + // The next step is slow: play holds near the end of the fixes, then goes + // on without it, far past them. + h.advance(SPAN); h.clock.coverageChanged(); h.advance(SNAPSHOT_WAIT_MS); h.advance(30 * STEP); @@ -548,3 +622,119 @@ test('a step a move back asked for that fails clears nothing and is asked again }); h.follower.stop(); }); + +test('with fixes past each snapshot, play holds near their end, not at the step still loading', async () => { + const SPAN = 600_000; + const h = harness({ spanMs: SPAN }); + h.follower.start(); + const at = WALL - 1_800_000; + h.clock.seek(at); + await flush(); + await h.answer(); + h.clock.play(); + h.advance(100); + h.clock.coverageChanged(); + await flush(); + assert.deepEqual(loads(h.calls).at(-1), { + type: 'load', + atMs: at + STEP, + replace: false, + }); + // Past the step still loading: the newest snapshot's fixes carry them. + h.advance(3 * STEP); + h.clock.coverageChanged(); + assert.ok(h.clock.now() > at + 3 * STEP); + assert.equal(h.clock.getState().buffering, false); + // Play holds a margin short of the end of those fixes, and waits there. + h.advance(SPAN); + assert.equal(h.clock.now(), at + SPAN - SNAPSHOT_HOLD_MARGIN_MS); + h.clock.coverageChanged(); + assert.equal(h.clock.getState().buffering, true); + await h.answer(); + assert.equal(h.clock.getState().buffering, false); + h.follower.stop(); +}); + +test('with fixes past each snapshot, a fast play asks for steps well ahead of the time', async () => { + const SPAN = 600_000; + const RATE = 60; + const h = harness({ spanMs: SPAN }); + h.follower.start(); + const at = WALL - 1_800_000; + h.clock.seek(at); + await flush(); + await h.answer(); + h.clock.setRate(RATE); + h.clock.play(); + h.advance(100); + h.clock.coverageChanged(); + await flush(); + // Each step answered asks for the next until they reach far enough ahead. + while (h.pending.length) await h.answer(); + const ahead = RATE * SNAPSHOT_PREFETCH_MS; + const newest = loads(h.calls).at(-1).atMs; + const time = h.clock.now(); + assert.ok(newest - time >= ahead, 'steps asked for ahead of the time'); + assert.ok(newest - time < ahead + STEP, 'and no further'); + assert.ok( + loads(h.calls).every((call, k) => k === 0 || call.replace === false), + 'each in step with the last, moving contacts on', + ); + h.follower.stop(); +}); + +test('without fixes past each snapshot, a fast play still asks a step at a time', async () => { + const h = harness(); + h.follower.start(); + const at = WALL - 1_800_000; + h.clock.seek(at); + await flush(); + await h.answer(); + h.clock.setRate(60); + h.clock.play(); + h.advance(10); + h.clock.coverageChanged(); + await flush(); + assert.equal(loads(h.calls).at(-1).atMs, at + STEP); + await h.answer(); + assert.equal(h.pending.length, 1); + assert.equal(loads(h.calls).at(-1).atMs, at + 2 * STEP); + h.follower.stop(); +}); + +test('play holds short of where the applied snapshot’s fixes actually reach, when that is short of the span', async () => { + const SPAN = 600_000; + const h = harness({ spanMs: SPAN }); + h.follower.start(); + const at = WALL - 1_800_000; + h.clock.seek(at); + await flush(); + // Its records' fixes end two minutes after its time, not ten. + await h.answer(0, { reachMs: at + 120_000 }); + h.clock.play(); + h.advance(100); + h.clock.coverageChanged(); + await flush(); + h.advance(SPAN); + assert.equal(h.clock.now(), at + 120_000 - SNAPSHOT_HOLD_MARGIN_MS); + h.follower.stop(); +}); + +test('a layer answers how far an applied snapshot’s fixes reach', () => { + assert.equal(snapshotAnswer({ records: [{ id: 'a' }] }), true); + assert.deepEqual( + snapshotAnswer({ + records: [ + { fixes: [{ atMs: 3 }, { atMs: 9 }] }, + { fixes: [{ atMs: 12 }, { atMs: 'x' }] }, + { id: 'b' }, + ], + }), + { reachMs: 12 }, + ); + // One record reaching far ahead does not stand for the rest. + const records = Array.from({ length: 20 }, (_, k) => ({ + fixes: [{ atMs: k === 0 ? 900 : 100 + k }], + })); + assert.deepEqual(snapshotAnswer({ records }), { reachMs: 118 }); +}); diff --git a/src/time/timelineFixes.js b/src/time/timelineFixes.js index e8b078cc3c..c55c311cf5 100644 --- a/src/time/timelineFixes.js +++ b/src/time/timelineFixes.js @@ -59,6 +59,33 @@ export function readTimelineFixes(value) { return fixes; } +/** The share of records whose fixes reach no further than fixesReachMs. */ +export const FIXES_REACH_SHARE = 0.9; + +/** + * How far the fixes a snapshot's records carry reach: the time by which + * FIXES_REACH_SHARE of them have their newest fix, so a few reaching far + * ahead do not stand for the rest (those whose fixes end sooner left), or + * null when none carries fixes. + * @param {Array<{fixes?: unknown}>|undefined} records + * @returns {number|null} + */ +export function fixesReachMs(records) { + const reaches = []; + for (const record of records ?? []) { + if (!Array.isArray(record?.fixes)) continue; + let reach = -Infinity; + for (const fix of record.fixes) { + const atMs = Number(fix?.atMs); + if (Number.isFinite(atMs) && atMs > reach) reach = atMs; + } + if (reach > -Infinity) reaches.push(reach); + } + if (!reaches.length) return null; + reaches.sort((a, b) => a - b); + return reaches[Math.ceil(FIXES_REACH_SHARE * reaches.length) - 1]; +} + /** * Two runs of entries in time order (`timeOf` reads an entry's epoch ms) as * one: `newer` stands in for the entries of `older` within the time it diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index 06553f7bc3..f68532c795 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -11,7 +11,11 @@ import { _routeInflightCountForTest, _setRouteUpstreamIntervalForTest, } from '../../server/providers/places/routes.js'; -import { ROUTE_STEPS_MAX } from '../../src/data/routeSteps.js'; +import { + ROUTE_STEPS_MAX, + normalizeOsrmSteps, +} from '../../src/data/routeSteps.js'; +import * as placePayloads from '../../src/data/placeProviderPayloads.js'; import { projectNearbyPlaces, projectTextSearchPlaces, @@ -465,6 +469,10 @@ test('identical concurrent route requests make one upstream call', async (t) => ); }); +test('the place payloads entry serves the same route steps the dev proxy does', () => { + assert.equal(placePayloads.normalizeOsrmSteps, normalizeOsrmSteps); +}); + test('a pathological maneuver count is bounded before it reaches the browser', async (t) => { _resetRouteUpstreamForTest(); const request = install(installRouteMiddleware); diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index 3546f38008..ed10b008f6 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -106,6 +106,9 @@ export class StyleManager extends ShellFacade { * @param {object} [options] * @param {boolean} [options.localePicker=true] - false removes the language * picker, for a host that offers its own language choice. + * @param {{lon: number, lat: number, height: number, heading?: number, + * pitch?: number}|null} [options.homeView] - where the title's logo goes + * back to (degrees): the view the app started from. */ constructor( viewer, @@ -116,6 +119,7 @@ export class StyleManager extends ShellFacade { requestServices, initialShareCode = null, localePicker = true, + homeView = null, } = {}, ) { super(); @@ -341,6 +345,7 @@ export class StyleManager extends ShellFacade { this._locationNavigation = new LocationNavigation({ viewer, placeSearch, + homeView, navigation: this._navigation, readCockpit: () => this.cockpitView, services: { @@ -1717,7 +1722,12 @@ export class StyleManager extends ShellFacade { const store = useGlobeActionsStore(applicationPinia()); if (this._resetToken) store.detach(this._resetToken); this._resetToken = controls - ? store.connect({ reset: () => controls.reset() }) + ? store.connect({ + reset: () => controls.reset(), + home: () => { + if (!this._disposed) void this.returnToStart(); + }, + }) : null; // A reset under way as the controls are replaced stays on the buttons. if (this._resetToken && this._globeResetting != null) diff --git a/src/ui/cockpitBridge.test.mjs b/src/ui/cockpitBridge.test.mjs index e7ecb36d2a..69a0e64fff 100644 --- a/src/ui/cockpitBridge.test.mjs +++ b/src/ui/cockpitBridge.test.mjs @@ -7,6 +7,7 @@ import assert from 'node:assert/strict'; import { createPinia } from 'pinia'; import { createApp, defineComponent, h, nextTick } from 'vue'; import { CockpitViewController } from './cockpitController.js'; +import { setLocale } from '../i18n/index.js'; import { useCockpitStore } from './stores/cockpit.js'; import CockpitView from './views/CockpitView.vue'; import ContextView from './views/ContextView.vue'; @@ -413,6 +414,33 @@ test('the bridge radar shows nearby ships without its own and steps its range', assert.ok(!$('#cockpit-radar') || $('#cockpit-radar').hidden); }); +test('the radar range and ring spacing agree with their distance (ru)', async (t) => { + const { $, cockpit } = fixture(t); + t.after(() => setLocale('en')); + setLocale('ru'); + cockpit.enter(); + await settle(); + const shown = () => [ + $('#cockpit-radar-range').textContent.trim(), + $('.cockpit-radar-rings').textContent.trim(), + ]; + // The ring spacing is a fraction at the short ranges: Intl.PluralRules + // gives 0.75 and 1.5 the form of their own. + const expected = [ + ['3 МОР. МИЛИ', 'КОЛЬЦА 0,75 МОР. МИЛИ'], + ['6 МОР. МИЛЬ', 'КОЛЬЦА 1,5 МОР. МИЛИ'], + ['12 МОР. МИЛЬ', 'КОЛЬЦА 3 МОР. МИЛИ'], + ['24 МОР. МИЛИ', 'КОЛЬЦА 6 МОР. МИЛЬ'], + ]; + for (const [index, labels] of expected.entries()) { + if (index) { + $('#cockpit-radar-range').click(); + await settle(); + } + assert.deepEqual(shown(), labels); + } +}); + test('contact navigation does not jump ship from the bridge', async (t) => { const { cockpit, navigations } = fixture(t); cockpit.enter(); @@ -1276,6 +1304,18 @@ test('a ship with no true heading is held, and labelled, on its course', async ( signals.some(([, , , detail]) => /COURSE 095°/.test(detail)), JSON.stringify(signals), ); + // A ship's course has a word of its own: pt RUMO, an aircraft's CURSO. + t.after(() => setLocale('en')); + setLocale('pt'); + signals.length = 0; + cockpit.exit(); + await settle(); + cockpit.enter(); + await settle(); + assert.ok( + signals.some(([, , , detail]) => /· RUMO 095°$/.test(detail)), + JSON.stringify(signals), + ); }); test('both entries name the subject the same way', async () => { diff --git a/src/ui/cockpitInstruments.js b/src/ui/cockpitInstruments.js index c7226fcb90..fdb5b0d825 100644 --- a/src/ui/cockpitInstruments.js +++ b/src/ui/cockpitInstruments.js @@ -1,5 +1,5 @@ /** Instrument values, routes and vision controls for the Cockpit controller. */ -import { formatNumber, t } from '../i18n/index.js'; +import { formatNumber, t, tn } from '../i18n/index.js'; import { COCKPIT_VISION_MODES, normalizeCockpitVisionMode, @@ -526,7 +526,10 @@ export function updateRadar(info) { ); this.publishRadar({ ...picture, - rangeLabel: t('{range} NM', { range: formatNumber(rangeNm) }), + // A plural, as the ring spacing is: ru «3 МОР. МИЛИ», «12 МОР. МИЛЬ». + rangeLabel: tn(rangeNm, '{range} NM', '{range} NM', { + range: formatNumber(rangeNm), + }), }); } diff --git a/src/ui/cockpitOrbitalFocus.test.mjs b/src/ui/cockpitOrbitalFocus.test.mjs index 73cc3505c7..836d6e8d99 100644 --- a/src/ui/cockpitOrbitalFocus.test.mjs +++ b/src/ui/cockpitOrbitalFocus.test.mjs @@ -24,6 +24,7 @@ import { fakeInput, } from '../input/testDoubles.mjs'; import { CockpitViewController } from './cockpitController.js'; +import { setLocale, t as translate } from '../i18n/index.js'; import { useCockpitStore } from './stores/cockpit.js'; import { useHudStore } from './stores/hud.js'; import CockpitView from './views/CockpitView.vue'; @@ -572,6 +573,18 @@ test('a site row turns the camera onto it, holds it, and reads its off-nadir ang assert.match(held.className, /^track actionable$/); assert.match(held.detail, /^FOCUS · BASE · OFF-NADIR/); assert.equal(siteRow(scene, 'alpha').getAttribute('aria-label'), 'Release the camera from Camp Alpha'); + // The held site's FOCUS is a status, worded apart from the FOCUS command. + t.after(() => setLocale('en')); + setLocale('es'); + await refreshRows(scene); + const heldEs = rows(scene).find((row) => row.target?.id === SITES.alpha.id); + assert.match(heldEs.detail, /^ENFOQUE · /); + assert.match( + $('#cockpit-orbital-focus').textContent, + /^ENFOQUE · /, + 'the card names the held site with the same word', + ); + assert.equal(translate('FOCUS'), 'ENFOCAR', 'the command keeps its verb'); }); test('another site row switches the focus; the held site row ends it', async (t) => { diff --git a/src/ui/cockpitOrbitalSignals.js b/src/ui/cockpitOrbitalSignals.js index c01bd56a2b..49818ea691 100644 --- a/src/ui/cockpitOrbitalSignals.js +++ b/src/ui/cockpitOrbitalSignals.js @@ -132,7 +132,8 @@ function siteRows(info, { settled = true } = {}) { }), }); const words = [installationClassLabel(site.class), angle]; - if (focused) words.unshift(t('FOCUS')); + // A status, as on the focus card, not the command: es «ENFOQUE», not «ENFOCAR». + if (focused) words.unshift(t('FOCUS', { context: 'site status' })); return { key: `site:${site.id}`, // The held site reads as the subject does. diff --git a/src/ui/cockpitPresence.test.mjs b/src/ui/cockpitPresence.test.mjs index fa1f4663b5..330edecfcb 100644 --- a/src/ui/cockpitPresence.test.mjs +++ b/src/ui/cockpitPresence.test.mjs @@ -7,6 +7,7 @@ import assert from 'node:assert/strict'; import { createPinia } from 'pinia'; import { createApp, defineComponent, h, nextTick } from 'vue'; import { CockpitViewController } from './cockpitController.js'; +import { setLocale } from '../i18n/index.js'; import { useCockpitStore } from './stores/cockpit.js'; import CockpitView from './views/CockpitView.vue'; import ContextView from './views/ContextView.vue'; @@ -260,3 +261,16 @@ test('entering asks for a panel layout before Vue shows the cards', async (t) => await new Promise((resolve) => setTimeout(resolve, 50)); assert.deepEqual(laid, ['context', 'signals']); }); + +test('an aircraft is acquired on its CURSO in Portuguese; a ship keeps RUMO', async (t) => { + const { cockpit } = fixture(t); + t.after(() => setLocale('en')); + setLocale('pt'); + const signals = []; + cockpit.pushCockpitSignal = (...args) => signals.push(args); + cockpit.enter(); + await nextTick(); + const acquired = signals.find(([key]) => key === 'track'); + assert.ok(acquired, JSON.stringify(signals)); + assert.equal(acquired[3], 'UAL123 · CURSO 092°'); +}); diff --git a/src/ui/cockpitTrackingController.js b/src/ui/cockpitTrackingController.js index 3cfcc76fb9..54ff27d670 100644 --- a/src/ui/cockpitTrackingController.js +++ b/src/ui/cockpitTrackingController.js @@ -686,9 +686,11 @@ export function enter({ kind = null } = {}) { 'track', t('TRACK ACQUIRED'), // A ship with no true heading is held on its course over ground; one - // with neither is named without a direction. + // with neither is named without a direction. A ship's course has a + // word of its own: pt «RUMO», where an aircraft's is «CURSO». info.trackSource === 'course' ? t('{label} · COURSE {heading}°', { + context: 'vessel', label: info.name, heading: trackHeading, }) diff --git a/src/ui/contextBindings.js b/src/ui/contextBindings.js index 8c6b8760ed..c4e3a46155 100644 --- a/src/ui/contextBindings.js +++ b/src/ui/contextBindings.js @@ -1,5 +1,6 @@ import { t } from '../i18n/index.js'; import { spaceMissionsIndexFailure } from './contextActions.js'; +import { translateStatusMessage } from './statusText.js'; import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js'; export function _initGlobalContextPanel() { @@ -112,7 +113,7 @@ export function _initGlobalContextPanel() { if (this.destroyed || searched === false) return false; const stats = this.installations.getStats?.(); this.showToast( - stats?.statusMessage || + (stats?.statusMessage && translateStatusMessage(stats.statusMessage)) || (stats?.status === 'zoom-in' ? t('Zoom in to search mapped installations') : t('Nearby installations refreshed')), diff --git a/src/ui/frameRateView.test.mjs b/src/ui/frameRateView.test.mjs index fa13e064a0..1b84641d34 100644 --- a/src/ui/frameRateView.test.mjs +++ b/src/ui/frameRateView.test.mjs @@ -48,3 +48,35 @@ test('the FPS readout sits in the title bar, hidden until the backquote key', as await nextTick(); assert.equal(readout(), null); }); + +test('the title logo is a button that asks for the way back to live at the start view', async (t) => { + document.body.replaceChildren(); + const pinia = createPinia(); + const app = createApp(SceneChromeView).use(pinia); + app.mount(document.body.appendChild(document.createElement('div'))); + t.after(() => app.unmount()); + const { useGlobeActionsStore } = await import('./stores/globeActions.js'); + const calls = []; + useGlobeActionsStore(pinia).connect({ home: () => calls.push('home') }); + const logo = document.querySelector('#title-bar h1 > button.title-logo'); + assert.ok(logo, 'the logo is the title heading’s button'); + assert.equal( + logo.getAttribute('aria-label'), + 'Back to live at the starting view', + ); + assert.ok(logo.hasAttribute('data-logo-gaze')); + logo.click(); + assert.deepEqual(calls, ['home']); +}); + +test('the title heading keeps its own name beside the logo button', async (t) => { + document.body.replaceChildren(); + const app = createApp(SceneChromeView).use(createPinia()); + app.mount(document.body.appendChild(document.createElement('div'))); + t.after(() => app.unmount()); + const heading = document.querySelector('#title-bar h1'); + const named = document.getElementById( + heading.getAttribute('aria-labelledby'), + ); + assert.equal(named.textContent.replace(/\s+/g, ' ').trim(), "GOD'S EYE VIEW"); +}); diff --git a/src/ui/layerBindings.js b/src/ui/layerBindings.js index 14bda13bdb..edad0c7bc1 100644 --- a/src/ui/layerBindings.js +++ b/src/ui/layerBindings.js @@ -158,6 +158,15 @@ export class LayerBindings { }); this._weatherShellModules.push(news); } + // Bike share flies into a covered city from its marker the same way. + const bikeshare = this._dataManager?.layers?.get('bikeshare')?.module; + if (typeof bikeshare?.attachShellServices === 'function') { + bikeshare.attachShellServices({ + runNavigation: (navigate) => + this.runImmediateNavigation('bike share', navigate), + }); + this._weatherShellModules.push(bikeshare); + } } _persistAwarenessSelection(event, cleared = false) { diff --git a/src/ui/locationNavigation.js b/src/ui/locationNavigation.js index e11447f033..233a314cab 100644 --- a/src/ui/locationNavigation.js +++ b/src/ui/locationNavigation.js @@ -3,6 +3,7 @@ import { stopFollowing } from '../data/followed.js'; import { t } from '../i18n/index.js'; import { createStateChannel } from '../app/stateChannel.js'; import { LocationControls } from './location.js'; +import { worldClock } from '../time/worldClock.js'; /** Own destination selection, lookup, orbit and world-jump lifetime. */ export class LocationNavigation { @@ -14,10 +15,11 @@ export class LocationNavigation { navigation, readCockpit, operations, + homeView = null, }) { Object.assign( this, - { viewer, placeSearch, services, navigation, readCockpit }, + { viewer, placeSearch, services, navigation, readCockpit, homeView }, elements, operations, ); @@ -315,7 +317,24 @@ export class LocationNavigation { } } - resetToGlobeView() { + /** + * Back to live, at the view the app started from (the logo): the world + * clock goes live and the camera flies to the start view as the globe reset + * does, letting go of whatever it follows. + */ + returnToStart() { + if (!this._disposed) worldClock.goLive(); + if (!this.homeView) return this.resetToGlobeView(); + // A globe reset under way flies elsewhere: this one replaces it. + this._cancelGlobeReset?.(); + return this.resetToGlobeView({ view: this.homeView }); + } + + /** + * Fly out to the full globe over the current spot, or to `view` (the start + * view's shape: `{ lon, lat, height, heading?, pitch? }`, degrees). + */ + resetToGlobeView({ view = null } = {}) { const { GLOBE_VIEW, flyToGlobeView, @@ -374,6 +393,7 @@ export class LocationNavigation { camera?.release(); this._beginWorldJumpTransition(); + const heightM = view?.height ?? GLOBE_VIEW.heightM; let resolveReset; const resetPromise = new Promise((resolve) => { resolveReset = resolve; @@ -391,7 +411,7 @@ export class LocationNavigation { ok: !cancelled, action: 'zoom_to_globe', cancelled, - heightKm: Math.round(GLOBE_VIEW.heightM / 1000), + heightKm: Math.round(heightM / 1000), centeredOn: { latitude: Number.isFinite(pose?.lat) ? Number(pose.lat.toFixed(2)) @@ -409,15 +429,13 @@ export class LocationNavigation { this._cancelGlobeReset = () => finish(true); timer = window.setTimeout(() => { const height = findCamera(this.viewer)?.pose().height; - finish( - !Number.isFinite(height) || - Math.abs(height - GLOBE_VIEW.heightM) > 1000, - ); + finish(!Number.isFinite(height) || Math.abs(height - heightM) > 1000); }, 4200); this._publishGlobeResetting?.(true); const target = flyToGlobeView(this.viewer, { onComplete: () => finish(false), onCancel: () => finish(true), + ...(view ? { view } : {}), }); if (!target) finish(true); return resetPromise; diff --git a/src/ui/news/NewsFeed.vue b/src/ui/news/NewsFeed.vue index 47e55c10f0..4c608f0fbd 100644 --- a/src/ui/news/NewsFeed.vue +++ b/src/ui/news/NewsFeed.vue @@ -1,6 +1,6 @@