mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-24 04:02:19 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
170b817679 | ||
|
|
d50f04efeb | ||
|
|
43bd25382d | ||
|
|
1f105a68af | ||
|
|
ec2f7d8ca7 | ||
|
|
51bf3d0807 | ||
|
|
d303d48693 | ||
|
|
e51853de3d | ||
|
|
46f8ea16c0 | ||
|
|
3973772b83 | ||
|
|
8604968746 | ||
|
|
1f64a9ce44 | ||
|
|
8fd0a35f6a | ||
|
|
e71ed72272 | ||
|
|
5555aba82c | ||
|
|
fc137bef85 | ||
|
|
ccffaeca4d | ||
|
|
154d3388e5 | ||
|
|
fb3f921ac7 | ||
|
|
797bd25841 | ||
|
|
5f1c230b52 | ||
|
|
6b216b3534 | ||
|
|
b2a6aa4d9f | ||
|
|
7b76525528 | ||
|
|
eeda6d51d1 | ||
|
|
9924cb15eb | ||
|
|
d60f2420f4 | ||
|
|
9a34d63f1d | ||
|
|
ca14954636 |
No files matched your search
+1
-1
@@ -44,7 +44,7 @@ How to read this:
|
||||
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
|
||||
| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" |
|
||||
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
|
||||
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
|
||||
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts; perimeters are coloured by when they were mapped (`poly_PolygonDateTime`, else the record's last edit `poly_DateCurrent`, which also moves when only the incident's attributes are edited, so such a fire can look newly grown) | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
|
||||
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
|
||||
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
|
||||
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
|
||||
|
||||
@@ -443,7 +443,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
|
||||
| ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) |
|
||||
| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 |
|
||||
| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 |
|
||||
| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 |
|
||||
| 🔥 **Fire Perimeters** | Incident boundaries coloured by how recently they were mapped; size, containment and cause on each card when the source reports them | WFIGS / NIFC | 🟢 |
|
||||
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
|
||||
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
|
||||
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
- Recent Imagery takes a box dragged across the dateline as the short box across
|
||||
±180° instead of refusing it as about 360° wide. A day counts when either side
|
||||
has imagery. A side confirmed empty is not draped, and the VIIRS overview
|
||||
drapes only a side confirmed to have data. Voice accepts named areas across
|
||||
the dateline. EXPORT and `get_recent_imagery` refuse such a box, since
|
||||
Worldview Snapshots cannot draw one (Byrd-IT, #1540).
|
||||
@@ -1,4 +0,0 @@
|
||||
- Quantized-mesh terrain can supply its tiles through `fetchTile`, as `xyz`
|
||||
imagery does: Cesium still reads `layer.json`, schedules, cancels and
|
||||
decodes the tiles, and a `missing` tile draws its parent's terrain there
|
||||
(samehkhamis, #1902).
|
||||
@@ -0,0 +1,8 @@
|
||||
- Color Fire Perimeters by how recently each area was mapped instead of by
|
||||
containment: each burned-area piece is yellow under 6 hours old, orange at
|
||||
6–24 hours, red at 1–3 days and dark red when older or of unknown age, with
|
||||
no line along the cuts between pieces. The legend counts fires by their last
|
||||
growth, the card adds "last growth … ago" and keeps containment, and
|
||||
`get_fire_perimeters` returns `last_growth`. A perimeter source now has one
|
||||
`getSnapshot` method, and `perimeterOptions: { inciweb: false }` turns off
|
||||
InciWeb links (gekh, #1910).
|
||||
@@ -0,0 +1,4 @@
|
||||
- Stop restyling the whole page on every DOM change. Rules that checked
|
||||
`body:has(...)` now read classes on the page root that the components owning
|
||||
that state set, and the Intel HUD runs no timers and writes nothing while it
|
||||
is not displayed (samehkhamis, #1911).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Leave the clock at live when Play is pressed at live. Play used to jump to
|
||||
the start of the track and play the whole range from there; paused in the
|
||||
past it still plays from that time (samehkhamis, #1915).
|
||||
+27
-22
@@ -1123,17 +1123,18 @@ Catalog calls check their cancellation signal immediately before executing a
|
||||
tool. Already-cancelled queries do not start; cancellation after execution starts
|
||||
continues to follow the existing tool and caller behavior.
|
||||
|
||||
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
|
||||
longitudes, matching the short-edge convention used for boundary intersections.
|
||||
An outline crossing ±180° contains nearby boxes and radius areas without also
|
||||
containing their counterparts near Greenwich. Returned perimeter coordinates
|
||||
use a circular mean for longitude, including multipart outlines. Incident cards
|
||||
also use a circular longitude mean over the largest outer ring (excluding its
|
||||
repeated closing vertex). Their relative-area comparison follows short longitude
|
||||
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
|
||||
Regression coverage lives in `src/tools/area.test.mjs`,
|
||||
`src/tools/queries/environment.test.mjs` and
|
||||
`src/layers/perimeters/cards.test.mjs`.
|
||||
Fire-perimeter queries test the polygon interiors and holes of each fire's
|
||||
pieces on continuous unwrapped longitudes, matching the short-edge convention
|
||||
used for boundary intersections: a fire is in the area when one of its pieces
|
||||
is. An outline crossing ±180° contains nearby boxes and radius areas without
|
||||
also containing their counterparts near Greenwich. A fire is returned at its
|
||||
card anchor, which the source gives; for WFIGS it is a circular longitude mean
|
||||
over the largest outer ring (excluding its repeated closing vertex), with the
|
||||
relative-area comparison following short longitude edges so a small
|
||||
dateline-crossing part cannot outweigh a larger ordinary part. Context's
|
||||
hazard list measures distance to the same anchor. Regression coverage lives in
|
||||
`src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs` and
|
||||
`src/layers/perimeters/records.test.mjs`.
|
||||
|
||||
## Scope display controls
|
||||
|
||||
@@ -6326,7 +6327,12 @@ Historical planning documents may not match runtime behavior.
|
||||
## Runtime Stack
|
||||
|
||||
- Vite + CesiumJS app with Google Photorealistic 3D Tiles
|
||||
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`
|
||||
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`. While `#intel-hud` is
|
||||
not displayed (it or a parent has `display: none`, or its view is
|
||||
unmounted), the Intel HUD runs no timers, drops a summary it was working
|
||||
out and publishes no readouts, only its own `active`, variant and colors,
|
||||
which stylesheets and layout elsewhere read; it shows current readouts, and
|
||||
a reply that was typing out in full, as soon as it is displayed again.
|
||||
- Layer management in `src/data/manager.js`
|
||||
- Map stack switching in `src/mapStackController.js`
|
||||
- Voice control in `src/voice/` (OpenAI Realtime over WebRTC)
|
||||
@@ -6404,7 +6410,11 @@ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
|
||||
anchors, recovery, keyboard and mobile states; emergency repainting is covered
|
||||
by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
|
||||
|
||||
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
|
||||
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Link checks cancel on disable or selection change.
|
||||
|
||||
Fire Perimeters draws the fires and burned-area pieces of its source's snapshot. The `getSnapshot` contract is documented in the JSDoc of `createFirePerimetersLayer` (`src/layers/perimeters/index.js`). Pieces are coloured by age at `at` (or now). Areas under 6 hours old are yellow, 6–24 hours orange, and 1–3 days red. Older areas, areas of unknown age and areas dated after `at` are dark red. The layer redraws when `revision` changes or a piece moves to another age band. A snapshot without a string `revision` is redrawn on every read. The legend counts fires by `lastGrowthTime` at the moment of the last successful read, matching the map, and shows the source's `note`. A failed read keeps the last picture and the row shows the error. For a snapshot with a past `at`, a card can link only to an InciWeb incident that began by that time. Of several same-name incidents in the fire's state, it links the one that began nearest the fire's discovery. If none of them began by then, or the ones that did failed to load, it links the fire's complex page by the same rule. A page that fails to load is skipped until the fire is selected again or a read finds its card without a link. `analyst_query` counts `ageHours` from `at` too and treats times after `at` as unknown.
|
||||
|
||||
WFIGS keeps one current perimeter per fire, so each of its polygons is one piece. Colour shows the age of the perimeter based on `poly_PolygonDateTime`. When that field is empty (8 of 54 fires on 2026-11-20), the source falls back to `poly_DateCurrent`, which changes with any edit to the record. A time more than 10 minutes ahead of the browser clock counts as unknown, a nearer one as now. The `revision` follows fire ids and `poly_DateCurrent`. For a fire without `poly_DateCurrent`, it follows the mapping time and outline. WFIGS snapshots always have `at: null`.
|
||||
|
||||
The incident card rounds the WFIGS size to whole acres, except under one acre,
|
||||
where it keeps the reported hundredths: a 0.25-acre fire reads `0.25 ac`, not
|
||||
@@ -8890,10 +8900,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool,
|
||||
pins and share links already supply complete boxes.
|
||||
|
||||
- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.
|
||||
- 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.
|
||||
- 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. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. 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 and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. 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. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. 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. 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.
|
||||
- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `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. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), 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).
|
||||
@@ -9924,12 +9934,7 @@ unless its plugin hands the application a map engine of its own
|
||||
terrain as `quantizedMesh` terrain at its URL (`src/maps/keylessTerrain.js`);
|
||||
while the keyless terrain does not answer, the ellipsoid stands in and the
|
||||
map stack tries it again behind it. A renderer without the `terrain`
|
||||
capability keeps the ellipsoid. A `quantizedMesh` terrain source can supply
|
||||
its tiles through `fetchTile`, like `xyz` imagery: Cesium still reads
|
||||
`layer.json` at the source's URL, schedules, cancels and decodes the tiles,
|
||||
and only each tile's bytes come from `fetchTile`; a `missing` tile draws its
|
||||
parent's terrain, a `defer`red one is asked for again shortly
|
||||
(`src/render/cesium/terrainTiles.js`).
|
||||
capability keeps the ellipsoid.
|
||||
|
||||
A viewer with no renderer bound gets the Cesium engine
|
||||
(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the
|
||||
|
||||
@@ -872,4 +872,4 @@ course. The stub keeps no drawn course. These wait for scenes that capture
|
||||
an icon mid-turn. Height queries that count a set
|
||||
(`includeInHeightQueries`) are not checked either: the stub's heights are
|
||||
scripted, so it does not model them. Nor are video frames (a check needs a
|
||||
video) or `fetchTile`, imagery's or terrain's (the stub fetches nothing).
|
||||
video) or `fetchTile` (the stub fetches nothing).
|
||||
+1
-1
@@ -310,7 +310,7 @@ and the development server's internal routes. See SECURITY.md.
|
||||
| `get_bhote_koshi_flood` | `events` | The 2026 Bhote Koshi flood: evidence trail in story order, flood path and imagery dates (CC BY-NC 4.0) |
|
||||
| `get_regional_brief` | `regional` | What and where a location is, its weather and recent headlines |
|
||||
| `get_cyclones` | `cyclones` | Active NHC/CPHC tropical cyclones, optionally in an area |
|
||||
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first |
|
||||
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first, with when each was last mapped (WFIGS mapping time, else the record's last edit) |
|
||||
| `get_terrain_height` | `terrain` | Ground, geoid and ellipsoid heights at up to 20 points |
|
||||
| `find_military_installations` | `installations` | OpenStreetMap military sites in an area of at most 10° per side |
|
||||
| `get_map_features` | `features` | Administrative areas, named places or monuments at a location (needs Overpass) |
|
||||
|
||||
+28
-1
@@ -629,7 +629,12 @@ slot whenever its view is drawn.
|
||||
store, which IntelHUD publishes to through its `publish` option: the
|
||||
readouts, the typing summary, the REC blink, visibility, layout variant
|
||||
and style colors; the vessel layer presents the selected vessel's
|
||||
readout through `src/hudReadouts.js` instead of writing into the HUD),
|
||||
readout through `src/hudReadouts.js` instead of writing into the HUD;
|
||||
the view reports through the store whether `#intel-hud` is displayed
|
||||
(not displayed once it is unmounted), and while it is not IntelHUD runs
|
||||
no timers and publishes only the root's `active`, variant and colors,
|
||||
then shows current readouts as soon as it is; the readouts that change many times a
|
||||
second keep their text node through `v-text-data`),
|
||||
the first-run mission launcher (the welcome view renders the card's
|
||||
visibility, busy state, status line, copy and scroll fade from the
|
||||
`gev-first-run` store that `initFirstRunExperience` publishes to, and its
|
||||
@@ -700,6 +705,28 @@ slot whenever its view is drawn.
|
||||
hosts to register panels and rail items is deferred until a host needs
|
||||
one.
|
||||
|
||||
## Page-root state classes
|
||||
|
||||
A stylesheet that styles one surface by the state of another, in a different
|
||||
view (the dock and credits while the Omnibar is on the page, the Stories
|
||||
entry while the loading screen shows), selects a class on `<html>` rather
|
||||
than `body:has(...)`. Chrome checks a `:has()` on body again after every node
|
||||
added or removed anywhere on the page and restyles the whole page when it
|
||||
does; a class changes only with the state it names. `src/ui/rail/rootClass.js`
|
||||
holds them: `v-root-class` on the element whose presence or state it names
|
||||
(the Omnibar, the voice control in the dock, `#intel-hud`, the first-run
|
||||
launcher, the World Timeline, the language picker), its hooks running inside
|
||||
Vue's patch so the class changes with the element; `followSelectorRootClass()`
|
||||
for markup Vue does not render (the loading screen, followed by the Stories
|
||||
view wherever in body it is added, removed or shown, as `:has()` would); and
|
||||
`followRootClass()` for nodes that move at run time (the left panel stack's
|
||||
own panels, followed by the layer panels view). They live on `<html>`, not
|
||||
`<body>`, whose class changes several owners follow to lay the page out
|
||||
again. A rule selects one as `body:is(.has-omnibar *, #gev-omnibar)`: the
|
||||
second argument never matches body and keeps the specificity the
|
||||
`:has(#gev-omnibar)` it replaced had. `src/ui/pageRootClasses.test.mjs`
|
||||
holds each class to its state and every stylesheet to the pattern.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit tests: stores and components run under `npm test`. Single-file
|
||||
|
||||
@@ -78,8 +78,6 @@
|
||||
"src/render/cesium/uploadProbe.test.mjs",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
"src/render/cesium/tileRequests.test.mjs",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/terrainTiles.test.mjs",
|
||||
"src/queries/heights.test.mjs",
|
||||
"src/render/cesium/heights.test.mjs",
|
||||
"src/render/cesium/drawLineAges.test.mjs",
|
||||
@@ -471,6 +469,8 @@
|
||||
"src/layers/perimeters/cards.test.mjs",
|
||||
"src/layers/perimeters/inciweb.test.mjs",
|
||||
"src/layers/perimeters/ownership.test.mjs",
|
||||
"src/app/layers/perimeters.test.mjs",
|
||||
"src/ui/spotConditions.test.mjs",
|
||||
"src/layers/droneAirspace/index.js",
|
||||
"src/layers/droneAirspace/records.js",
|
||||
"src/layers/droneAirspace/source.js",
|
||||
@@ -1449,6 +1449,7 @@
|
||||
"src/hudReadouts.js",
|
||||
"src/ui/stores/hud.js",
|
||||
"src/ui/views/intelHudView.test.mjs",
|
||||
"src/ui/pageRootClasses.test.mjs",
|
||||
"src/testSupport/hudReadouts.mjs",
|
||||
"src/ui/stores/firstRun.js",
|
||||
"src/firstRunLauncherView.test.mjs",
|
||||
|
||||
@@ -194,6 +194,8 @@
|
||||
"src/ui/stores/owners.js",
|
||||
"src/ui/rail/rangeValue.js",
|
||||
"src/ui/rail/classToggle.js",
|
||||
"src/ui/rail/rootClass.js",
|
||||
"src/ui/rail/textData.js",
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/rail/fieldValue.js",
|
||||
"src/ui/rail/statusText.js",
|
||||
@@ -279,6 +281,7 @@
|
||||
"src/i18n/marker.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/layers/perimeters/source.js",
|
||||
"src/layers/perimeters/records.js",
|
||||
"src/ui/spotConditions.js",
|
||||
"src/ui/views/panels/SpotConditions.vue",
|
||||
"src/data/wikidataCities.js",
|
||||
@@ -1387,7 +1390,6 @@
|
||||
"src/render/cesium/effects.js",
|
||||
"src/render/cesium/screenModulation.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
"src/render/cesium/imageryFrames.js",
|
||||
@@ -2435,7 +2437,6 @@
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/cesium/effects.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/query.js",
|
||||
"src/render/cesium/quality.js",
|
||||
"src/render/input/wheel.js",
|
||||
@@ -2534,7 +2535,6 @@
|
||||
"src/render/stub/math.js",
|
||||
"src/render/cesium/unbound.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
@@ -3224,7 +3224,6 @@
|
||||
"src/sources/requestDeadline.js",
|
||||
"src/layers/traffic/lifecycle.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
@@ -3390,7 +3389,6 @@
|
||||
"modules": [
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
"src/render/cesium/imageryFrames.js",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
@@ -3972,7 +3970,6 @@
|
||||
"src/maps/catalog.js",
|
||||
"src/maps/controller.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
@@ -4286,7 +4283,6 @@
|
||||
"src/render/motion/iconMotion.js",
|
||||
"src/render/cesium/query.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/drawHit.js",
|
||||
"src/render/cesium/draw.js",
|
||||
@@ -4859,6 +4855,7 @@
|
||||
"src/ui/layerRowText.js",
|
||||
"src/ui/layerPanel/LayerRows.vue",
|
||||
"src/ui/rail/classToggle.js",
|
||||
"src/ui/rail/rootClass.js",
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/layerPanel/RowText.vue",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
@@ -6258,7 +6255,6 @@
|
||||
"src/layers/recentImagery/rendering.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/layers/recentImagery/thumbnails.js",
|
||||
"src/maps/imageryHost.js",
|
||||
"src/layers/streetLevel/index.js",
|
||||
@@ -8198,6 +8194,7 @@
|
||||
"src/data/militaryInstallationData.js",
|
||||
"src/layers/launches/source.js",
|
||||
"src/layers/perimeters/source.js",
|
||||
"src/layers/perimeters/records.js",
|
||||
"src/layers/radio/source.js",
|
||||
"src/layers/radio/policy.js",
|
||||
"src/layers/satellites/source.js",
|
||||
|
||||
@@ -23,6 +23,7 @@ const API_URL =
|
||||
'attr_IncidentTypeCategory',
|
||||
'attr_FireDiscoveryDateTime',
|
||||
'poly_DateCurrent',
|
||||
'poly_PolygonDateTime',
|
||||
'attr_FireCause',
|
||||
'attr_FireBehaviorGeneral',
|
||||
'attr_TotalIncidentPersonnel',
|
||||
|
||||
@@ -67,6 +67,8 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
|
||||
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
|
||||
* places live aircraft, vessels, transit and trains; without one each layer
|
||||
* uses its own motion.
|
||||
* `perimeterOptions: { inciweb: false }` leaves the Fire Perimeters cards
|
||||
* without InciWeb links, and the layer never asks InciWeb.
|
||||
*/
|
||||
export function createApplicationCatalog({
|
||||
surface,
|
||||
@@ -75,6 +77,7 @@ export function createApplicationCatalog({
|
||||
metadata = APPLICATION_LAYER_METADATA,
|
||||
vesselOptions,
|
||||
newsOptions,
|
||||
perimeterOptions,
|
||||
resolveAsset,
|
||||
nepalBoundaryResolver,
|
||||
streetLevelProviders,
|
||||
@@ -145,6 +148,7 @@ export function createApplicationCatalog({
|
||||
createApplicationEarthquakes({ source: sources.earthquakes }),
|
||||
createApplicationAirQuality({ source: sources['air-quality'] }),
|
||||
createApplicationFirePerimeters({
|
||||
...perimeterOptions,
|
||||
source: sources['fire-perimeters'],
|
||||
}),
|
||||
createApplicationGnssIntegrity({
|
||||
|
||||
@@ -7,6 +7,8 @@ import { catalogControlServices } from './catalog.js';
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
|
||||
import { worldClock } from '../time/worldClock.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
@@ -254,3 +256,48 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
|
||||
`${String(windowMs)} falls back to the default`,
|
||||
);
|
||||
});
|
||||
|
||||
test('perimeterOptions reach Fire Perimeters: inciweb false never asks InciWeb', async (t) => {
|
||||
const lifetime = new AbortController();
|
||||
const { signal } = lifetime;
|
||||
const sources = fixtureSources([], []);
|
||||
sources['fire-perimeters'] = {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
fetchedAt: null,
|
||||
stale: false,
|
||||
revision: 'r',
|
||||
note: null,
|
||||
fires: [],
|
||||
pieces: [],
|
||||
}),
|
||||
};
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return Response.json([]);
|
||||
});
|
||||
const viewer = { scene: { pick: () => null } };
|
||||
bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
const layer = createApplicationCatalog({
|
||||
sources,
|
||||
signal,
|
||||
surface: fixtureSurface(signal),
|
||||
perimeterOptions: { inciweb: false, inputFor: () => input.input },
|
||||
}).get('fire-perimeters');
|
||||
t.after(() => {
|
||||
layer.destroy();
|
||||
input.destroy();
|
||||
lifetime.abort();
|
||||
worldClock.goLive();
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
assert.equal(await layer.update(viewer), true);
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(
|
||||
requested.filter((url) => url.includes('inciweb')),
|
||||
[],
|
||||
);
|
||||
});
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
/** Wire fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters({
|
||||
inciweb = true,
|
||||
...options
|
||||
} = {}) {
|
||||
return createFirePerimetersLayer({
|
||||
overlayHost: {
|
||||
setEntries: overlays.setOverlayEntries,
|
||||
@@ -15,10 +18,17 @@ export function createApplicationFirePerimeters(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
...(inciweb !== false && {
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
}),
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
picking,
|
||||
...options,
|
||||
// inciweb: false outranks InciWeb sources in options.
|
||||
...(inciweb === false && {
|
||||
inciwebSource: null,
|
||||
inciwebPublications: null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createApplicationFirePerimeters } from './perimeters.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
[-108.0, 35.2],
|
||||
[-108.0, 35.3],
|
||||
[-108.1, 35.2],
|
||||
];
|
||||
const source = {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
fetchedAt: null,
|
||||
stale: false,
|
||||
revision: 'r',
|
||||
note: null,
|
||||
fires: [{ id: 'f', name: 'Fixture', anchor: { lon: -108.05, lat: 35.25 } }],
|
||||
pieces: [{ fireId: 'f', born: null, polygons: [[ring]], outline: [ring] }],
|
||||
}),
|
||||
};
|
||||
|
||||
for (const inciweb of [true, false]) {
|
||||
test(`inciweb: ${inciweb} ${inciweb ? 'asks' : 'never asks'} InciWeb`, async (t) => {
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return Response.json([]);
|
||||
});
|
||||
const viewer = { scene: { pick: () => null } };
|
||||
bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
t.after(() => input.destroy());
|
||||
const getIndex = t.mock.fn(async () => []);
|
||||
const layer = createApplicationFirePerimeters({
|
||||
source,
|
||||
inciweb,
|
||||
...(inciweb === false && { inciwebSource: { getIndex } }),
|
||||
inputFor: () => input.input,
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
assert.equal(await layer.update(viewer), true);
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(
|
||||
requested.filter((url) => url.includes('inciweb')),
|
||||
inciweb ? ['/api/fire-perimeters/inciweb/index'] : [],
|
||||
);
|
||||
assert.equal(getIndex.mock.callCount(), 0);
|
||||
layer.destroy(viewer);
|
||||
});
|
||||
}
|
||||
+3
-1
@@ -39,6 +39,7 @@ import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
|
||||
import {
|
||||
getRenderGovernorDiagnostics,
|
||||
governorRequestRender,
|
||||
FOLLOW_FRAME_RATE,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
@@ -273,7 +274,8 @@ export function createApplicationTools({
|
||||
// The follow camera recomputes the tracked target's dead-reckon position
|
||||
// every frame — tracking anything is a per-frame animation. (perf wave 2)
|
||||
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
|
||||
if (followed) holdContinuousRender('tracked-entity');
|
||||
if (followed)
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
else releaseContinuousRender('tracked-entity');
|
||||
});
|
||||
|
||||
|
||||
@@ -243,7 +243,7 @@ const RECOGNIZED = new Set([
|
||||
// credit
|
||||
'#cesium-credits',
|
||||
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
|
||||
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits",
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits",
|
||||
'body.ui-clean-view #cesium-credits',
|
||||
'body.recording-mode #cesium-credits',
|
||||
// dock
|
||||
@@ -274,12 +274,12 @@ const DOCKED_RAIL = 'body.context-docked #right-context-rail';
|
||||
// the Omnibar and the voice control share the dock; outside it the legacy
|
||||
// layout below governs.
|
||||
const OMNIBAR_SCOPE =
|
||||
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(:has(#gev-omnibar):has(#command-dock > #gev-voice-control))';
|
||||
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(.has-omnibar.dock-has-voice *)';
|
||||
const OMNIBAR = Object.freeze({
|
||||
dock: `${OMNIBAR_SCOPE} #command-dock`,
|
||||
credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`,
|
||||
minimalCredit: `${OMNIBAR_SCOPE}:has(#intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
|
||||
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) #right-context-rail`,
|
||||
minimalCredit: `${OMNIBAR_SCOPE}:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
|
||||
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #right-context-rail`,
|
||||
trays: `${OMNIBAR_SCOPE} #command-dock > :is(#location-bar, #control-panel)`,
|
||||
});
|
||||
// What each Omnibar-scope rule may set on a modelled box; the Omnibar
|
||||
@@ -518,7 +518,7 @@ const CREDIT_SELECTORS = [
|
||||
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
|
||||
];
|
||||
const MINIMAL_HUD_CREDIT =
|
||||
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits";
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits";
|
||||
const TRAY_ORDINARY = [
|
||||
'#command-dock .dock-popover-content',
|
||||
'#command-dock #location-bar .dock-popover-content',
|
||||
@@ -1279,7 +1279,7 @@ test('expanded Context keeps the credits beside it right to left and with the mi
|
||||
// The minimal HUD puts the credits bottom right, where the column docks.
|
||||
assert.ok(
|
||||
rule(
|
||||
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):has\\( #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
|
||||
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):is\\( \\.hud-minimal-active \\*, #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
|
||||
'right: calc\\(36px \\+ var\\(--context-dock-width\\)\\)',
|
||||
),
|
||||
'with the minimal HUD, the credits end before the expanded column',
|
||||
|
||||
@@ -10,6 +10,7 @@ import { straightSegment } from './fixCurve.js';
|
||||
import {
|
||||
norm180,
|
||||
distance,
|
||||
distanceSquared,
|
||||
clone,
|
||||
copyInto,
|
||||
toDegrees,
|
||||
@@ -385,8 +386,32 @@ let instances = 0;
|
||||
/** A plan that ran out longer ago than this (ms) is not eased away from. */
|
||||
const RECOVER_STALE_PLAN_MS = 1_000;
|
||||
|
||||
/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
|
||||
/** How far ahead (ms) a placed contact's segment runs before it is asked
|
||||
* again, in view and near the eye. */
|
||||
const PLACED_PLAN_MS = 1000;
|
||||
/** The same out of view, or farther than PLACED_NEAR_M from the eye: off
|
||||
* screen a contact's path is not seen, and that far a straight segment
|
||||
* over this long (half as long again at most, as spread) is well under a
|
||||
* pixel off it. Asking for each contact every second would rewrite the
|
||||
* whole fleet every second. */
|
||||
const PLACED_FAR_PLAN_MS = 4000;
|
||||
/** Nearer the eye than this (m), a placed contact in view is planned every
|
||||
* PLACED_PLAN_MS. */
|
||||
const PLACED_NEAR_M = 300_000;
|
||||
|
||||
/**
|
||||
* Each contact's plans run between 1/2 and 3/2 of their length, by its id,
|
||||
* so the fleet's plans run out spread over the passes, not together in one
|
||||
* (contacts first planned in the same pass would otherwise stay in step).
|
||||
*/
|
||||
export function placedPlanSpread(id) {
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < id.length; i++) {
|
||||
hash ^= id.charCodeAt(i);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return 0.5 + ((hash >>> 0) % 1024) / 1024;
|
||||
}
|
||||
|
||||
/** A display delay that never changes (ms). */
|
||||
function fixedDelay(ms) {
|
||||
@@ -465,6 +490,8 @@ export function createAircraftIcons({
|
||||
* @type {Map<string, {drawn: number, checked: number}>}
|
||||
*/
|
||||
const rotors = new Map();
|
||||
/** When a rotor in view was last given a new frame (wall ms). */
|
||||
let rotorDrawnAtMs = -Infinity;
|
||||
|
||||
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
|
||||
const _displayMs = () =>
|
||||
@@ -492,7 +519,8 @@ export function createAircraftIcons({
|
||||
const motionClock = (scene) =>
|
||||
scene
|
||||
? { kind: 'scene' }
|
||||
: { kind: 'live', delayMs: displayDelay.currentMs };
|
||||
: // The layer's pace asks for the frames its moving rows need.
|
||||
{ kind: 'live', delayMs: displayDelay.currentMs, frames: 'owner' };
|
||||
|
||||
/**
|
||||
* Once a frame: move the display delay on, and put the set's motion on
|
||||
@@ -815,12 +843,28 @@ export function createAircraftIcons({
|
||||
planFrom.set(icao24, validFrom);
|
||||
}
|
||||
|
||||
/** The camera, while the fleet pass re-plans the rows that ran out:
|
||||
* `{eye, inView(position)}` (null: every plan is a near one). */
|
||||
let planView = null;
|
||||
|
||||
/** How long a placed contact at `position` is planned for (ms). */
|
||||
function _placedPlanMs(icao24, position) {
|
||||
const near =
|
||||
!planView ||
|
||||
(distanceSquared(planView.eye, position) <
|
||||
PLACED_NEAR_M * PLACED_NEAR_M &&
|
||||
planView.inView(position));
|
||||
return (
|
||||
(near ? PLACED_PLAN_MS : PLACED_FAR_PLAN_MS) * placedPlanSpread(icao24)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan a live contact a host-supplied placement places: from where it
|
||||
* places it at `t` (display ms, the live clock's delayed time) to where it
|
||||
* places it PLACED_PLAN_MS on, asked again when that runs out. Display
|
||||
* time is wall time less the display delay, so the placement is asked at
|
||||
* the wall times the segment's ends stand for.
|
||||
* places it a plan's length on (`_placedPlanMs`), asked again when that
|
||||
* runs out. Display time is wall time less the display delay, so the
|
||||
* placement is asked at the wall times the segment's ends stand for.
|
||||
* @returns {boolean} False when there is no placement, the layer follows
|
||||
* the world clock, or it has no answer for this contact.
|
||||
*/
|
||||
@@ -839,7 +883,7 @@ export function createAircraftIcons({
|
||||
)
|
||||
return true;
|
||||
easeEnds.delete(icao24);
|
||||
const t1 = t + PLACED_PLAN_MS;
|
||||
const t1 = t + _placedPlanMs(icao24, from);
|
||||
const to = vec();
|
||||
const end = placeAt(icao24, t1 + leadMs, info, history, to);
|
||||
const motion = end
|
||||
@@ -903,12 +947,17 @@ export function createAircraftIcons({
|
||||
* moved back (a seek, or the clock run backward): it is drawn where it was
|
||||
* then, as it is when the time moves on.
|
||||
*/
|
||||
function _replanExpired(t) {
|
||||
if (followsClock() && t < replannedAt)
|
||||
for (const [icao24, from] of planFrom)
|
||||
if (from > t) _planIcon(icao24, { rewound: true });
|
||||
replannedAt = t;
|
||||
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
|
||||
function _replanExpired(t, view = null) {
|
||||
planView = view;
|
||||
try {
|
||||
if (followsClock() && t < replannedAt)
|
||||
for (const [icao24, from] of planFrom)
|
||||
if (from > t) _planIcon(icao24, { rewound: true });
|
||||
replannedAt = t;
|
||||
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
|
||||
} finally {
|
||||
planView = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -930,6 +979,7 @@ export function createAircraftIcons({
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
const eye = viewer ? findCamera(viewer)?.pose()?.position : null;
|
||||
let active = 0;
|
||||
let fading = 0;
|
||||
for (const id of icons.ids()) {
|
||||
if (!icons.shown(id) && !state._models.has(id)) continue;
|
||||
const item = icons.item(id);
|
||||
@@ -952,10 +1002,13 @@ export function createAircraftIcons({
|
||||
spriteHalfHeightPx: item.size[1] * half,
|
||||
});
|
||||
if (focus.active || focus.transitioning) active++;
|
||||
if (focus.transitioning) fading++;
|
||||
if (focusAlphaNeedsWrite(current, focus.factor))
|
||||
icons.setFocus(id, focus.factor);
|
||||
}
|
||||
state._iconFocusActive = active;
|
||||
// Rows still fading in or out, for the layer's pace.
|
||||
state._iconFocusFading = fading;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1043,6 +1096,7 @@ export function createAircraftIcons({
|
||||
if (!_aboveHorizon(position, occluder)) continue;
|
||||
if (inView && !inView(position)) continue;
|
||||
rotor.drawn = frame;
|
||||
rotorDrawnAtMs = nowMs;
|
||||
if (tracked) {
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
continue;
|
||||
@@ -1106,6 +1160,11 @@ export function createAircraftIcons({
|
||||
return rotors.size > 0;
|
||||
}
|
||||
|
||||
/** When a rotor in view was last given a new frame (wall ms), for the pace. */
|
||||
function _rotorDrawnAtMs() {
|
||||
return rotorDrawnAtMs;
|
||||
}
|
||||
|
||||
/** Add a row for a new contact, hidden while it is the tracked one. */
|
||||
function _addIcon(icao24) {
|
||||
state._icons.put(_baseItem(icao24, icao24 !== state._trackedIcao), {
|
||||
@@ -1178,6 +1237,7 @@ export function createAircraftIcons({
|
||||
_fleetLook,
|
||||
_turnRotors,
|
||||
_rotorsTurning,
|
||||
_rotorDrawnAtMs,
|
||||
_addIcon,
|
||||
_forgetContact,
|
||||
_iconIds,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createAircraftIcons,
|
||||
createContactIcons,
|
||||
floorCoastArc,
|
||||
placedPlanSpread,
|
||||
} from './aircraftIconLayer.js';
|
||||
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
|
||||
@@ -37,7 +38,11 @@ test('following the world clock, contacts draw at the world’s time on the scen
|
||||
icons._createIcons(viewer);
|
||||
const set = draw.find('flights-icons:');
|
||||
// Live: a poll interval behind real time, on the delayed live clock.
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.equal(icons._displayMs(), Date.now() - 30_000);
|
||||
following = true;
|
||||
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
|
||||
@@ -45,7 +50,11 @@ test('following the world clock, contacts draw at the world’s time on the scen
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
|
||||
following = false;
|
||||
icons._syncMotionClock();
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -68,7 +77,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
});
|
||||
icons._createIcons(viewer);
|
||||
const set = draw.find('flights-icons:');
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
// Reports 90 s old every 30 s: the delay heads for about two minutes.
|
||||
for (let i = 0; i < 20; i++)
|
||||
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
|
||||
@@ -76,7 +89,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
t.mock.timers.setTime(WORLD_MS + 10_000);
|
||||
icons._syncMotionClock();
|
||||
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 32_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.equal(icons._displayMs(), Date.now() - 32_000);
|
||||
// Following the world clock: no delay, and it is not moved on meanwhile.
|
||||
following = true;
|
||||
@@ -87,7 +104,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
assert.equal(delay.currentMs, 32_000);
|
||||
following = false;
|
||||
icons._syncMotionClock();
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 34_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -481,3 +502,110 @@ test('back at live, a placed contact eases from where it is drawn over a recover
|
||||
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
|
||||
);
|
||||
});
|
||||
|
||||
/** A layer whose placement has every contact flying east from `at(id)`. */
|
||||
function placedFleet(ids, at) {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
|
||||
records: { data: new Map(ids.map((id) => [id, {}])) },
|
||||
};
|
||||
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, at(id, wallMs));
|
||||
return { courseDeg: 90, speedMps: 200 };
|
||||
},
|
||||
});
|
||||
for (const id of ids)
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: at(id, WORLD_MS),
|
||||
motion: { kind: 'hold', courseDeg: 90 },
|
||||
course: 90,
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
);
|
||||
return { icons, set: state._icons };
|
||||
}
|
||||
|
||||
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const ids = Array.from({ length: 400 }, (_, i) =>
|
||||
(0xa00000 + i * 37).toString(16),
|
||||
);
|
||||
const { icons, set } = placedFleet(ids, () => fromDegrees(0, 30, 3_000));
|
||||
icons._replanExpired(Date.now());
|
||||
const ends = ids.map((id) => set.expires(id) - WORLD_MS);
|
||||
for (const ms of ends) assert.ok(ms >= 500 && ms < 1_500, `${ms} ms`);
|
||||
// An 80 ms pass (the fleet's tick) has an eighth of the fleet at most.
|
||||
const perPass = new Map();
|
||||
for (const ms of ends) {
|
||||
const pass = Math.floor(ms / 80);
|
||||
perPass.set(pass, (perPass.get(pass) ?? 0) + 1);
|
||||
}
|
||||
assert.ok(
|
||||
Math.max(...perPass.values()) <= ids.length / 8,
|
||||
`${Math.max(...perPass.values())} in one pass`,
|
||||
);
|
||||
// Planned again when it runs out, each runs as long as before, from then.
|
||||
const first = new Map(ids.map((id) => [id, set.expires(id)]));
|
||||
t.mock.timers.tick(1_500);
|
||||
icons._replanExpired(Date.now());
|
||||
for (const id of ids) {
|
||||
const item = set.item(id);
|
||||
assert.equal(item.motion.t0, Date.now(), id);
|
||||
assert.equal(
|
||||
set.expires(id) - Date.now(),
|
||||
first.get(id) - WORLD_MS,
|
||||
`${id} runs as long`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a placed contact far from the eye or out of view is planned for longer than a near one in view', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const where = {
|
||||
n: fromDegrees(0, 30, 3_000),
|
||||
f: fromDegrees(10, 30, 3_000),
|
||||
o: fromDegrees(0.01, 30, 3_000),
|
||||
};
|
||||
const ids = Object.keys(where);
|
||||
const { icons, set } = placedFleet(ids, (id) => where[id]);
|
||||
const eye = fromDegrees(0, 30, 60_000);
|
||||
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
// In view: all but 'o', told apart by where the placement puts it.
|
||||
const view = { eye, inView: (p) => metres(p, where.o) > 1 };
|
||||
const length = (id) =>
|
||||
(set.expires(id) - set.item(id).motion.t0) / placedPlanSpread(id);
|
||||
icons._replanExpired(Date.now(), view);
|
||||
assert.ok(Math.abs(length('n') - 1_000) < 1, `near ${length('n')}`);
|
||||
assert.ok(Math.abs(length('f') - 4_000) < 1, `far ${length('f')}`);
|
||||
assert.ok(Math.abs(length('o') - 4_000) < 1, `out of view ${length('o')}`);
|
||||
|
||||
// The camera is the pass's only: a contact planned after it, as a new
|
||||
// report plans it, takes a near plan, even after a pass that threw.
|
||||
icons._planIcon('f');
|
||||
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a pass ${length('f')}`);
|
||||
t.mock.timers.tick(5_000);
|
||||
assert.throws(() =>
|
||||
icons._replanExpired(Date.now(), {
|
||||
eye,
|
||||
inView: () => {
|
||||
throw new Error('camera gone');
|
||||
},
|
||||
}),
|
||||
);
|
||||
icons._planIcon('f');
|
||||
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
|
||||
});
|
||||
@@ -14,6 +14,12 @@ import {
|
||||
showModel,
|
||||
} from './modelRecord.js';
|
||||
import { modelDrawnScale } from './modelVisualAnchor.js';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
} from '../renderPace.js';
|
||||
import { ROTOR_FPS } from './rotorFrames.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { aircraftLayerPartState } from './modelPartDrivers.js';
|
||||
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
|
||||
@@ -119,6 +125,70 @@ export function createAircraftModels({
|
||||
let instances = 0;
|
||||
/** The fleet items this tick wrote, sent together when it ends. */
|
||||
let pendingItems = [];
|
||||
|
||||
// The pace: how often the fleet is drawn while nothing else draws
|
||||
// (renderPace.js). The icons move on the GPU, so a frame is all a move
|
||||
// takes; an airliner crosses a hundredth of a pixel a second on the whole
|
||||
// globe and hundreds from close by, so the rate follows the fastest icon
|
||||
// in view.
|
||||
const pace = createRenderPace({ owner: setPrefix, render: services.render });
|
||||
const screenSpeed = createScreenSpeed();
|
||||
/** How often the icons' on-screen speed is read, in ms. */
|
||||
const PACE_READ_MS = 250;
|
||||
/** Each icon's move is read over this much of its drawn path, in ms. */
|
||||
const PACE_SPAN_MS = 1000;
|
||||
/** While icons fade for a focus change, they are drawn this often. */
|
||||
const PACE_FADE_HZ = 20;
|
||||
/** A rotor drawn this recently is in view. */
|
||||
const PACE_ROTOR_SEEN_MS = 600;
|
||||
let paceReadMs = -Infinity;
|
||||
let pacePxPerSec = 0;
|
||||
|
||||
/**
|
||||
* The fastest icon in view's speed on screen, in pixels a second: each
|
||||
* shown icon's drawn position now and PACE_SPAN_MS on, which takes in a
|
||||
* new fix being blended in as well as its flight.
|
||||
*/
|
||||
function _readIconSpeed(pose) {
|
||||
const icons = state._icons;
|
||||
if (!icons || !screenSpeed.begin(pose, _viewport().height)) return 0;
|
||||
const t = parts.icons._displayMs();
|
||||
for (const id of icons.ids()) {
|
||||
if (!icons.shown(id)) continue;
|
||||
screenSpeed.add(
|
||||
icons.position(id, t),
|
||||
icons.position(id, t + PACE_SPAN_MS),
|
||||
);
|
||||
}
|
||||
return screenSpeed.pxPerSec(PACE_SPAN_MS / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a second the fleet needs as the camera stands (the pace clamps
|
||||
* it to its range). Infinity: as often as the pace allows.
|
||||
*/
|
||||
function _paceHz(nowMs = Date.now()) {
|
||||
const pose = _pose();
|
||||
if (!pose?.position) return Infinity;
|
||||
// Models, and the Cockpit's contacts, are moved on every frame.
|
||||
if (
|
||||
state._cockpitContactMode ||
|
||||
state._models.size ||
|
||||
_modelRegimeActive(pose)
|
||||
)
|
||||
return Infinity;
|
||||
if (nowMs - paceReadMs >= PACE_READ_MS) {
|
||||
paceReadMs = nowMs;
|
||||
pacePxPerSec = _readIconSpeed(pose);
|
||||
}
|
||||
let hz = paceHzForSpeed(pacePxPerSec);
|
||||
if (state._iconFocusFading > 0 && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
|
||||
// A helicopter in view turns its rotor ROTOR_FPS times a second.
|
||||
const rotorAtMs = parts.icons._rotorDrawnAtMs?.() ?? -Infinity;
|
||||
if (nowMs - rotorAtMs < PACE_ROTOR_SEEN_MS && hz < ROTOR_FPS)
|
||||
hz = ROTOR_FPS;
|
||||
return hz;
|
||||
}
|
||||
/** The ground sample's exclusions, kept while the sets they name live. */
|
||||
let exclusions = null;
|
||||
|
||||
@@ -952,6 +1022,7 @@ export function createAircraftModels({
|
||||
}
|
||||
}
|
||||
state._icons?.flush();
|
||||
pace.set(_paceHz());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -970,7 +1041,14 @@ export function createAircraftModels({
|
||||
|
||||
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
|
||||
parts.icons._syncImageSwitch();
|
||||
parts.icons._replanExpired(t);
|
||||
// Far and out-of-view contacts are planned for longer (the camera says
|
||||
// which are which).
|
||||
parts.icons._replanExpired(
|
||||
t,
|
||||
pose?.position
|
||||
? { eye: pose.position, inView: (position) => inView(pose, position) }
|
||||
: null,
|
||||
);
|
||||
const renderTime = parts.motion._displayTimeAt(
|
||||
t,
|
||||
state._scratchFleetRenderTime,
|
||||
@@ -1136,5 +1214,11 @@ export function createAircraftModels({
|
||||
_handBackDeselected,
|
||||
_updateTrackedModel,
|
||||
_fleetTick,
|
||||
_paceHz,
|
||||
_startPace: () => {
|
||||
paceReadMs = -Infinity;
|
||||
pace.start();
|
||||
},
|
||||
_stopPace: pace.stop,
|
||||
};
|
||||
}
|
||||
@@ -114,11 +114,14 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
};
|
||||
let now = 1_000_000;
|
||||
let iconRecedeSyncs = 0;
|
||||
const replanViews = [];
|
||||
const parts = {
|
||||
icons: {
|
||||
_displayMs: () => now,
|
||||
_syncImageSwitch() {},
|
||||
_replanExpired() {},
|
||||
_replanExpired(_t, view) {
|
||||
replanViews.push(view);
|
||||
},
|
||||
_focusIcons() {},
|
||||
_occluder: () => null,
|
||||
_aboveHorizon: () => true,
|
||||
@@ -160,6 +163,9 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
failNextUpsert: () => (failNextUpsert = true),
|
||||
/** How often the icons were told to recede by the tuning as it is now. */
|
||||
iconRecedeSyncs: () => iconRecedeSyncs,
|
||||
/** The camera each fleet tick re-planned the icons with. */
|
||||
replanViews,
|
||||
eye,
|
||||
/** Mark a contact as not there yet at the time drawn, or there again. */
|
||||
setUnseen(id, value) {
|
||||
if (value) unseenIds.add(id);
|
||||
@@ -476,3 +482,15 @@ test('the selected contact keeps a loaded, hidden fleet model that takes it back
|
||||
assert.equal(f.fleet().items.get('a1').show, true);
|
||||
assert.equal(f.shown.get('a1'), false);
|
||||
});
|
||||
|
||||
test('the fleet tick re-plans the icons with the camera: its eye, and what it sees', () => {
|
||||
const f = fleetFixture(new Map([['a1', far(1)]]));
|
||||
f.tick();
|
||||
const [view] = f.replanViews;
|
||||
assert.equal(view.eye, f.eye);
|
||||
// The camera looks along -z: ahead of the eye is in view, behind it not.
|
||||
const ahead = { x: f.eye.x, y: f.eye.y, z: f.eye.z - 10_000 };
|
||||
const behind = { x: f.eye.x, y: f.eye.y, z: f.eye.z + 10_000 };
|
||||
assert.equal(view.inView(ahead), true);
|
||||
assert.equal(view.inView(behind), false);
|
||||
});
|
||||
@@ -64,7 +64,8 @@ export const ANALYST_LAYERS = Object.freeze(
|
||||
|
||||
/** Fields every record carries regardless of layer. */
|
||||
const COMMON_FIELDS = Object.freeze(['id', 'lat', 'lon']);
|
||||
/** Derived per-record field for layers with a time field (hours before now). */
|
||||
/** Derived per-record field for layers with a time field (hours before the
|
||||
* moment the layer's records show: now, or its past snapshot's time). */
|
||||
const AGE_FIELD = 'ageHours';
|
||||
/** Spatial scope kinds `query()` accepts. */
|
||||
const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
@@ -582,6 +583,8 @@ function offerTop(top, candidate, limit, dir) {
|
||||
* engine and the Contacts-window path so both format and rank alike.
|
||||
* @param {Array<{key: string, rows: object[]}>} groups Candidate rows.
|
||||
* @param {object} options
|
||||
* @param {Map<string, number|null>} [options.recordsAt] Per-layer snapshot times in epoch ms.
|
||||
* Ages count from the layer’s snapshot time when given, otherwise from now.
|
||||
* @returns {Promise<object|null>} Selection, or null when cancelled.
|
||||
*/
|
||||
export async function selectAnalystRows(
|
||||
@@ -595,6 +598,7 @@ export async function selectAnalystRows(
|
||||
ref = null,
|
||||
inScope = null,
|
||||
now = Date.now(),
|
||||
recordsAt = null,
|
||||
isCurrent = () => true,
|
||||
distanceOf = null,
|
||||
} = {},
|
||||
@@ -603,8 +607,10 @@ export async function selectAnalystRows(
|
||||
const ageOf = (key, row) => {
|
||||
const field = timeFieldOf(key);
|
||||
const t = field ? row[field] : null;
|
||||
const from = recordsAt?.get(key);
|
||||
const ref = Number.isFinite(from) ? from : now;
|
||||
return Number.isFinite(t)
|
||||
? Math.round(((now - t) / 3_600_000) * 10) / 10
|
||||
? Math.round(((ref - t) / 3_600_000) * 10) / 10
|
||||
: null;
|
||||
};
|
||||
const distance = (row) => {
|
||||
@@ -771,6 +777,7 @@ export function createAnalystEngine(providers) {
|
||||
spec = normalized.spec;
|
||||
|
||||
// 1) Source records, grouped by layer and never copied.
|
||||
const recordsAt = followUp ? lastResult.recordsAt : new Map();
|
||||
let groups;
|
||||
let layersQueried;
|
||||
let queriedSnapshots;
|
||||
@@ -786,6 +793,7 @@ export function createAnalystEngine(providers) {
|
||||
queriedSnapshots = [];
|
||||
for (const key of layers) {
|
||||
const rows = providers.getRecords(key) || [];
|
||||
recordsAt.set(key, providers.getRecordsAt?.(key) ?? null);
|
||||
const snapshot = providers.getLayerSnapshot?.(key);
|
||||
if (snapshot) queriedSnapshots.push(snapshot);
|
||||
const coverage = providers.getRecordCoverage?.(key, rows) || {};
|
||||
@@ -1048,6 +1056,7 @@ export function createAnalystEngine(providers) {
|
||||
: null,
|
||||
inScope,
|
||||
now: providers.now?.() ?? Date.now(),
|
||||
recordsAt,
|
||||
isCurrent,
|
||||
});
|
||||
if (!selection || !isCurrent()) return cancelled();
|
||||
@@ -1147,6 +1156,7 @@ export function createAnalystEngine(providers) {
|
||||
if (!isCurrent()) return cancelled();
|
||||
lastResult = {
|
||||
matched: memoryOverride?.matched || selection.matched,
|
||||
recordsAt,
|
||||
distanceOf: memoryOverride?.distanceOf || rememberedDistanceOf,
|
||||
layerKeys: [...(memoryOverride?.layerKeys || layers)],
|
||||
coverage: memoryOverride?.coverage || result.coverage,
|
||||
|
||||
@@ -896,6 +896,24 @@ test('time fields filter by ISO and derive ageHours; the feed window is exposed'
|
||||
assert.equal(age.coverage.layersQueried[0].window, 'last 24 h');
|
||||
});
|
||||
|
||||
test('perimeter age follows the snapshot time of the remembered rows', async () => {
|
||||
const discoveredTime = Date.UTC(2024, 6, 1);
|
||||
let at = Date.UTC(2024, 6, 2);
|
||||
const engine = createAnalystEngine({
|
||||
now: () => Date.UTC(2026, 6, 2),
|
||||
getRecords: () => [{ id: 'Pine', discoveredTime }],
|
||||
getRecordsAt: () => at,
|
||||
});
|
||||
const first = await engine.query({
|
||||
layers: ['fire-perimeters'],
|
||||
scope: { kind: 'anywhere' },
|
||||
});
|
||||
assert.equal(first.items[0].ageHours, 24);
|
||||
at = null;
|
||||
const followUp = await engine.query({ followUp: true });
|
||||
assert.equal(followUp.items[0].ageHours, 24);
|
||||
});
|
||||
|
||||
test('follow-up provenance stays attached to old rows after a feed recovers', async () => {
|
||||
let state = 'stale';
|
||||
const engine = createAnalystEngine({
|
||||
|
||||
@@ -34,6 +34,7 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { PACE_MIN_HZ } from '../renderPace.js';
|
||||
|
||||
import {
|
||||
DETECTION_ENABLE_FADE_MS,
|
||||
@@ -448,31 +449,34 @@ test('the render-governor gate covers the parked case, with teeth on the painter
|
||||
// until some unrelated frame happens along.
|
||||
//
|
||||
// It cannot, and the reason is structural rather than lucky: an AIR bracket can
|
||||
// only exist while an aircraft layer is enabled, and both aircraft layers take a
|
||||
// continuous-render hold for their own per-frame fleet animation. So for exactly
|
||||
// as long as there is anything to bracket, the scene is rendering every frame
|
||||
// and the overlay repaints with it. (Measured live 2026-08-23 on a parked
|
||||
// camera: an outside-aircraft population change moved the painted bracket count
|
||||
// with no camera input, holds = ["flights"], requestRenderMode = false.)
|
||||
// only exist while an aircraft layer is enabled, and both aircraft layers pace
|
||||
// the render loop for their fleet (src/renderPace.js): never fewer than
|
||||
// PACE_MIN_HZ frames a second however still the camera, more as the fleet
|
||||
// moves faster on screen. So for exactly as long as there is anything to
|
||||
// bracket, the scene keeps drawing and the overlay repaints with it, at most a
|
||||
// third of a second behind. (Before the pace the layers held the loop on every
|
||||
// frame; measured live 2026-08-23 on a parked camera, an outside-aircraft
|
||||
// population change moved the painted bracket count with no camera input.)
|
||||
//
|
||||
// That is a COUPLING, so it deserves a pin. If a later perf pass strips these
|
||||
// holds the way it stripped detection's — a reasonable-looking change — bracket
|
||||
// That is a COUPLING, so it deserves a pin. If a later perf pass stops the
|
||||
// aircraft layers pacing, or lets the pace's floor reach zero, bracket
|
||||
// promptness goes with them, silently. This test is where that shows up.
|
||||
test('aircraft brackets stay prompt because the aircraft layers hold the render loop', async () => {
|
||||
test('aircraft brackets stay prompt because the aircraft layers pace the render loop', async () => {
|
||||
assert.ok(PACE_MIN_HZ >= 3, 'a still scene still draws a few times a second');
|
||||
for (const file of ['./flights.js', './militaryFlights.js']) {
|
||||
const source = readLayerSource(new URL(file, import.meta.url));
|
||||
const enable = /\n([ \t]*)enable\([\s\S]*?\n\1\},/.exec(source)?.[0];
|
||||
assert.ok(enable, `${file}: enable() is still identifiable`);
|
||||
assert.match(
|
||||
enable,
|
||||
/holdContinuousRender\('(flights|military)'\)/,
|
||||
`${file}: enabling the layer must hold continuous render — detection no longer ` +
|
||||
'holds one, so this is what keeps its AIR brackets repainting on a parked scene',
|
||||
/parts\.rendering\._startPace\(\)/,
|
||||
`${file}: enabling the layer must start its pace — detection no longer ` +
|
||||
'holds the loop, so this is what keeps its AIR brackets repainting on a parked scene',
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/releaseContinuousRender\('(flights|military)'\)/,
|
||||
`${file}: and the hold must be released, or the governor can never idle`,
|
||||
/parts\.rendering\._stopPace\(\)/,
|
||||
`${file}: and the pace must be stopped, or the governor can never idle`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -57,6 +57,34 @@ function install(options = {}, hook = 'configureServer') {
|
||||
};
|
||||
}
|
||||
|
||||
test('the WFIGS query asks for the mapping and edit times, and rows keep both', async () => {
|
||||
let url;
|
||||
const request = install({
|
||||
now: () => 1234,
|
||||
fetchImpl: async (input) => {
|
||||
url = new URL(input);
|
||||
return Response.json({
|
||||
features: [
|
||||
{
|
||||
...feature('timed'),
|
||||
properties: {
|
||||
attr_UniqueFireIdentifier: 'timed',
|
||||
poly_PolygonDateTime: 100,
|
||||
poly_DateCurrent: 200,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
const res = await request();
|
||||
const fields = url.searchParams.get('outFields').split(',');
|
||||
assert.ok(fields.includes('poly_PolygonDateTime'));
|
||||
assert.ok(fields.includes('poly_DateCurrent'));
|
||||
assert.equal(res.body.rows[0].polygonTime, 100);
|
||||
assert.equal(res.body.rows[0].updatedTime, 200);
|
||||
});
|
||||
|
||||
for (const hook of ['configureServer', 'configurePreviewServer']) {
|
||||
test(`${hook}: paging stops at five pages and normalizes the combined snapshot`, async () => {
|
||||
const calls = [];
|
||||
|
||||
@@ -65,7 +65,10 @@ const START_SIZE_PX = 1024;
|
||||
const MAX_SIZE_PX = 4096;
|
||||
|
||||
function createAtlas() {
|
||||
const slotOfKey = new Map();
|
||||
// By URL, then by size: a URL is hashed once as it is, where a key built
|
||||
// from it would be a new string to hash on every look-up (an SVG data URL
|
||||
// runs to kilobytes, and a fleet's write looks up two a row).
|
||||
const slotsOfUrl = new Map();
|
||||
const entries = [];
|
||||
const listeners = new Set();
|
||||
const atlas = {
|
||||
@@ -90,8 +93,8 @@ function createAtlas() {
|
||||
* @returns {number}
|
||||
*/
|
||||
slot(url, sizePx, source) {
|
||||
const key = `${sizePx}|${url}`;
|
||||
const known = slotOfKey.get(key);
|
||||
let bySize = slotsOfUrl.get(url);
|
||||
const known = bySize?.get(sizePx);
|
||||
if (known !== undefined) return known;
|
||||
if (entries.length >= MAX_ICON_SLOTS)
|
||||
throw new RangeError(
|
||||
@@ -100,7 +103,8 @@ function createAtlas() {
|
||||
const slot = entries.length;
|
||||
const entry = { url, sizePx, image: null, x: 0, y: 0 };
|
||||
entries.push(entry);
|
||||
slotOfKey.set(key, slot);
|
||||
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
|
||||
bySize.set(sizePx, slot);
|
||||
if (source) placeLoaded(entry, source);
|
||||
else load(entry);
|
||||
return slot;
|
||||
@@ -108,7 +112,7 @@ function createAtlas() {
|
||||
|
||||
/** Whether `url` at `sizePx` already has a slot. */
|
||||
has(url, sizePx) {
|
||||
return slotOfKey.has(`${sizePx}|${url}`);
|
||||
return slotsOfUrl.get(url)?.has(sizePx) === true;
|
||||
},
|
||||
|
||||
/** Whether a slot's image is packed and drawable. */
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { iconAtlas } from './iconAtlas.js';
|
||||
|
||||
test('an atlas slot is one per image and size, and has() agrees with slot()', () => {
|
||||
const url = `data:image/svg+xml;charset=utf-8,${'%3Csvg%3E'.repeat(400)}#slots`;
|
||||
const other = `${url}-other`;
|
||||
assert.equal(iconAtlas.has(url, 20), false);
|
||||
const small = iconAtlas.slot(url, 20);
|
||||
assert.equal(iconAtlas.has(url, 20), true);
|
||||
assert.equal(iconAtlas.slot(url, 20), small, 'the same image and size');
|
||||
// A copy of the URL, not the same string, finds it too.
|
||||
assert.equal(iconAtlas.slot(url.slice(0), 20), small);
|
||||
assert.equal(iconAtlas.has(url, 40), false, 'another size is another slot');
|
||||
const large = iconAtlas.slot(url, 40);
|
||||
assert.notEqual(large, small);
|
||||
assert.equal(iconAtlas.has(url, 40), true);
|
||||
assert.equal(
|
||||
iconAtlas.has(other, 20),
|
||||
false,
|
||||
'another image is another slot',
|
||||
);
|
||||
assert.notEqual(iconAtlas.slot(other, 20), small);
|
||||
});
|
||||
@@ -920,7 +920,7 @@ test('the Stories announcement waits behind the welcome card', () => {
|
||||
// the card is dismissed.
|
||||
assert.match(
|
||||
css,
|
||||
/body:has\(#first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
|
||||
/body:is\(\.launcher-shown \*, #first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
|
||||
);
|
||||
// The selector only works while Stories still renders the popup as #hPop
|
||||
// inside #gev-stories.
|
||||
@@ -1110,10 +1110,11 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
|
||||
// Pistes extend the generated layer enums and alias hint; voice geometry
|
||||
// adds the analyst area scopes and the osm-places layer.
|
||||
// control_cockpit states the own-layer entry rule (Contacts not required).
|
||||
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
|
||||
// Fire Perimeters queries add lastGrowthTime.
|
||||
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
|
||||
assert.equal(
|
||||
crypto.createHash('sha256').update(block).digest('hex'),
|
||||
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
|
||||
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
|
||||
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
|
||||
);
|
||||
const instructions = fs.readFileSync(
|
||||
|
||||
+140
-22
@@ -227,6 +227,17 @@ const NEARBY_POINTS = Object.values(CITY_POIS).flatMap((city) =>
|
||||
* and the altitude-scaled GSD/NIIRS figures. Readouts update on independent
|
||||
* fixed cadences.
|
||||
*/
|
||||
/**
|
||||
* The view's attributes on #intel-hud itself: shown or not, layout variant
|
||||
* and style colors. Stylesheets and layout elsewhere on the page read them.
|
||||
*/
|
||||
const HUD_FRAME_KEYS = Object.freeze(['active', 'variant', 'colors']);
|
||||
|
||||
/** @param {object} view @returns {object} Its {@link HUD_FRAME_KEYS}. */
|
||||
function pickFrame(view) {
|
||||
return Object.fromEntries(HUD_FRAME_KEYS.map((key) => [key, view[key]]));
|
||||
}
|
||||
|
||||
export class IntelHUD {
|
||||
/**
|
||||
* @param {object} viewer - The scene the HUD sits over.
|
||||
@@ -254,6 +265,19 @@ export class IntelHUD {
|
||||
this.placeSearch = placeSearch;
|
||||
this.viewer = viewer;
|
||||
this._visible = false;
|
||||
// Whether the HUD's view is on screen (setDisplayed). While it is not,
|
||||
// no timer runs and no readout is worked out or published; what was
|
||||
// skipped is caught up when it is back.
|
||||
this._displayed = true;
|
||||
this._unseen = { settle: false, show: false, summary: false };
|
||||
/** Summary updates under way; one still running when the view goes is
|
||||
* dropped and asked again when it is back. */
|
||||
this._summaryRuns = 0;
|
||||
/** The text the typewriter is typing out, while it types. */
|
||||
this._summaryTypingText = null;
|
||||
/** When the view stopped being displayed (Date.now()), or null. */
|
||||
this._undisplayedAt = null;
|
||||
this._destroyed = false;
|
||||
this._autoMode = true; // auto show/hide based on style
|
||||
this._currentStyle = 'normal';
|
||||
/** The presented HUD; see {@link IntelHUD#_initView}. */
|
||||
@@ -320,20 +344,8 @@ export class IntelHUD {
|
||||
};
|
||||
this._onCameraMoveEnd = () => {
|
||||
this._markSummaryDirty();
|
||||
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
|
||||
// leave the prior city on-screen after a long CCTV focus flight.
|
||||
// Refresh deterministic camera context synchronously on settle; the AI
|
||||
// summary can still upgrade it on its normal cadence.
|
||||
if (this._visible) {
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
// First settled view: request the AI summary now rather than waiting for
|
||||
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
|
||||
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
|
||||
this._firstSummaryKicked = true;
|
||||
void this._updateSummary(true, true);
|
||||
}
|
||||
if (this._displayed) this._settle();
|
||||
else this._unseen.settle = true;
|
||||
};
|
||||
|
||||
// Session-consistent pseudorandom identifiers (generated once at construction)
|
||||
@@ -358,6 +370,27 @@ export class IntelHUD {
|
||||
this._startTimers();
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera has settled: show the readouts and the plain summary for the
|
||||
* view it settled on.
|
||||
*/
|
||||
_settle() {
|
||||
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
|
||||
// leave the prior city on-screen after a long CCTV focus flight.
|
||||
// Refresh deterministic camera context synchronously on settle; the AI
|
||||
// summary can still upgrade it on its normal cadence.
|
||||
if (this._visible) {
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
// First settled view: request the AI summary now rather than waiting for
|
||||
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
|
||||
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
|
||||
this._firstSummaryKicked = true;
|
||||
void this._updateSummary(true, true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Show the HUD's words in the new locale; drop AI text in the old one. */
|
||||
_relocalize() {
|
||||
this._markSummaryDirty();
|
||||
@@ -374,7 +407,8 @@ export class IntelHUD {
|
||||
? {}
|
||||
: { vessel: { active: false, text: t('AIS: --') } }),
|
||||
});
|
||||
if (this._visible && this._latestMetrics) this._updateCameraData();
|
||||
if (this._visible && this._displayed && this._latestMetrics)
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
|
||||
@@ -417,10 +451,17 @@ export class IntelHUD {
|
||||
*/
|
||||
_present(patch) {
|
||||
Object.assign(this._view, patch);
|
||||
const signature = JSON.stringify(this._view);
|
||||
// Not displayed: only the view's own attributes are published, which the
|
||||
// page's stylesheets and layout read from #intel-hud while it is hidden
|
||||
// too; the readouts wait until it is displayed again.
|
||||
const view = this._displayed
|
||||
? this._view
|
||||
: { ...this._shown, ...pickFrame(this._view) };
|
||||
const signature = JSON.stringify(view);
|
||||
if (signature === this._viewSignature) return;
|
||||
this._viewSignature = signature;
|
||||
this._publish(Object.freeze({ ...this._view }));
|
||||
this._shown = Object.freeze({ ...view });
|
||||
this._publish(this._shown);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -429,6 +470,7 @@ export class IntelHUD {
|
||||
* cadences and are cleaned up in {@link destroy}.
|
||||
*/
|
||||
_startTimers() {
|
||||
this._stopTimers();
|
||||
// Timestamp — every second
|
||||
this._timestampInterval = setInterval(() => {
|
||||
this._present({ timestamp: this._formatUTC() });
|
||||
@@ -455,6 +497,18 @@ export class IntelHUD {
|
||||
}, HUD_SUMMARY_INTERVAL_MS);
|
||||
}
|
||||
|
||||
/** Stop the periodic timers {@link _startTimers} started. */
|
||||
_stopTimers() {
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._recBlinkInterval);
|
||||
clearInterval(this._updateInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
this._timestampInterval = null;
|
||||
this._recBlinkInterval = null;
|
||||
this._updateInterval = null;
|
||||
this._summaryInterval = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the HUD's world time as a UTC Zulu string.
|
||||
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SSZ` format.
|
||||
@@ -844,6 +898,7 @@ export class IntelHUD {
|
||||
_stopSummaryTyping() {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -853,6 +908,7 @@ export class IntelHUD {
|
||||
*/
|
||||
_typeSummary(text) {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingText = text;
|
||||
let index = 0;
|
||||
this._present({ summary: '' });
|
||||
this._summaryTypingInterval = setInterval(() => {
|
||||
@@ -861,6 +917,7 @@ export class IntelHUD {
|
||||
this._present({ summary: text });
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
return;
|
||||
}
|
||||
this._present({ summary: text.slice(0, index) });
|
||||
@@ -873,6 +930,16 @@ export class IntelHUD {
|
||||
* by character; otherwise sets it instantly.
|
||||
*/
|
||||
async _updateSummary(animate = false, force = false) {
|
||||
this._summaryRuns += 1;
|
||||
try {
|
||||
await this._runSummaryUpdate(animate, force);
|
||||
} finally {
|
||||
this._summaryRuns -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link _updateSummary}'s work. */
|
||||
async _runSummaryUpdate(animate, force) {
|
||||
const fallbackText = this._composeSummary();
|
||||
if (!this._latestMetrics) {
|
||||
this._setSummaryText(fallbackText, animate);
|
||||
@@ -1002,7 +1069,8 @@ export class IntelHUD {
|
||||
}
|
||||
|
||||
_setSummaryText(text, animate) {
|
||||
if (animate) {
|
||||
// Nothing types out off screen: the text is there when the view is back.
|
||||
if (animate && this._displayed) {
|
||||
this._typeSummary(text);
|
||||
return;
|
||||
}
|
||||
@@ -1123,11 +1191,63 @@ export class IntelHUD {
|
||||
show() {
|
||||
this._visible = true;
|
||||
this._present({ active: true });
|
||||
if (this._displayed) this._refreshShown();
|
||||
else this._unseen.show = true;
|
||||
}
|
||||
|
||||
/** Readouts and a fresh summary for a HUD just shown. */
|
||||
_refreshShown() {
|
||||
this._updateCameraData(); // immediate update
|
||||
this._markSummaryDirty();
|
||||
void this._updateSummary(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the HUD's view is on screen. A stylesheet can give the view
|
||||
* `display: none`, or the view can be unmounted; until it is displayed
|
||||
* again no timer runs, a summary being worked out is dropped and only the
|
||||
* view's own attributes ({@link HUD_FRAME_KEYS}) are published. Then the
|
||||
* timers start again and current readouts show at once.
|
||||
* @param {boolean} displayed
|
||||
*/
|
||||
setDisplayed(displayed) {
|
||||
displayed = Boolean(displayed);
|
||||
if (this._destroyed || displayed === this._displayed) return;
|
||||
this._displayed = displayed;
|
||||
if (!displayed) {
|
||||
this._undisplayedAt = Date.now();
|
||||
this._stopTimers();
|
||||
// A reply still typing is finished: the view shows all of it when it
|
||||
// is back, not the rest of it typing out.
|
||||
const typing = this._summaryTypingText;
|
||||
this._stopSummaryTyping();
|
||||
if (typing !== null) this._present({ summary: typing });
|
||||
// A summary being worked out is dropped, and asked again when the
|
||||
// view is back.
|
||||
if (this._summaryRuns > 0) {
|
||||
this._unseen.summary = true;
|
||||
this._markSummaryDirty();
|
||||
this._summaryRequest?.abort();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const { settle, show } = this._unseen;
|
||||
// The summary refresh that would have come round while it was away.
|
||||
const summary =
|
||||
this._unseen.summary ||
|
||||
Date.now() - (this._undisplayedAt ?? Date.now()) >=
|
||||
HUD_SUMMARY_INTERVAL_MS;
|
||||
this._unseen = { settle: false, show: false, summary: false };
|
||||
this._undisplayedAt = null;
|
||||
this._startTimers();
|
||||
// Publishes the whole view: what changed while it was not displayed.
|
||||
this._present({ timestamp: this._formatUTC() });
|
||||
if (settle) this._settle();
|
||||
if (show && this._visible) this._refreshShown();
|
||||
else if (!settle && this._visible) this._updateCameraData();
|
||||
if (summary && !show && this._visible) void this._updateSummary(true);
|
||||
}
|
||||
|
||||
/** Hide the HUD overlay. */
|
||||
hide() {
|
||||
this._visible = false;
|
||||
@@ -1214,10 +1334,8 @@ export class IntelHUD {
|
||||
|
||||
/** Tear down all running intervals. Call when discarding the HUD instance. */
|
||||
destroy() {
|
||||
clearInterval(this._updateInterval);
|
||||
clearInterval(this._recBlinkInterval);
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
this._destroyed = true;
|
||||
this._stopTimers();
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
for (const off of this._offCamera.splice(0)) off();
|
||||
this._dataManagerUnsubscribe?.();
|
||||
|
||||
@@ -1845,11 +1845,6 @@
|
||||
"Unnamed incident": "حادث بلا اسم",
|
||||
"Open {title} on InciWeb": "فتح {title} على InciWeb",
|
||||
"Perimeter source unavailable": "مصدر محيطات الحرائق غير متاح",
|
||||
"Not contained or unknown": "بلا احتواء أو غير معروف",
|
||||
"Under 50% contained": "الاحتواء: أقل من 50%",
|
||||
"50–99% contained": "الاحتواء: 50–99%",
|
||||
"Fully contained": "احتواء كامل",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "يبيّن اللون نسبة الاحتواء المُبلَّغ عنها. المحيطات مبسّطة إلى نحو 100 م.",
|
||||
"Malformed perimeter snapshot": "لقطة المحيطات مشوّهة",
|
||||
"radio tag|All": "الكل",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
|
||||
@@ -4856,5 +4851,12 @@
|
||||
"JTWC warning ↗": "تحذير JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "نشرات وتحذيرات الأعاصير النشطة",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "اختر عاصفة على الخريطة، أو اختر عاصفة من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مكان فارغ من الخريطة لإلغاء التحديد. نشرات NOAA NHC/CPHC وتحذيرات JTWC. يصف مخروط NHC عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا منطقة الخطر كاملة. منطقة خطر رياح 34 عقدة لدى JTWC هي حيث قد تصل رياح بسرعة 34 عقدة، موسّعةً بخطأ توقع المسار؛ وهي ليست مخروطًا. تسميات نقاط التوقع هي ساعات المهلة لدى المصدر، لا أوقات محسوبة من وقت الإصدار. تتبع الأشكال سطح الأرض؛ والارتفاع ليس ارتفاعًا جويًا. ارجع إلى النشرة الرسمية أو إلى مركز الإنذار الإقليمي.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}",
|
||||
"last growth {age} ago": "آخر توسّع قبل {age}",
|
||||
"Last 6 hours": "آخر 6 ساعات",
|
||||
"6–24 hours": "6–24 ساعة",
|
||||
"1–3 days": "1–3 أيام",
|
||||
"Older or unknown": "أقدم أو غير معروف",
|
||||
"Colour shows the age of each area.": "يبيّن اللون عمر كل منطقة.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "يُحسب العمر من وقت رسم WFIGS للحدود، وإلا فمن آخر تعديل للسجل. الحدود مبسّطة إلى نحو 100 م."
|
||||
}
|
||||
@@ -1727,11 +1727,6 @@
|
||||
"Unnamed incident": "Unbenannter Einsatz",
|
||||
"Open {title} on InciWeb": "{title} auf InciWeb öffnen",
|
||||
"Perimeter source unavailable": "Quelle der Brandgrenzen nicht verfügbar",
|
||||
"Not contained or unknown": "Nicht eingedämmt oder unbekannt",
|
||||
"Under 50% contained": "Unter 50 % eingedämmt",
|
||||
"50–99% contained": "50–99 % eingedämmt",
|
||||
"Fully contained": "Vollständig eingedämmt",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Die Farbe zeigt die gemeldete Eindämmung. Brandgrenzen sind auf etwa 100 m vereinfacht.",
|
||||
"Malformed perimeter snapshot": "Fehlerhafter Brandgrenzen-Snapshot",
|
||||
"radio tag|All": "Alle",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "Verzeichnisaktualisierung eingeschränkt; der vorherige Senderkatalog wird gezeigt.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"JTWC warning ↗": "JTWC-Warnung ↗",
|
||||
"Active cyclone advisories and warnings": "Aktive Wirbelsturm-Lageberichte und -Warnungen",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Wähle einen Sturm auf der Karte oder in der Liste, um ihn auszuwählen und die Kamera hinzubewegen. Ein Klick auf eine leere Kartenstelle hebt die Auswahl auf. Lageberichte von NOAA NHC/CPHC und Warnungen des JTWC. Der NHC-Kegel beschreibt die Unsicherheit der vorhergesagten Zugbahn des Zentrums, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Der 34-Knoten-Gefahrenbereich des JTWC ist das Gebiet, das Winde von 34 Knoten erreichen können, erweitert um den Fehler der Zugbahnvorhersage; er ist kein Kegel. Die Beschriftungen der Vorhersagepunkte sind die Vorlaufstunden der Quelle, keine aus der Ausgabe berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Höhe ist keine Wetterhöhe. Maßgeblich sind der offizielle Lagebericht oder das regionale Warnzentrum.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}",
|
||||
"last growth {age} ago": "zuletzt gewachsen vor {age}",
|
||||
"Last 6 hours": "Letzte 6 Stunden",
|
||||
"6–24 hours": "6–24 Stunden",
|
||||
"1–3 days": "1–3 Tage",
|
||||
"Older or unknown": "Älter oder unbekannt",
|
||||
"Colour shows the age of each area.": "Die Farbe zeigt das Alter jeder Fläche.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Alter ab der Kartierung durch WFIGS, sonst ab der letzten Änderung des Datensatzes. Brandgrenzen auf ca. 100 m vereinfacht."
|
||||
}
|
||||
@@ -1411,11 +1411,6 @@
|
||||
"Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
|
||||
"Routing unavailable": "Rutas no disponibles",
|
||||
"Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
|
||||
"Not contained or unknown": "Sin contener o desconocido",
|
||||
"Under 50% contained": "Contenido por debajo del 50%",
|
||||
"50–99% contained": "Contenido al 50–99%",
|
||||
"Fully contained": "Totalmente contenido",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
|
||||
"MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
|
||||
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
|
||||
"DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"JTWC warning ↗": "Aviso del JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Avisos activos de ciclones",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecciona una tormenta en el mapa o elige una en la lista para seleccionarla y mover la cámara. Haz clic en una zona vacía del mapa para quitar la selección. Avisos de NOAA NHC/CPHC y del JTWC. El cono del NHC describe la incertidumbre de la trayectoria prevista del centro, no el tamaño de la tormenta ni toda la zona de peligro. La zona de peligro de 34 nudos del JTWC es donde pueden llegar vientos de 34 nudos, ampliada por el error de la trayectoria prevista; no es un cono. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas desde la emisión. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial o el centro de avisos regional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
|
||||
"last growth {age} ago": "último crecimiento hace {age}",
|
||||
"Last 6 hours": "Últimas 6 horas",
|
||||
"6–24 hours": "6–24 horas",
|
||||
"1–3 days": "1–3 días",
|
||||
"Older or unknown": "Más antiguo o desconocido",
|
||||
"Colour shows the age of each area.": "El color indica la antigüedad de cada zona.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Antigüedad desde el mapeo de WFIGS o, si falta, desde la última edición del registro. Perímetros simplificados a ~100 m."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"Unnamed incident": "Incident sans nom",
|
||||
"Open {title} on InciWeb": "Ouvrir {title} sur InciWeb",
|
||||
"Perimeter source unavailable": "Source des périmètres indisponible",
|
||||
"Not contained or unknown": "Non circonscrit ou inconnu",
|
||||
"Under 50% contained": "Circonscrit à moins de 50 %",
|
||||
"50–99% contained": "Circonscrit à 50–99 %",
|
||||
"Fully contained": "Entièrement circonscrit",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "La couleur indique la part du périmètre déclarée circonscrite. Les périmètres sont simplifiés à environ 100 m.",
|
||||
"Malformed perimeter snapshot": "Instantané des périmètres mal formé",
|
||||
"radio tag|All": "Toutes",
|
||||
"News": "Actualités",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"JTWC warning ↗": "Avertissement du JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Bulletins et avertissements cycloniques en cours",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Sélectionnez une tempête sur la carte, ou choisissez-en une dans la liste pour la sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Bulletins NOAA NHC/CPHC et avertissements du JTWC. Le cône du NHC décrit l’incertitude de la trajectoire prévue du centre, pas la taille de la tempête ni toute la zone de danger. La zone de danger de 34 nœuds du JTWC est l’endroit que peuvent atteindre des vents de 34 nœuds, élargi de l’erreur de prévision de trajectoire ; ce n’est pas un cône. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l’émission. La géométrie suit la surface ; la hauteur n’est pas une altitude météorologique. Consultez le bulletin officiel ou le centre d’avertissement régional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}",
|
||||
"last growth {age} ago": "dernière progression il y a {age}",
|
||||
"Last 6 hours": "6 dernières heures",
|
||||
"6–24 hours": "6–24 heures",
|
||||
"1–3 days": "1–3 jours",
|
||||
"Older or unknown": "Plus ancien ou inconnu",
|
||||
"Colour shows the age of each area.": "La couleur indique l’âge de chaque zone.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Âge compté depuis la cartographie WFIGS, sinon depuis la dernière modification de la fiche. Périmètres simplifiés à ~100 m."
|
||||
}
|
||||
@@ -919,11 +919,6 @@
|
||||
"Unnamed incident": "אירוע ללא שם",
|
||||
"Open {title} on InciWeb": "פתיחת {title} ב-InciWeb",
|
||||
"Perimeter source unavailable": "מקור ההיקף אינו זמין",
|
||||
"Not contained or unknown": "ללא הכלה או לא ידוע",
|
||||
"Under 50% contained": "הכלה מתחת ל-50%",
|
||||
"50–99% contained": "הכלה 50–99%",
|
||||
"Fully contained": "הכלה מלאה",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "הצבע מציג את ההכלה שדווחה. ההיקפים מפושטים לכ-100 מ׳.",
|
||||
"Malformed perimeter snapshot": "תמונת מצב היקף פגומה",
|
||||
"radio tag|All": "הכול",
|
||||
"News": "חדשות",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"JTWC warning ↗": "אזהרת JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "עדכוני ציקלונים ואזהרות פעילים",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "בחרו סופה במפה, או בחרו סופה ברשימה כדי לסמן אותה ולהזיז אליה את המצלמה. לחיצה על מקום ריק במפה מבטלת את הבחירה. עדכוני NOAA NHC/CPHC ואזהרות JTWC. החרוט של NHC מתאר את אי-הוודאות במסלול החזוי של המרכז, לא את גודל הסופה ולא את כל אזור הסכנה. אזור הסכנה של 34 קשר של JTWC הוא המקום שאליו עשויות להגיע רוחות של 34 קשר, מורחב בשגיאת תחזית המסלול; הוא אינו חרוט. התוויות של נקודות התחזית הן שעות התחזית של המקור, לא זמנים שחושבו ממועד הפרסום. הצורות עוקבות אחר פני השטח; הגובה אינו גובה מטאורולוגי. עיינו בעדכון הרשמי או במרכז ההתרעות האזורי.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}",
|
||||
"last growth {age} ago": "התפשטות אחרונה לפני {age}",
|
||||
"Last 6 hours": "6 השעות האחרונות",
|
||||
"6–24 hours": "6–24 שעות",
|
||||
"1–3 days": "1–3 ימים",
|
||||
"Older or unknown": "ישן יותר או לא ידוע",
|
||||
"Colour shows the age of each area.": "הצבע מציין את הגיל של כל שטח.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "הגיל נספר ממועד המיפוי של WFIGS, או מהעריכה האחרונה של הרשומה. קווי המתאר מפושטים לכ־100 מ׳."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"Unnamed incident": "Incendio senza nome",
|
||||
"Open {title} on InciWeb": "Apri {title} su InciWeb",
|
||||
"Perimeter source unavailable": "Fonte dei perimetri non disponibile",
|
||||
"Not contained or unknown": "Non contenuto o dato non disponibile",
|
||||
"Under 50% contained": "Contenuto a meno del 50%",
|
||||
"50–99% contained": "Contenuto al 50–99%",
|
||||
"Fully contained": "Completamente contenuto",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Il colore indica il contenimento riportato. I perimetri sono semplificati a circa 100 m.",
|
||||
"Malformed perimeter snapshot": "Snapshot dei perimetri non valido",
|
||||
"radio tag|All": "Tutti",
|
||||
"News": "Notizie",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"JTWC warning ↗": "Avviso JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Bollettini e avvisi attivi sui cicloni",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Seleziona una tempesta sulla mappa o sceglila nell’elenco per selezionarla e spostare la telecamera. Fai clic su un punto vuoto della mappa per annullare la selezione. Bollettini NOAA NHC/CPHC e avvisi JTWC. Il cono NHC descrive l’incertezza della traccia prevista del centro, non le dimensioni della tempesta né l’intera area di pericolo. L’area di pericolo a 34 nodi del JTWC è dove possono arrivare venti a 34 nodi, ampliata dall’errore di previsione della traccia; non è un cono. Le etichette dei punti di previsione sono ore di anticipo della fonte, non orari calcolati dall’emissione. La geometria segue la superficie; l’altezza non è quota meteorologica. Consulta il bollettino ufficiale o il centro di allerta regionale.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}",
|
||||
"last growth {age} ago": "ultima espansione {age} fa",
|
||||
"Last 6 hours": "Ultime 6 ore",
|
||||
"6–24 hours": "6–24 ore",
|
||||
"1–3 days": "1–3 giorni",
|
||||
"Older or unknown": "Più vecchio o sconosciuto",
|
||||
"Colour shows the age of each area.": "Il colore indica l’età di ciascuna area.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Età dalla mappatura WFIGS, altrimenti dall’ultima modifica del record. Perimetri semplificati a ~100 m."
|
||||
}
|
||||
@@ -1024,11 +1024,6 @@
|
||||
"Unnamed incident": "名称未設定の火災",
|
||||
"Open {title} on InciWeb": "InciWebで{title}を開く",
|
||||
"Perimeter source unavailable": "延焼範囲のソースを利用できません",
|
||||
"Not contained or unknown": "封じ込め率0%または不明",
|
||||
"Under 50% contained": "封じ込め率50%未満",
|
||||
"50–99% contained": "封じ込め率50–99%",
|
||||
"Fully contained": "封じ込め率100%",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "色は報告された封じ込め率を示します。延焼範囲の輪郭は約100 mの精度で簡略化されています。",
|
||||
"Malformed perimeter snapshot": "延焼範囲スナップショットの形式が不正です",
|
||||
"radio tag|All": "すべて",
|
||||
"News": "ニュース",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"JTWC warning ↗": "JTWC警報 ↗",
|
||||
"Active cyclone advisories and warnings": "発表中のサイクロン情報と警報",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "地図上の嵐を選ぶか、リストから嵐を選ぶと選択され、カメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報とJTWCの警報です。NHCの予報円は中心の予報進路の不確かさを表すもので、嵐の大きさや危険域全体ではありません。JTWCの34ノット風の危険域は、34ノットの風が及ぶおそれのある範囲を進路予報の誤差分だけ広げたもので、予報円ではありません。予報点のラベルは情報源の予報時間で、発表時刻から計算した時刻ではありません。形状は地表に沿って描かれ、高さは気象上の高度ではありません。公式の情報または地域の警報センターを確認してください。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表",
|
||||
"last growth {age} ago": "{age}前に最終拡大",
|
||||
"Last 6 hours": "過去6時間",
|
||||
"6–24 hours": "6–24時間",
|
||||
"1–3 days": "1–3日",
|
||||
"Older or unknown": "それ以前または不明",
|
||||
"Colour shows the age of each area.": "色は各区域の経過時間を示します。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "経過時間は WFIGS の測図時刻から、なければ記録の最終編集時刻から数えます。境界線は約 100 m に簡略化されています。"
|
||||
}
|
||||
@@ -1068,11 +1068,6 @@
|
||||
"Unnamed incident": "Sem nome",
|
||||
"Open {title} on InciWeb": "Abrir {title} no InciWeb",
|
||||
"Perimeter source unavailable": "Fonte de perímetros indisponível",
|
||||
"Not contained or unknown": "Não contido ou desconhecido",
|
||||
"Under 50% contained": "Menos de 50% contido",
|
||||
"50–99% contained": "50–99% contido",
|
||||
"Fully contained": "Totalmente contido",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "A cor indica a contenção informada. Os perímetros são simplificados para cerca de 100 m.",
|
||||
"Malformed perimeter snapshot": "Snapshot de perímetros malformado",
|
||||
"radio tag|All": "Todas",
|
||||
"News": "Notícias",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"JTWC warning ↗": "Aviso do JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Boletins e avisos de ciclones ativos",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecione uma tempestade no mapa ou escolha uma na lista para selecioná-la e mover a câmera. Clique em uma área vazia do mapa para limpar a seleção. Boletins da NOAA NHC/CPHC e avisos do JTWC. O cone do NHC descreve a incerteza da trajetória prevista do centro, não o tamanho da tempestade nem toda a área de perigo. A área de perigo de 34 nós do JTWC é onde ventos de 34 nós podem chegar, ampliada pelo erro da previsão de trajetória; não é um cone. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial ou o centro de alertas regional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
|
||||
"last growth {age} ago": "último crescimento há {age}",
|
||||
"Last 6 hours": "Últimas 6 horas",
|
||||
"6–24 hours": "6–24 horas",
|
||||
"1–3 days": "1–3 dias",
|
||||
"Older or unknown": "Mais antigo ou desconhecido",
|
||||
"Colour shows the age of each area.": "A cor indica a idade de cada área.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Idade a partir do mapeamento do WFIGS ou, na falta dele, da última edição do registro. Perímetros simplificados a ~100 m."
|
||||
}
|
||||
@@ -1439,11 +1439,6 @@
|
||||
"Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
|
||||
"Routing unavailable": "Построение маршрута недоступно",
|
||||
"Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
|
||||
"Not contained or unknown": "Не локализован или неизвестно",
|
||||
"Under 50% contained": "Локализован менее чем на 50%",
|
||||
"50–99% contained": "Локализован на 50–99%",
|
||||
"Fully contained": "Полностью локализован",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
|
||||
"MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
|
||||
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
|
||||
"DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"JTWC warning ↗": "Предупреждение JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Действующие сводки и предупреждения о циклонах",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить камеру. Щелчок по пустому месту карты снимает выделение. Сводки NOAA NHC/CPHC и предупреждения JTWC. Конус NHC показывает неопределённость прогнозного трека центра, а не размер шторма или всю опасную зону. Опасная зона ветра 34 узла JTWC — это область, куда может дойти ветер 34 узла, расширенная на ошибку прогноза трека; это не конус. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска. Геометрия следует поверхности; высота не является метеорологической высотой. Сверяйтесь с официальной сводкой или региональным центром предупреждений.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}",
|
||||
"last growth {age} ago": "последний рост {age} назад",
|
||||
"Last 6 hours": "Последние 6 часов",
|
||||
"6–24 hours": "6–24 часа",
|
||||
"1–3 days": "1–3 дня",
|
||||
"Older or unknown": "Старше или неизвестно",
|
||||
"Colour shows the age of each area.": "Цвет показывает возраст каждого участка.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Возраст — от картирования WFIGS, иначе от последней правки записи. Контуры упрощены до ~100 м."
|
||||
}
|
||||
@@ -1643,11 +1643,6 @@
|
||||
"Unnamed incident": "Namnlös händelse",
|
||||
"Open {title} on InciWeb": "Öppna {title} på InciWeb",
|
||||
"Perimeter source unavailable": "Källa för brandgränser otillgänglig",
|
||||
"Not contained or unknown": "Inte under kontroll eller okänt",
|
||||
"Under 50% contained": "Mindre än 50 % under kontroll",
|
||||
"50–99% contained": "50–99 % under kontroll",
|
||||
"Fully contained": "Helt under kontroll",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Färgen visar rapporterad kontrollgrad. Brandgränserna är förenklade till cirka 100 m.",
|
||||
"Malformed perimeter snapshot": "Felformaterad ögonblicksbild av brandgränser",
|
||||
"radio tag|All": "Alla",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "Uppdateringen av katalogen är begränsad; visar den tidigare stationskatalogen.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"JTWC warning ↗": "JTWC-varning ↗",
|
||||
"Active cyclone advisories and warnings": "Aktiva cyklonbulletiner och varningar",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran. Klicka på en tom plats på kartan för att rensa markeringen. Bulletiner från NOAA NHC/CPHC och varningar från JTWC. NHC:s kon beskriver osäkerheten i centrums prognosbana, inte stormens storlek eller hela riskområdet. JTWC:s riskområde för 34 knop är där vindar på 34 knop kan nå, vidgat med felet i banprognosen; det är ingen kon. Etiketterna på prognospunkterna är källans prognostimmar, inte tider räknade från utgivningen. Geometrin följer ytan; höjden är inte väderhöjd. Läs den officiella bulletinen eller den regionala varningscentralen.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}",
|
||||
"last growth {age} ago": "senaste tillväxt för {age} sedan",
|
||||
"Last 6 hours": "Senaste 6 timmarna",
|
||||
"6–24 hours": "6–24 timmar",
|
||||
"1–3 days": "1–3 dagar",
|
||||
"Older or unknown": "Äldre eller okänt",
|
||||
"Colour shows the age of each area.": "Färgen visar åldern på varje område.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Åldern räknas från WFIGS kartläggning, annars från postens senaste ändring. Brandgränser förenklade till ~100 m."
|
||||
}
|
||||
@@ -1092,11 +1092,6 @@
|
||||
"Unnamed incident": "Без назви",
|
||||
"Open {title} on InciWeb": "Відкрити {title} в InciWeb",
|
||||
"Perimeter source unavailable": "Джерело контурів пожеж недоступне",
|
||||
"Not contained or unknown": "Не локалізовано або невідомо",
|
||||
"Under 50% contained": "Локалізовано менш ніж на 50%",
|
||||
"50–99% contained": "Локалізовано на 50–99%",
|
||||
"Fully contained": "Повністю локалізовано",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Колір показує заявлений ступінь локалізації. Контури спрощено приблизно до 100 м.",
|
||||
"Malformed perimeter snapshot": "Некоректний знімок контурів пожеж",
|
||||
"radio tag|All": "Усі",
|
||||
"News": "Новини",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"JTWC warning ↗": "Попередження JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Чинні зведення та попередження про циклони",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Виберіть шторм на карті або у списку, щоб виділити його й перемістити камеру. Клацання по порожньому місцю карти знімає виділення. Зведення NOAA NHC/CPHC та попередження JTWC. Конус NHC показує невизначеність прогнозного треку центру, а не розмір шторму чи всю небезпечну зону. Небезпечна зона вітру 34 вузли JTWC — це область, куди може дійти вітер 34 вузли, розширена на похибку прогнозу треку; це не конус. Підписи прогнозних точок — завчасність джерела в годинах, а не час, обчислений від випуску. Геометрія повторює поверхню; висота не є метеорологічною висотою. Звіряйтеся з офіційним зведенням або регіональним центром попереджень.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}",
|
||||
"last growth {age} ago": "останнє зростання {age} тому",
|
||||
"Last 6 hours": "Останні 6 годин",
|
||||
"6–24 hours": "6–24 години",
|
||||
"1–3 days": "1–3 дні",
|
||||
"Older or unknown": "Старше або невідомо",
|
||||
"Colour shows the age of each area.": "Колір показує вік кожної ділянки.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Вік — від картування WFIGS, інакше від останнього редагування запису. Контури спрощено до ~100 м."
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"Unnamed incident": "未命名火情",
|
||||
"Open {title} on InciWeb": "在 InciWeb 上打开 {title}",
|
||||
"Perimeter source unavailable": "周界数据源不可用",
|
||||
"Not contained or unknown": "未控制或未知",
|
||||
"Under 50% contained": "控制低于 50%",
|
||||
"50–99% contained": "控制 50–99%",
|
||||
"Fully contained": "已全部控制",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "颜色表示报告的控制比例。周界简化至约 100 m。",
|
||||
"Malformed perimeter snapshot": "周界快照格式错误",
|
||||
"radio tag|All": "全部",
|
||||
"News": "新闻",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"JTWC warning ↗": "JTWC 警报 ↗",
|
||||
"Active cyclone advisories and warnings": "生效的气旋公告和警报",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地图上选择风暴,或在列表中选择风暴以选中它并移动镜头。点击地图空白处可取消选择。NOAA NHC/CPHC 公告和 JTWC 警报。NHC 的预报不确定范围表示中心预报路径的不确定性,而不是风暴大小或整个危险区域。JTWC 的 34 节风危险区是 34 节风可能到达的范围,并按路径预报误差加宽;它不是预报不确定范围。预报点标签是数据源的预报时效(小时),不是根据发布时间计算的时刻。几何形状贴合地表;高度不是气象高度。请以官方公告或区域警报中心为准。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}",
|
||||
"last growth {age} ago": "最近一次扩展于 {age}前",
|
||||
"Last 6 hours": "过去 6 小时",
|
||||
"6–24 hours": "6–24 小时",
|
||||
"1–3 days": "1–3 天",
|
||||
"Older or unknown": "更早或未知",
|
||||
"Colour shows the age of each area.": "颜色表示各区域在所示时刻的年龄。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "时长从 WFIGS 测绘时间算起,否则从记录的最后编辑时间算起。边界已简化至约 100 米。"
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"Unnamed incident": "未命名火情",
|
||||
"Open {title} on InciWeb": "在 InciWeb 上打開 {title}",
|
||||
"Perimeter source unavailable": "周界數據源不可用",
|
||||
"Not contained or unknown": "未控制或未知",
|
||||
"Under 50% contained": "控制低於 50%",
|
||||
"50–99% contained": "控制 50–99%",
|
||||
"Fully contained": "已全部控制",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "顏色表示報告的控制比例。周界簡化至約 100 m。",
|
||||
"Malformed perimeter snapshot": "周界快照格式錯誤",
|
||||
"radio tag|All": "全部",
|
||||
"News": "新聞",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"JTWC warning ↗": "JTWC 警報 ↗",
|
||||
"Active cyclone advisories and warnings": "生效的氣旋公告和警報",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地圖上選擇風暴,或在列表中選擇風暴以選中它並移動鏡頭。點擊地圖空白處可取消選擇。NOAA NHC/CPHC 公告和 JTWC 警報。NHC 的預報不確定範圍表示中心預報路徑的不確定性,而不是風暴大小或整個危險區域。JTWC 的 34 節風危險區是 34 節風可能到達的範圍,並按路徑預報誤差加寬;它不是預報不確定範圍。預報點標籤是數據源的預報時效(小時),不是根據發布時間計算的時刻。幾何形狀貼合地表;高度不是氣象高度。請以官方公告或區域警報中心為準。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}",
|
||||
"last growth {age} ago": "最近一次擴展於 {age}前",
|
||||
"Last 6 hours": "過去 6 小時",
|
||||
"6–24 hours": "6–24 小時",
|
||||
"1–3 days": "1–3 天",
|
||||
"Older or unknown": "更早或未知",
|
||||
"Colour shows the age of each area.": "顏色表示各區域在所示時刻的年齡。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "時長從 WFIGS 測繪時間算起,否則從記錄的最後編輯時間算起。邊界已簡化至約 100 米。"
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createIcons } from './icons.js';
|
||||
import { createContactIcons } from '../../data/aircraftIconLayer.js';
|
||||
import {
|
||||
createContactIcons,
|
||||
placedPlanSpread,
|
||||
} from '../../data/aircraftIconLayer.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import {
|
||||
aircraftMotionRegime,
|
||||
@@ -269,8 +272,10 @@ test('a live contact a placement places is drawn along where it places it', (t)
|
||||
const now = icons._displayMs();
|
||||
const leadMs = Date.now() - now;
|
||||
icons._planIcon('p');
|
||||
// A plan's length, as this contact's are spread (a second on average).
|
||||
const planMs = 1000 * placedPlanSpread('p');
|
||||
// Asked for the wall times the segment's ends stand for.
|
||||
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
|
||||
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
|
||||
assert.equal(regimes.length, 0, 'its own motion is not planned');
|
||||
const item = set.item('p');
|
||||
assert.equal(item.motion.kind, 'lerp');
|
||||
@@ -284,16 +289,16 @@ test('a live contact a placement places is drawn along where it places it', (t)
|
||||
Cesium.Cartesian3.distance(
|
||||
item.motion.to,
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
(now + 1000 + leadMs - t0) / 10_000,
|
||||
(now + planMs + leadMs - t0) / 10_000,
|
||||
30,
|
||||
2000,
|
||||
),
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(item.motion.t0, now);
|
||||
assert.equal(item.motion.t1, now + 1000);
|
||||
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
|
||||
assert.equal(set.expires('p'), now + 1000);
|
||||
assert.equal(item.motion.t1, now + planMs);
|
||||
assert.ok(Math.abs(item.motion.courseSlopeDeg - planMs / 1000) < 1e-9);
|
||||
assert.equal(set.expires('p'), now + planMs);
|
||||
|
||||
// No answer: the layer's own motion plans it.
|
||||
places = false;
|
||||
|
||||
@@ -11,7 +11,6 @@ export function createLifecycle({
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { onMilitaryLayerActiveChange } = services.militaryRegistry;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
@@ -112,7 +111,8 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
@@ -168,7 +168,7 @@ export function createLifecycle({
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
releaseContinuousRender('flights');
|
||||
parts.rendering._stopPace();
|
||||
parts.rendering._releaseModels();
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
@@ -208,7 +208,7 @@ export function createLifecycle({
|
||||
flightState._enrichActive = 0;
|
||||
flightState._enrichLastDispatchMs = 0;
|
||||
parts.controller._abortActiveUpdates();
|
||||
releaseContinuousRender('flights'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -10,7 +10,6 @@ export function createLifecycle({
|
||||
resolveAsset,
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { setMilitaryLayerActive } = services.militaryRegistry;
|
||||
@@ -93,7 +92,8 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('military'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
@@ -151,7 +151,7 @@ export function createLifecycle({
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
releaseContinuousRender('military');
|
||||
parts.rendering._stopPace();
|
||||
parts.rendering._releaseModels();
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
@@ -191,7 +191,7 @@ export function createLifecycle({
|
||||
flightState.timeline?.stop();
|
||||
flightState.lifetime.abort();
|
||||
parts.controller._abortActiveUpdates();
|
||||
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -8,13 +8,14 @@ import { buildIncidentCard } from './cards.js';
|
||||
|
||||
const now = Date.UTC(2026, 9, 14);
|
||||
const row = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Lake',
|
||||
acres: 1200,
|
||||
containedPct: 40,
|
||||
state: 'CA',
|
||||
discoveredTime: now - 2 * 3600e3,
|
||||
updatedTime: now - 3600e3,
|
||||
lastGrowthTime: now - 3 * 3600e3,
|
||||
cause: 'Human',
|
||||
behavior: 'Moderate',
|
||||
complexity: 'Type 3 Incident',
|
||||
@@ -33,6 +34,7 @@ test('en: the fire card keeps its English wording', () => {
|
||||
'part of North Complex',
|
||||
'Human cause · Moderate · Type 3 Incident',
|
||||
'1,500 personnel · Plumas County · $4.2M to date',
|
||||
'last growth 3h ago',
|
||||
'discovered 2h ago · updated 1h ago',
|
||||
'InciWeb ↗ · click card to open',
|
||||
]);
|
||||
@@ -44,8 +46,8 @@ for (const locale of ['es', 'ru']) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
assert.notEqual(
|
||||
t('Fully contained'),
|
||||
'Fully contained',
|
||||
t('Older or unknown'),
|
||||
'Older or unknown',
|
||||
'legend is translated',
|
||||
);
|
||||
const card = buildIncidentCard(row, now, {
|
||||
@@ -60,6 +62,7 @@ for (const locale of ['es', 'ru']) {
|
||||
'contained',
|
||||
'discovered',
|
||||
'updated',
|
||||
'last growth',
|
||||
'part of',
|
||||
'cause',
|
||||
'personnel',
|
||||
|
||||
@@ -3,7 +3,7 @@ import { formatNumber, t, tn } from '../../i18n/index.js';
|
||||
|
||||
export const PERIMETER_OVERLAY_SOURCE_ID = 'fire-perimeters';
|
||||
|
||||
/** CSS accent for a perimeter card by containment progress (mirrors the fill). */
|
||||
/** CSS accent for a perimeter card by containment progress. */
|
||||
export function containmentAccent(containedPct) {
|
||||
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
|
||||
if (containedPct < 50) return '#ff7a00';
|
||||
@@ -11,55 +11,6 @@ export function containmentAccent(containedPct) {
|
||||
return '#8bc34a';
|
||||
}
|
||||
|
||||
/** Shoelace area along short longitude edges (degree², relative sizes only). */
|
||||
function ringArea(ring) {
|
||||
let sum = 0;
|
||||
let [x1, y1] = ring[0];
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
let delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) delta -= 360;
|
||||
else if (delta < -180) delta += 360;
|
||||
const x2 = x1 + delta;
|
||||
const y2 = ring[i][1];
|
||||
sum += x1 * y2 - x2 * y1;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
}
|
||||
return Math.abs(sum / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor point for the incident card: the vertex mean of the largest polygon's
|
||||
* outer ring, with circular longitude. Callers own the Cartesian conversion.
|
||||
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
|
||||
* @returns {{lon: number, lat: number}}
|
||||
*/
|
||||
export function perimeterAnchorDegrees(polygons) {
|
||||
let best = null;
|
||||
let bestArea = -1;
|
||||
for (const rings of polygons) {
|
||||
const outer = rings[0];
|
||||
const area = ringArea(outer);
|
||||
if (area > bestArea) {
|
||||
bestArea = area;
|
||||
best = outer;
|
||||
}
|
||||
}
|
||||
// Vertex mean over the closed ring (first == last point dropped): perimeters
|
||||
// are compact enough that this stays inside or near the polygon.
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let lat = 0;
|
||||
const count = best.length - 1;
|
||||
const toRad = Math.PI / 180;
|
||||
for (let i = 0; i < count; i++) {
|
||||
sinLon += Math.sin(best[i][0] * toRad);
|
||||
cosLon += Math.cos(best[i][0] * toRad);
|
||||
lat += best[i][1];
|
||||
}
|
||||
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
|
||||
* es "4,2 M$". Null under $1,000.
|
||||
@@ -149,8 +100,9 @@ function formatAge(deltaMs) {
|
||||
/**
|
||||
* Build the overlay-host entry for one selected incident. The caller supplies
|
||||
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
|
||||
* @param {Object} row - Normalized perimeter row (see records.js).
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {Object} row - A snapshot fire (see records.js).
|
||||
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
|
||||
* `at`, or now.
|
||||
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
|
||||
* @returns {Object} World-overlay entry without `position`.
|
||||
*/
|
||||
@@ -194,13 +146,17 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
if (cost) response.push(t('{cost} to date', { cost }));
|
||||
}
|
||||
|
||||
const ago = (time) => (time == null ? null : formatAge(nowMs - time));
|
||||
const growth = ago(row.lastGrowthTime);
|
||||
const lastGrowth = growth
|
||||
? t('last growth {age} ago', { age: growth })
|
||||
: null;
|
||||
|
||||
const ages = [];
|
||||
const discovered = formatAge(nowMs - row.discoveredTime);
|
||||
if (row.discoveredTime != null && discovered)
|
||||
ages.push(t('discovered {age} ago', { age: discovered }));
|
||||
const updated = formatAge(nowMs - row.updatedTime);
|
||||
if (row.updatedTime != null && updated)
|
||||
ages.push(t('updated {age} ago', { age: updated }));
|
||||
const discovered = ago(row.discoveredTime);
|
||||
if (discovered) ages.push(t('discovered {age} ago', { age: discovered }));
|
||||
const updated = ago(row.updatedTime);
|
||||
if (updated) ages.push(t('updated {age} ago', { age: updated }));
|
||||
|
||||
const details = [facts.join(' · ')];
|
||||
if (row.complexName)
|
||||
@@ -209,6 +165,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
);
|
||||
if (situation.length) details.push(situation.join(' · '));
|
||||
if (response.length) details.push(response.join(' · '));
|
||||
if (lastGrowth) details.push(lastGrowth);
|
||||
if (ages.length) details.push(ages.join(' · '));
|
||||
if (link) details.push(t('InciWeb ↗ · click card to open'));
|
||||
|
||||
@@ -216,7 +173,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
name: row.name || t('Unnamed incident'),
|
||||
});
|
||||
return {
|
||||
id: `fire-perimeter-card:${row.stableId}`,
|
||||
id: `fire-perimeter-card:${row.id}`,
|
||||
// `selected` picks the paint lane and collision protection; an explicit
|
||||
// paintLane would override it in the host's lane resolver.
|
||||
selected: true,
|
||||
|
||||
@@ -1,99 +1,12 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { perimeterAnchorDegrees, buildIncidentCard } from './cards.js';
|
||||
|
||||
const square = [
|
||||
[-108.2, 35.0],
|
||||
[-108.0, 35.0],
|
||||
[-108.0, 35.2],
|
||||
[-108.2, 35.2],
|
||||
[-108.2, 35.0],
|
||||
];
|
||||
const tiny = [
|
||||
[-107.01, 34.0],
|
||||
[-107.0, 34.0],
|
||||
[-107.0, 34.01],
|
||||
[-107.01, 34.0],
|
||||
];
|
||||
|
||||
test('the card anchors at the vertex mean of the largest polygon', () => {
|
||||
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
|
||||
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
|
||||
});
|
||||
|
||||
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
|
||||
const vertices = [
|
||||
[179, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
];
|
||||
for (let start = 0; start < vertices.length; start++) {
|
||||
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
|
||||
for (const points of [rotated, [...rotated].reverse()]) {
|
||||
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
|
||||
for (const boundary of [-180, 180]) {
|
||||
const ring = [
|
||||
[179, 10],
|
||||
[boundary, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
[179, 10],
|
||||
];
|
||||
const anchor = perimeterAnchorDegrees([[ring]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('multipart cards compare polygon areas along short dateline edges', () => {
|
||||
const ordinary = [
|
||||
[10, 20],
|
||||
[11, 20],
|
||||
[11, 21],
|
||||
[10, 21],
|
||||
[10, 20],
|
||||
];
|
||||
for (const width of [0.2, 2]) {
|
||||
const crossing = [
|
||||
[180 - width / 2, 10],
|
||||
[-180 + width / 2, 10],
|
||||
[-180 + width / 2, 10 + width],
|
||||
[180 - width / 2, 10 + width],
|
||||
[180 - width / 2, 10],
|
||||
];
|
||||
for (const ring of [crossing, [...crossing].reverse()]) {
|
||||
for (const polygons of [
|
||||
[[ring], [ordinary]],
|
||||
[[ordinary], [ring]],
|
||||
]) {
|
||||
const anchor = perimeterAnchorDegrees(polygons);
|
||||
if (width < 1) {
|
||||
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
|
||||
} else {
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
import { buildIncidentCard } from './cards.js';
|
||||
|
||||
test('a full incident row renders name, size, containment, and ages', () => {
|
||||
const now = 1758000000000;
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: '2026-NMGNF-000123',
|
||||
id: '2026-NMGNF-000123',
|
||||
name: 'Frijoles',
|
||||
acres: 15956.4,
|
||||
containedPct: 74,
|
||||
@@ -101,6 +14,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
category: 'WF',
|
||||
discoveredTime: now - 36 * 3600000,
|
||||
updatedTime: now - 2 * 3600000,
|
||||
lastGrowthTime: now - 5 * 3600000,
|
||||
cause: 'Natural',
|
||||
behavior: 'Active',
|
||||
personnel: 380,
|
||||
@@ -116,6 +30,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
'15,956 ac · 74% contained · US-NM',
|
||||
'Natural cause · Active · Type 3 Incident',
|
||||
'380 personnel · Sandoval County · $4.2M to date',
|
||||
'last growth 5h ago',
|
||||
'discovered 1d ago · updated 2h ago',
|
||||
]);
|
||||
assert.equal(card.selected, true);
|
||||
@@ -125,7 +40,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
test('missing attributes degrade to available facts instead of placeholders', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: null,
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -149,7 +64,7 @@ test('missing attributes degrade to available facts instead of placeholders', ()
|
||||
test('a known InciWeb page adds a link line to the card', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Timber',
|
||||
acres: 25426,
|
||||
containedPct: 44,
|
||||
@@ -177,7 +92,7 @@ test('a known InciWeb page adds a link line to the card', () => {
|
||||
test('the selected card claims the selected paint lane, not the ambient lane', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -204,7 +119,7 @@ test('the selected card claims the selected paint lane, not the ambient lane', (
|
||||
|
||||
test('costs near a unit boundary promote to the larger unit', () => {
|
||||
const base = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -232,7 +147,7 @@ test('costs near a unit boundary promote to the larger unit', () => {
|
||||
test('a complex member names its complex on the card', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 342923,
|
||||
containedPct: 99,
|
||||
@@ -256,7 +171,7 @@ test('a complex member names its complex on the card', () => {
|
||||
test('a card without a link is not interactive', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -279,7 +194,7 @@ test('a card without a link is not interactive', () => {
|
||||
test('partial incident details render only the facts that exist', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Whiskey',
|
||||
acres: 542,
|
||||
containedPct: 48,
|
||||
@@ -305,7 +220,7 @@ test('partial incident details render only the facts that exist', () => {
|
||||
|
||||
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
|
||||
const row = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Grey',
|
||||
acres: 0.25,
|
||||
containedPct: null,
|
||||
@@ -333,3 +248,22 @@ test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () =>
|
||||
'1 ac · containment unknown · US-WA',
|
||||
);
|
||||
});
|
||||
|
||||
test('ages count from the moment shown, not from the clock', () => {
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'past',
|
||||
name: 'Past',
|
||||
containedPct: 10,
|
||||
discoveredTime: at - 3 * 86400000,
|
||||
updatedTime: at - 30 * 60000,
|
||||
lastGrowthTime: at - 7 * 3600000,
|
||||
},
|
||||
at,
|
||||
);
|
||||
assert.deepEqual(card.details.slice(-2), [
|
||||
'last growth 7h ago',
|
||||
'discovered 3d ago · updated 30m ago',
|
||||
]);
|
||||
});
|
||||
@@ -17,19 +17,8 @@ function normalizeName(name) {
|
||||
.replace(/ fire$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one WFIGS incident against the publication catalog.
|
||||
* Only rows whose normalized title equals the incident's normalized name
|
||||
* count. Ambiguity resolves by the tau dispatch unit's state prefix, then
|
||||
* by newest incident id (same-state duplicates are usually reburns of the
|
||||
* same name). The `/node/{id}` link 301s to the canonical page, so no slug
|
||||
* construction is needed.
|
||||
* @param {?Array} publications - Publication catalog rows.
|
||||
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
|
||||
* @returns {?string} InciWeb node URL.
|
||||
*/
|
||||
export function resolveInciwebNodeLink(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return null;
|
||||
function nodeCandidates(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return [];
|
||||
const wanted = normalizeName(name);
|
||||
let candidates = publications.filter(
|
||||
(row) =>
|
||||
@@ -51,20 +40,26 @@ export function resolveInciwebNodeLink(publications, { name, state }) {
|
||||
row.tau.slice(0, 2).toLowerCase() === statePrefix,
|
||||
);
|
||||
} else if (candidates.length > 1) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
if (candidates.length > 1) {
|
||||
// Same-state duplicates are usually reburns of the same name — newest
|
||||
// wins here, and the publication-currency check guards the final link.
|
||||
candidates = [
|
||||
candidates.reduce((a, b) =>
|
||||
Number(a.incident_id) >= Number(b.incident_id) ? a : b,
|
||||
),
|
||||
];
|
||||
}
|
||||
return candidates.length === 1
|
||||
? `https://inciweb.wildfire.gov/node/${candidates[0].incident_id}`
|
||||
: null;
|
||||
// Same-state duplicates are usually reburns of the same name. Newest wins live.
|
||||
return candidates
|
||||
.sort((a, b) => Number(b.incident_id) - Number(a.incident_id))
|
||||
.map((row) => `https://inciweb.wildfire.gov/node/${row.incident_id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one WFIGS incident against the publication catalog.
|
||||
* Only rows whose normalized title equals the incident's normalized name
|
||||
* count. Matches are filtered by the tau dispatch unit's state prefix.
|
||||
* The `/node/{id}` link 301s to the canonical page, so no slug construction
|
||||
* is needed.
|
||||
* @param {?Array} publications - Publication catalog rows.
|
||||
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
|
||||
* @returns {?string} InciWeb node URL.
|
||||
*/
|
||||
export function resolveInciwebNodeLink(publications, incident) {
|
||||
return nodeCandidates(publications, incident)[0] ?? null;
|
||||
}
|
||||
|
||||
/** The publication id inside a node link produced above, or null. */
|
||||
@@ -79,7 +74,8 @@ export function inciwebNodeId(link) {
|
||||
// whose page predates discovery by more than this is an archived
|
||||
// same-name incident from a earlier season.
|
||||
const CREATED_BEFORE_DISCOVERY_MS = 60 * 24 * 3600000;
|
||||
// Without a discovery date, require recent editorial activity on the page.
|
||||
// Without a discovery date, require editorial activity on the page in the
|
||||
// 180 days up to the moment shown.
|
||||
const CHANGED_WITHIN_MS = 180 * 24 * 3600000;
|
||||
|
||||
/**
|
||||
@@ -97,7 +93,8 @@ export function isCurrentPublication(
|
||||
return createdMs >= discoveredTime - CREATED_BEFORE_DISCOVERY_MS;
|
||||
}
|
||||
if (Number.isFinite(changedMs)) {
|
||||
return nowMs - changedMs <= CHANGED_WITHIN_MS;
|
||||
const age = nowMs - changedMs;
|
||||
return age >= 0 && age <= CHANGED_WITHIN_MS;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -132,6 +129,14 @@ export function createInciwebPublicationSource({
|
||||
};
|
||||
}
|
||||
|
||||
/** Every same-name page that could be this incident's, newest first: the own name's, else its complex's. */
|
||||
export function findInciwebLinks(publications, { name, state, complexName }) {
|
||||
const links = nodeCandidates(publications, { name, state });
|
||||
return links.length
|
||||
? links
|
||||
: nodeCandidates(publications, { name: complexName, state });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one WFIGS incident to its InciWeb page, or null.
|
||||
* The incident's own name is tried first; a member of a complex whose own
|
||||
@@ -143,11 +148,8 @@ export function createInciwebPublicationSource({
|
||||
* - WFIGS row facts.
|
||||
* @returns {?string} InciWeb URL.
|
||||
*/
|
||||
export function findInciwebLink(publications, { name, state, complexName }) {
|
||||
return (
|
||||
resolveInciwebNodeLink(publications, { name, state }) ??
|
||||
resolveInciwebNodeLink(publications, { name: complexName, state })
|
||||
);
|
||||
export function findInciwebLink(publications, incident) {
|
||||
return findInciwebLinks(publications, incident)[0] ?? null;
|
||||
}
|
||||
|
||||
/** Fetch the full InciWeb incident catalog. */
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
resolveInciwebNodeLink,
|
||||
createInciwebIndexSource,
|
||||
createInciwebPublicationSource,
|
||||
@@ -142,6 +143,34 @@ test('ambiguous titles disambiguate by state, then newest id', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('same-name pages list newest first, falling back to the complex', () => {
|
||||
const rows = [
|
||||
{
|
||||
incident_id: '100',
|
||||
tau: 'ORXXX Coyote Fire',
|
||||
incident_title: 'Coyote Fire',
|
||||
},
|
||||
{
|
||||
incident_id: '328922',
|
||||
tau: 'OR95S Coyote Fire',
|
||||
incident_title: 'Coyote Fire',
|
||||
},
|
||||
{ incident_id: '5', tau: 'ORXXX', incident_title: 'Big Complex' },
|
||||
];
|
||||
const incident = {
|
||||
name: 'Coyote',
|
||||
state: 'US-OR',
|
||||
complexName: 'Big Complex',
|
||||
};
|
||||
assert.deepEqual(findInciwebLinks(rows, incident), [
|
||||
'https://inciweb.wildfire.gov/node/328922',
|
||||
'https://inciweb.wildfire.gov/node/100',
|
||||
]);
|
||||
assert.deepEqual(findInciwebLinks(rows, { ...incident, name: 'Nope' }), [
|
||||
'https://inciweb.wildfire.gov/node/5',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a complex member falls back to its complex page', () => {
|
||||
assert.equal(
|
||||
findInciwebLink(catalog, {
|
||||
@@ -214,6 +243,14 @@ test('publication currency accepts pages created around or after discovery', ()
|
||||
),
|
||||
false,
|
||||
);
|
||||
// An edit after the moment shown says nothing about the page then.
|
||||
assert.equal(
|
||||
isCurrentPublication(
|
||||
{ createdMs: now - 900 * day, changedMs: now + 10 * day },
|
||||
{ discoveredTime: null, nowMs: now },
|
||||
),
|
||||
false,
|
||||
);
|
||||
// Unusable timestamps fail closed.
|
||||
assert.equal(
|
||||
isCurrentPublication(
|
||||
|
||||
+277
-143
@@ -1,34 +1,64 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
|
||||
import {
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
perimeterAnchorDegrees,
|
||||
buildIncidentCard,
|
||||
containmentAccent,
|
||||
} from './cards.js';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
inciwebNodeId,
|
||||
isCurrentPublication,
|
||||
} from './inciweb.js';
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||||
export { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
export {
|
||||
normalizeFirePerimeterSnapshot,
|
||||
perimeterAnchorDegrees,
|
||||
} from './records.js';
|
||||
export { createWfigsPerimeterSource } from './source.js';
|
||||
export * from './cards.js';
|
||||
export * from './inciweb.js';
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
/**
|
||||
* Fill/line colour for a perimeter by containment progress (same ramp as the
|
||||
* card accent), as a renderer colour `[r, g, b, a]`.
|
||||
* Piece colours by age, newest first. A piece of unknown birth, or born after
|
||||
* the moment shown, is drawn as the oldest; the legend counts fires by
|
||||
* `lastGrowthTime` the same way.
|
||||
*/
|
||||
export function containmentColor(containedPct) {
|
||||
return hexColor(containmentAccent(containedPct));
|
||||
export const PERIMETER_AGE_BANDS = Object.freeze(
|
||||
[
|
||||
{ upToMs: 6 * HOUR_MS, color: '#ffc72e', label: msg('Last 6 hours') },
|
||||
{ upToMs: 24 * HOUR_MS, color: '#ff730d', label: msg('6–24 hours') },
|
||||
{ upToMs: 72 * HOUR_MS, color: '#d9290d', label: msg('1–3 days') },
|
||||
{
|
||||
upToMs: Infinity,
|
||||
color: '#730f0a',
|
||||
label: msg('Older or unknown'),
|
||||
},
|
||||
].map((band) => Object.freeze(band)),
|
||||
);
|
||||
|
||||
function perimeterAgeBand(time, atMs) {
|
||||
const last = PERIMETER_AGE_BANDS.length - 1;
|
||||
if (!Number.isFinite(time) || time > atMs) return last;
|
||||
return PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => atMs - time < upToMs);
|
||||
}
|
||||
|
||||
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
|
||||
const FILL_ALPHA = 0.35;
|
||||
const LINE_ALPHA = 0.9;
|
||||
const LINE_WIDTH_PX = 2;
|
||||
|
||||
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
|
||||
const validLine = (line, min) =>
|
||||
Array.isArray(line) &&
|
||||
line.length >= min &&
|
||||
line.every(
|
||||
(point) =>
|
||||
Array.isArray(point) &&
|
||||
Number.isFinite(point[0]) &&
|
||||
Number.isFinite(point[1]),
|
||||
);
|
||||
const validAnchor = (anchor) =>
|
||||
Number.isFinite(anchor?.lon) && Number.isFinite(anchor?.lat);
|
||||
|
||||
/**
|
||||
* The draw sets the perimeters are drawn in start with this; each layer has
|
||||
@@ -52,10 +82,29 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
|
||||
/**
|
||||
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
|
||||
*
|
||||
* Each perimeter is a ground-clamped fill in one renderer draw set and its
|
||||
* fire line a draped line in another (`drawOf(viewer)`), made at `init`.
|
||||
* Given a Cesium viewer with no renderer bound, the
|
||||
* caller loads the package's `./render/cesium/unbound` export first.
|
||||
* `source.getSnapshot({signal})` resolves to the snapshot the layer draws
|
||||
* (records.js `firePerimeterSnapshot` builds it from WFIGS):
|
||||
* - `at`: the moment shown, epoch ms, or null for now. Ages, colours and the
|
||||
* legend count from it.
|
||||
* - `fetchedAt` (epoch ms or null) and `stale`: a stale snapshot is dated by
|
||||
* its `fetchedAt`.
|
||||
* - `revision`: a string that changes whenever any piece does. Without a
|
||||
* string revision the layer redraws on every read.
|
||||
* - `note`: text the layer row shows with the legend, or null.
|
||||
* - `fires`: `id` (string), `anchor` (`{lon, lat}` degrees, where the card
|
||||
* stands), `lastGrowthTime` (epoch ms or null; the legend counts by it) and
|
||||
* the card facts (`name`, `acres`, `containedPct`, `state`,
|
||||
* `discoveredTime`, `updatedTime`, …). A fire without an id or anchor is
|
||||
* dropped. A fire may have no pieces: it keeps its card and legend count.
|
||||
* - `pieces`: `fireId` (a listed fire's id; any other piece is dropped),
|
||||
* `born` (epoch ms or null; the piece's colour), `polygons` (each
|
||||
* `[outer, ...holes]`, rings of `[lon, lat]`) and `outline` (lines of
|
||||
* `[lon, lat]` drawn as the fire line, apart from the fill, so a piece cut
|
||||
* from a larger area has no line along the cut).
|
||||
*
|
||||
* When to read again (a timeline, the camera) is the host's call, through
|
||||
* the manager's `refreshLayer`. Given a Cesium viewer with no renderer bound,
|
||||
* the caller loads the package's `./render/cesium/unbound` export first.
|
||||
*/
|
||||
export function createFirePerimetersLayer({
|
||||
source,
|
||||
@@ -71,12 +120,17 @@ export function createFirePerimetersLayer({
|
||||
let _viewer = null;
|
||||
let _request = null;
|
||||
let _linkRequest = null;
|
||||
let _snapshotSignature = null;
|
||||
// What the sets show: the snapshot revision and each piece's age band.
|
||||
let _drawnKey = null;
|
||||
let _fills = null;
|
||||
let _lines = null;
|
||||
let _setIds = new Set();
|
||||
let _count = 0;
|
||||
let _lastUpdate = null;
|
||||
// The moment the snapshot shows (null: now), and the source's legend note.
|
||||
let _at = null;
|
||||
let _note = null;
|
||||
// The moment the drawn colours were computed at; the legend counts at it
|
||||
// too, so it matches the map between reads.
|
||||
let _bandsAt = null;
|
||||
// The proxy's last snapshot, served while WFIGS is unreachable.
|
||||
let _stale = false;
|
||||
let _lastError = null;
|
||||
@@ -88,16 +142,26 @@ export function createFirePerimetersLayer({
|
||||
let _inciwebIndex = [];
|
||||
let _indexFetchedAt = 0;
|
||||
let _indexFetchInFlight = false;
|
||||
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
|
||||
const _rowById = new Map();
|
||||
// Link → currency verdict from the publication check; unknown links are
|
||||
// absent. Failed checks are not cached so a transient outage retries.
|
||||
const _linkVerdicts = new Map();
|
||||
let _fireById = new Map();
|
||||
/** `<set id>\n<item id>` → the fire that item belongs to. */
|
||||
const _fireByItem = new Map();
|
||||
const shownAt = () => _at ?? Date.now();
|
||||
const _linkPublications = new Map();
|
||||
// Retry failed pages on reselection or when a read finds the card linkless.
|
||||
const _linkFailures = new Set();
|
||||
function abortLinkVerification() {
|
||||
_linkRequest?.controller.abort();
|
||||
_linkRequest = null;
|
||||
}
|
||||
|
||||
function resetSelection() {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
}
|
||||
|
||||
const canSelect = () => overlayHost && inputFor && picking;
|
||||
|
||||
/**
|
||||
@@ -141,29 +205,57 @@ export function createFirePerimetersLayer({
|
||||
.getPublication(id, { signal })
|
||||
.then((publication) => {
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkVerdicts.set(
|
||||
link,
|
||||
isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
}),
|
||||
);
|
||||
if (_selectedId === row.stableId) publishSelectedCard();
|
||||
_linkPublications.set(link, publication ?? {});
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
})
|
||||
.catch(() => {
|
||||
// Fail closed without caching: no link now, retry on reselection.
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkFailures.add(link);
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
})
|
||||
.finally(() => {
|
||||
if (_linkRequest === request) _linkRequest = null;
|
||||
});
|
||||
}
|
||||
|
||||
function isCurrentLink(publication, row) {
|
||||
if (
|
||||
_at !== null &&
|
||||
!(Number.isFinite(publication.createdMs) && publication.createdMs <= _at)
|
||||
)
|
||||
return false;
|
||||
return isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
nowMs: shownAt(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The current page among verified candidates: the one whose incident began
|
||||
* nearest the fire's discovery, else (no discovery date) the newest.
|
||||
*/
|
||||
function chooseLink(links, row) {
|
||||
let best = null;
|
||||
let bestGap = Infinity;
|
||||
for (const link of links) {
|
||||
const publication = _linkPublications.get(link);
|
||||
if (!publication || !isCurrentLink(publication, row)) continue;
|
||||
const gap = Number.isFinite(row.discoveredTime)
|
||||
? Math.abs(publication.createdMs - row.discoveredTime)
|
||||
: 0;
|
||||
if (best === null || gap < bestGap) {
|
||||
best = link;
|
||||
bestGap = gap;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function publishSelectedCard() {
|
||||
if (!canSelect()) return;
|
||||
const row = _selectedId ? _rowById.get(_selectedId) : null;
|
||||
const row = _selectedId ? _fireById.get(_selectedId) : null;
|
||||
if (!row) {
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
overlayHost.setEntries(
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
@@ -171,12 +263,36 @@ export function createFirePerimetersLayer({
|
||||
);
|
||||
return;
|
||||
}
|
||||
const candidate = findInciwebLink(_inciwebIndex, row);
|
||||
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
|
||||
_selectedLink =
|
||||
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
|
||||
// Live, the newest same-name page stands for the incident. A past `at`
|
||||
// checks each own-name page, since the newest may postdate it, and the
|
||||
// complex's pages only when none of those is current.
|
||||
const groups =
|
||||
_at === null
|
||||
? [findInciwebLinks(_inciwebIndex, row).slice(0, 1)]
|
||||
: [
|
||||
findInciwebLinks(_inciwebIndex, {
|
||||
name: row.name,
|
||||
state: row.state,
|
||||
}),
|
||||
findInciwebLinks(_inciwebIndex, {
|
||||
name: row.complexName,
|
||||
state: row.state,
|
||||
}),
|
||||
];
|
||||
_selectedLink = null;
|
||||
for (const links of groups) {
|
||||
const unverified = links.find(
|
||||
(link) => !_linkPublications.has(link) && !_linkFailures.has(link),
|
||||
);
|
||||
if (unverified) {
|
||||
verifyLink(unverified, row);
|
||||
break;
|
||||
}
|
||||
_selectedLink = chooseLink(links, row);
|
||||
if (_selectedLink) break;
|
||||
}
|
||||
const card = {
|
||||
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
|
||||
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
|
||||
position: fromDegrees(row.anchor.lon, row.anchor.lat),
|
||||
};
|
||||
if (!openExternal) card.interactive = false;
|
||||
@@ -201,11 +317,9 @@ export function createFirePerimetersLayer({
|
||||
* of this layer's own sets, for an incident drawn now; else null.
|
||||
*/
|
||||
function pickedIncidentId(hit) {
|
||||
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
|
||||
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
|
||||
return null;
|
||||
const incidentId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
|
||||
return _rowById.has(incidentId) ? incidentId : null;
|
||||
if (!hit || hit.surface) return null;
|
||||
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
|
||||
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
@@ -236,6 +350,7 @@ export function createFirePerimetersLayer({
|
||||
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
|
||||
if (incidentId) {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = incidentId;
|
||||
publishSelectedCard();
|
||||
return;
|
||||
@@ -247,23 +362,67 @@ export function createFirePerimetersLayer({
|
||||
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
|
||||
}
|
||||
if (_selectedId) {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
publishSelectedCard();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function drawPieces(pieces, bands) {
|
||||
const nextFills = [];
|
||||
const nextLines = [];
|
||||
const counts = new Map();
|
||||
_fireByItem.clear();
|
||||
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
|
||||
const itemId = (fireId, kind) => {
|
||||
const key = `${kind}${fireId}`;
|
||||
const n = counts.get(key) ?? 0;
|
||||
counts.set(key, n + 1);
|
||||
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
|
||||
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
|
||||
return id;
|
||||
};
|
||||
for (const [index, piece] of pieces.entries()) {
|
||||
const { color } = PERIMETER_AGE_BANDS[bands[index]];
|
||||
// Each exterior keeps its own holes.
|
||||
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
|
||||
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 3)))
|
||||
continue;
|
||||
nextFills.push({
|
||||
id: itemId(piece.fireId, ''),
|
||||
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
|
||||
fill: hexColor(color, FILL_ALPHA),
|
||||
height: 'clampGround',
|
||||
});
|
||||
}
|
||||
// The fire line: the piece's outline draped on the ground, apart from
|
||||
// its fill, so a piece cut from a larger area has no line along the
|
||||
// cut (lines take ECEF, draw.d.ts `LineItem`).
|
||||
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
|
||||
if (!validLine(line, 2)) continue;
|
||||
nextLines.push({
|
||||
id: itemId(piece.fireId, 'line:'),
|
||||
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
|
||||
widthPx: LINE_WIDTH_PX,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: hexColor(color, LINE_ALPHA) },
|
||||
});
|
||||
}
|
||||
}
|
||||
_fills.set(nextFills);
|
||||
_lines.set(nextLines);
|
||||
console.log(
|
||||
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
|
||||
);
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickSubscription?.();
|
||||
_clickSubscription = null;
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
if (overlayHost) {
|
||||
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
|
||||
@@ -292,9 +451,7 @@ export function createFirePerimetersLayer({
|
||||
clampTo: 'both',
|
||||
show: false,
|
||||
});
|
||||
_setIds = new Set([_fills.id, _lines.id]);
|
||||
_viewer = viewer;
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -318,87 +475,58 @@ export function createFirePerimetersLayer({
|
||||
clearSelection();
|
||||
},
|
||||
|
||||
async update() {
|
||||
async update(_viewerArg, { signal } = {}) {
|
||||
if (!_enabled || !_fills) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
refreshInciwebIndex(request.signal);
|
||||
const abort = () => request.abort(signal.reason);
|
||||
if (signal?.aborted) abort();
|
||||
else signal?.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
// The source contract is getSnapshot; a source that can also say how
|
||||
// fresh its rows are (the WFIGS proxy) offers getSnapshotDetail.
|
||||
const snapshot =
|
||||
typeof source.getSnapshotDetail === 'function'
|
||||
? await source.getSnapshotDetail({ signal: request.signal })
|
||||
: { rows: await source.getSnapshot({ signal: request.signal }) };
|
||||
refreshInciwebIndex(request.signal);
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
const { rows } = snapshot;
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
_stale = snapshot.stale === true;
|
||||
// A stale snapshot is as old as its fetch, not this poll.
|
||||
const updatedAt =
|
||||
_stale && Number.isFinite(snapshot.fetchedAt)
|
||||
? snapshot.fetchedAt
|
||||
: Date.now();
|
||||
|
||||
// Incident facts may change independently of the polygon's source clock.
|
||||
const signature = JSON.stringify(
|
||||
rows
|
||||
.map(({ polygons, ...facts }) => facts)
|
||||
.sort((a, b) => a.stableId.localeCompare(b.stableId)),
|
||||
_at = Number.isFinite(snapshot.at) ? snapshot.at : null;
|
||||
_note = typeof snapshot.note === 'string' ? snapshot.note : null;
|
||||
// A fire needs an id and the anchor its card stands on; a piece
|
||||
// needs its fire.
|
||||
const fires = new Map();
|
||||
for (const fire of snapshot.fires)
|
||||
if (typeof fire?.id === 'string' && validAnchor(fire.anchor))
|
||||
fires.set(fire.id, fire);
|
||||
const pieces = snapshot.pieces.filter((piece) =>
|
||||
fires.has(piece?.fireId),
|
||||
);
|
||||
if (signature === _snapshotSignature) {
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
return true;
|
||||
const atMs = shownAt();
|
||||
const bands = pieces.map((piece) => perimeterAgeBand(piece.born, atMs));
|
||||
const drawKey =
|
||||
typeof snapshot.revision === 'string'
|
||||
? `${snapshot.revision}\n${bands.join('')}`
|
||||
: null;
|
||||
_fireById = fires;
|
||||
_bandsAt = atMs;
|
||||
if (drawKey === null || drawKey !== _drawnKey) {
|
||||
drawPieces(pieces, bands);
|
||||
_drawnKey = drawKey;
|
||||
}
|
||||
abortLinkVerification();
|
||||
const nextFills = [];
|
||||
const nextLines = [];
|
||||
_rowById.clear();
|
||||
for (const row of rows) {
|
||||
const color = containmentColor(row.containedPct);
|
||||
for (const [index, rings] of row.polygons.entries()) {
|
||||
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
|
||||
// Each exterior keeps its own holes.
|
||||
nextFills.push({
|
||||
id,
|
||||
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
|
||||
fill: withAlpha(color, 0.25),
|
||||
height: 'clampGround',
|
||||
});
|
||||
// The fire line: the exterior ring draped on the ground (lines
|
||||
// take ECEF, draw.d.ts `LineItem`).
|
||||
nextLines.push({
|
||||
id,
|
||||
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
|
||||
widthPx: 2,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: withAlpha(color, 0.9) },
|
||||
});
|
||||
}
|
||||
// Keep a geometry-free projection: the coordinate arrays would
|
||||
// otherwise be retained for the layer's lifetime while only the
|
||||
// anchor is ever read again.
|
||||
const { polygons, ...facts } = row;
|
||||
_rowById.set(row.stableId, {
|
||||
...facts,
|
||||
anchor: perimeterAnchorDegrees(polygons),
|
||||
});
|
||||
// Refresh (or drop) the selected incident's card against the new
|
||||
// snapshot: its ages move with `at` even when nothing is redrawn.
|
||||
if (_selectedId) {
|
||||
if (_selectedLink === null && !_linkRequest) _linkFailures.clear();
|
||||
publishSelectedCard();
|
||||
}
|
||||
|
||||
_fills.set(nextFills);
|
||||
_lines.set(nextLines);
|
||||
_snapshotSignature = signature;
|
||||
// Refresh (or drop) the selected incident's card against the new feed.
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_count = rows.length;
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
console.log(
|
||||
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
@@ -409,6 +537,7 @@ export function createFirePerimetersLayer({
|
||||
_stale = false;
|
||||
return false;
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
@@ -418,18 +547,20 @@ export function createFirePerimetersLayer({
|
||||
_request = null;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_rowById.clear();
|
||||
_snapshotSignature = null;
|
||||
_fireById = new Map();
|
||||
_fireByItem.clear();
|
||||
_drawnKey = null;
|
||||
_at = null;
|
||||
_bandsAt = null;
|
||||
_note = null;
|
||||
_inciwebIndex = [];
|
||||
_indexFetchedAt = 0;
|
||||
_linkVerdicts.clear();
|
||||
_linkPublications.clear();
|
||||
_viewer = null;
|
||||
_enabled = false;
|
||||
_fills?.dispose();
|
||||
_lines?.dispose();
|
||||
_fills = _lines = null;
|
||||
_setIds = new Set();
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -442,11 +573,15 @@ export function createFirePerimetersLayer({
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
const result = [];
|
||||
for (const row of _rowById.values()) {
|
||||
for (const fire of _fireById.values()) {
|
||||
if (result.length >= limit) break;
|
||||
const { anchor, stableId, ...facts } = row;
|
||||
const { anchor, id, ...facts } = fire;
|
||||
// A time after the moment shown is unknown in this snapshot.
|
||||
if (_at !== null)
|
||||
for (const key of ['discoveredTime', 'updatedTime', 'lastGrowthTime'])
|
||||
if (facts[key] > _at) facts[key] = null;
|
||||
result.push({
|
||||
id: stableId,
|
||||
id,
|
||||
...facts,
|
||||
lat: anchor.lat,
|
||||
lon: anchor.lon,
|
||||
@@ -455,34 +590,33 @@ export function createFirePerimetersLayer({
|
||||
return result;
|
||||
},
|
||||
|
||||
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
|
||||
getAnalystRecordsAt() {
|
||||
return _at;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
const bands = [
|
||||
{ label: t('Not contained or unknown'), color: containmentAccent(0) },
|
||||
{ label: t('Under 50% contained'), color: containmentAccent(1) },
|
||||
{ label: t('50–99% contained'), color: containmentAccent(50) },
|
||||
{ label: t('Fully contained'), color: containmentAccent(100) },
|
||||
];
|
||||
const atMs = _bandsAt;
|
||||
const counts = PERIMETER_AGE_BANDS.map(() => 0);
|
||||
for (const fire of _fireById.values())
|
||||
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
|
||||
return {
|
||||
chips: [],
|
||||
legend: bands.map((band, index) => ({
|
||||
...band,
|
||||
count: [..._rowById.values()].filter(
|
||||
(row) => containmentAccent(row.containedPct) === band.color,
|
||||
).length,
|
||||
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
|
||||
label: t(band.label),
|
||||
color: band.color,
|
||||
count: counts[index],
|
||||
...(index === 0
|
||||
? {
|
||||
blurb: t(
|
||||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||||
),
|
||||
}
|
||||
? { blurb: t('Colour shows the age of each area.') }
|
||||
: {}),
|
||||
})),
|
||||
...(_note ? { info: t(_note) } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: _count,
|
||||
count: _fireById.size,
|
||||
lastUpdate: _lastUpdate,
|
||||
error: _lastError,
|
||||
stale: _stale,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,14 @@
|
||||
/**
|
||||
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
|
||||
* the snapshot the layer draws (firePerimeterSnapshot).
|
||||
*
|
||||
* The server and the package's `./layers/perimeters/source` export import
|
||||
* this module, so it marks text with msg() only. The layer translates `note`
|
||||
* when it shows it.
|
||||
*/
|
||||
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
|
||||
/**
|
||||
* Normalize a WFIGS feed, skipping individually invalid features.
|
||||
* Only a payload that is not a feature collection at all rejects the whole
|
||||
@@ -80,6 +91,7 @@ export function normalizeFirePerimeterSnapshot(geojson) {
|
||||
: null,
|
||||
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
|
||||
updatedTime: finiteOrNull(properties.poly_DateCurrent),
|
||||
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
|
||||
cause: textOrNull(properties.attr_FireCause),
|
||||
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
|
||||
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
|
||||
@@ -92,3 +104,114 @@ export function normalizeFirePerimeterSnapshot(geojson) {
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Shoelace area along short longitude edges (degree², relative sizes only). */
|
||||
function ringArea(ring) {
|
||||
let sum = 0;
|
||||
let [x1, y1] = ring[0];
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
let delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) delta -= 360;
|
||||
else if (delta < -180) delta += 360;
|
||||
const x2 = x1 + delta;
|
||||
const y2 = ring[i][1];
|
||||
sum += x1 * y2 - x2 * y1;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
}
|
||||
return Math.abs(sum / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor point for the incident card: the vertex mean of the largest polygon's
|
||||
* outer ring, with circular longitude. Callers own the Cartesian conversion.
|
||||
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
|
||||
* @returns {{lon: number, lat: number}}
|
||||
*/
|
||||
export function perimeterAnchorDegrees(polygons) {
|
||||
let best = null;
|
||||
let bestArea = -1;
|
||||
for (const rings of polygons) {
|
||||
const outer = rings[0];
|
||||
const area = ringArea(outer);
|
||||
if (area > bestArea) {
|
||||
bestArea = area;
|
||||
best = outer;
|
||||
}
|
||||
}
|
||||
// Vertex mean over the closed ring (first == last point dropped): perimeters
|
||||
// are compact enough that this stays inside or near the polygon.
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let lat = 0;
|
||||
const count = best.length - 1;
|
||||
const toRad = Math.PI / 180;
|
||||
for (let i = 0; i < count; i++) {
|
||||
sinLon += Math.sin(best[i][0] * toRad);
|
||||
cosLon += Math.cos(best[i][0] * toRad);
|
||||
lat += best[i][1];
|
||||
}
|
||||
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
|
||||
}
|
||||
|
||||
/** WFIGS times up to this far ahead of our clock (clock skew) are taken as now; later ones are unknown. */
|
||||
const CLOCK_SKEW_MS = 10 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The WFIGS snapshot for the Fire Perimeters layer (contract:
|
||||
* `createFirePerimetersLayer`), from the proxy's rows.
|
||||
*
|
||||
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
|
||||
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
|
||||
* record's last edit `poly_DateCurrent`).
|
||||
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
|
||||
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
|
||||
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
|
||||
* revision: string, note: string, fires: object[], pieces: object[]}}
|
||||
*/
|
||||
export function firePerimeterSnapshot(
|
||||
rows,
|
||||
{ fetchedAt = null, stale = false, now = Date.now() } = {},
|
||||
) {
|
||||
const fires = [];
|
||||
const pieces = [];
|
||||
const versions = [];
|
||||
for (const row of rows) {
|
||||
const { stableId, polygons, polygonTime, ...facts } = row;
|
||||
const mapped = polygonTime ?? facts.updatedTime;
|
||||
const grown =
|
||||
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS
|
||||
? Math.min(mapped, now)
|
||||
: null;
|
||||
fires.push({
|
||||
...facts,
|
||||
id: stableId,
|
||||
lastGrowthTime: grown,
|
||||
anchor: perimeterAnchorDegrees(polygons),
|
||||
});
|
||||
for (const rings of polygons)
|
||||
pieces.push({
|
||||
fireId: stableId,
|
||||
born: grown,
|
||||
polygons: [rings],
|
||||
outline: rings,
|
||||
});
|
||||
// Without poly_DateCurrent, the mapping time and outline stand in for it.
|
||||
versions.push(
|
||||
Number.isFinite(facts.updatedTime)
|
||||
? `${stableId}@${facts.updatedTime}`
|
||||
: `${stableId}@${polygonTime ?? ''}:${JSON.stringify(polygons)}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
at: null,
|
||||
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
|
||||
stale: stale === true,
|
||||
revision: versions.sort().join('|'),
|
||||
note: msg(
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
|
||||
),
|
||||
fires,
|
||||
pieces,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
import {
|
||||
perimeterAnchorDegrees,
|
||||
normalizeFirePerimeterSnapshot,
|
||||
firePerimeterSnapshot,
|
||||
} from './records.js';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
@@ -22,6 +26,7 @@ function feature(overrides = {}) {
|
||||
attr_IncidentTypeCategory: 'WF',
|
||||
attr_FireDiscoveryDateTime: 1757900000000,
|
||||
poly_DateCurrent: 1757950000000,
|
||||
poly_PolygonDateTime: 1757940000000,
|
||||
attr_FireCause: 'Natural',
|
||||
attr_FireBehaviorGeneral: 'Active',
|
||||
attr_TotalIncidentPersonnel: 380,
|
||||
@@ -59,6 +64,7 @@ test('a valid snapshot yields one row per incident with polygons preserved', ()
|
||||
category: 'WF',
|
||||
discoveredTime: 1757900000000,
|
||||
updatedTime: 1757950000000,
|
||||
polygonTime: 1757940000000,
|
||||
cause: 'Natural',
|
||||
behavior: 'Active',
|
||||
personnel: 380,
|
||||
@@ -90,6 +96,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
attr_IncidentTypeCategory: null,
|
||||
attr_FireDiscoveryDateTime: null,
|
||||
poly_DateCurrent: null,
|
||||
poly_PolygonDateTime: null,
|
||||
attr_FireCause: null,
|
||||
attr_FireBehaviorGeneral: null,
|
||||
attr_TotalIncidentPersonnel: null,
|
||||
@@ -110,6 +117,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: rows[0].category,
|
||||
discoveredTime: rows[0].discoveredTime,
|
||||
updatedTime: rows[0].updatedTime,
|
||||
polygonTime: rows[0].polygonTime,
|
||||
cause: rows[0].cause,
|
||||
behavior: rows[0].behavior,
|
||||
personnel: rows[0].personnel,
|
||||
@@ -126,6 +134,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: null,
|
||||
discoveredTime: null,
|
||||
updatedTime: null,
|
||||
polygonTime: null,
|
||||
cause: null,
|
||||
behavior: null,
|
||||
personnel: null,
|
||||
@@ -199,3 +208,223 @@ test('a perimeter with no rings is skipped rather than rendered empty', () => {
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, 'other');
|
||||
});
|
||||
|
||||
const NOW = 1758000000000;
|
||||
const rowsOf = (...features) => normalizeFirePerimeterSnapshot({ features });
|
||||
// feature() replaces all properties with the overrides' own: keep the rest.
|
||||
const fixture = (id, properties) =>
|
||||
feature({ id, properties: { ...feature().properties, ...properties } });
|
||||
|
||||
test('each WFIGS polygon becomes one piece of its fire, born when it was mapped', () => {
|
||||
const hole = [
|
||||
[-108.08, 35.22],
|
||||
[-108.02, 35.22],
|
||||
[-108.02, 35.25],
|
||||
[-108.08, 35.22],
|
||||
];
|
||||
const snapshot = firePerimeterSnapshot(
|
||||
rowsOf(
|
||||
feature({
|
||||
geometry: { type: 'MultiPolygon', coordinates: [[ring, hole], [ring]] },
|
||||
}),
|
||||
),
|
||||
{ fetchedAt: NOW - 1000, now: NOW },
|
||||
);
|
||||
assert.equal(snapshot.at, null);
|
||||
assert.equal(snapshot.stale, false);
|
||||
assert.equal(snapshot.fetchedAt, NOW - 1000);
|
||||
assert.equal(
|
||||
snapshot.note,
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
|
||||
);
|
||||
assert.equal(snapshot.fires.length, 1);
|
||||
const [fire] = snapshot.fires;
|
||||
assert.equal(fire.id, '2026-NMGNF-000123');
|
||||
assert.equal(fire.lastGrowthTime, 1757940000000);
|
||||
assert.equal(fire.containedPct, 40);
|
||||
assert.equal('stableId' in fire || 'polygons' in fire, false);
|
||||
assert.ok(Math.abs(fire.anchor.lat - 35.2333) < 0.01);
|
||||
assert.deepEqual(
|
||||
snapshot.pieces.map(({ fireId, born, polygons, outline }) => [
|
||||
fireId,
|
||||
born,
|
||||
polygons,
|
||||
outline,
|
||||
]),
|
||||
[
|
||||
['2026-NMGNF-000123', 1757940000000, [[ring, hole]], [ring, hole]],
|
||||
['2026-NMGNF-000123', 1757940000000, [[ring]], [ring]],
|
||||
],
|
||||
'the outline is every ring, holes included',
|
||||
);
|
||||
});
|
||||
|
||||
test('a perimeter without its mapping time falls back to the last edit; a future time is unknown', () => {
|
||||
const [fallback, future, futureEdit, none] = firePerimeterSnapshot(
|
||||
rowsOf(
|
||||
fixture(1, { poly_PolygonDateTime: null }),
|
||||
fixture(2, {
|
||||
attr_UniqueFireIdentifier: 'future',
|
||||
poly_PolygonDateTime: NOW + 3600000,
|
||||
}),
|
||||
fixture(3, {
|
||||
attr_UniqueFireIdentifier: 'future-edit',
|
||||
poly_PolygonDateTime: null,
|
||||
poly_DateCurrent: NOW + 3600000,
|
||||
}),
|
||||
fixture(4, {
|
||||
attr_UniqueFireIdentifier: 'none',
|
||||
poly_PolygonDateTime: null,
|
||||
poly_DateCurrent: null,
|
||||
}),
|
||||
),
|
||||
{ now: NOW },
|
||||
).fires;
|
||||
assert.equal(fallback.lastGrowthTime, 1757950000000);
|
||||
assert.equal(future.lastGrowthTime, null);
|
||||
assert.equal(futureEdit.lastGrowthTime, null);
|
||||
assert.equal(none.lastGrowthTime, null);
|
||||
// A clock a few minutes ahead of ours is taken as now.
|
||||
const skewed = firePerimeterSnapshot(
|
||||
rowsOf(fixture(1, { poly_PolygonDateTime: NOW + 60000 })),
|
||||
{ now: NOW },
|
||||
);
|
||||
assert.equal(skewed.fires[0].lastGrowthTime, NOW);
|
||||
assert.equal(skewed.pieces[0].born, NOW);
|
||||
});
|
||||
|
||||
test('the revision follows fire ids and update times, not feed order', () => {
|
||||
const a = feature();
|
||||
const b = fixture(2, { attr_UniqueFireIdentifier: 'b' });
|
||||
const revision = (...features) =>
|
||||
firePerimeterSnapshot(rowsOf(...features), { now: NOW }).revision;
|
||||
assert.equal(revision(a, b), revision(b, a));
|
||||
assert.notEqual(
|
||||
revision(a, b),
|
||||
revision(
|
||||
a,
|
||||
fixture(2, { attr_UniqueFireIdentifier: 'b', poly_DateCurrent: 1 }),
|
||||
),
|
||||
);
|
||||
assert.notEqual(revision(a, b), revision(a));
|
||||
|
||||
const undated = fixture(1, { poly_DateCurrent: null });
|
||||
const shifted = ring.map(([lon, lat]) => [lon + 1, lat]);
|
||||
assert.notEqual(
|
||||
revision(undated),
|
||||
revision({
|
||||
...undated,
|
||||
geometry: { type: 'Polygon', coordinates: [shifted] },
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
revision(undated),
|
||||
revision(
|
||||
fixture(1, {
|
||||
poly_DateCurrent: null,
|
||||
poly_PolygonDateTime: NOW,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('the snapshot carries staleness', () => {
|
||||
const snapshot = firePerimeterSnapshot(rowsOf(feature()), {
|
||||
stale: true,
|
||||
fetchedAt: 'yesterday',
|
||||
now: NOW,
|
||||
});
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, null);
|
||||
assert.deepEqual(
|
||||
snapshot.fires.map(({ id }) => id),
|
||||
['2026-NMGNF-000123'],
|
||||
);
|
||||
});
|
||||
|
||||
const square = [
|
||||
[-108.2, 35.0],
|
||||
[-108.0, 35.0],
|
||||
[-108.0, 35.2],
|
||||
[-108.2, 35.2],
|
||||
[-108.2, 35.0],
|
||||
];
|
||||
const tiny = [
|
||||
[-107.01, 34.0],
|
||||
[-107.0, 34.0],
|
||||
[-107.0, 34.01],
|
||||
[-107.01, 34.0],
|
||||
];
|
||||
|
||||
test('the card anchors at the vertex mean of the largest polygon', () => {
|
||||
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
|
||||
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
|
||||
});
|
||||
|
||||
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
|
||||
const vertices = [
|
||||
[179, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
];
|
||||
for (let start = 0; start < vertices.length; start++) {
|
||||
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
|
||||
for (const points of [rotated, [...rotated].reverse()]) {
|
||||
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
|
||||
for (const boundary of [-180, 180]) {
|
||||
const ring = [
|
||||
[179, 10],
|
||||
[boundary, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
[179, 10],
|
||||
];
|
||||
const anchor = perimeterAnchorDegrees([[ring]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('multipart cards compare polygon areas along short dateline edges', () => {
|
||||
const ordinary = [
|
||||
[10, 20],
|
||||
[11, 20],
|
||||
[11, 21],
|
||||
[10, 21],
|
||||
[10, 20],
|
||||
];
|
||||
for (const width of [0.2, 2]) {
|
||||
const crossing = [
|
||||
[180 - width / 2, 10],
|
||||
[-180 + width / 2, 10],
|
||||
[-180 + width / 2, 10 + width],
|
||||
[180 - width / 2, 10 + width],
|
||||
[180 - width / 2, 10],
|
||||
];
|
||||
for (const ring of [crossing, [...crossing].reverse()]) {
|
||||
for (const polygons of [
|
||||
[[ring], [ordinary]],
|
||||
[[ordinary], [ring]],
|
||||
]) {
|
||||
const anchor = perimeterAnchorDegrees(polygons);
|
||||
if (width < 1) {
|
||||
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
|
||||
} else {
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,42 +1,35 @@
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { firePerimeterSnapshot } from './records.js';
|
||||
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the Layers panel shows them translated.
|
||||
const msg = (text) => text;
|
||||
// Failures stay English data. The Layers panel shows them translated.
|
||||
|
||||
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
/** Request a snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
export function createWfigsPerimeterSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
/**
|
||||
* The rows with how fresh they are: the proxy answers from its last
|
||||
* snapshot, marked stale, while WFIGS is unreachable.
|
||||
* @returns {Promise<{rows: object[], stale: boolean, fetchedAt: number|null}>}
|
||||
*/
|
||||
async function getSnapshotDetail({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/fire-perimeters', { signal });
|
||||
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
80 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (!Array.isArray(payload?.rows))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
return {
|
||||
rows: payload.rows,
|
||||
stale: payload.stale === true,
|
||||
fetchedAt: Number.isFinite(payload.fetchedAt) ? payload.fetchedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
/** The perimeter rows (see getSnapshotDetail for staleness). */
|
||||
async getSnapshot(options = {}) {
|
||||
return (await getSnapshotDetail(options)).rows;
|
||||
/**
|
||||
* Current perimeters as fires and their pieces (firePerimeterSnapshot).
|
||||
* The proxy answers from its last snapshot, marked stale, while WFIGS is
|
||||
* unreachable.
|
||||
*/
|
||||
async getSnapshot({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/fire-perimeters', { signal });
|
||||
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
80 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (!Array.isArray(payload?.rows))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
return firePerimeterSnapshot(payload.rows, {
|
||||
fetchedAt: payload.fetchedAt,
|
||||
stale: payload.stale === true,
|
||||
});
|
||||
},
|
||||
getSnapshotDetail,
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ const validPayload = {
|
||||
],
|
||||
};
|
||||
|
||||
test('a successful response yields normalized perimeter rows', async () => {
|
||||
test('a successful response yields the snapshot of fires and pieces', async () => {
|
||||
let requested;
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async (url) => {
|
||||
@@ -30,9 +30,13 @@ test('a successful response yields normalized perimeter rows', async () => {
|
||||
});
|
||||
},
|
||||
});
|
||||
const rows = await source.getSnapshot();
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.deepEqual(
|
||||
snapshot.fires.map((fire) => fire.id),
|
||||
['2026-NMGNF-000123'],
|
||||
);
|
||||
assert.deepEqual(snapshot.pieces[0].polygons, [[ring]]);
|
||||
assert.equal(snapshot.at, null);
|
||||
assert.equal(requested, '/api/fire-perimeters');
|
||||
});
|
||||
|
||||
@@ -160,22 +164,20 @@ test('a failed refresh serves the last snapshot marked stale for a day, then ref
|
||||
assert.equal((await ask()).status, 502, 'a day-old snapshot is not served');
|
||||
});
|
||||
|
||||
test('the snapshot detail carries the proxy staleness and fetch time', async () => {
|
||||
test('the snapshot carries the proxy staleness and fetch time', async () => {
|
||||
const fetchedAt = Date.UTC(2026, 9, 25, 12);
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [], stale: true, fetchedAt }),
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshotDetail(), {
|
||||
rows: [],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshot(), []);
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, fetchedAt);
|
||||
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
|
||||
});
|
||||
|
||||
test('getSnapshot works when taken off its source object', async () => {
|
||||
const { getSnapshot } = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [] }),
|
||||
});
|
||||
assert.deepEqual(await getSnapshot(), []);
|
||||
assert.deepEqual((await getSnapshot()).fires, []);
|
||||
});
|
||||
@@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => {
|
||||
};
|
||||
await assert.rejects(
|
||||
searchHls({
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
box: { west: -181, south: 0, east: -179, north: 1 },
|
||||
fetchImpl,
|
||||
}),
|
||||
/dateline/,
|
||||
/±180/,
|
||||
);
|
||||
await assert.rejects(
|
||||
searchHls({ box: BOX, now: 'never', fetchImpl }),
|
||||
@@ -251,6 +251,22 @@ test('an invalid box or clock is refused before any request', async () => {
|
||||
assert.equal(called, false);
|
||||
});
|
||||
|
||||
test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => {
|
||||
const calls = [];
|
||||
const result = await searchHls({
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
days: 2,
|
||||
now: '2026-09-21T00:00:00Z',
|
||||
fetchImpl: async (url) => {
|
||||
calls.push(url);
|
||||
return response({ json: { hits: 1, items: [ummItem({})] } });
|
||||
},
|
||||
});
|
||||
assert.equal(calls.length, 2, 'one search per product');
|
||||
assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1')));
|
||||
assert.ok(result.candidates.some((candidate) => candidate.product === 'S30'));
|
||||
});
|
||||
|
||||
test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => {
|
||||
const items = (count) =>
|
||||
Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` }));
|
||||
|
||||
@@ -581,6 +581,8 @@ export function createRecentImageryLayer({
|
||||
for (const slotId of SLOT_IDS) {
|
||||
const candidate = candidateFor(shown[slotId]);
|
||||
if (candidate && _hostInfo.collection) {
|
||||
const { availableBoxes, emptyBoxes } =
|
||||
thumbnails.get(candidate.key) ?? {};
|
||||
renderer.showSlot(slotId, candidate, _box, {
|
||||
alpha: _alpha,
|
||||
splitDirection: !live
|
||||
@@ -588,6 +590,8 @@ export function createRecentImageryLayer({
|
||||
: (slotId === 'a') !== _swapped
|
||||
? 'left'
|
||||
: 'right',
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
});
|
||||
} else {
|
||||
renderer.hideSlot(slotId);
|
||||
@@ -897,21 +901,22 @@ export function createRecentImageryLayer({
|
||||
// The new automatic day's probe may have been cancelled off-screen.
|
||||
requestThumbnails();
|
||||
}
|
||||
if (pruned) syncRender();
|
||||
const followed =
|
||||
Boolean(_followKey) &&
|
||||
_followKey === _focusKey &&
|
||||
drapable(candidateFor(_followKey)) &&
|
||||
applyPreview(_followKey);
|
||||
// A pinned or previewed day that was still being probed drapes now.
|
||||
const shown = plan();
|
||||
const owned = renderer.getOwned?.() || {};
|
||||
const drapesChanged = SLOT_IDS.some(
|
||||
(slotId) => (owned[slotId]?.key || null) !== shown[slotId],
|
||||
);
|
||||
if (drapesChanged && !pruned && !followed) syncRender();
|
||||
// One render per probe: the key can stay the same while its halves change.
|
||||
// A host found moved changes the divider, so the panel renders in full.
|
||||
const moved = !followed && syncHost();
|
||||
if (!followed) syncRender();
|
||||
notify('thumbnail');
|
||||
if (pruned || followed || drapesChanged) notify();
|
||||
if (pruned || followed || drapesChanged || moved) notify();
|
||||
});
|
||||
syncHost();
|
||||
if (_box && !_candidates.length) void runSearch();
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import assert from 'node:assert/strict';
|
||||
import { until } from '../../testSupport/kartaViewFakes.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
|
||||
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
|
||||
import { MapSourceController } from '../../maps/controller.js';
|
||||
@@ -14,11 +18,16 @@ import {
|
||||
SPLIT_PUBLISH_MS,
|
||||
createRecentImageryLayer,
|
||||
} from './index.js';
|
||||
import { createImageryBoxPreview } from './rendering.js';
|
||||
import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import {
|
||||
BOX,
|
||||
CANDIDATES,
|
||||
FIJI_BOX,
|
||||
boxToolFakes,
|
||||
candidate,
|
||||
fakeCatalog,
|
||||
@@ -1564,6 +1573,424 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
|
||||
assert.equal(f.snap().notice, 'Search cancelled');
|
||||
});
|
||||
|
||||
test('a box dragged across the dateline is searched, listed and draped as one box', async () => {
|
||||
const f = fixture();
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
f.layer.enable();
|
||||
assert.equal(f.layer.setBox(box), true);
|
||||
assert.equal(f.snap().boxError, null);
|
||||
assert.deepEqual(f.catalog.searches.at(-1).request.box, box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.equal(f.snap().candidates.length, 4);
|
||||
assert.equal(f.snap().preview.key, S18);
|
||||
assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped');
|
||||
assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°');
|
||||
});
|
||||
|
||||
test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => {
|
||||
const f = fixture();
|
||||
const priorGet = f.thumbnails.get;
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
let boxes = [west];
|
||||
f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes });
|
||||
f.layer.enable();
|
||||
f.layer.setBox(box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
f.thumbnails.probeRequested();
|
||||
const slot = Object.keys(f.owned()).find((id) => f.owned()[id]);
|
||||
assert.ok(slot, 'a day is already on the map');
|
||||
const key = f.owned()[slot].key;
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, [west]);
|
||||
boxes = [west, east];
|
||||
f.thumbnails.probe(key, 'present');
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, boxes);
|
||||
f.layer.destroy();
|
||||
});
|
||||
|
||||
const sideOf = (url) =>
|
||||
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
|
||||
? 'west'
|
||||
: 'east';
|
||||
/** A snapshot response; `present: null` sends no Data-Present header. */
|
||||
const snapshotAnswer = (present, status = 200) =>
|
||||
new Response('img', {
|
||||
status,
|
||||
headers: present === null ? {} : { 'Data-Present': String(present) },
|
||||
});
|
||||
|
||||
function realLayer({
|
||||
fetchImpl,
|
||||
candidates,
|
||||
maxDecoded = 16,
|
||||
halfDeadlineMs = 50,
|
||||
}) {
|
||||
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs });
|
||||
let nextUrl = 0;
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
createObjectUrl: () => `blob:${++nextUrl}`,
|
||||
revokeObjectUrl: () => {},
|
||||
maxDecoded,
|
||||
});
|
||||
const globe = fakeGlobePort();
|
||||
const layer = createRecentImageryLayer({
|
||||
catalog: {
|
||||
searchHls: async () => ({ candidates, truncated: false, errors: [] }),
|
||||
},
|
||||
renderer: createRecentImageryRenderer(),
|
||||
thumbnails: loader,
|
||||
host: () => ({ collection: globe.imagery, kind: 'globe' }),
|
||||
globeOf: () => globe,
|
||||
now: () => new Date('2026-11-13T15:00:00Z'),
|
||||
});
|
||||
layer.init({ camera: {} });
|
||||
return { layer, loader, globe };
|
||||
}
|
||||
|
||||
test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const sides = [];
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) => {
|
||||
const side = sideOf(url);
|
||||
sides.push(side);
|
||||
return snapshotAnswer(side === 'east');
|
||||
},
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
assert.equal(layer.setBox(FIJI_BOX), true);
|
||||
// The probe asks about both halves, wider first. The layer drapes the one with data.
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length > 0, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(sides, ['east', 'west']);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[nonCrossingBoxes(FIJI_BOX)[1]],
|
||||
);
|
||||
assert.equal(loader.get(day.key).status, 'present');
|
||||
const snapshot = layer.getSnapshot();
|
||||
assert.equal(snapshot.candidates[0].thumbnail.status, 'present');
|
||||
assert.equal(snapshot.candidates[0].drapable, true);
|
||||
assert.equal(snapshot.auto?.key, day.key);
|
||||
layer.destroy();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async () => snapshotAnswer(false),
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(
|
||||
layer.getSnapshot().candidates.some((c) => c.key === day.key),
|
||||
false,
|
||||
'an empty day leaves the strip',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, box] of [
|
||||
['a plain box', { west: -98, south: 30, east: -97, north: 31 }],
|
||||
['a dateline box', FIJI_BOX],
|
||||
]) {
|
||||
test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(box);
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === nonCrossingBoxes(box).length, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const before = [...globe.layers];
|
||||
const added = globe.added.length;
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.added.length, added);
|
||||
assert.deepEqual(globe.layers, before);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => {
|
||||
const day1 = candidate('VIIRS', '2026-11-10');
|
||||
const day2 = candidate('VIIRS', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((resolve) => {
|
||||
releaseDay2 = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) await gate;
|
||||
else if (sideOf(url) === 'east' && ++eastCalls === 2)
|
||||
throw new TypeError('Failed to fetch');
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.setSources({ hls: false, viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).status, 'present');
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[west, east],
|
||||
'a half that failed on the re-probe stays draped',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (sideOf(url) === 'east') {
|
||||
eastCalls += 1;
|
||||
if (eastCalls === 1) return snapshotAnswer(false);
|
||||
throw new TypeError('Failed to fetch');
|
||||
}
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
assert.equal(loader.get(day1.key).emptyBoxes.length, 1);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
assert.deepEqual(
|
||||
{
|
||||
available: entry.availableBoxes.length,
|
||||
empty: entry.emptyBoxes.length,
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ available: 1, empty: 1, layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((r) => (release = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(null);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox({ west: -98, south: 30, east: -97, north: 31 });
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === 1, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
assert.equal(globe.layers.length, 1);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, failEast] of [
|
||||
['answers 503', async () => snapshotAnswer(null, 503)],
|
||||
[
|
||||
'rejects',
|
||||
async () => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
},
|
||||
],
|
||||
['never answers', () => new Promise(() => {})],
|
||||
]) {
|
||||
test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) =>
|
||||
sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(),
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key)?.status === 'error', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day.key);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ empty: [boxKey(west)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let round = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (round === 0)
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(true)
|
||||
: snapshotAnswer(null);
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(null)
|
||||
: snapshotAnswer(false);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key)?.status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
round = 1;
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(
|
||||
() =>
|
||||
loader.get(day2.key)?.status === 'present' &&
|
||||
loader.get(day1.key).objectUrl === null,
|
||||
{ ticks: 2000 },
|
||||
),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day1.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
await until(() => !loader.get(day1.key).loading, { ticks: 2000 });
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
const [, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
status: entry.status,
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ status: 'present', empty: [boxKey(east)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => {
|
||||
for (const order of [
|
||||
[S18, V15],
|
||||
|
||||
@@ -72,13 +72,11 @@ export const PRODUCTS = Object.freeze({
|
||||
|
||||
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const toRadians = (degrees) => (degrees * Math.PI) / 180;
|
||||
/** A longitude brought back into ±180 after one step past it. */
|
||||
const wrapLon = (value) =>
|
||||
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
|
||||
const pad2 = (value) => String(value).padStart(2, '0');
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east crosses the dateline and `validateBox`
|
||||
* rejects it. Null when any edge is nonfinite.
|
||||
*/
|
||||
/** A box edge as a number, or null when it is missing, blank or not numeric. */
|
||||
function edgeNumber(value) {
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
||||
@@ -87,6 +85,11 @@ function edgeNumber(value) {
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east is the short arc across the dateline.
|
||||
* Null when any edge is nonfinite.
|
||||
*/
|
||||
function normalizeBox(box) {
|
||||
if (!box || typeof box !== 'object') return null;
|
||||
const [west, south, east, north] = [
|
||||
@@ -105,8 +108,45 @@ function normalizeBox(box) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Side lengths of a box in km: the box's own longitude span (never the
|
||||
* shorter way round the globe) at its mid-latitude, and its latitude span.
|
||||
* Degrees of longitude going east from `west` to `east`. A west > east pair
|
||||
* wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and
|
||||
* `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`,
|
||||
* even the long way round.
|
||||
* @param {number} west Degrees.
|
||||
* @param {number} east Degrees.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function lonSpanDeg(west, east) {
|
||||
return east >= west ? east - west : east + 360 - west;
|
||||
}
|
||||
|
||||
/** A comparable key for a degrees box. */
|
||||
export const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
|
||||
/**
|
||||
* One or two boxes with west <= east that cover the same area. A dateline
|
||||
* box is split at ±180 so each side is a plain rectangle for a draped layer
|
||||
* or a Worldview request. A box with a missing or nonfinite edge is [].
|
||||
* So is a dateline box of zero width (west 180, east -180).
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function nonCrossingBoxes(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
if (!normalized) return [];
|
||||
const { west, south, east, north } = normalized;
|
||||
if (!(west > east)) return [normalized];
|
||||
const parts = [];
|
||||
if (west < 180) parts.push({ west, south, east: 180, north });
|
||||
if (east > -180) parts.push({ west: -180, south, east, north });
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Side lengths of a box in km: the longitude span at its mid-latitude (the
|
||||
* short arc when the box crosses the dateline; a west <= east box is not
|
||||
* shortened), and its latitude span.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ width: number, height: number }}
|
||||
*/
|
||||
@@ -116,7 +156,7 @@ export function boxSideKm(box) {
|
||||
const midLat = (normalized.south + normalized.north) / 2;
|
||||
return {
|
||||
width:
|
||||
(normalized.east - normalized.west) *
|
||||
lonSpanDeg(normalized.west, normalized.east) *
|
||||
KM_PER_DEG_LAT *
|
||||
Math.cos(toRadians(midLat)),
|
||||
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
|
||||
@@ -126,9 +166,11 @@ export function boxSideKm(box) {
|
||||
const refuse = (reason, message) => ({ ok: false, reason, message });
|
||||
|
||||
/**
|
||||
* Validate a selection box for the catalog and the tile providers.
|
||||
* Validate a selection box for the catalog and the tile providers. A box
|
||||
* with west > east is the short arc across the dateline and is accepted
|
||||
* when that arc is under the size cap.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
*/
|
||||
export function validateBox(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
@@ -136,8 +178,6 @@ export function validateBox(box) {
|
||||
const { west, south, east, north } = normalized;
|
||||
if (Math.abs(west) > 180 || Math.abs(east) > 180)
|
||||
return refuse('invalid', msg('Longitudes must be within ±180°'));
|
||||
if (west > east)
|
||||
return refuse('dateline', msg('Select one side of the dateline'));
|
||||
if (
|
||||
Math.abs(south) > MERCATOR_LAT_LIMIT ||
|
||||
Math.abs(north) > MERCATOR_LAT_LIMIT
|
||||
@@ -146,7 +186,7 @@ export function validateBox(box) {
|
||||
'polar',
|
||||
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
|
||||
);
|
||||
if (east === west || north === south)
|
||||
if (lonSpanDeg(west, east) === 0 || north === south)
|
||||
return refuse('degenerate', msg('Box must enclose an area'));
|
||||
const { width, height } = boxSideKm(normalized);
|
||||
if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)
|
||||
@@ -183,7 +223,9 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The centre of a box that does not cross the dateline, in degrees.
|
||||
* The centre of a box, in degrees. A dateline box (west > east) is centred
|
||||
* on the short arc, not the arithmetic mean, which would be the other side
|
||||
* of the globe.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ lon: number, lat: number } | null}
|
||||
*/
|
||||
@@ -191,14 +233,18 @@ export function boxCentre(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
if (!normalized) return null;
|
||||
return {
|
||||
lon: (normalized.west + normalized.east) / 2,
|
||||
lon: wrapLon(
|
||||
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
|
||||
),
|
||||
lat: (normalized.south + normalized.north) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A square box centred on a pin, `sideKm` on the ground (the east–west extent
|
||||
* widens by 1/cos(lat)); null when the result would not validate.
|
||||
* widens by 1/cos(lat)); null when the result would not validate. A pin whose
|
||||
* box passes ±180 gets the short-arc box (west > east), the same convention
|
||||
* as a dragged dateline box, with edges wrapped into ±180.
|
||||
* @param {number} lon Degrees.
|
||||
* @param {number} lat Degrees.
|
||||
* @param {number} [sideKm]
|
||||
@@ -207,16 +253,19 @@ export function boxCentre(box) {
|
||||
export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {
|
||||
if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)
|
||||
return null;
|
||||
if (Math.abs(lon) > 180) return null;
|
||||
const cosLat = Math.cos(toRadians(lat));
|
||||
if (cosLat <= 0) return null;
|
||||
const halfLat = sideKm / 2 / KM_PER_DEG_LAT;
|
||||
const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);
|
||||
// A half-width of 90° or more is not a short arc; refuse rather than wrap.
|
||||
if (halfLon >= 90) return null;
|
||||
const clampLat = (value) =>
|
||||
Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));
|
||||
const result = validateBox({
|
||||
west: lon - halfLon,
|
||||
west: wrapLon(lon - halfLon),
|
||||
south: clampLat(lat - halfLat),
|
||||
east: lon + halfLon,
|
||||
east: wrapLon(lon + halfLon),
|
||||
north: clampLat(lat + halfLat),
|
||||
});
|
||||
return result.ok ? result.box : null;
|
||||
@@ -449,15 +498,31 @@ export function coverageFor(candidate, box) {
|
||||
.filter((ring) => Array.isArray(ring) && ring.length >= 3);
|
||||
if (!normalized || !footprints.length) return 'unknown';
|
||||
const { west, south, east, north } = normalized;
|
||||
const centre = boxCentre(normalized);
|
||||
// A dateline box is one continuous range starting at its west edge. A
|
||||
// longitude on the east side (at or past ±180) shifts by 360. One just
|
||||
// outside the west corner stays put: shifting every value below west would
|
||||
// send that corner the long way round and miss a footprint that covers it.
|
||||
const crossing = west > east;
|
||||
const project = (lon) =>
|
||||
crossing && lon < west && (lon <= east || lon - east < west - lon)
|
||||
? lon + 360
|
||||
: lon;
|
||||
const samples = [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
[(west + east) / 2, (south + north) / 2],
|
||||
[project(west), south],
|
||||
[project(east), south],
|
||||
[project(east), north],
|
||||
[project(west), north],
|
||||
[project(centre.lon), centre.lat],
|
||||
];
|
||||
return samples.every(([lon, lat]) =>
|
||||
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
|
||||
footprints.some((ring) =>
|
||||
pointInPolygon(
|
||||
lon,
|
||||
lat,
|
||||
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
|
||||
),
|
||||
),
|
||||
)
|
||||
? 'full'
|
||||
: 'partial';
|
||||
@@ -606,6 +671,10 @@ export function wvsSnapshotUrl({
|
||||
const normalized = normalizeBox(box);
|
||||
if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);
|
||||
if (!normalized) throw new TypeError('A finite box is required');
|
||||
// Worldview Snapshots rejects a BBOX whose west is greater than its east
|
||||
// (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse.
|
||||
if (normalized.west > normalized.east)
|
||||
throw new TypeError('A snapshot cannot cross the dateline');
|
||||
const bbox = [
|
||||
normalized.south,
|
||||
normalized.west,
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
boxFromPin,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
boxFromRectangle,
|
||||
boxSideKm,
|
||||
coverageFor,
|
||||
@@ -51,11 +53,20 @@ function hls(product, day, clouds, extra = {}) {
|
||||
return { ...groupGranulesByDay(granules)[0], ...extra };
|
||||
}
|
||||
|
||||
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
|
||||
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
|
||||
const reason = (box) => validateBox(box).reason;
|
||||
const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 });
|
||||
assert.equal(dateline.ok, true);
|
||||
assert.equal(dateline.box.west, 179);
|
||||
assert.equal(dateline.box.east, -179);
|
||||
assert.equal(
|
||||
reason({ west: 179, south: 0, east: -179, north: 1 }),
|
||||
'dateline',
|
||||
reason({ west: 170, south: 0, east: -170, north: 1 }),
|
||||
'too-large',
|
||||
'a 20° dateline arc is still over the 1,000 km cap',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 180, south: 0, east: -180, north: 1 }),
|
||||
'degenerate',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
|
||||
@@ -70,10 +81,6 @@ test('validateBox refuses dateline, polar, degenerate, invalid and oversized box
|
||||
validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,
|
||||
'Imagery stops at ±85.05° latitude',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,
|
||||
'Select one side of the dateline',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,
|
||||
true,
|
||||
@@ -137,10 +144,14 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400
|
||||
lon: 10,
|
||||
lat: 5,
|
||||
});
|
||||
assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), {
|
||||
lon: 180,
|
||||
lat: 1,
|
||||
});
|
||||
assert.equal(boxCentre(null), null);
|
||||
});
|
||||
|
||||
test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {
|
||||
test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => {
|
||||
const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });
|
||||
assert.ok(Math.abs(equator.width - 111.32) < 1e-6);
|
||||
assert.ok(Math.abs(equator.height - 111.32) < 1e-6);
|
||||
@@ -149,6 +160,13 @@ test('box width is the longitude span at the mid-latitude, never the shortest ar
|
||||
const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };
|
||||
assert.ok(boxSideKm(nearlyGlobal).width > 30000);
|
||||
assert.equal(validateBox(nearlyGlobal).reason, 'too-large');
|
||||
const crossing = boxSideKm({
|
||||
west: 179,
|
||||
south: -0.5,
|
||||
east: -179,
|
||||
north: 0.5,
|
||||
});
|
||||
assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width));
|
||||
});
|
||||
|
||||
test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {
|
||||
@@ -167,7 +185,12 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha
|
||||
assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);
|
||||
assert.equal(boxFromPin(NaN, 0), null);
|
||||
assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');
|
||||
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
|
||||
assert.equal(boxFromPin(181, 0), null, 'longitude out of range');
|
||||
assert.equal(
|
||||
boxFromPin(0, 0, 400000),
|
||||
null,
|
||||
'half-width of 90 degrees or more',
|
||||
);
|
||||
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
|
||||
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
|
||||
});
|
||||
@@ -298,6 +321,34 @@ test('coverage samples the box corners and centre against the union of footprint
|
||||
assert.equal(coverageFor(withRings(null), BOX), 'unknown');
|
||||
});
|
||||
|
||||
test('coverage of a dateline box uses the short arc, not the long way', () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const ring = (west, east, south = -0.1, north = 1.1) => [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
];
|
||||
const withRings = (...rings) => ({
|
||||
granules: rings.map((footprint) => granule({ footprint })),
|
||||
});
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.5, -178.5)), box),
|
||||
'full',
|
||||
'one footprint that crosses ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box),
|
||||
'full',
|
||||
'a pair split exactly at ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(179, 180)), box),
|
||||
'partial',
|
||||
'one side does not cover the other',
|
||||
);
|
||||
});
|
||||
|
||||
test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {
|
||||
const candidates = [
|
||||
hls('S30', '2026-09-20', [10, null]),
|
||||
@@ -429,6 +480,17 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e
|
||||
() => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),
|
||||
TypeError,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
wvsSnapshotUrl({
|
||||
product: 'S30',
|
||||
day: '2026-09-18',
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
width: 64,
|
||||
height: 64,
|
||||
}),
|
||||
/snapshot cannot cross the dateline/,
|
||||
);
|
||||
});
|
||||
|
||||
test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {
|
||||
@@ -437,3 +499,52 @@ test('thumbnails load the focused card, then the visible cards outward, then the
|
||||
assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);
|
||||
assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);
|
||||
});
|
||||
|
||||
test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
|
||||
const near = (a, b) => Math.abs(a - b) < 1e-6;
|
||||
const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492
|
||||
const spanOk = (box) => {
|
||||
const { width, height } = boxSideKm(box);
|
||||
assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`);
|
||||
assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`);
|
||||
assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span');
|
||||
};
|
||||
// 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side.
|
||||
for (const lon of [179.9, -179.9]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west < box.east, `no wrap needed at ${lon}`);
|
||||
assert.ok(near((box.west + box.east) / 2, lon));
|
||||
}
|
||||
// A pin on the line, or close enough that the box passes it, wraps.
|
||||
for (const lon of [180, -180, 179.99, -179.99]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west > box.east, `crossing at ${lon}`);
|
||||
assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180');
|
||||
assert.ok(
|
||||
near(
|
||||
box.west,
|
||||
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
nonCrossingBoxes(box).length,
|
||||
2,
|
||||
'splits for tiling and Worldview',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon),
|
||||
) < 1e-6,
|
||||
);
|
||||
}
|
||||
// 0 is an ordinary box.
|
||||
const mid = boxFromPin(0, 0);
|
||||
spanOk(mid);
|
||||
assert.ok(mid.west < mid.east && near(mid.west, -half));
|
||||
// Off the equator the east-west extent widens but stays a short arc.
|
||||
const high = boxFromPin(-179.99, 60);
|
||||
spanOk(high);
|
||||
assert.ok(high.west > high.east);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
|
||||
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
|
||||
* renderer's globe port, draped on whichever surface the map stack draws.
|
||||
* Recent Imagery drapes two slots through the renderer's globe port, slot
|
||||
* `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS
|
||||
* layers, one per available part, on whichever surface the map stack draws.
|
||||
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
|
||||
* requests pass a small semaphore of our own, shared by both slots, through
|
||||
* each layer's admission hook; the renderer's own request limits stay
|
||||
@@ -15,7 +15,13 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { markBaseTileset } from '../../render/baseTilesets.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PRODUCTS, gibsTemplate } from './model.js';
|
||||
import {
|
||||
PRODUCTS,
|
||||
boxKey,
|
||||
gibsTemplate,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
} from './model.js';
|
||||
|
||||
const SLOT_IDS = ['a', 'b'];
|
||||
const SPLITS = new Set(['left', 'right', 'none']);
|
||||
@@ -29,8 +35,27 @@ function clampAlpha(value) {
|
||||
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
|
||||
}
|
||||
|
||||
const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
/** One comparable key for a slot's draped parts. */
|
||||
const partsKey = (parts) => parts.map(boxKey).sort().join(';');
|
||||
|
||||
/**
|
||||
* The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would
|
||||
* draw an empty side black, so it drapes only parts Worldview confirmed
|
||||
* present, and no part of a dateline box before the probe answers. A PNG
|
||||
* drapes every part not confirmed empty.
|
||||
*/
|
||||
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
|
||||
const parts = nonCrossingBoxes(box);
|
||||
const keys = (list) => new Set(list.map(boxKey));
|
||||
if (PRODUCTS[candidate.product]?.format !== 'jpg') {
|
||||
if (!Array.isArray(emptyBoxes)) return parts;
|
||||
const empty = keys(emptyBoxes);
|
||||
return parts.filter((part) => !empty.has(boxKey(part)));
|
||||
}
|
||||
if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts;
|
||||
const proven = keys(availableBoxes);
|
||||
return parts.filter((part) => proven.has(boxKey(part)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit a tile request while the semaphore has room. A request that finds
|
||||
@@ -77,7 +102,7 @@ export function createRecentImageryRenderer({
|
||||
let host = NO_HOST;
|
||||
let destroyed = false;
|
||||
const admission = { limit: maxTileRequests, inFlight: 0 };
|
||||
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
|
||||
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
|
||||
const owned = { a: null, b: null };
|
||||
const admit = admitTileRequests(admission, requestRender);
|
||||
|
||||
@@ -105,36 +130,53 @@ export function createRecentImageryRenderer({
|
||||
const record = owned[slotId];
|
||||
if (!record) return false;
|
||||
owned[slotId] = null;
|
||||
record.layer.remove();
|
||||
for (const layer of record.layers) layer.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
function applyLook(record) {
|
||||
record.layer.alpha = record.alpha;
|
||||
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
for (const layer of record.layers) {
|
||||
layer.alpha = record.alpha;
|
||||
layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function mount(slotId, { candidate, box, alpha, split }) {
|
||||
const layer = host.globe.imagery.add(specFor(candidate, box));
|
||||
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
|
||||
function mount(slotId, { candidate, parts, alpha, split }) {
|
||||
if (!parts.length) return false;
|
||||
owned[slotId] = {
|
||||
layers: parts.map((part) =>
|
||||
host.globe.imagery.add(specFor(candidate, part)),
|
||||
),
|
||||
globe: host.globe,
|
||||
candidate,
|
||||
parts,
|
||||
alpha,
|
||||
split,
|
||||
};
|
||||
applyLook(owned[slotId]);
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Drape a candidate into a slot. The same candidate on the same host only
|
||||
* updates its look; anything else replaces the slot's layer.
|
||||
* Drape the parts of a candidate's box that the evidence allows (see drapedParts).
|
||||
* The same candidate on the same port keeps the layer of each unchanged part.
|
||||
* @param {'a'|'b'} slotId
|
||||
* @param {object} candidate
|
||||
* @param {object} box Degrees box.
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
|
||||
* @returns {boolean} Whether a layer is now draped for the slot.
|
||||
*/
|
||||
showSlot(
|
||||
slotId,
|
||||
candidate,
|
||||
box,
|
||||
{ alpha = 1, splitDirection = 'none' } = {},
|
||||
{
|
||||
alpha = 1,
|
||||
splitDirection = 'none',
|
||||
availableBoxes = null,
|
||||
emptyBoxes = null,
|
||||
} = {},
|
||||
) {
|
||||
if (destroyed || !candidate?.key || !box) return false;
|
||||
if (!host.globe) {
|
||||
@@ -143,21 +185,52 @@ export function createRecentImageryRenderer({
|
||||
}
|
||||
const current = owned[slotId];
|
||||
const look = { alpha: clampAlpha(alpha), split: splitDirection };
|
||||
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
|
||||
if (
|
||||
current &&
|
||||
current.globe === host.globe &&
|
||||
current.candidate.key === candidate.key &&
|
||||
boxKey(current.box) === boxKey(box)
|
||||
parts.length
|
||||
) {
|
||||
if (current.alpha !== look.alpha || current.split !== look.split) {
|
||||
if (partsKey(current.parts) !== partsKey(parts)) {
|
||||
const previous = new Map(
|
||||
current.parts.map((part, i) => [boxKey(part), current.layers[i]]),
|
||||
);
|
||||
// A new half goes right above the slot's surviving half, so both
|
||||
// halves keep the same place against the other slot.
|
||||
const survivor = parts
|
||||
.map((part) => previous.get(boxKey(part)))
|
||||
.find(Boolean);
|
||||
const at = survivor
|
||||
? host.globe.imagery.list().indexOf(survivor) + 1
|
||||
: undefined;
|
||||
const layers = parts.map((part) => {
|
||||
const key = boxKey(part);
|
||||
const layer = previous.get(key);
|
||||
previous.delete(key);
|
||||
return (
|
||||
layer ?? host.globe.imagery.add(specFor(candidate, part), at)
|
||||
);
|
||||
});
|
||||
for (const layer of previous.values()) layer.remove();
|
||||
Object.assign(current, { layers, parts, ...look });
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-show');
|
||||
} else if (
|
||||
current.alpha !== look.alpha ||
|
||||
current.split !== look.split
|
||||
) {
|
||||
Object.assign(current, look);
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-look');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
removeOwned(slotId);
|
||||
mount(slotId, { candidate, box, ...look });
|
||||
const removed = removeOwned(slotId);
|
||||
if (!mount(slotId, { candidate, parts, ...look })) {
|
||||
if (removed) requestRender('recent-imagery-hide');
|
||||
return false;
|
||||
}
|
||||
requestRender('recent-imagery-show');
|
||||
return true;
|
||||
},
|
||||
@@ -221,7 +294,7 @@ export function createRecentImageryRenderer({
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Number of layers this renderer owns (never above two). */
|
||||
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
|
||||
ownedCount() {
|
||||
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
|
||||
},
|
||||
@@ -247,11 +320,11 @@ let previewSeq = 0;
|
||||
|
||||
/** A box with no area has no fill: a press, or a drag along one axis. */
|
||||
const hasArea = (box) =>
|
||||
Boolean(box) && box.east > box.west && box.north > box.south;
|
||||
Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
|
||||
|
||||
/** A box with no extent draws nothing: a press that has not moved yet. */
|
||||
const hasExtent = (box) =>
|
||||
Boolean(box) && (box.east > box.west || box.north > box.south);
|
||||
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
|
||||
|
||||
/**
|
||||
* The box tool's preview: the box being dragged, a translucent fill and a
|
||||
|
||||
@@ -5,7 +5,9 @@ import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { BOX } from './testDoubles.mjs';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX } from './testDoubles.mjs';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
@@ -271,3 +273,210 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe
|
||||
box = { west: -96, south: 32, east: -95, north: 33 };
|
||||
assert.doesNotThrow(() => preview.changed());
|
||||
});
|
||||
|
||||
test('a dateline box drapes one layer on each side of ±180 and removes both', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }),
|
||||
true,
|
||||
);
|
||||
assert.equal(renderer.ownedCount(), 1);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((item) => item.spec.rectangle),
|
||||
[
|
||||
{ west: 179, south: 0, east: 180, north: 1 },
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
],
|
||||
);
|
||||
assert.equal(globe.layers[0].alpha, 0.4);
|
||||
assert.equal(globe.layers[1].alpha, 0.4);
|
||||
assert.equal(globe.layers[0].split, 'left');
|
||||
assert.equal(globe.layers[1].split, 'left');
|
||||
renderer.setAlpha('a', 0.2);
|
||||
assert.equal(globe.layers[0].alpha, 0.2);
|
||||
assert.equal(globe.layers[1].alpha, 0.2);
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.2 });
|
||||
assert.equal(globe.added.length, 2, 'the same box does not remount');
|
||||
renderer.hideSlot('a');
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[east],
|
||||
);
|
||||
renderer.showSlot('b', VIIRS, FIJI_BOX, {
|
||||
availableBoxes: [east, west],
|
||||
splitDirection: 'right',
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.split),
|
||||
['none', 'right', 'right'],
|
||||
);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
|
||||
const next = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe: next });
|
||||
assert.deepEqual(
|
||||
next.layers.map((layer) => layer.spec.rectangle),
|
||||
[east, west, east],
|
||||
);
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] });
|
||||
assert.equal(next.layers.length, 4);
|
||||
renderer.destroy();
|
||||
assert.equal(next.layers.length, 0);
|
||||
});
|
||||
|
||||
test('no allowed half, or halves of another box, drapes nothing', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
for (const availableBoxes of [[], [BOX]]) {
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(renderer.showSlot('a', VIIRS, BOX), true);
|
||||
assert.equal(globe.layers.length, 1);
|
||||
assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('evidence going from none to empty removes the drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', S30, FIJI_BOX);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
availableBoxes: [],
|
||||
emptyBoxes: nonCrossingBoxes(FIJI_BOX),
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => {
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
for (const [product, expected] of [
|
||||
[S30, [west, east]],
|
||||
[VIIRS, [east]],
|
||||
]) {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', product, FIJI_BOX, {
|
||||
availableBoxes: [east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
expected,
|
||||
);
|
||||
renderer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => {
|
||||
const renderer = createRecentImageryRenderer();
|
||||
const globe = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe });
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const layerFor = (box) =>
|
||||
globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box));
|
||||
|
||||
// An HLS day drapes both halves before its probe answers.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' });
|
||||
const kept = layerFor(west);
|
||||
assert.ok(kept);
|
||||
const added = globe.added.length;
|
||||
|
||||
// The probe confirms the east half empty: only the east layer goes.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [east],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the narrowing');
|
||||
assert.equal(globe.added.length, added, 'narrowing adds no layer');
|
||||
assert.equal(layerFor(east), undefined);
|
||||
|
||||
// A later probe admits east again: only the east layer is added.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west, east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the widening');
|
||||
assert.equal(globe.added.length, added + 1);
|
||||
assert.equal(kept.alpha, 0.4);
|
||||
assert.equal(kept.split, 'left');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('widening slot a over the dateline keeps it below slot b on both sides', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const topOn = (box) =>
|
||||
globe.layers
|
||||
.filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box))
|
||||
.at(-1)
|
||||
.spec.url.includes('S30')
|
||||
? 'A'
|
||||
: 'B';
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] });
|
||||
renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('the drag preview draws a wrapped fill and outline across the dateline', async () => {
|
||||
const draw = fakeDrawPort();
|
||||
let box = { west: 179, south: 0, east: 179, north: 0 };
|
||||
const preview = createImageryBoxPreview({}, () => box, { draw });
|
||||
const [fills, outlines] = draw.sets.values();
|
||||
preview.setVisible(true);
|
||||
|
||||
box = { ...box, east: -179 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.size, 0);
|
||||
assert.equal(outlines.items.get('edge').show, true);
|
||||
assert.deepEqual(
|
||||
outlines.items.get('edge').positions[1],
|
||||
fromDegrees(-179, 0),
|
||||
);
|
||||
|
||||
box = { ...box, north: 1 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.get('box').show, true);
|
||||
assert.deepEqual(fills.items.get('box').geometry.rect, box);
|
||||
const edge = outlines.items.get('edge');
|
||||
assert.equal(edge.show, true);
|
||||
assert.deepEqual(edge.positions, [
|
||||
fromDegrees(179, 0),
|
||||
fromDegrees(-179, 0),
|
||||
fromDegrees(-179, 1),
|
||||
fromDegrees(179, 1),
|
||||
fromDegrees(179, 0),
|
||||
]);
|
||||
await preview.destroy();
|
||||
});
|
||||
@@ -1,10 +1,107 @@
|
||||
import { searchHls } from './catalog.js';
|
||||
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
|
||||
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
|
||||
|
||||
/**
|
||||
* Deadline for one half's response headers, so a day whose other half
|
||||
* answered is not held at "checking".
|
||||
*/
|
||||
const DEFAULT_HALF_DEADLINE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
|
||||
* probed as its two non-crossing halves, wider first. A plain box is its
|
||||
* one normalized half. A day has data when either half does.
|
||||
*/
|
||||
function requestBoxes(box) {
|
||||
return nonCrossingBoxes(box).sort(
|
||||
(a, b) => b.east - b.west - (a.east - a.west),
|
||||
);
|
||||
}
|
||||
|
||||
/** A response's Data-Present answer in lower case, or '' when it failed or has none. */
|
||||
export const dataPresent = (response) =>
|
||||
response?.ok
|
||||
? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase()
|
||||
: '';
|
||||
|
||||
/**
|
||||
* One half's snapshot fetch, raced against its own deadline so a half that
|
||||
* never answers, even over a transport that ignores AbortSignal, still
|
||||
* settles. Its deadline cancels only this half. The caller can cancel it
|
||||
* at any time, including while its body is being read.
|
||||
*/
|
||||
function probeHalf(
|
||||
url,
|
||||
{ fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl },
|
||||
) {
|
||||
const controller = new AbortController();
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = null;
|
||||
const finishTimeout = () => {
|
||||
if (timer !== null) clearTimeoutImpl(timer);
|
||||
timer = null;
|
||||
};
|
||||
const stop = (reason) => {
|
||||
controller.abort(reason);
|
||||
finishTimeout();
|
||||
// Settle even if the transport ignores abort.
|
||||
reject(reason);
|
||||
};
|
||||
if (signal?.aborted) {
|
||||
stop(signal.reason);
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener('abort', () => stop(signal.reason), {
|
||||
once: true,
|
||||
});
|
||||
if (deadlineMs > 0)
|
||||
timer = setTimeoutImpl(
|
||||
() =>
|
||||
stop(new DOMException('Thumbnail half timed out', 'TimeoutError')),
|
||||
deadlineMs,
|
||||
);
|
||||
let promise;
|
||||
try {
|
||||
promise = Promise.resolve(fetchImpl(url, { signal: controller.signal }));
|
||||
} catch (error) {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
promise.then(
|
||||
(value) => {
|
||||
finishTimeout();
|
||||
resolve(value);
|
||||
},
|
||||
(error) => {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-enumerable per-half evidence for the box's non-crossing halves:
|
||||
* presentBoxes lists the halves Worldview confirmed present, emptyBoxes
|
||||
* the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js.
|
||||
*/
|
||||
function withHalves(response, { presentBoxes, emptyBoxes }) {
|
||||
Object.defineProperties(response, {
|
||||
presentBoxes: { value: presentBoxes, configurable: true },
|
||||
emptyBoxes: { value: emptyBoxes, configurable: true },
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
|
||||
* Thumbnail responses must expose Data-Present: true for image admission, or
|
||||
* false for confirmed empty coverage, including injected getThumbnail sources.
|
||||
* getThumbnail also sets presentBoxes and emptyBoxes (see withHalves),
|
||||
* also on the error it throws when another half was confirmed empty.
|
||||
* Without per-half evidence the renderer drapes every side of an HLS
|
||||
* dateline box and no side of a VIIRS one.
|
||||
*/
|
||||
export function createRecentImagerySource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
@@ -12,24 +109,68 @@ export function createRecentImagerySource({
|
||||
thumbnailUrl = wvsSnapshotUrl,
|
||||
tileTemplate = gibsTemplate,
|
||||
credit = 'NASA GIBS',
|
||||
halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS,
|
||||
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
|
||||
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
|
||||
} = {}) {
|
||||
return {
|
||||
credit,
|
||||
searchHls: (query) => search({ ...query, fetchImpl }),
|
||||
async getThumbnail(candidate, box, { size = 256, signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{ signal },
|
||||
const halves = requestBoxes(box);
|
||||
const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0;
|
||||
const results = await Promise.allSettled(
|
||||
halves.map((half) =>
|
||||
probeHalf(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box: half,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{
|
||||
fetchImpl,
|
||||
signal,
|
||||
deadlineMs,
|
||||
setTimeoutImpl,
|
||||
clearTimeoutImpl,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
return response;
|
||||
// Per half, its Data-Present answer or null when it did not answer.
|
||||
const answers = results.map((result) =>
|
||||
result.status === 'fulfilled' ? dataPresent(result.value) : null,
|
||||
);
|
||||
const halvesWhere = (value) =>
|
||||
halves.filter((_, i) => answers[i] === value);
|
||||
// A missing answer is an error unless another half proved data. The
|
||||
// error keeps a half confirmed empty (see withHalves).
|
||||
const failure = results.find((result) => result.status === 'rejected');
|
||||
if (failure && !answers.includes('true')) {
|
||||
const emptyBoxes = halvesWhere('false');
|
||||
if (Object.isExtensible(failure.reason))
|
||||
withHalves(
|
||||
failure.reason,
|
||||
emptyBoxes.length
|
||||
? { presentBoxes: [], emptyBoxes }
|
||||
: { presentBoxes: null, emptyBoxes: null },
|
||||
);
|
||||
throw failure.reason;
|
||||
}
|
||||
// Show the first half with data (the wider wins a tie), else the first
|
||||
// not confirmed empty, so an unreadable answer is never called empty.
|
||||
// Every half answered here unless one proved data.
|
||||
let shown = answers.indexOf('true');
|
||||
if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false');
|
||||
if (shown < 0) shown = 0;
|
||||
return withHalves(results[shown].value, {
|
||||
presentBoxes: halvesWhere('true'),
|
||||
emptyBoxes: halvesWhere('false'),
|
||||
});
|
||||
},
|
||||
getTileTemplate: (product, day) => tileTemplate(product, day),
|
||||
};
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { manualTimers } from './testDoubles.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
|
||||
test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => {
|
||||
const controller = new AbortController();
|
||||
const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal };
|
||||
const query = {
|
||||
box: { west: 0, east: 1, south: 0, north: 1 },
|
||||
signal: controller.signal,
|
||||
};
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
const calls = [];
|
||||
const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); };
|
||||
const fetchImpl = async (...args) => {
|
||||
calls.push(args);
|
||||
return new Response('image');
|
||||
};
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl,
|
||||
search: async (request) => {
|
||||
@@ -16,27 +23,263 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
|
||||
assert.equal(request.box, query.box);
|
||||
return [candidate];
|
||||
},
|
||||
thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
thumbnailUrl: ({ product, day, width }) =>
|
||||
`https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) =>
|
||||
`https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
credit: 'Example imagery',
|
||||
});
|
||||
assert.deepEqual(await source.searchHls(query), [candidate]);
|
||||
assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image');
|
||||
assert.equal(
|
||||
await (
|
||||
await source.getThumbnail(candidate, query.box, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
).text(),
|
||||
'image',
|
||||
);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256');
|
||||
assert.equal(calls[0][1].signal, controller.signal);
|
||||
assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}');
|
||||
// The fetch gets a private signal chained to the caller's.
|
||||
const halfSignal = calls[0][1].signal;
|
||||
assert.notEqual(halfSignal, controller.signal);
|
||||
assert.equal(halfSignal.aborted, false);
|
||||
controller.abort();
|
||||
assert.equal(halfSignal.aborted, true);
|
||||
assert.equal(
|
||||
source.getTileTemplate(candidate.product, candidate.day),
|
||||
'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}',
|
||||
);
|
||||
assert.equal(source.credit, 'Example imagery');
|
||||
});
|
||||
|
||||
test('cancelled thumbnail acquisition does not return stale responses or retry', async () => {
|
||||
const controller = new AbortController();
|
||||
const box = { west: 0, south: 0, east: 1, north: 1 };
|
||||
let calls = 0;
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://imagery.example/thumbnail',
|
||||
fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); },
|
||||
fetchImpl: async () => {
|
||||
calls++;
|
||||
controller.abort();
|
||||
return new Response('image');
|
||||
},
|
||||
});
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => {
|
||||
requested.push(box);
|
||||
return 'https://imagery.example/thumbnail';
|
||||
},
|
||||
fetchImpl: async () => new Response('image'),
|
||||
});
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179.9,
|
||||
south: 0,
|
||||
east: -179,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested, [
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
{ west: 179.9, south: 0, east: 180, north: 1 },
|
||||
]);
|
||||
requested.length = 0;
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179,
|
||||
south: 0,
|
||||
east: -179.9,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 });
|
||||
assert.equal(requested.length, 2);
|
||||
assert.ok(requested.every((box) => box.west <= box.east));
|
||||
});
|
||||
|
||||
const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 };
|
||||
// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG.
|
||||
const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' };
|
||||
const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 };
|
||||
const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 };
|
||||
|
||||
const dated = (present, body = 'image') =>
|
||||
new Response(body, { headers: { 'Data-Present': present } });
|
||||
function halvesSource(answers, options = {}) {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
...options,
|
||||
thumbnailUrl: ({ box }) =>
|
||||
`https://imagery.example/${box.west}/${box.east}`,
|
||||
fetchImpl: async (url) => {
|
||||
requested.push(url);
|
||||
const answer = answers[url.split('imagery.example/')[1]];
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer.clone ? answer : answer();
|
||||
},
|
||||
});
|
||||
return { source, requested };
|
||||
}
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
|
||||
test('a crossing box probes both halves and is present when only the narrow half has data', async () => {
|
||||
const { source, requested } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(requested.length, 2);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box with data only on the wider half is present and shows the wider side', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
});
|
||||
|
||||
test('a crossing box is empty only when both halves are confirmed empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'false');
|
||||
assert.deepEqual(response.presentBoxes, []);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box is not called empty when the other half failed', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': () => new Response('x', { status: 503 }),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.ok, false);
|
||||
});
|
||||
|
||||
test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a rejected half does not hide data on the other half, and never reads as empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
const failing = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
await assert.rejects(
|
||||
failing.source.getThumbnail(candidate, NARROW_WEST),
|
||||
/network/,
|
||||
);
|
||||
});
|
||||
|
||||
for (const [label, answer] of [
|
||||
['rejected', new Error('network')],
|
||||
['hung', () => new Promise(() => {})],
|
||||
['answered without a presence', () => dated('unknown', 'maybe')],
|
||||
]) {
|
||||
for (const product of [JPEG_CANDIDATE, candidate]) {
|
||||
test(`a ${product.product} half that ${label} is neither present nor empty`, async () => {
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') },
|
||||
{ halfDeadlineMs: 20 },
|
||||
);
|
||||
const response = await source.getThumbnail(product, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => {
|
||||
const controller = new AbortController();
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://example.invalid/',
|
||||
halfDeadlineMs: 10000,
|
||||
fetchImpl: () => {
|
||||
controller.abort();
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const outcome = await Promise.race([
|
||||
source
|
||||
.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal })
|
||||
.then(
|
||||
() => 'resolved',
|
||||
(error) => error.name,
|
||||
),
|
||||
new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)),
|
||||
]);
|
||||
assert.equal(outcome, 'AbortError');
|
||||
});
|
||||
|
||||
test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => {
|
||||
const hang = () => new Promise(() => {});
|
||||
const { source, requested } = halvesSource(
|
||||
{ '-180/-179': hang, '179.9/180': hang },
|
||||
{ halfDeadlineMs: 10 },
|
||||
);
|
||||
await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), {
|
||||
name: 'TimeoutError',
|
||||
});
|
||||
assert.equal(requested.length, 2);
|
||||
});
|
||||
|
||||
test("the caller's cancellation rejects at once and stops every half", async () => {
|
||||
const aborted = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => String(box.west),
|
||||
fetchImpl: (url, { signal }) => {
|
||||
signal.addEventListener('abort', () => aborted.push(url), { once: true });
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
await assert.rejects(result, { name: 'AbortError' });
|
||||
assert.deepEqual(aborted, ['-180', '179.9']);
|
||||
});
|
||||
|
||||
test('a successful probe leaves no deadline timer behind', async () => {
|
||||
const timers = manualTimers();
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': dated('true'), '179.9/180': dated('false') },
|
||||
timers,
|
||||
);
|
||||
await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
|
||||
assert.equal(timers.armed(), 0);
|
||||
assert.equal(timers.cleared.length, 2);
|
||||
});
|
||||
@@ -16,6 +16,13 @@ export const BOX = Object.freeze({
|
||||
north: 30.3,
|
||||
});
|
||||
|
||||
export const FIJI_BOX = Object.freeze({
|
||||
west: 179,
|
||||
south: -18,
|
||||
east: -177,
|
||||
north: -17,
|
||||
});
|
||||
|
||||
export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
/** Timers that fire only when the test says so. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
|
||||
* candidate day. The response's `Data-Present` header is the only proof that
|
||||
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
|
||||
* a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and
|
||||
* `Acquisition-Time` carries the sensing time. Fetches are bounded, and so
|
||||
* are decoded images: residency is least-recently-USED, where a request or a
|
||||
@@ -8,16 +8,28 @@
|
||||
* card on every render, so a read that counted would evict the visible cards
|
||||
* first). Eviction revokes the image only; what the probe proved is kept.
|
||||
*/
|
||||
import { thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { boxKey, thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource, dataPresent } from './source.js';
|
||||
|
||||
const EMPTY = Object.freeze({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */
|
||||
function keepProvenHalves(previous, next, opposite) {
|
||||
if (!Array.isArray(next) || !Array.isArray(opposite)) return previous;
|
||||
const drop = new Set([...next, ...opposite].map(boxKey));
|
||||
return [
|
||||
...next,
|
||||
...(previous ?? []).filter((half) => !drop.has(boxKey(half))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]
|
||||
*/
|
||||
@@ -90,18 +102,22 @@ export function createThumbnailLoader({
|
||||
let status = 'error';
|
||||
let objectUrl = null;
|
||||
let acquisitionTime = null;
|
||||
// Per-half evidence (see withHalves in source.js), or null without it.
|
||||
let availableBoxes = null;
|
||||
let emptyBoxes = null;
|
||||
let cancelled = false;
|
||||
try {
|
||||
const response = await requestThumbnail(entry.candidate, entry.box, {
|
||||
size,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Each half's explicit answer counts even when the shown response fails.
|
||||
availableBoxes = response?.presentBoxes ?? null;
|
||||
emptyBoxes = response?.emptyBoxes ?? null;
|
||||
if (controller.signal.aborted) {
|
||||
cancelled = true;
|
||||
} else if (response?.ok) {
|
||||
const present = String(
|
||||
response.headers?.get?.('Data-Present') ?? '',
|
||||
).toLowerCase();
|
||||
const present = dataPresent(response);
|
||||
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
|
||||
if (present === 'false') {
|
||||
status = 'empty';
|
||||
@@ -117,7 +133,11 @@ export function createThumbnailLoader({
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || error?.name === 'AbortError')
|
||||
cancelled = true;
|
||||
else status = 'error';
|
||||
else {
|
||||
status = 'error';
|
||||
availableBoxes = error?.presentBoxes ?? availableBoxes;
|
||||
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
|
||||
}
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
entry.loading = false;
|
||||
@@ -129,6 +149,17 @@ export function createThumbnailLoader({
|
||||
pump();
|
||||
return;
|
||||
}
|
||||
// Each half keeps its latest explicit answer.
|
||||
entry.availableBoxes = keepProvenHalves(
|
||||
entry.availableBoxes,
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
);
|
||||
entry.emptyBoxes = keepProvenHalves(
|
||||
entry.emptyBoxes,
|
||||
emptyBoxes,
|
||||
availableBoxes,
|
||||
);
|
||||
// A failed re-fetch of an evicted image keeps what the day proved.
|
||||
if (status !== 'error' || entry.status !== 'present') {
|
||||
entry.status = status;
|
||||
@@ -196,6 +227,8 @@ export function createThumbnailLoader({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
controller: null,
|
||||
touched: 0,
|
||||
@@ -272,7 +305,7 @@ export function createThumbnailLoader({
|
||||
/**
|
||||
* Read a day's state. A read is not a use: it never changes residency.
|
||||
* @param {string} key Candidate key.
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
|
||||
*/
|
||||
get(key) {
|
||||
const entry = entries.get(key);
|
||||
@@ -281,6 +314,8 @@ export function createThumbnailLoader({
|
||||
status: entry.status,
|
||||
objectUrl: entry.objectUrl,
|
||||
acquisitionTime: entry.acquisitionTime,
|
||||
availableBoxes: entry.availableBoxes,
|
||||
emptyBoxes: entry.emptyBoxes,
|
||||
loading: entry.loading,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { BOX, response, settle } from './testDoubles.mjs';
|
||||
|
||||
const candidate = (product, day) => ({
|
||||
key: `${product}:${day}`,
|
||||
product,
|
||||
day,
|
||||
});
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
|
||||
|
||||
/** A fetch whose responses the test releases, in any order. */
|
||||
function fakeFetch() {
|
||||
@@ -68,6 +64,8 @@ test('Data-Present decides the day: present with an object URL and sensing time,
|
||||
status: 'present',
|
||||
objectUrl: 'blob:1',
|
||||
acquisitionTime: '2026-09-18T17:12:00Z',
|
||||
availableBoxes: [BOX],
|
||||
emptyBoxes: [],
|
||||
loading: false,
|
||||
});
|
||||
assert.equal(loader.get('L30:2026-09-16').status, 'empty');
|
||||
@@ -337,6 +335,75 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
|
||||
assert.deepEqual(revoked, ['blob:1']);
|
||||
});
|
||||
|
||||
test('the loader proves a dateline day present from one half and hands that half on', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const time = day.day + 'T22:10:00Z';
|
||||
const { loader } = fixture({
|
||||
fetchImpl: async (url) => {
|
||||
const east =
|
||||
new URL(url).searchParams.get('BBOX').split(',')[1] === '-180';
|
||||
return response({
|
||||
headers: east
|
||||
? { 'Data-Present': 'true', 'Acquisition-Time': time }
|
||||
: { 'Data-Present': 'false' },
|
||||
});
|
||||
},
|
||||
});
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settle();
|
||||
const entry = loader.get(day.key);
|
||||
assert.equal(entry.status, 'present');
|
||||
assert.equal(entry.acquisitionTime, time);
|
||||
assert.ok(entry.objectUrl);
|
||||
assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a dateline day whose halves both hang is an error, not "checking" forever', async () => {
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl: () => new Promise(() => {}),
|
||||
halfDeadlineMs: 20,
|
||||
});
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
});
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const settled = new Promise((resolve) => loader.subscribe(resolve));
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settled;
|
||||
assert.equal(loader.get(day.key).status, 'error');
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present day drops a half only when it is confirmed empty', async () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
const answers = [
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west], emptyBoxes: [east] },
|
||||
];
|
||||
const { loader } = fixture({
|
||||
maxDecoded: 1,
|
||||
requestThumbnail: async () =>
|
||||
Object.assign(
|
||||
response({ headers: { 'Data-Present': 'true' } }),
|
||||
answers.shift(),
|
||||
),
|
||||
});
|
||||
const day1 = candidate('VIIRS', '2026-11-04');
|
||||
const day2 = candidate('VIIRS', '2026-11-05');
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
loader.request(day2, box);
|
||||
await settle();
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
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');
|
||||
|
||||
@@ -292,6 +292,8 @@ function recordingRendering(state) {
|
||||
if (point) point.show = show;
|
||||
},
|
||||
_setPointsShown() {},
|
||||
_startPace() {},
|
||||
_stopPace() {},
|
||||
_setOrbitPathShown(noradId, show) {
|
||||
if (state._orbitPaths.has(noradId)) rings.set(noradId, show);
|
||||
},
|
||||
|
||||
@@ -30,7 +30,6 @@ export function createLifecycle({
|
||||
// Unregistered on destroy, so a page that builds the app again holds no old layer; init
|
||||
// registers it again.
|
||||
let uncover = worldClock.register(clockSource);
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
/** Run the shared per-frame tick before each frame draws. */
|
||||
@@ -98,7 +97,8 @@ export function createLifecycle({
|
||||
|
||||
enable(viewer) {
|
||||
layerState._enabled = true;
|
||||
holdContinuousRender('satellites'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the dots move on screen (rendering.js, the pace).
|
||||
parts.rendering._startPace();
|
||||
parts.rendering._setPointsShown(
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
@@ -137,7 +137,7 @@ export function createLifecycle({
|
||||
parts.catalog._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
layerState._enabled = false;
|
||||
releaseContinuousRender('satellites');
|
||||
parts.rendering._stopPace();
|
||||
parts.rendering._setPointsShown(false);
|
||||
parts.rendering._setOrbitPathsShown(false);
|
||||
for (const model of parts.stationModels ?? [])
|
||||
@@ -165,7 +165,7 @@ export function createLifecycle({
|
||||
parts.catalog._abortActiveUpdates();
|
||||
uncover?.();
|
||||
uncover = null;
|
||||
releaseContinuousRender('satellites'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
layerState._enabled = false;
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -2,6 +2,11 @@ import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { gstime } from 'satellite.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
} from '../../renderPace.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ORBIT_REBAKE_MS,
|
||||
@@ -104,6 +109,49 @@ export function createRendering({
|
||||
/** The frame the tick last ran in: the tracked sample's cache key. */
|
||||
let renderedFrame = -1;
|
||||
|
||||
// The pace: how often the dots are drawn while nothing else draws. A dot
|
||||
// in low orbit crosses under half a pixel a second on the whole globe and
|
||||
// hundreds of pixels a second from close by, so the rate follows the
|
||||
// fastest dot in view (renderPace.js) instead of holding the loop at the
|
||||
// display's rate.
|
||||
const pace = createRenderPace({
|
||||
owner: 'satellites',
|
||||
render: services.render,
|
||||
});
|
||||
const screenSpeed = createScreenSpeed();
|
||||
/** While dots fade for a focus change, they are drawn this often. */
|
||||
const PACE_FADE_HZ = 20;
|
||||
/** The least time a reading spans: shorter, and the clock's jitter shows. */
|
||||
const PACE_READ_MS = 100;
|
||||
/** Wall time of the last reading of the dots' speed, and its result. */
|
||||
let paceWallMs = 0;
|
||||
let pacePxPerSec = 0;
|
||||
/** Where the eye was at the last reading: a dot's move is taken from it. */
|
||||
const paceEye = { x: 0, y: 0, z: 0 };
|
||||
const paceEyeMove = { x: 0, y: 0, z: 0 };
|
||||
let paceFading = false;
|
||||
/** Whether the layer is on and paced: its dots' speed is read. */
|
||||
let pacing = false;
|
||||
|
||||
/** Set the rate from the fastest dot seen; called once a drawn frame. */
|
||||
function _applyPace() {
|
||||
let hz = paceHzForSpeed(pacePxPerSec);
|
||||
if (paceFading && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
|
||||
pace.set(hz);
|
||||
}
|
||||
|
||||
function _startPace() {
|
||||
pacing = true;
|
||||
paceWallMs = 0;
|
||||
pacePxPerSec = 0;
|
||||
pace.start();
|
||||
}
|
||||
|
||||
function _stopPace() {
|
||||
pacing = false;
|
||||
pace.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
|
||||
* aligned with live SGP4 positions propagated at another epoch: a column-
|
||||
@@ -654,6 +702,26 @@ export function createRendering({
|
||||
|
||||
function _reckonPoints(nowMs) {
|
||||
const gmst = gstime(new Date(nowMs));
|
||||
// The pace's reading, at most every PACE_READ_MS: how far the fastest
|
||||
// dot in view moved on screen since the last one.
|
||||
const wallMs = performance.now();
|
||||
const sinceS = (wallMs - paceWallMs) / 1000;
|
||||
const reading = pacing && wallMs - paceWallMs >= PACE_READ_MS;
|
||||
const camera = reading ? findCamera(layerState._viewer) : null;
|
||||
const view = camera?.pose?.() ?? null;
|
||||
const eye = view?.position;
|
||||
// The eye's own move since the last reading: a camera riding one
|
||||
// satellite sees its neighbours nearly still.
|
||||
if (eye) {
|
||||
paceEyeMove.x = eye.x - paceEye.x;
|
||||
paceEyeMove.y = eye.y - paceEye.y;
|
||||
paceEyeMove.z = eye.z - paceEye.z;
|
||||
}
|
||||
const measure =
|
||||
reading &&
|
||||
sinceS < 5 &&
|
||||
screenSpeed.begin(view, camera?.viewport?.().height, paceEyeMove);
|
||||
const lastWallMs = paceWallMs;
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (!point.show || noradId === layerState._trackedNorad) continue;
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
@@ -669,7 +737,24 @@ export function createRendering({
|
||||
reckonEarthFixed(sample, nowMs, gmst, point.pos);
|
||||
_markDirty(noradId);
|
||||
sat.reckonedAtMs = nowMs;
|
||||
if (!reading) continue;
|
||||
// Where the dot was at the last reading, kept on its satellite. One
|
||||
// not read then (hidden, or just loaded) is not measured: it jumps.
|
||||
const from = (sat.paceFrom ??= { x: 0, y: 0, z: 0, atMs: -1 });
|
||||
if (measure && from.atMs === lastWallMs) screenSpeed.add(from, point.pos);
|
||||
from.x = point.pos.x;
|
||||
from.y = point.pos.y;
|
||||
from.z = point.pos.z;
|
||||
from.atMs = wallMs;
|
||||
}
|
||||
if (!reading) return;
|
||||
if (eye) {
|
||||
paceEye.x = eye.x;
|
||||
paceEye.y = eye.y;
|
||||
paceEye.z = eye.z;
|
||||
}
|
||||
if (measure) pacePxPerSec = screenSpeed.pxPerSec(sinceS);
|
||||
paceWallMs = wallMs;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -691,6 +776,7 @@ export function createRendering({
|
||||
renderedFrame = Number.isFinite(t?.frame) ? t.frame : renderedFrame + 1;
|
||||
if (layerState._enabled) _tickAfterFrame();
|
||||
_flushPoints();
|
||||
_applyPace();
|
||||
}
|
||||
|
||||
/** The tick's part read before the frame's own sample is taken. */
|
||||
@@ -733,9 +819,17 @@ export function createRendering({
|
||||
|
||||
if (layerState._params.showPoints) {
|
||||
const worldMs = layerState.now();
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
// The dots move at the pace, not on every drawn frame: moving them
|
||||
// asks for the next frame, so a frame drawn for any reason would keep
|
||||
// the loop drawing; and a drag over the whole globe need not send
|
||||
// every dot to the GPU sixty times a second to move it a hair.
|
||||
if (pace.take()) {
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
}
|
||||
} else {
|
||||
pacePxPerSec = 0;
|
||||
}
|
||||
|
||||
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
|
||||
@@ -781,8 +875,10 @@ export function createRendering({
|
||||
if (
|
||||
!layerState._params.showPoints ||
|
||||
!focusPassIsNeeded(target, layerState._activeFocusCount)
|
||||
)
|
||||
) {
|
||||
paceFading = false;
|
||||
return;
|
||||
}
|
||||
if (nowMs - layerState._lastFocusUpdate < 80) return;
|
||||
layerState._lastFocusUpdate = nowMs;
|
||||
const query = findQuery(layerState._viewer);
|
||||
@@ -837,6 +933,7 @@ export function createRendering({
|
||||
).color,
|
||||
});
|
||||
layerState._activeFocusCount = result.activeCount;
|
||||
paceFading = Boolean(result.transitioning);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -939,6 +1036,9 @@ export function createRendering({
|
||||
_propagateAll,
|
||||
_reckonPoints,
|
||||
_preRenderTick,
|
||||
_startPace,
|
||||
_stopPace,
|
||||
_paceForTest: () => ({ ...pace.state(), pxPerSec: pacePxPerSec }),
|
||||
_updatePointFocus,
|
||||
applySatellitePointFocusDeemphasis,
|
||||
_flushPoints,
|
||||
|
||||
@@ -5,6 +5,8 @@ import { VISIBILITY_UPDATE_MS } from './policy.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { PACE_MAX_HZ, PACE_MIN_HZ } from '../../renderPace.js';
|
||||
import { createVesselIconBook } from './iconBook.js';
|
||||
|
||||
// The layer must let the scene idle: it asks for frames for forced passes,
|
||||
// for vessels that move, and one trailing frame after the camera stops, and
|
||||
@@ -270,7 +272,7 @@ test('a placement that places nothing asks for no frames; one that places a draw
|
||||
assert.deepEqual(requests, ['ais-vessels-placement']);
|
||||
});
|
||||
|
||||
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (t) => {
|
||||
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel, at most 30 a second; a slow one three times a second', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
@@ -295,23 +297,24 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
|
||||
};
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientHeight: 1000 } });
|
||||
// How long after a pass the next frame is asked for, once the vessel moved
|
||||
// `dLat` in the 16 ms since the pass before.
|
||||
// `dLat` in the 40 ms since the pass before (passes come at most 30 a
|
||||
// second, so a frame 16 ms on would not move it).
|
||||
const waitAfterStep = (dLat) => {
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000); // whatever frame that asked for comes and goes
|
||||
assert.equal(timers.size, 0);
|
||||
mono += 16;
|
||||
mono += 40;
|
||||
spot = { lat: spot.lat + dLat, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.equal(timers.size, 1);
|
||||
const [timer] = [...timers.values()];
|
||||
return timer.at - now();
|
||||
};
|
||||
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
|
||||
// is asked for within the frame.
|
||||
assert.ok(waitAfterStep(0.0001) <= 16);
|
||||
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
|
||||
assert.equal(waitAfterStep(0.0000001), 1000);
|
||||
// About 11 m in a pass, 20 km away: over half a pixel, so the next frame
|
||||
// is asked for within the pass's own span.
|
||||
assert.ok(waitAfterStep(0.0001) <= 40);
|
||||
// About 1 cm in a frame: half a pixel takes seconds, so at the floor.
|
||||
assert.ok(Math.abs(waitAfterStep(0.0000001) - 1000 / PACE_MIN_HZ) < 1e-6);
|
||||
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
|
||||
// next frame comes within two frames.
|
||||
camera.frustum = new Cesium.OrthographicOffCenterFrustum({
|
||||
@@ -324,7 +327,20 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
|
||||
});
|
||||
camera.viewMatrix = Cesium.Matrix4.IDENTITY;
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientWidth: 1000 } });
|
||||
assert.ok(waitAfterStep(0.0001) <= 32);
|
||||
assert.ok(waitAfterStep(0.0001) <= 80);
|
||||
// A frame sooner than a thirtieth of a second after a pass moves nothing:
|
||||
// the next pass is asked for when one may come.
|
||||
mono += 100;
|
||||
spot = { lat: spot.lat + 0.001, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000);
|
||||
const drawn = layer.testing._vesselVisualForTest(record).drawnLat;
|
||||
mono += 16;
|
||||
spot = { lat: spot.lat + 0.001, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.equal(layer.testing._vesselVisualForTest(record).drawnLat, drawn);
|
||||
const [held] = [...timers.values()];
|
||||
assert.ok(Math.abs(held.at - now() - (1000 / PACE_MAX_HZ - 16)) < 1e-6);
|
||||
});
|
||||
|
||||
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
|
||||
@@ -722,3 +738,49 @@ test('following the clock, a vessel the visibility pass shows before the clock p
|
||||
);
|
||||
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
|
||||
});
|
||||
|
||||
test('a placement pass writes the vessels it moved to the set at once, not one a vessel', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
t.after(() => {
|
||||
if (originalDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = originalDocument;
|
||||
});
|
||||
const spots = new Map([
|
||||
['111', { lat: 51.93, lon: 4.05 }],
|
||||
['222', { lat: 51.94, lon: 4.06 }],
|
||||
]);
|
||||
const { layer, camera } = setup({
|
||||
placement: { layer: () => ({ place: (id) => spots.get(id) }) },
|
||||
});
|
||||
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
|
||||
camera.frustum = { fovy: 1 };
|
||||
const writes = [];
|
||||
const icons = createVesselIconBook({
|
||||
id: 'vessels',
|
||||
upsert: (list) => writes.push(list.map((item) => item.id)),
|
||||
remove: noop,
|
||||
});
|
||||
const records = [
|
||||
{ mmsi: '111', lat: 51.93, lon: 4.05 },
|
||||
{ mmsi: '222', lat: 51.94, lon: 4.06 },
|
||||
];
|
||||
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
|
||||
bindFakeCesiumScene(viewer);
|
||||
layer.testing._setVesselStateForTest({ viewer, records, icons });
|
||||
for (const record of records) {
|
||||
const visual = layer.testing._prepareVesselVisualForTest(record);
|
||||
visual.visible = true;
|
||||
// Drawn already, as the layer draws a vessel it was sent.
|
||||
icons.put({ id: visual.iconId }, { expiresAt: null });
|
||||
}
|
||||
layer.testing._runPlacementPassForTest();
|
||||
mono += 100;
|
||||
for (const [id, spot] of spots)
|
||||
spots.set(id, { lat: spot.lat + 0.001, lon: spot.lon });
|
||||
writes.length = 0;
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.deepEqual(writes, [['111', '222']]);
|
||||
});
|
||||
+108
-19
@@ -48,13 +48,19 @@ 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';
|
||||
import { PACE_MAX_HZ, PACE_MIN_HZ, PACE_STEP_PX } from '../../renderPace.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
|
||||
* when it does not. */
|
||||
const VESSEL_STEP_PX = 0.5;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves. */
|
||||
const PLACEMENT_FRAME_MS = 1000;
|
||||
const VESSEL_STEP_PX = PACE_STEP_PX;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves:
|
||||
* the floor every moving layer keeps (renderPace.js). */
|
||||
const PLACEMENT_FRAME_MS = 1000 / PACE_MIN_HZ;
|
||||
/** And at most this often: the most a moving layer draws (renderPace.js). */
|
||||
const PLACEMENT_MIN_WAIT_MS = 1000 / PACE_MAX_HZ;
|
||||
/** While vessels' emphasis changes for a focus, they are drawn this often. */
|
||||
const VESSEL_FOCUS_FPS = 20;
|
||||
/** How often each vessel not drawn moves on as the world clock plays (wall
|
||||
* ms), so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
@@ -482,6 +488,12 @@ export function createRendering({
|
||||
function putIcon(visual, item) {
|
||||
if (!segmentsOn()) {
|
||||
planFrom.delete(item.id);
|
||||
// In a placement pass, written with the pass's others at its end:
|
||||
// one write to the set, not one a vessel.
|
||||
if (placedIcons && state.icons.expiresAt(item.id) === undefined) {
|
||||
placedIcons.push(item);
|
||||
return;
|
||||
}
|
||||
state.icons.put(item, { expiresAt: null });
|
||||
return;
|
||||
}
|
||||
@@ -989,26 +1001,88 @@ export function createRendering({
|
||||
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
|
||||
}
|
||||
|
||||
// Live with a host-supplied placement, vessels move on between refreshes:
|
||||
// drawn where it places them every frame, with the next frame asked for
|
||||
// as soon as a drawn vessel would move visibly, so they move while the
|
||||
// scene idles.
|
||||
// Live with a host-supplied placement, vessels move on between refreshes.
|
||||
// Drawn ones move once the fastest would have moved VESSEL_STEP_PX on
|
||||
// screen since the pass that last moved them, at least three times a second
|
||||
// and at most thirty (renderPace.js), and
|
||||
// at once when the camera moves or zooms, new rows come or a vessel comes
|
||||
// into view (underClockStep, on wall time). Moving an icon asks for a
|
||||
// frame, so moving them on every frame would draw every frame: the frames
|
||||
// between are left alone, and the next one is asked for when it is due.
|
||||
let placementDue = true;
|
||||
/** The icons a placement pass moved, while it runs (`putIcon`). */
|
||||
let placedIcons = null;
|
||||
/** Wall ms of the last pass that moved live-placed vessels. */
|
||||
let placedWallMs = -Infinity;
|
||||
function followPlacements() {
|
||||
const nowMs = vesselState._aisRuntime.now();
|
||||
const wallMs = performance.now();
|
||||
// Never more often than a moving layer draws: a pass moving icons asks
|
||||
// for a frame of its own, so without this a vessel close by moving
|
||||
// over half a pixel a frame would draw every frame.
|
||||
const sinceMs = wallMs - placedWallMs;
|
||||
if (!placementDue && sinceMs < PLACEMENT_MIN_WAIT_MS) {
|
||||
askFrameIn(PLACEMENT_MIN_WAIT_MS - sinceMs);
|
||||
return;
|
||||
}
|
||||
if (!placementDue && underClockStep(nowMs, wallMs)) {
|
||||
askFrameIn(
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
PLACEMENT_FRAME_MS - (wallMs - clockStep.wallMs),
|
||||
VESSEL_STEP_PX / clockStep.pxPerMs - (nowMs - clockStep.atMs),
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
placementDue = false;
|
||||
placedWallMs = wallMs;
|
||||
const motion = startMotionPass();
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
if (!drawnNow(record, visual)) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) motion.moving = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(record, visual, lat, lon, motion);
|
||||
placedIcons = [];
|
||||
try {
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
if (!drawnNow(record, visual)) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) motion.moving = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
// How fast it moves is measured over the time since it was last
|
||||
// placed.
|
||||
const elapsedMs =
|
||||
placed && visual.placedAtMs > 0
|
||||
? nowMs - visual.placedAtMs
|
||||
: undefined;
|
||||
visual.placedAtMs = placed ? nowMs : undefined;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(
|
||||
record,
|
||||
visual,
|
||||
lat,
|
||||
lon,
|
||||
motion,
|
||||
elapsedMs > 0 ? elapsedMs : undefined,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
const moved = placedIcons;
|
||||
placedIcons = null;
|
||||
state.icons?.putMany(moved);
|
||||
}
|
||||
askMotionFrame(motion);
|
||||
noteClockStep(nowMs, motion);
|
||||
}
|
||||
|
||||
/** Move live-placed vessels on the next frame however little they moved,
|
||||
* and ask for that frame: new rows came, or a vessel came into view. */
|
||||
function placeNow() {
|
||||
if (!services.placement || followsClock(vesselState)) return;
|
||||
placementDue = true;
|
||||
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
|
||||
}
|
||||
|
||||
// One pass of moving vessels: whether any drawn vessel is moving, how far
|
||||
@@ -1126,6 +1200,12 @@ export function createRendering({
|
||||
/** Ask for a vessel frame `waitMs` from now; one already asked for no
|
||||
* later stands. */
|
||||
function askFrameIn(waitMs) {
|
||||
// A frame sooner than the next pass may come would move nothing, then
|
||||
// ask again: two frames a move.
|
||||
waitMs = Math.max(
|
||||
waitMs,
|
||||
PLACEMENT_MIN_WAIT_MS - (performance.now() - placedWallMs),
|
||||
);
|
||||
const runtime = vesselState._aisRuntime;
|
||||
const dueMs = runtime.now() + waitMs;
|
||||
if (placementFrameTimer !== null) {
|
||||
@@ -1143,6 +1223,7 @@ export function createRendering({
|
||||
function cancelPlacementFrame() {
|
||||
motionPassWallMs = null;
|
||||
forgetClockStep();
|
||||
placementDue = true;
|
||||
drawnBehind = false;
|
||||
hiddenFollowedAtWallMs = null;
|
||||
if (placementFrameTimer === null) return;
|
||||
@@ -1171,6 +1252,8 @@ export function createRendering({
|
||||
function updateVisibility(force = false) {
|
||||
if (!state.feed.enabled) return;
|
||||
if (force) governorRequestRender('ais-vessels-update');
|
||||
// New rows are drawn where they were reported: placed before they show.
|
||||
if (force) placementDue = true;
|
||||
const now = focusNowMs(performance.now());
|
||||
const focusTarget = getFocusTarget();
|
||||
const regularPass =
|
||||
@@ -1230,9 +1313,13 @@ export function createRendering({
|
||||
// The time the clock pass drew (a playing clock's time moves on within
|
||||
// the frame), so only vessels it did not reach are moved.
|
||||
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
|
||||
let cameIntoView = false;
|
||||
for (const record of state.records.all) {
|
||||
const visual = getVisual(record);
|
||||
const wasVisible = visual.visible;
|
||||
visual.visible = isVisible(visual.cullPosition, occluder, record);
|
||||
// One that comes into view was not placed while hidden.
|
||||
if (visual.visible && wasVisible === false) cameIntoView = true;
|
||||
// One in view that the clock passes have not moved to the time yet
|
||||
// (a seek while paused shows it before its turn) is moved there and
|
||||
// judged again: no later pass would move it while the clock rests.
|
||||
@@ -1246,6 +1333,7 @@ export function createRendering({
|
||||
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
|
||||
if (visual.visible) labelCandidates.push(record);
|
||||
}
|
||||
if (cameIntoView) placeNow();
|
||||
updateClusteredLabels(labelCandidates);
|
||||
}
|
||||
if (focusPass && query && pose) {
|
||||
@@ -1258,8 +1346,9 @@ export function createRendering({
|
||||
cameraDistanceFor: (position) => distance(pose.position, position),
|
||||
});
|
||||
state.activeFocusCount = result.activeCount;
|
||||
// Drawn while emphasis changes, at the rate fades draw elsewhere.
|
||||
if (result.activeCount > 0 || result.transitioning)
|
||||
holdContinuousRender('ais-vessels');
|
||||
holdContinuousRender('ais-vessels', { maxFps: VESSEL_FOCUS_FPS });
|
||||
else releaseContinuousRender('ais-vessels');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,16 +796,20 @@ export function createCesiumDraw({
|
||||
setsVersion += 1;
|
||||
};
|
||||
record.rebuild = rebuild;
|
||||
// A set whose owner asks for its frames is changed in place without
|
||||
// asking for one: the owner writes it as a frame begins (asking then
|
||||
// would draw that frame twice), or its next frame draws the change.
|
||||
const ownerFrames = () => spec.motionClock?.frames === 'owner';
|
||||
// Changed in place: what height queries see through may have changed.
|
||||
const patched = () => {
|
||||
setsVersion += 1;
|
||||
requestRender();
|
||||
if (!ownerFrames()) requestRender();
|
||||
};
|
||||
// Icons changed in place: height queries see through the sets' pick
|
||||
// ids, which an icon keeps, so only icons added or gone change them.
|
||||
const iconsPatched = (synced) => {
|
||||
if (synced === ICONS_CHANGED) setsVersion += 1;
|
||||
requestRender();
|
||||
if (!ownerFrames()) requestRender();
|
||||
};
|
||||
// A shape's pulse the renderer cannot run is refused before anything
|
||||
// changes.
|
||||
@@ -925,7 +929,9 @@ export function createCesiumDraw({
|
||||
spec.motionClock?.kind === 'live'
|
||||
) {
|
||||
spec.motionClock = options.motionClock;
|
||||
requestRender();
|
||||
// A set whose owner asks for its frames reads the new delay in
|
||||
// the owner's next one: the delay alone asks for none.
|
||||
if (options.motionClock.frames !== 'owner') requestRender();
|
||||
return;
|
||||
}
|
||||
// Refused, changing nothing, where icons on the GPU cannot take it
|
||||
|
||||
@@ -2294,7 +2294,7 @@ test('points show only within their display range', () => {
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('the fire perimeters layer draws holed ground fills and draped fire lines on a viewer of its own', async () => {
|
||||
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
|
||||
const { createFirePerimetersLayer } =
|
||||
await import('../../layers/perimeters/index.js');
|
||||
const scene = fakeScene();
|
||||
@@ -2313,9 +2313,19 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
];
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: {
|
||||
getSnapshot: async () => [
|
||||
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
|
||||
],
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
revision: 'r',
|
||||
fires: [{ id: 'a', containedPct: 0, anchor: { lon: -108, lat: 35.2 } }],
|
||||
pieces: [
|
||||
{
|
||||
fireId: 'a',
|
||||
born: null,
|
||||
polygons: [[outer, hole]],
|
||||
outline: [outer, hole],
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -2336,9 +2346,9 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
assert.equal(instance.geometry._polygonHierarchy.holes.length, 1);
|
||||
const [line] = of(Cesium.GroundPolylinePrimitive);
|
||||
assert.equal(line.classificationType, Cesium.ClassificationType.BOTH);
|
||||
assert.equal(line.geometryInstances.length, 1, 'the exterior ring only');
|
||||
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
|
||||
assert.equal(line.geometryInstances[0].geometry.width, 2);
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
|
||||
layer.destroy();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
|
||||
@@ -163,6 +163,8 @@ export function createSceneFrame(viewer) {
|
||||
const holds = new Map();
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = listenerList(uncaught);
|
||||
// Told every hold taken or released.
|
||||
const holdsListeners = listenerList(uncaught);
|
||||
const pendingRenders = new Set();
|
||||
const gone = () => disposed || scene.isDestroyed?.();
|
||||
const sceneTime = (time) =>
|
||||
@@ -250,6 +252,7 @@ export function createSceneFrame(viewer) {
|
||||
holds.set(reason, (holds.get(reason) ?? 0) + 1);
|
||||
if (!gone()) scene.requestRender();
|
||||
if (first) heldListeners.fire(true);
|
||||
holdsListeners.fire();
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
@@ -260,9 +263,11 @@ export function createSceneFrame(viewer) {
|
||||
// What changed in the last held frame still gets drawn.
|
||||
if (!gone()) scene.requestRender();
|
||||
if (holds.size === 0) heldListeners.fire(false);
|
||||
holdsListeners.fire();
|
||||
};
|
||||
},
|
||||
onHeldChange: (cb) => heldListeners.on(cb),
|
||||
onHoldsChange: (cb) => holdsListeners.on(cb),
|
||||
mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'),
|
||||
diagnostics: () => ({
|
||||
mode: port.mode(),
|
||||
@@ -331,6 +336,7 @@ export function createSceneFrame(viewer) {
|
||||
for (const off of removers.splice(0)) off();
|
||||
for (const list of Object.values(listeners)) list.clear();
|
||||
heldListeners.clear();
|
||||
holdsListeners.clear();
|
||||
holds.clear();
|
||||
// Waits settle rather than stay attached to a scene gone quiet.
|
||||
for (const done of [...pendingRenders]) done();
|
||||
|
||||
@@ -23,7 +23,6 @@ import { createCesiumImagery } from './imagery.js';
|
||||
import { attributionText } from './vectorBase.js';
|
||||
import { loadVectorStyle } from '../vectorBase/index.js';
|
||||
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
|
||||
import { tileFetchResource, trackTileRequests } from './terrainTiles.js';
|
||||
|
||||
// The base marks live outside the adapter, so code that is not Cesium's can
|
||||
// mark a base; they are re-exported here for the code that still is.
|
||||
@@ -69,26 +68,15 @@ async function terrainProvider(spec, { worldDataToken }) {
|
||||
);
|
||||
},
|
||||
});
|
||||
const options = {
|
||||
const resource = new Cesium.Resource({
|
||||
url: spec.url,
|
||||
retryCallback: policy.retryCallback,
|
||||
retryAttempts: policy.retryAttempts,
|
||||
};
|
||||
if (spec.fetchTile !== undefined && typeof spec.fetchTile !== 'function')
|
||||
throw new TypeError('Quantized-mesh terrain fetchTile is a function');
|
||||
// With `fetchTile`, Cesium still reads `layer.json` at the url; each
|
||||
// tile's bytes come from `fetchTile`.
|
||||
const tiles = new WeakMap();
|
||||
const resource = spec.fetchTile
|
||||
? tileFetchResource(options, spec.fetchTile, (request) =>
|
||||
request ? tiles.get(request) : undefined,
|
||||
)
|
||||
: new Cesium.Resource(options);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
});
|
||||
return Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestVertexNormals: spec.requestVertexNormals ?? false,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return spec.fetchTile ? trackTileRequests(provider, tiles) : provider;
|
||||
}
|
||||
throw new TypeError(`Unknown terrain kind: ${spec.kind}`);
|
||||
}
|
||||
|
||||
@@ -491,38 +491,6 @@ test('terrain: quantized mesh at its url, asked again when its host is busy', as
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain: quantized mesh tiles through fetchTile', async (t) => {
|
||||
const { scene, port } = setup();
|
||||
const made = new Cesium.EllipsoidTerrainProvider();
|
||||
const own = made.requestTileGeometry;
|
||||
const asked = [];
|
||||
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async (...args) => {
|
||||
asked.push(args);
|
||||
return made;
|
||||
});
|
||||
const fetchTile = async () => ({ missing: true });
|
||||
await port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile,
|
||||
});
|
||||
assert.equal(scene.terrainProvider, made);
|
||||
const [[resource]] = asked;
|
||||
assert.equal(resource.url, 'https://terrain.example/mesh');
|
||||
assert.ok(resource.retryAttempts > 0, 'layer.json keeps its retry policy');
|
||||
assert.ok(resource instanceof Cesium.Resource);
|
||||
assert.notEqual(resource.constructor, Cesium.Resource);
|
||||
assert.notEqual(made.requestTileGeometry, own, 'tile requests are tracked');
|
||||
await assert.rejects(
|
||||
port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile: 'nope',
|
||||
}),
|
||||
/fetchTile is a function/,
|
||||
);
|
||||
});
|
||||
|
||||
test('setBase replaces the imagery and says what it drew', async () => {
|
||||
const { scene, port } = setup();
|
||||
const overlay = port.imagery.add({ kind: 'xyz', url: url('overlay') });
|
||||
|
||||
@@ -870,7 +870,13 @@ export function createGpuIcons({
|
||||
},
|
||||
/** Whether a live-clock row is still moving: frames should keep coming. */
|
||||
animating() {
|
||||
if (spec.motionClock?.kind === 'scene' || spec.show === false)
|
||||
// A set whose owner asks for its frames (`frames: 'owner'`) is not
|
||||
// kept drawing by its moving rows.
|
||||
if (
|
||||
spec.motionClock?.kind === 'scene' ||
|
||||
spec.motionClock?.frames === 'owner' ||
|
||||
spec.show === false
|
||||
)
|
||||
return false;
|
||||
return set.count > 0 && clockMs() < movingUntil;
|
||||
},
|
||||
|
||||
@@ -221,6 +221,40 @@ test('rows moving on a live clock keep frames coming until their segments end',
|
||||
assert.equal(scene.renders, onScene);
|
||||
});
|
||||
|
||||
test('a live set whose owner asks for its frames asks for none itself', () => {
|
||||
const { scene, part, draw } = drawOver();
|
||||
const set = draw.icons({
|
||||
id: 'gpu:owned',
|
||||
motionClock: { kind: 'live', delayMs: 2000, frames: 'owner' },
|
||||
});
|
||||
const now = Date.now();
|
||||
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
|
||||
set.set([
|
||||
icon('a', {
|
||||
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
|
||||
}),
|
||||
]);
|
||||
const moving = scene.renders;
|
||||
part.afterRender();
|
||||
assert.equal(scene.renders, moving, 'moving rows ask for no frame');
|
||||
set.setOptions({
|
||||
motionClock: { kind: 'live', delayMs: 3000, frames: 'owner' },
|
||||
});
|
||||
assert.equal(scene.renders, moving, 'a new delay asks for no frame');
|
||||
// A row restyled in place, as the owner does when a frame begins (a
|
||||
// helicopter's rotor), asks for none either: that frame draws it.
|
||||
set.upsert([
|
||||
icon('a', {
|
||||
scale: 2,
|
||||
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
|
||||
}),
|
||||
]);
|
||||
assert.equal(scene.renders, moving, 'a write in place asks for no frame');
|
||||
set.setOptions({ motionClock: { kind: 'live', delayMs: 4000 } });
|
||||
part.afterRender();
|
||||
assert.ok(scene.renders > moving, 'back to the set: frames again');
|
||||
});
|
||||
|
||||
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
|
||||
const { scene, part, draw } = drawOver();
|
||||
// An item's own `recede` is not the contract's: it changes nothing.
|
||||
|
||||
@@ -158,6 +158,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'renderer.whenSettled',
|
||||
'renderer.resize',
|
||||
'frame.onHeldChange',
|
||||
'frame.onHoldsChange',
|
||||
'frame.setTargetFps',
|
||||
'globe.setTerrain',
|
||||
'globe.setPhotoreal',
|
||||
|
||||
@@ -96,6 +96,8 @@ export function cesiumCapabilities(scene, only) {
|
||||
// Cesium's AUTODETECT tracking frame (`follow.js`).
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
// Every hold and release is told (`onHoldsChange`).
|
||||
'holdChanges',
|
||||
// The zoom-out guard reads the scene's own controller and frame events.
|
||||
...(scene?.screenSpaceCameraController && scene?.preRender
|
||||
? ['keepEarthFramed']
|
||||
@@ -302,7 +304,10 @@ export function createCesiumPorts(
|
||||
const holds = new Map();
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = listenerList(report);
|
||||
// Told every hold taken or released.
|
||||
const holdsListeners = listenerList(report);
|
||||
function applyHolds() {
|
||||
holdsListeners.fire();
|
||||
const continuous = holds.size > 0;
|
||||
if (scene.requestRenderMode === !continuous) return;
|
||||
scene.requestRenderMode = !continuous;
|
||||
@@ -383,6 +388,9 @@ export function createCesiumPorts(
|
||||
};
|
||||
},
|
||||
onHeldChange: (cb) => heldListeners.on(cb),
|
||||
...(capabilities.has('holdChanges')
|
||||
? { onHoldsChange: (cb) => holdsListeners.on(cb) }
|
||||
: {}),
|
||||
/** Cesium can idle, so it draws on demand. */
|
||||
mode: () => 'demand',
|
||||
diagnostics: () => ({
|
||||
@@ -862,6 +870,7 @@ export function createCesiumPorts(
|
||||
for (const list of Object.values(rendererListeners)) list.clear();
|
||||
for (const list of Object.values(frameListeners)) list.clear();
|
||||
heldListeners.clear();
|
||||
holdsListeners.clear();
|
||||
drawPart.dispose();
|
||||
cameraPart.dispose();
|
||||
creditsPart.dispose();
|
||||
|
||||
@@ -15,6 +15,7 @@ test('capabilities follow what the scene supports', () => {
|
||||
'pointVisibility',
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
'holdChanges',
|
||||
'columns',
|
||||
'motionSegments',
|
||||
'courseGlide',
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* @module render/cesium/terrainTiles
|
||||
* @description Quantized-mesh terrain tiles fetched through a terrain
|
||||
* spec's `fetchTile`, the way imagery layers fetch theirs.
|
||||
*
|
||||
* Cesium still reads `layer.json` itself, decides which tiles a frame needs,
|
||||
* schedules and cancels their requests and decodes the meshes; only the
|
||||
* fetch of each tile's bytes goes through `fetchTile`. Every resource
|
||||
* Cesium derives from the terrain's resource (its `layer.json`, each tile)
|
||||
* is a {@link tileFetchResource}, so a tile request reaches `fetchTile`
|
||||
* with the tile's URL as Cesium resolved it.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Delay before a deferred terrain tile is asked for again. */
|
||||
export const TERRAIN_RETRY_DELAY_MS = 250;
|
||||
|
||||
/** A tile `fetchTile` says is not there; Cesium draws the parent's instead. */
|
||||
export class MissingTerrainTile extends Error {
|
||||
constructor() {
|
||||
super('Terrain tile is missing');
|
||||
this.name = 'MissingTerrainTile';
|
||||
}
|
||||
}
|
||||
|
||||
const wait = (ms, signal) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(done, ms);
|
||||
function done() {
|
||||
signal.removeEventListener('abort', aborted);
|
||||
resolve();
|
||||
}
|
||||
function aborted() {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason);
|
||||
}
|
||||
signal.addEventListener('abort', aborted, { once: true });
|
||||
});
|
||||
|
||||
/** Whether a resource's template values name one tile. */
|
||||
const isTile = (values) =>
|
||||
Number.isInteger(values?.x) &&
|
||||
Number.isInteger(values?.y) &&
|
||||
Number.isInteger(values?.z);
|
||||
|
||||
/**
|
||||
* A Cesium `Resource` whose tile fetches go through `fetchTile`.
|
||||
*
|
||||
* `tileOf` gives the tile, in the terrain's own tiling scheme (rows from
|
||||
* the north, as `requestTileGeometry` counts them), that a Cesium request
|
||||
* is for; without one it is read from the resolved template values.
|
||||
* @param {object} options Cesium `Resource` options.
|
||||
* @param {(request: {tile: import('../contract/globe').TileRequest,
|
||||
* url: string, signal: AbortSignal})
|
||||
* => Promise<import('../contract/globe').TileFetch>} fetchTile
|
||||
* @param {(request: object|undefined) => import('../contract/globe').TileRequest|undefined} tileOf
|
||||
* @param {{retryDelayMs?: number}} [timing]
|
||||
* @returns {object} A Cesium `Resource`.
|
||||
*/
|
||||
export function tileFetchResource(options, fetchTile, tileOf, timing = {}) {
|
||||
const retryDelayMs = timing.retryDelayMs ?? TERRAIN_RETRY_DELAY_MS;
|
||||
|
||||
class TileFetchResource extends Cesium.Resource {
|
||||
/**
|
||||
* Clones stay of this kind, so derived tile resources keep the hook.
|
||||
* `clone(result)` copies every field onto `result`, its URL included.
|
||||
*/
|
||||
clone(result) {
|
||||
return super.clone(
|
||||
result ?? new TileFetchResource({ url: this.url, parseUrl: false }),
|
||||
);
|
||||
}
|
||||
|
||||
fetchArrayBuffer() {
|
||||
const values = this.templateValues;
|
||||
if (!isTile(values)) return super.fetchArrayBuffer();
|
||||
const request = this.request;
|
||||
const url = this.url;
|
||||
const tile = tileOf(request) ?? {
|
||||
x: values.x,
|
||||
y: values.y,
|
||||
level: values.z,
|
||||
};
|
||||
if (
|
||||
request.state === Cesium.RequestState.ISSUED ||
|
||||
request.state === Cesium.RequestState.ACTIVE
|
||||
)
|
||||
throw new Cesium.RuntimeError('The Resource is already being fetched.');
|
||||
const controller = new AbortController();
|
||||
request.url = url;
|
||||
request.state = Cesium.RequestState.UNISSUED;
|
||||
request.deferred = undefined;
|
||||
// Cesium cancels a request whose tile is no longer wanted.
|
||||
request.cancelFunction = () => controller.abort();
|
||||
request.requestFunction = async () => {
|
||||
for (;;) {
|
||||
const answer = await fetchTile({
|
||||
tile: { ...tile },
|
||||
url,
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.signal.throwIfAborted();
|
||||
if (answer?.defer) {
|
||||
await wait(retryDelayMs, controller.signal);
|
||||
continue;
|
||||
}
|
||||
if (!answer || answer.missing) throw new MissingTerrainTile();
|
||||
return answer.bytes;
|
||||
}
|
||||
};
|
||||
const promise = Cesium.RequestScheduler.request(request);
|
||||
if (!promise) return undefined;
|
||||
return promise.finally(() => {
|
||||
request.cancelFunction = undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new TileFetchResource(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* A terrain provider whose tile requests tell `tileFetchResource` which
|
||||
* tile each is for. Requests Cesium makes without a `Request` are given one.
|
||||
* @param {object} provider Cesium `CesiumTerrainProvider`.
|
||||
* @param {WeakMap<object, import('../contract/globe').TileRequest>} tiles
|
||||
* @returns {object} The same provider.
|
||||
*/
|
||||
export function trackTileRequests(provider, tiles) {
|
||||
const own = provider.requestTileGeometry.bind(provider);
|
||||
provider.requestTileGeometry = (x, y, level, request) => {
|
||||
const asked = request ?? new Cesium.Request({ throttle: false });
|
||||
tiles.set(asked, { x, y, level });
|
||||
return own(x, y, level, asked);
|
||||
};
|
||||
return provider;
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
MissingTerrainTile,
|
||||
tileFetchResource,
|
||||
trackTileRequests,
|
||||
} from './terrainTiles.js';
|
||||
|
||||
const ROOT = 'https://terrain.invalid/mesh/';
|
||||
const LAYER = JSON.stringify({
|
||||
tilejson: '2.1.0',
|
||||
format: 'quantized-mesh-1.0',
|
||||
version: '1.0.0',
|
||||
scheme: 'tms',
|
||||
tiles: ['{z}/{x}/{y}.terrain?v={version}'],
|
||||
projection: 'EPSG:4326',
|
||||
bounds: [-180, -90, 180, 90],
|
||||
minzoom: 0,
|
||||
maxzoom: 2,
|
||||
available: [
|
||||
[{ startX: 0, startY: 0, endX: 1, endY: 0 }],
|
||||
[{ startX: 0, startY: 0, endX: 3, endY: 1 }],
|
||||
[{ startX: 0, startY: 0, endX: 7, endY: 3 }],
|
||||
],
|
||||
});
|
||||
|
||||
/** One triangle over the tile: the smallest mesh Cesium decodes. */
|
||||
function meshBytes() {
|
||||
const view = new DataView(new ArrayBuffer(160));
|
||||
let at = 88; // centre, heights, bounding sphere, horizon point: all zero
|
||||
view.setFloat64(24 + 8 + 24, 1, true); // bounding sphere radius
|
||||
const u32 = (v) => (view.setUint32(at, v, true), (at += 4));
|
||||
const u16 = (v) => (view.setUint16(at, v, true), (at += 2));
|
||||
u32(3);
|
||||
// Zig-zag deltas of u (0, 32767, 0), v (0, 0, 32767) and h (0, 0, 0).
|
||||
[0, 65534, 65533, 0, 0, 65534, 0, 0, 0].forEach(u16);
|
||||
u32(1);
|
||||
[0, 0, 0].forEach(u16); // high-water-mark indices 0, 1, 2
|
||||
(u32(2), u16(0), u16(2)); // west
|
||||
(u32(2), u16(0), u16(1)); // south
|
||||
(u32(1), u16(1)); // east
|
||||
(u32(1), u16(2)); // north
|
||||
return view.buffer.slice(0, at);
|
||||
}
|
||||
|
||||
/** Answers `layer.json` the way a host would; tiles never reach the network. */
|
||||
function serveLayer(t) {
|
||||
const fetched = [];
|
||||
t.mock.method(
|
||||
Cesium.Resource._Implementations,
|
||||
'loadWithXhr',
|
||||
(url, responseType, method, data, headers, deferred) => {
|
||||
fetched.push(url);
|
||||
if (url.startsWith(`${ROOT}layer.json`)) deferred.resolve(LAYER);
|
||||
else deferred.reject(new Error(`unexpected fetch ${url}`));
|
||||
},
|
||||
);
|
||||
return fetched;
|
||||
}
|
||||
|
||||
async function terrain(fetchTile, timing) {
|
||||
const tiles = new WeakMap();
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
fetchTile,
|
||||
(request) => (request ? tiles.get(request) : undefined),
|
||||
timing,
|
||||
);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return trackTileRequests(provider, tiles);
|
||||
}
|
||||
|
||||
test('terrain fetchTile: tiles come from fetchTile, layer.json from the url', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
const data = await provider.requestTileGeometry(
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.deepEqual(
|
||||
fetched.map((u) => new URL(u).pathname),
|
||||
['/mesh/layer.json'],
|
||||
);
|
||||
assert.equal(asked.length, 1);
|
||||
// Rows from the north for the tile; the URL is Cesium's, rows from the
|
||||
// south as the layer's tms scheme counts them.
|
||||
assert.deepEqual(asked[0].tile, { x: 1, y: 0, level: 1 });
|
||||
assert.equal(asked[0].url, `${ROOT}1/1/1.terrain?v=1.0.0`);
|
||||
assert.ok(asked[0].signal instanceof AbortSignal);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a request Cesium makes without a Request still names its tile', async (t) => {
|
||||
serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request.tile);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
await provider.requestTileGeometry(3, 1, 2);
|
||||
assert.deepEqual(asked, [{ x: 3, y: 1, level: 2 }]);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a missing tile fails, so the parent is drawn there', async (t) => {
|
||||
serveLayer(t);
|
||||
const provider = await terrain(async () => ({ missing: true }));
|
||||
await assert.rejects(
|
||||
provider.requestTileGeometry(0, 0, 0, new Cesium.Request()),
|
||||
MissingTerrainTile,
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a deferred tile is asked for again', async (t) => {
|
||||
serveLayer(t);
|
||||
let calls = 0;
|
||||
const provider = await terrain(
|
||||
async () => (++calls < 3 ? { defer: true } : { bytes: meshBytes() }),
|
||||
{ retryDelayMs: 1 },
|
||||
);
|
||||
const data = await provider.requestTileGeometry(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: cancelling the request aborts the fetch', async (t) => {
|
||||
serveLayer(t);
|
||||
let signal;
|
||||
const provider = await terrain(
|
||||
(request) =>
|
||||
new Promise((resolve, reject) => {
|
||||
signal = request.signal;
|
||||
signal.addEventListener('abort', () => reject(signal.reason));
|
||||
}),
|
||||
);
|
||||
const request = new Cesium.Request();
|
||||
const pending = provider.requestTileGeometry(0, 0, 0, request);
|
||||
pending.catch(() => {});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(signal.aborted, false);
|
||||
request.cancel();
|
||||
// Cesium's scheduler cancels on its next update.
|
||||
Cesium.RequestScheduler.update();
|
||||
assert.equal(signal.aborted, true);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: resources that are not tiles fetch as before', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
async () => assert.fail('not a tile'),
|
||||
() => undefined,
|
||||
);
|
||||
const derived = resource.getDerivedResource({ url: 'layer.json' });
|
||||
assert.equal(derived.constructor, resource.constructor);
|
||||
assert.equal(await derived.fetchArrayBuffer(), LAYER);
|
||||
assert.equal(fetched.length, 1);
|
||||
});
|
||||
@@ -6618,6 +6618,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
|
||||
deepEqual(heard, [true, false], 'nothing once off');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'frame.onHoldsChange',
|
||||
'onHoldsChange is told every hold and release, whoever holds, and nothing once off',
|
||||
(h, r) => {
|
||||
let heard = 0;
|
||||
const off = r.frame.onHoldsChange(() => (heard += 1));
|
||||
try {
|
||||
const one = r.frame.holdContinuous('conformance:one');
|
||||
const two = r.frame.holdContinuous('conformance:two');
|
||||
one();
|
||||
two();
|
||||
equal(heard, 4, 'two holds and two releases');
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
r.frame.holdContinuous('conformance:after')();
|
||||
equal(heard, 4, 'nothing once off');
|
||||
},
|
||||
{ capability: 'holdChanges' },
|
||||
),
|
||||
check(
|
||||
'frame.setTargetFps',
|
||||
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
|
||||
|
||||
Vendored
+3
-1
@@ -228,4 +228,6 @@ export type Capability =
|
||||
/** Reading the frame the eye is placed in (`camera.followFrame`). */
|
||||
| 'followFrame'
|
||||
/** A `threshold` per `changed` listener (`camera.on`). */
|
||||
| 'cameraChangeThreshold';
|
||||
| 'cameraChangeThreshold'
|
||||
/** Hearing every hold taken or released (`frame.onHoldsChange`). */
|
||||
| 'holdChanges';
|
||||
Vendored
+14
-1
@@ -133,7 +133,20 @@ export interface SetSpec {
|
||||
* `live` (the default) is wall time minus `delayMs`, as a live feed is
|
||||
* drawn a little behind real time; `scene` is the frame port's scene time.
|
||||
*/
|
||||
motionClock?: { kind: 'live'; delayMs?: number } | { kind: 'scene' };
|
||||
motionClock?:
|
||||
| {
|
||||
kind: 'live';
|
||||
delayMs?: number;
|
||||
/**
|
||||
* Who asks for the frames moving rows need: the set itself, one after
|
||||
* another while a row moves (the default), or its `owner`, at the
|
||||
* rate the rows move on screen. An owner's set may also draw a
|
||||
* change written in place on the owner's next frame without asking
|
||||
* for one (the owner writes as a frame begins).
|
||||
*/
|
||||
frames?: 'set' | 'owner';
|
||||
}
|
||||
| { kind: 'scene' };
|
||||
show?: boolean;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+6
@@ -78,6 +78,12 @@ export interface FramePort {
|
||||
* it) and stop (its last released): `true` held, `false` not.
|
||||
*/
|
||||
onHeldChange(cb: (held: boolean) => void): Off;
|
||||
/**
|
||||
* `holdChanges`: hear every hold taken or released, whoever holds
|
||||
* (diagnostics' `holds` has changed), where `onHeldChange` hears only the
|
||||
* first hold and the last release.
|
||||
*/
|
||||
onHoldsChange?(cb: () => void): Off;
|
||||
mode(): 'demand' | 'continuous';
|
||||
diagnostics(): FrameDiagnostics;
|
||||
/** Stop ticking while the page is hidden; resume on `false`. */
|
||||
|
||||
Vendored
+1
-18
@@ -40,24 +40,7 @@ export type TerrainSpec = (
|
||||
* Quantized-mesh terrain (Cesium's tile format) in the folder `url`,
|
||||
* holding `layer.json` and its tiles; heights above the ellipsoid.
|
||||
*/
|
||||
| {
|
||||
kind: 'quantizedMesh';
|
||||
url: string;
|
||||
requestVertexNormals?: boolean;
|
||||
/**
|
||||
* Fetches a tile in place of the renderer, as imagery's `fetchTile`
|
||||
* does, with the tile's URL as the renderer resolved it (`layer.json`
|
||||
* is still read from `url`). `tile` is in the terrain's tiling scheme,
|
||||
* rows counted from the north; `bytes` are the tile uncompressed.
|
||||
* `missing` draws the parent tile's terrain there; `defer` asks
|
||||
* again shortly. `signal` aborts when the tile is no longer wanted.
|
||||
*/
|
||||
fetchTile?: (request: {
|
||||
tile: TileRequest;
|
||||
url: string;
|
||||
signal: AbortSignal;
|
||||
}) => Promise<TileFetch>;
|
||||
}
|
||||
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
|
||||
) & {
|
||||
/** Vertical exaggeration of the drawn terrain; default 1. */
|
||||
exaggeration?: number;
|
||||
|
||||
@@ -55,6 +55,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'occlusionTest',
|
||||
'pointVisibility',
|
||||
'keepEarthFramed',
|
||||
'holdChanges',
|
||||
]);
|
||||
|
||||
/** @type {readonly import('./frame').FrameStep[]} */
|
||||
@@ -120,8 +121,8 @@ export const PORTS = deepFreeze({
|
||||
'destroy',
|
||||
),
|
||||
),
|
||||
frame: Object.fromEntries(
|
||||
required(
|
||||
frame: Object.fromEntries([
|
||||
...required(
|
||||
'on',
|
||||
'requestRender',
|
||||
'holdContinuous',
|
||||
@@ -135,7 +136,8 @@ export const PORTS = deepFreeze({
|
||||
'setTime',
|
||||
'time',
|
||||
),
|
||||
),
|
||||
['onHoldsChange', 'holdChanges'],
|
||||
]),
|
||||
globe: Object.fromEntries([
|
||||
...required(
|
||||
'setBase',
|
||||
|
||||
@@ -190,6 +190,16 @@ export function createStubRenderer(options = {}) {
|
||||
let holdSeq = 0;
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = new Set();
|
||||
const holdsListeners = new Set();
|
||||
function tellHolds() {
|
||||
for (const entry of [...holdsListeners])
|
||||
if (holdsListeners.has(entry))
|
||||
try {
|
||||
entry.cb();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
function tellHeld(held) {
|
||||
for (const entry of [...heldListeners])
|
||||
try {
|
||||
@@ -359,9 +369,11 @@ export function createStubRenderer(options = {}) {
|
||||
const key = ++holdSeq;
|
||||
continuous.set(key, String(reason));
|
||||
if (continuous.size === 1) tellHeld(true);
|
||||
tellHolds();
|
||||
return () => {
|
||||
if (!continuous.delete(key)) return;
|
||||
if (continuous.size === 0) tellHeld(false);
|
||||
tellHolds();
|
||||
};
|
||||
},
|
||||
onHeldChange(cb) {
|
||||
@@ -369,6 +381,15 @@ export function createStubRenderer(options = {}) {
|
||||
heldListeners.add(entry);
|
||||
return () => heldListeners.delete(entry);
|
||||
},
|
||||
...(capabilities.has('holdChanges')
|
||||
? {
|
||||
onHoldsChange(cb) {
|
||||
const entry = { cb };
|
||||
holdsListeners.add(entry);
|
||||
return () => holdsListeners.delete(entry);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
mode: () => 'demand',
|
||||
diagnostics: () => ({
|
||||
mode: 'demand',
|
||||
|
||||
+140
-7
@@ -29,8 +29,13 @@
|
||||
* short stable strings ('flights', 'traffic', 'style-anim', …) so the
|
||||
* diagnostics read like a story.
|
||||
*
|
||||
* Frame rate: while the loop is held it draws at the display's own refresh
|
||||
* rate; while nothing holds it, the governor caps it at IDLE_FRAME_RATE,
|
||||
* Frame rate: a hold may say the most frames a second it needs
|
||||
* (`holdContinuousRender(owner, { maxFps })`); while held the loop draws at
|
||||
* the highest rate its holders asked for, and at the display's own refresh
|
||||
* rate as soon as one holder asked for none. Moving layers hold through
|
||||
* their pace (renderPace.js) at 15 to 30; a followed target counts as
|
||||
* FOLLOW_FRAME_RATE unless a pointer or the wheel is steering the camera.
|
||||
* While nothing holds it, the governor caps it at IDLE_FRAME_RATE,
|
||||
* because Cesium still ticks the clock, data sources and every
|
||||
* pre/post-update listener once per animation frame even when it skips the
|
||||
* draw. The frame port says when its first hold is taken and its last
|
||||
@@ -42,11 +47,19 @@
|
||||
* The governor is O(1) passive: no per-frame work of its own, ever.
|
||||
*/
|
||||
|
||||
import { PACE_MAX_HZ } from './renderPace.js';
|
||||
|
||||
/** @typedef {import('./render/contract/frame').FramePort} FramePort */
|
||||
/** @typedef {import('./render/contract/camera').CameraPort} CameraPort */
|
||||
|
||||
/** Frames a second the loop ticks while nothing moves. */
|
||||
export const IDLE_FRAME_RATE = 60;
|
||||
/**
|
||||
* Frames a second for a camera that only rides along with what it follows:
|
||||
* the most a moving layer draws (renderPace.js), leaving room in the frame
|
||||
* for everything else. The person steering it still gets the display's rate.
|
||||
*/
|
||||
export const FOLLOW_FRAME_RATE = PACE_MAX_HZ;
|
||||
|
||||
let _frame = null;
|
||||
/** Owners holding, each with the frame port's release once installed. */
|
||||
@@ -56,11 +69,108 @@ let _removeCameraListeners = null;
|
||||
/** Stops hearing the installed port's holds. */
|
||||
let _offHeldChange = null;
|
||||
|
||||
/** The loop's rate: the display's while held, IDLE_FRAME_RATE while not. */
|
||||
function applyRate(held) {
|
||||
_frame?.setTargetFps(held ? 0 : IDLE_FRAME_RATE);
|
||||
/** The most frames a second each owner said its hold needs; none: the display's. */
|
||||
const _rateOf = new Map();
|
||||
/**
|
||||
* Whether a pointer is down, or the wheel turned in the last moment: the
|
||||
* person is steering the camera. Kept apart, so the wheel's moment ending
|
||||
* never ends a drag.
|
||||
*/
|
||||
const _pointersDown = new Set();
|
||||
let _wheeling = false;
|
||||
let _steeringTimer = null;
|
||||
const steering = () => _pointersDown.size > 0 || _wheeling;
|
||||
|
||||
/**
|
||||
* The camera's own moves (a drag, a zoom, a flight) draw at the display's
|
||||
* rate. A camera carried by what it follows needs only the follow rate,
|
||||
* unless the person is steering it at the same time.
|
||||
*/
|
||||
function cameraRate() {
|
||||
return !steering() && _holds.has('tracked-entity') ? FOLLOW_FRAME_RATE : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rate while held: the highest any holder asked for, and the display's
|
||||
* (0) as soon as one holder asked for none. The renderer's own holds
|
||||
* (animated styles) ask for none; a frame port with `onHoldsChange` says
|
||||
* when one is taken or let go, and one without it is heard at the loop's
|
||||
* first hold and last release only.
|
||||
*/
|
||||
function heldRate() {
|
||||
let rate = 0;
|
||||
for (const owner of _frame.diagnostics().holds) {
|
||||
const asked = owner === 'camera' ? cameraRate() : _rateOf.get(owner);
|
||||
if (!asked) return 0;
|
||||
if (asked > rate) rate = asked;
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
/** The loop's rate: the holders' while held, IDLE_FRAME_RATE while not. */
|
||||
function applyRate(held = (_frame?.diagnostics().holds.length ?? 0) > 0) {
|
||||
_frame?.setTargetFps(held ? heldRate() : IDLE_FRAME_RATE);
|
||||
}
|
||||
|
||||
/** Change the steering inputs, and the rate if steering changed. */
|
||||
function changeSteering(change) {
|
||||
const was = steering();
|
||||
change();
|
||||
if (steering() !== was) applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pointer and wheel input on the page: the person is steering the camera.
|
||||
* A release the page never hears (the pointer let go over another window)
|
||||
* ends when the page loses focus or is hidden.
|
||||
*/
|
||||
function watchSteering(target, { schedule, unschedule }) {
|
||||
if (typeof target?.addEventListener !== 'function') return null;
|
||||
// Every pointer down counts (a pinch is two), until it is let go.
|
||||
const down = (event) =>
|
||||
changeSteering(() => _pointersDown.add(event?.pointerId ?? 0));
|
||||
const up = (event) =>
|
||||
changeSteering(() => _pointersDown.delete(event?.pointerId ?? 0));
|
||||
const allUp = () => changeSteering(() => _pointersDown.clear());
|
||||
// The window's own blur, not an element's inside the page.
|
||||
const blur = (event) => {
|
||||
if (!event || event.target === target) allUp();
|
||||
};
|
||||
const wheel = () => {
|
||||
changeSteering(() => (_wheeling = true));
|
||||
if (_steeringTimer !== null) unschedule(_steeringTimer);
|
||||
_steeringTimer = schedule(() => {
|
||||
_steeringTimer = null;
|
||||
changeSteering(() => (_wheeling = false));
|
||||
}, 300);
|
||||
};
|
||||
const hidden = () => {
|
||||
if (globalThis.document?.visibilityState === 'hidden') allUp();
|
||||
};
|
||||
const options = { passive: true, capture: true };
|
||||
target.addEventListener('pointerdown', down, options);
|
||||
target.addEventListener('pointerup', up, options);
|
||||
target.addEventListener('pointercancel', up, options);
|
||||
target.addEventListener('blur', blur, options);
|
||||
target.addEventListener('wheel', wheel, options);
|
||||
const doc = globalThis.document;
|
||||
doc?.addEventListener?.('visibilitychange', hidden);
|
||||
return () => {
|
||||
target.removeEventListener('pointerdown', down, options);
|
||||
target.removeEventListener('pointerup', up, options);
|
||||
target.removeEventListener('pointercancel', up, options);
|
||||
target.removeEventListener('blur', blur, options);
|
||||
target.removeEventListener('wheel', wheel, options);
|
||||
doc?.removeEventListener?.('visibilitychange', hidden);
|
||||
if (_steeringTimer !== null) unschedule(_steeringTimer);
|
||||
_steeringTimer = null;
|
||||
_pointersDown.clear();
|
||||
_wheeling = false;
|
||||
};
|
||||
}
|
||||
/** Stops hearing the pointer and the wheel. */
|
||||
let _removeSteeringListeners = null;
|
||||
|
||||
/** Debug trail of the most recent one-shot render requests (idle mode only). */
|
||||
const _recentRequests = [];
|
||||
const RECENT_REQUEST_CAP = 16;
|
||||
@@ -185,11 +295,21 @@ export function installRenderGovernor(
|
||||
if (_frame) releaseFrameHolds();
|
||||
_offHeldChange?.();
|
||||
_frame = frame;
|
||||
_offHeldChange = frame.onHeldChange(applyRate);
|
||||
const offHeld = frame.onHeldChange(applyRate);
|
||||
const offHolds = frame.onHoldsChange?.(() => applyRate()) ?? null;
|
||||
_offHeldChange = () => {
|
||||
offHeld();
|
||||
offHolds?.();
|
||||
};
|
||||
applyRate(frame.diagnostics().holds.length > 0);
|
||||
for (const ownerId of _holds.keys()) holdOnFrame(ownerId);
|
||||
}
|
||||
_removeCameraListeners = watchCameraMotion(camera, { schedule, unschedule });
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = watchSteering(globalThis.window, {
|
||||
schedule,
|
||||
unschedule,
|
||||
});
|
||||
}
|
||||
|
||||
function releaseFrameHolds() {
|
||||
@@ -206,10 +326,15 @@ function releaseFrameHolds() {
|
||||
* @param {string} ownerId Short stable id, e.g. 'flights', 'traffic'.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function holdContinuousRender(ownerId) {
|
||||
export function holdContinuousRender(ownerId, { maxFps = 0 } = {}) {
|
||||
if (!ownerId) return;
|
||||
if (maxFps > 0) _rateOf.set(ownerId, maxFps);
|
||||
else _rateOf.delete(ownerId);
|
||||
if (!_holds.has(ownerId)) _holds.set(ownerId, null);
|
||||
holdOnFrame(ownerId);
|
||||
// A second holder, or a new rate, changes the rate without changing
|
||||
// whether the loop is held.
|
||||
applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,7 +348,9 @@ export function releaseContinuousRender(ownerId) {
|
||||
if (!ownerId || !_holds.has(ownerId)) return;
|
||||
const release = _holds.get(ownerId);
|
||||
_holds.delete(ownerId);
|
||||
_rateOf.delete(ownerId);
|
||||
release?.();
|
||||
applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,11 +389,14 @@ export function uninstallRenderGovernor(frame) {
|
||||
if (!_frame || _frame !== frame) return;
|
||||
_removeCameraListeners?.();
|
||||
_removeCameraListeners = null;
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = null;
|
||||
releaseFrameHolds();
|
||||
_offHeldChange?.();
|
||||
_offHeldChange = null;
|
||||
_frame = null;
|
||||
_holds.clear();
|
||||
_rateOf.clear();
|
||||
_recentRequests.length = 0;
|
||||
}
|
||||
|
||||
@@ -274,9 +404,12 @@ export function uninstallRenderGovernor(frame) {
|
||||
export function _resetRenderGovernorForTest() {
|
||||
_removeCameraListeners?.();
|
||||
_removeCameraListeners = null;
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = null;
|
||||
_offHeldChange?.();
|
||||
_offHeldChange = null;
|
||||
_frame = null;
|
||||
_holds.clear();
|
||||
_rateOf.clear();
|
||||
_recentRequests.length = 0;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
_resetRenderGovernorForTest,
|
||||
uninstallRenderGovernor,
|
||||
IDLE_FRAME_RATE,
|
||||
FOLLOW_FRAME_RATE,
|
||||
} from './renderGovernor.js';
|
||||
import { framePortFor } from './testSupport/fakeFramePort.mjs';
|
||||
|
||||
@@ -293,3 +294,126 @@ test('installing again drops a camera hold the old listeners can no longer relea
|
||||
assert.equal(scene.requestRenderMode, true);
|
||||
assert.equal(timers.pending, 0);
|
||||
});
|
||||
|
||||
test('a hold may cap the rate: the highest asked wins, an uncapped hold is the display rate', () => {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const frame = framePortFor(viewer.scene);
|
||||
installRenderGovernor(frame);
|
||||
holdContinuousRender('satellites', { maxFps: 15 });
|
||||
assert.equal(scene.targetFps, 15);
|
||||
holdContinuousRender('flights', { maxFps: 30 });
|
||||
assert.equal(scene.targetFps, 30, 'the highest asked');
|
||||
holdContinuousRender('flights', { maxFps: 20 });
|
||||
assert.equal(scene.targetFps, 20, 'a holder lowering its rate');
|
||||
holdContinuousRender('traffic');
|
||||
assert.equal(scene.targetFps, 0, 'a hold without a rate: the display rate');
|
||||
releaseContinuousRender('traffic');
|
||||
assert.equal(scene.targetFps, 20);
|
||||
releaseContinuousRender('flights');
|
||||
assert.equal(scene.targetFps, 15);
|
||||
releaseContinuousRender('satellites');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
});
|
||||
|
||||
test('the renderer holding the loop itself asks for no rate: the display rate', () => {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const frame = framePortFor(viewer.scene);
|
||||
installRenderGovernor(frame);
|
||||
const release = frame.holdContinuous('effects:animated');
|
||||
holdContinuousRender('satellites', { maxFps: 15 });
|
||||
assert.equal(scene.targetFps, 0);
|
||||
release();
|
||||
assert.equal(scene.targetFps, 15, 'heard as soon as the renderer lets go');
|
||||
const again = frame.holdContinuous('effects:animated');
|
||||
assert.equal(scene.targetFps, 0, 'and as soon as it holds again');
|
||||
again();
|
||||
releaseContinuousRender('satellites');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
});
|
||||
|
||||
test('a camera carried by a followed target draws at the follow rate unless a pointer steers it', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const camera = makeCamera();
|
||||
installRenderGovernor(framePortFor(viewer.scene), { camera });
|
||||
camera.raise('moveStart');
|
||||
assert.equal(scene.targetFps, 0, 'a camera move: the display rate');
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'following');
|
||||
assert.equal(FOLLOW_FRAME_RATE, 30);
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
assert.equal(scene.targetFps, 0, 'steering: the display rate');
|
||||
page.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
releaseContinuousRender('tracked-entity');
|
||||
assert.equal(scene.targetFps, 0, 'the camera moving on its own');
|
||||
camera.raise('moveEnd');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
|
||||
test('steering ends when the page loses focus, and a wheel moment ending never ends a drag', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const timers = fakeTimers();
|
||||
const { viewer, scene } = makeViewer();
|
||||
installRenderGovernor(framePortFor(viewer.scene), timers);
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
holdContinuousRender('camera');
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
assert.equal(scene.targetFps, 0, 'dragging: the display rate');
|
||||
// Let go over another window: the page never hears the release.
|
||||
page.dispatchEvent(new Event('blur'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'focus lost: steering ends');
|
||||
// A wheel turn, then a drag begun before its moment ends.
|
||||
page.dispatchEvent(new Event('wheel'));
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
timers.run();
|
||||
assert.equal(scene.targetFps, 0, 'the drag goes on at the display rate');
|
||||
page.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
|
||||
test('a pinch steers until its last finger lifts; an element losing focus is not the page losing it', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const { viewer, scene } = makeViewer();
|
||||
installRenderGovernor(framePortFor(viewer.scene), fakeTimers());
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
holdContinuousRender('camera');
|
||||
const pointer = (type, pointerId) => Object.assign(new Event(type), { pointerId });
|
||||
page.dispatchEvent(pointer('pointerdown', 1));
|
||||
page.dispatchEvent(pointer('pointerdown', 2));
|
||||
page.dispatchEvent(pointer('pointerup', 1));
|
||||
assert.equal(scene.targetFps, 0, 'one finger still down');
|
||||
// The search box's blur reaches the window's capturing listener.
|
||||
const field = new EventTarget();
|
||||
field.addEventListener('blur', () => {});
|
||||
const blur = new Event('blur');
|
||||
Object.defineProperty(blur, 'target', { value: field });
|
||||
page.dispatchEvent(blur);
|
||||
assert.equal(scene.targetFps, 0, 'still steering');
|
||||
page.dispatchEvent(pointer('pointerup', 2));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Draws a moving layer as often as its marks move on screen, in place of a
|
||||
* hold on the render loop for as long as the layer is on.
|
||||
*
|
||||
* A mark should move at most PACE_STEP_PX between two draws, so a layer
|
||||
* needs `fastest on-screen speed / PACE_STEP_PX` draws a second. The pace
|
||||
* keeps that between PACE_MIN_HZ (animated marks never stall) and
|
||||
* PACE_MAX_HZ (room in the frame for everything else the scene draws).
|
||||
* Below PACE_HOLD_HZ it asks for one frame at a time on a timer, so the
|
||||
* loop stays on demand; from there it holds the loop at a rate the display
|
||||
* divides evenly (the render governor's rate per hold).
|
||||
*
|
||||
* The person steering the camera still draws at the display's rate: that is
|
||||
* the camera's hold, not a layer's (see renderGovernor.js).
|
||||
*/
|
||||
|
||||
/** The most a mark may move on screen between two draws, in pixels. */
|
||||
export const PACE_STEP_PX = 0.5;
|
||||
/** Draws a second however slowly the marks move. */
|
||||
export const PACE_MIN_HZ = 3;
|
||||
/** Draws a second however fast the marks move. */
|
||||
export const PACE_MAX_HZ = 30;
|
||||
/** From this many draws a second the pace holds the loop instead. */
|
||||
export const PACE_HOLD_HZ = 12;
|
||||
/** Below this the hold is let go again (a gap, so it does not flap; above
|
||||
* ROTOR_FPS, so a turning rotor alone draws on the timer at its own rate). */
|
||||
export const PACE_RELEASE_HZ = 11;
|
||||
/** Held rates, each dividing 60 and 120 evenly so draws come at even gaps. */
|
||||
const HELD_RATES = [15, 20, 30];
|
||||
|
||||
/** Draws a second for marks crossing the screen at `pxPerSec`. */
|
||||
export function paceHzForSpeed(pxPerSec) {
|
||||
return pxPerSec / PACE_STEP_PX;
|
||||
}
|
||||
|
||||
/** The held rate for a need of `hz` draws a second. */
|
||||
function heldRateFor(hz) {
|
||||
for (const rate of HELD_RATES) if (hz <= rate) return rate;
|
||||
return PACE_MAX_HZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.owner The hold's owner id ('flights', 'satellites').
|
||||
* @param {object} [options.render] The render governor's calls
|
||||
* (holdContinuousRender, releaseContinuousRender, governorRequestRender).
|
||||
* @param {Function} [options.setTimeout] Injectable timers for tests.
|
||||
* @param {Function} [options.clearTimeout]
|
||||
* @param {() => number} [options.now] Injectable wall clock (ms) for tests.
|
||||
*/
|
||||
export function createRenderPace({
|
||||
owner,
|
||||
render,
|
||||
setTimeout: schedule = globalThis.setTimeout,
|
||||
clearTimeout: unschedule = globalThis.clearTimeout,
|
||||
now = () => globalThis.performance?.now() ?? Date.now(),
|
||||
}) {
|
||||
const hold = render?.holdContinuousRender ?? (() => {});
|
||||
const release = render?.releaseContinuousRender ?? (() => {});
|
||||
const request = render?.governorRequestRender ?? (() => {});
|
||||
let running = false;
|
||||
let hz = PACE_MIN_HZ;
|
||||
let held = false;
|
||||
/** The rate the hold asked for, or -1 while not held. */
|
||||
let heldFps = -1;
|
||||
let timer = null;
|
||||
let timerHz = 0;
|
||||
/** Whether the timer's wait ended: the marks move on the next frame. */
|
||||
let due = false;
|
||||
/** Wall ms the marks last moved. */
|
||||
let movedMs = -Infinity;
|
||||
|
||||
function arm() {
|
||||
if (!running || held) return;
|
||||
if (timer !== null) {
|
||||
// A pending wait at a much slower rate is cut short.
|
||||
if (hz <= timerHz * 1.5) return;
|
||||
unschedule(timer);
|
||||
}
|
||||
timerHz = hz;
|
||||
timer = schedule(() => {
|
||||
timer = null;
|
||||
due = true;
|
||||
request(owner);
|
||||
arm();
|
||||
}, 1000 / hz);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the draws a second needed now (any number: it is clamped to the
|
||||
* pace's range; Infinity asks for the most). Called once a drawn frame.
|
||||
*/
|
||||
function set(needHz) {
|
||||
if (!running) return;
|
||||
const clamped = Math.min(
|
||||
PACE_MAX_HZ,
|
||||
needHz >= PACE_MIN_HZ ? needHz : PACE_MIN_HZ,
|
||||
);
|
||||
// Up at once, down gently: the fastest mark leaving the view is no
|
||||
// reason to step the next one.
|
||||
hz = clamped >= hz ? clamped : Math.max(clamped, hz * 0.9);
|
||||
const wantHold = held ? hz >= PACE_RELEASE_HZ : hz >= PACE_HOLD_HZ;
|
||||
if (wantHold) {
|
||||
const maxFps = heldRateFor(hz);
|
||||
if (!held || maxFps !== heldFps) hold(owner, { maxFps });
|
||||
heldFps = maxFps;
|
||||
if (timer !== null) unschedule(timer);
|
||||
timer = null;
|
||||
} else if (held) {
|
||||
release(owner);
|
||||
heldFps = -1;
|
||||
}
|
||||
held = wantHold;
|
||||
arm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the layer's marks should move in this frame, for a layer that
|
||||
* moves them itself (moving them asks for a frame, so a layer moving them
|
||||
* on every drawn frame keeps the loop drawing). Marks the move when true.
|
||||
*/
|
||||
function take() {
|
||||
const at = now();
|
||||
if (!running || held || due || at - movedMs >= 1000 / hz) {
|
||||
due = false;
|
||||
movedMs = at;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
// Until the first frame says what is needed.
|
||||
hz = PACE_RELEASE_HZ;
|
||||
due = true;
|
||||
movedMs = -Infinity;
|
||||
request(owner);
|
||||
arm();
|
||||
}
|
||||
|
||||
function stop() {
|
||||
running = false;
|
||||
if (timer !== null) unschedule(timer);
|
||||
timer = null;
|
||||
held = false;
|
||||
heldFps = -1;
|
||||
due = false;
|
||||
release(owner);
|
||||
}
|
||||
|
||||
return {
|
||||
set,
|
||||
take,
|
||||
start,
|
||||
stop,
|
||||
state: () => ({ running, hz, held, heldFps }),
|
||||
};
|
||||
}
|
||||
|
||||
/** cos 60°: marks further than this from the view's axis are not read. */
|
||||
const VIEW_COS = 0.5;
|
||||
|
||||
/**
|
||||
* Reads how fast the fastest mark crosses the screen, from each mark's move
|
||||
* as an angle at the eye. Use: `begin` with the camera, `add` each mark's
|
||||
* two positions (ECEF), then `pxPerSec` with the time between them.
|
||||
* The flat screen stretches an angle away from its centre by 1 / cos², so
|
||||
* that is applied too.
|
||||
*/
|
||||
export function createScreenSpeed() {
|
||||
let eye = null;
|
||||
let dir = null;
|
||||
let ex = 0;
|
||||
let ey = 0;
|
||||
let ez = 0;
|
||||
let focal = 0;
|
||||
let fastest2 = 0;
|
||||
|
||||
return {
|
||||
/**
|
||||
* @param {{position: {x,y,z}, direction: {x,y,z}, fovy: number}|null} pose
|
||||
* @param {number} heightPx The canvas's height in CSS pixels.
|
||||
* @param {{x,y,z}} [eyeMove] How far the eye itself moved between the
|
||||
* two positions: a camera riding one mark sees its neighbours nearly
|
||||
* still.
|
||||
* @returns {boolean} Whether there is a camera to read with.
|
||||
*/
|
||||
begin(pose, heightPx, eyeMove = null) {
|
||||
fastest2 = 0;
|
||||
eye = pose?.position ?? null;
|
||||
dir = pose?.direction ?? null;
|
||||
if (!eye || !dir || !(pose.fovy > 0)) {
|
||||
eye = null;
|
||||
return false;
|
||||
}
|
||||
ex = eyeMove?.x ?? 0;
|
||||
ey = eyeMove?.y ?? 0;
|
||||
ez = eyeMove?.z ?? 0;
|
||||
focal = (heightPx || 900) / 2 / Math.tan(pose.fovy / 2);
|
||||
return true;
|
||||
},
|
||||
/** One mark's move from `from` to `to` (ECEF metres). */
|
||||
add(from, to) {
|
||||
if (!eye || !from || !to) return;
|
||||
const dx = to.x - eye.x;
|
||||
const dy = to.y - eye.y;
|
||||
const dz = to.z - eye.z;
|
||||
const range2 = dx * dx + dy * dy + dz * dz;
|
||||
const along = dx * dir.x + dy * dir.y + dz * dir.z;
|
||||
if (!(along > 0) || along * along < VIEW_COS * VIEW_COS * range2) return;
|
||||
const mx = to.x - from.x - ex;
|
||||
const my = to.y - from.y - ey;
|
||||
const mz = to.z - from.z - ez;
|
||||
// The angle the move subtends, stretched by 1 / cos² off the centre.
|
||||
const turn2 =
|
||||
((mx * mx + my * my + mz * mz) * range2) /
|
||||
(along * along * along * along);
|
||||
if (turn2 > fastest2) fastest2 = turn2;
|
||||
},
|
||||
/** The fastest mark's on-screen speed, for moves `seconds` apart. */
|
||||
pxPerSec(seconds) {
|
||||
if (!eye || !(seconds > 0)) return 0;
|
||||
return (Math.sqrt(fastest2) * focal) / seconds;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
PACE_MAX_HZ,
|
||||
PACE_MIN_HZ,
|
||||
PACE_STEP_PX,
|
||||
} from './renderPace.js';
|
||||
|
||||
/** A pace with fake timers, clock and render calls. */
|
||||
function makePace() {
|
||||
const calls = [];
|
||||
const timers = new Map();
|
||||
let nextId = 1;
|
||||
let nowMs = 0;
|
||||
const pace = createRenderPace({
|
||||
owner: 'dots',
|
||||
render: {
|
||||
holdContinuousRender: (owner, options) =>
|
||||
calls.push(['hold', owner, options.maxFps]),
|
||||
releaseContinuousRender: (owner) => calls.push(['release', owner]),
|
||||
governorRequestRender: (owner) => calls.push(['request', owner]),
|
||||
},
|
||||
setTimeout(fn, ms) {
|
||||
const id = nextId++;
|
||||
timers.set(id, { fn, ms });
|
||||
return id;
|
||||
},
|
||||
clearTimeout: (id) => timers.delete(id),
|
||||
now: () => nowMs,
|
||||
});
|
||||
return {
|
||||
pace,
|
||||
calls,
|
||||
timers,
|
||||
advance(ms) {
|
||||
nowMs += ms;
|
||||
},
|
||||
fire() {
|
||||
const [id, timer] = [...timers][0];
|
||||
timers.delete(id);
|
||||
timer.fn();
|
||||
return timer.ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('a mark may move half a pixel between draws', () => {
|
||||
assert.equal(PACE_STEP_PX, 0.5);
|
||||
assert.equal(paceHzForSpeed(1), 2);
|
||||
assert.equal(paceHzForSpeed(10), 20);
|
||||
});
|
||||
|
||||
test('slow marks are drawn three times a second, one frame at a time', () => {
|
||||
const { pace, calls, timers, fire } = makePace();
|
||||
pace.start();
|
||||
pace.set(0.2);
|
||||
pace.set(0.2);
|
||||
// From the starting rate it eases down, never below the floor.
|
||||
for (let i = 0; i < 40; i++) pace.set(0.2);
|
||||
assert.equal(pace.state().hz, PACE_MIN_HZ);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.ok(timers.size === 1, 'one wait out');
|
||||
// The wait out from the start runs out, then the next is at the floor.
|
||||
fire();
|
||||
assert.equal(fire(), 1000 / PACE_MIN_HZ);
|
||||
assert.deepEqual(calls.at(-1), ['request', 'dots']);
|
||||
assert.ok(!calls.some(([kind]) => kind === 'hold'));
|
||||
});
|
||||
|
||||
test('fast marks hold the loop at a rate the display divides, never above 30', () => {
|
||||
const { pace, calls, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(13);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', 15]);
|
||||
assert.equal(timers.size, 0, 'held: no waits');
|
||||
pace.set(18);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', 20]);
|
||||
pace.set(500);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', PACE_MAX_HZ]);
|
||||
assert.equal(pace.state().hz, PACE_MAX_HZ);
|
||||
pace.set(Infinity);
|
||||
assert.equal(pace.state().heldFps, PACE_MAX_HZ);
|
||||
// The same rate again asks the governor for nothing.
|
||||
const before = calls.length;
|
||||
pace.set(40);
|
||||
assert.equal(calls.length, before);
|
||||
});
|
||||
|
||||
test('the hold is let go below the release rate, not at the hold rate', () => {
|
||||
const { pace, calls } = makePace();
|
||||
pace.start();
|
||||
pace.set(14);
|
||||
assert.equal(pace.state().held, true);
|
||||
// Down gently: a tenth a frame at most.
|
||||
for (let i = 0; i < 2; i++) pace.set(10);
|
||||
assert.equal(pace.state().held, true, 'still above the release rate');
|
||||
for (let i = 0; i < 20; i++) pace.set(1);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.ok(calls.some(([kind]) => kind === 'release'));
|
||||
});
|
||||
|
||||
test('marks a layer moves itself move at the pace, and on every frame while held', () => {
|
||||
const { pace, advance, fire } = makePace();
|
||||
pace.start();
|
||||
assert.equal(pace.take(), true, 'first frame moves');
|
||||
assert.equal(pace.take(), false, 'same instant: no move');
|
||||
for (let i = 0; i < 40; i++) pace.set(0);
|
||||
advance(100);
|
||||
assert.equal(pace.take(), false, 'too soon at three a second');
|
||||
fire();
|
||||
assert.equal(pace.take(), true, 'the wait ended');
|
||||
advance(1000 / PACE_MIN_HZ);
|
||||
assert.equal(pace.take(), true, 'a third of a second on');
|
||||
pace.set(30);
|
||||
assert.equal(pace.take(), true);
|
||||
assert.equal(pace.take(), true, 'held: every drawn frame');
|
||||
});
|
||||
|
||||
test('stopping lets the hold go and ends the waits; a stopped pace moves every frame', () => {
|
||||
const { pace, calls, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(25);
|
||||
pace.stop();
|
||||
assert.deepEqual(calls.at(-1), ['release', 'dots']);
|
||||
assert.equal(timers.size, 0);
|
||||
pace.set(25);
|
||||
assert.equal(pace.state().held, false, 'set does nothing once stopped');
|
||||
assert.equal(pace.take(), true);
|
||||
assert.equal(pace.take(), true);
|
||||
});
|
||||
|
||||
/** A camera at `z` metres up the z axis looking down it, 60° field. */
|
||||
function poseAt(z) {
|
||||
return {
|
||||
position: { x: 0, y: 0, z },
|
||||
direction: { x: 0, y: 0, z: -1 },
|
||||
fovy: Math.PI / 3,
|
||||
};
|
||||
}
|
||||
|
||||
test('screen speed: a move across the view axis, from its angle at the eye', () => {
|
||||
const speed = createScreenSpeed();
|
||||
assert.equal(speed.begin(poseAt(1000), 1000), true);
|
||||
// 10 m sideways at 1 km ahead, over one second.
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 0 });
|
||||
const focal = 500 / Math.tan(Math.PI / 6);
|
||||
// Measured at the move's end: 10 m off-axis, a hair off-centre.
|
||||
const px = speed.pxPerSec(1);
|
||||
assert.ok(Math.abs(px - (10 / 1000) * focal) / px < 0.001, `${px}`);
|
||||
assert.ok(Math.abs(speed.pxPerSec(2) - px / 2) < 1e-9);
|
||||
});
|
||||
|
||||
test('screen speed: the fastest mark counts, marks behind or far off-axis do not', () => {
|
||||
const speed = createScreenSpeed();
|
||||
speed.begin(poseAt(1000), 1000);
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 5, y: 0, z: 0 });
|
||||
// Behind the eye.
|
||||
speed.add({ x: 0, y: 0, z: 2000 }, { x: 500, y: 0, z: 2000 });
|
||||
// 80° off the axis.
|
||||
speed.add({ x: 5000, y: 0, z: 900 }, { x: 5500, y: 0, z: 900 });
|
||||
const focal = 500 / Math.tan(Math.PI / 6);
|
||||
assert.ok(Math.abs(speed.pxPerSec(1) - (5 / 1000) * focal) < 0.01);
|
||||
});
|
||||
|
||||
test('screen speed: a mark moving with the eye stands still on screen', () => {
|
||||
const speed = createScreenSpeed();
|
||||
speed.begin(poseAt(1000), 1000, { x: 7, y: 0, z: 0 });
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 7, y: 0, z: 0 });
|
||||
assert.equal(speed.pxPerSec(1), 0);
|
||||
});
|
||||
|
||||
test('screen speed: no camera, no reading', () => {
|
||||
const speed = createScreenSpeed();
|
||||
assert.equal(speed.begin(null, 900), false);
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
|
||||
assert.equal(speed.pxPerSec(1), 0);
|
||||
});
|
||||
|
||||
test('a need of ten a second, once held, falls back to single frames at ten', () => {
|
||||
const { pace, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(30);
|
||||
for (let i = 0; i < 40; i++) pace.set(10);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.equal(Math.round(pace.state().hz), 10);
|
||||
assert.equal(timers.size, 1);
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
* Cesium port does (`src/render/cesium/ports.js`): holds, counted per
|
||||
* reason, keep `requestRenderMode` false; releasing the last asks for one
|
||||
* frame; a request is the scene's `requestRender`; the first hold and the
|
||||
* last release are told to `onHeldChange`; a rate set is kept as the
|
||||
* last release are told to `onHeldChange`, every hold and release to
|
||||
* `onHoldsChange`; a rate set is kept as the
|
||||
* scene's `targetFps`. Only the members the governor uses. One port per
|
||||
* scene, so a test can uninstall what it installed.
|
||||
* @param {{requestRenderMode?: boolean, requestRender?: () => void}} scene
|
||||
@@ -20,10 +21,12 @@ const ports = new WeakMap();
|
||||
function makePort(scene) {
|
||||
const holds = new Map();
|
||||
const heldListeners = new Set();
|
||||
const holdsListeners = new Set();
|
||||
let wasHeld = false;
|
||||
const apply = () => {
|
||||
const held = holds.size > 0;
|
||||
scene.requestRenderMode = !held;
|
||||
for (const cb of [...holdsListeners]) cb();
|
||||
if (held === wasHeld) return;
|
||||
wasHeld = held;
|
||||
for (const cb of [...heldListeners]) cb(held);
|
||||
@@ -34,6 +37,10 @@ function makePort(scene) {
|
||||
heldListeners.add(cb);
|
||||
return () => heldListeners.delete(cb);
|
||||
},
|
||||
onHoldsChange(cb) {
|
||||
holdsListeners.add(cb);
|
||||
return () => holdsListeners.delete(cb);
|
||||
},
|
||||
diagnostics: () => ({ holds: [...holds.keys()] }),
|
||||
setTargetFps(fps) {
|
||||
scene.targetFps = fps;
|
||||
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user