Compare commits

..
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 e9c9de0878 docs(changelog): add the #1907 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:13:45 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 01187cbe7a feat(vessels): draw vessels as shaded sprites seen from the camera's angle
Vessels on the map were flat, top-down hulls turned along their course,
drawn at one size at every range.

Each hull shape (the ten vessel kinds, a dredger and a pilot boat) is
now rendered in Blender into a view sheet like the aircraft's
(public/sprites/vessel-views.webp: 208 views a shape, 7.5 degrees apart
from straight above down to the horizon, 4096 x 2496, grey, 2.2 MB),
cut at the waterline. On a renderer with `viewSheets` the Vessels layer
draws a vessel as the view of its hull from where the eye is, with the
flat hull as the fallback while the sheet loads or if it cannot load.
A vessel keeps its kind's colour; aids to navigation keep their upright
buoy; a renderer without view sheets draws the flat hulls as before.

Every AIS ship type code 0-99 maps to a shape in the sheet
(`vesselShape`, vesselTypes.js), pinned by a test. Type text such as
"Search & Rescue" and "Anti Pollution" is now recognised, which also
gives those vessels their right kind colour.

Size: a vessel's icon now follows its range from the eye on the same
range aircraft icons use (1.5 times its former size up close, its
former size at about 1,000 km, a third from 8,000 km out), so it stays
under an aircraft's icon at every range, and the vessel set recedes
toward the horizon as the aircraft sets do.

Tools: the bake script handles both sheets
(scripts/bake-view-sheet.py; `npm run build:aircraft-views`,
`npm run build:vessel-views`), and refuses a partial bake over a shipped
sheet. scripts/qa-view-sheet.mjs writes contact sheets of a bake;
scripts/qa-aircraft-views.mjs takes `--layer vessels`. The aircraft
sheet is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:10:58 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 b4ff9b1e07 docs(changelog): add the #1903 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 01:22:05 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 efdac0ba70 feat(aircraft): draw far-away aircraft as shaded sprites seen from the camera's angle
Aircraft on the map were flat, top-down SVG silhouettes turned along
their course: from an oblique camera they read as paper cut-outs lying
on the ground.

Each aircraft class (and each helicopter rotor frame) is now rendered in
Blender from a sphere of directions into one sheet of shaded sprites
(public/sprites/aircraft-views.webp: 302 views a class, 7.5 degrees
apart from straight above to 30 degrees below the horizon, 4096 x 3648,
grey, 3.1 MB). The renderer lays a contact flat on the ground along its
course, works out where the eye is in that frame and draws the nearest
view, mirrored for the port side. The view is a card standing at the
contact, square to the direction it was rendered from, so between views
the sprite is tilted (foreshortened and turned) as the aircraft would
be; views are not blended. Sprites are neutral, so the fleet, tracked
and military tints still apply.

Renderer: a new `viewSheets` capability, `DrawPort.views(id, sheet)` and
an image `{views, first, fallback}` for icon items (src/data/viewSheet.js
holds the layout and maths, in JS and GLSL). A view row draws from the
sheet's own texture, kept as luminance and alpha; until the sheet has
loaded, and if it cannot load, it draws its flat `fallback` along its
course as before. View sheets are offered on WebGL 2 only, and on
WebGL 1 the icon shader is as it was.

Layers: Flights, Military Flights (fleet and tracked contact) and Local
ADS-B draw views; the TR-3B, airport vehicles, ground stations and
Cockpit's far pips stay flat, as does any renderer without the
capability.

Tools: `npm run build:aircraft-views` bakes the sheet from the repo's
own fleet models (about 7 minutes); scripts/qa-aircraft-view-sheet.mjs
writes contact sheets of a bake and scripts/qa-aircraft-views.mjs
photographs a grid of every class in the app from above, tilted, from
below and round an orbit.

With 5,000 contacts on an M3 Max the frame takes 5.9-6.1 ms against
5.9 ms with the flat glyphs.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 01:21:39 +01:00
83 changed files with 4538 additions and 3331 deletions

No files matched your search

@@ -1,6 +0,0 @@
- 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).
@@ -0,0 +1,8 @@
- Aircraft on the map are shaded sprites that show the view of the aircraft
from where the camera is, instead of flat top-down silhouettes: each class
(and each helicopter rotor frame) is drawn from a sheet rendered from a
sphere of camera angles, laid flat along its course, so a plane seen at an
oblique angle looks solid. Flights, Military Flights (fleet and tracked
contact) and Local ADS-B use it; the TR-3B, airport vehicles, ground
stations and Cockpit's far pips stay flat, and a renderer without view
sheets draws the flat glyphs as before (Mazeyar Moeini Feizabadi, #1903).
+10
View File
@@ -0,0 +1,10 @@
- Vessels on the map are shaded sprites that show the view of the ship from
where the camera is, instead of flat top-down hulls: each hull shape (the
ten vessel kinds, a dredger and a pilot boat) is drawn from a sheet
rendered from straight above down to the horizon, laid flat on the water
along its course, so a ship seen at an oblique angle looks solid. A
vessel keeps its kind's colour; aids to navigation keep their upright buoy,
and a renderer without view sheets draws the flat hulls as before. A
vessel's size now follows the camera's range: larger up close, smaller
than an aircraft from far out, and shrinking and fading toward the
horizon as aircraft do (Mazeyar Moeini Feizabadi, #1907).
-6
View File
@@ -1,6 +0,0 @@
- The app opens with the loading screen's logo turning into the globe: the
eye's arcs fly out, the planet in the pupil becomes the real globe, which
spins, grows and stops with the whole planet in view over your country, taken
from the browser's time zone. The title's logo goes back to that view. A
share link, a Stories link, reduced motion and `?intro=0` open as before
(gekh, #1909).
+4 -4
View File
@@ -8890,10 +8890,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. 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.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. 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.** 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.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
@@ -8909,7 +8909,7 @@ pins and share links already supply complete boxes.
30-second backoff ahead of the current clock are ignored. A smaller rollback
can retain a bounded retry delay of up to 30 seconds.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Angle-aware aircraft sprites.** On a renderer with the `viewSheets` capability, each aircraft class (and each of the helicopter's three rotor frames) draws from the aircraft view sheet instead of its flat glyph: `/sprites/aircraft-views.webp`, the classes rendered shaded in neutral grey from a sphere of camera angles (`src/data/viewSheet.js`, baked by `scripts/bake-view-sheet.py --sheet aircraft`, `npm run build:aircraft-views`). The icon lies flat on the earth along its course and the renderer draws the view that matches where the eye is, so an aircraft seen obliquely looks solid; the tints (white fleet, cyan tracked, amber military) multiply the grey as before. `src/data/aircraftViews.js` maps an icon kind and rotor frame to its block of the sheet and registers the sheet once per draw port. Only an icon drawn along its course (`rotationMode: 'course'`) takes a view, and it has no near image (`imageLod`), the sheet having one resolution. Flights and Military Flights draw every fleet contact this way, and their tracked billboard too (drawn along the tracked display course instead of turned on screen, so selecting a contact still changes only its colour); Local ADS-B draws its markers along their track. The TR-3B triangle, airport vehicles, ground stations and Cockpit's far-contact pips keep their flat sprites, and on a renderer without the capability every icon is the flat glyph with its near image, as before. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, milLine truncated
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
+2
View File
@@ -49,6 +49,8 @@
"opensky:import": "./scripts/opensky-import-client.sh",
"build": "vite build",
"build:panel": "node scripts/build-panel.mjs",
"build:aircraft-views": "node scripts/build-view-sheet.mjs --sheet aircraft",
"build:vessel-views": "node scripts/build-view-sheet.mjs --sheet vessels",
"preview": "vite preview",
"test": "node scripts/run-unit-tests.mjs",
"test:perf": "node scripts/run-perf-tests.mjs",
+4
View File
@@ -35,6 +35,10 @@ How the layers use them:
the route or category colour is painted.
- The whole set loads once, up front, when a layer that draws it starts; no
model is fetched while a session runs.
- The aircraft and helicopter models are also rendered from every side into
the aircraft view sheet, the shaded sprites far-away aircraft are drawn
with, and one ship model for each vessel hull shape, cut at its waterline,
into the vessel view sheet ([`../sprites/`](../sprites/README.md)).
`src/data/fleetModels.js` reads the set and chooses each vehicle's model;
`src/data/fleetModels.test.mjs` checks that every model `types.json` names is
+106
View File
@@ -0,0 +1,106 @@
# View Sheets
A view sheet is one image of small shaded sprites: each subject rendered from
a sphere of camera angles. On a renderer with the `viewSheets` capability a
layer lays a contact flat on the earth along its course and the renderer
draws the frame nearest to where the eye is, as a card that tilts as the eye
moves off its direction until the next frame is the nearer (frames are not
blended), so a contact seen at an oblique angle looks solid and turns with
the camera.
- `aircraft-views.webp` holds the far-away aircraft of Flights, Military
Flights and Local ADS-B.
- `vessel-views.webp` holds the vessels of the vessel layer.
Each has a manifest beside it (`.json`).
The sprites are rendered from the project's own procedural fleet models
([`../models/fleet/`](../models/README.md)), so, like them, they contain no
third-party artwork and are covered by the repository's
[MIT license](../../LICENSE).
| Path | What it holds |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aircraft-views.webp` | 4096 × 3648 px, lossless WebP: 64 px cells, 64 a row, 57 rows. Grey: every pixel's red, green and blue are equal. |
| `aircraft-views.json` | The layout (`cellPx`, `columns`, `rows`, `ringStepDeg`, `rings`, `fill`, `grey`) and each subject's first cell, fleet model and bounding radius in metres. |
| `vessel-views.webp` | 4096 × 2496 px, lossless WebP: 64 px cells, 64 a row, 39 rows. Grey. |
| `vessel-views.json` | Its manifest, of the same shape. |
## Layout
A sheet holds each subject as a block of consecutive cells, row-major:
subject `i` starts at cell `i × frames`. Within a block the frames lie in
rings 7.5° apart from straight above (ring 0, one frame) downward. A ring
runs from the eye dead ahead of the nose or bow, round the starboard side, to
dead astern. The renderer mirrors a starboard frame for an eye on the port
side, so the light is symmetric about the subject's centre plane. A frame is
an orthographic view centred on the model's origin, its bounding sphere
spanning 0.92 of the cell, turned so that straight above the nose points up
the image. `src/data/viewSheet.js` holds the layouts (`AIRCRAFT_VIEWS`,
`VESSEL_VIEWS`) and the maths that picks a frame;
`src/data/viewSheet.test.mjs` checks the manifests, the shipped images and
the bake script against them.
| Sheet | Frames a subject | Rings | Subjects, in order |
| -------- | ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Aircraft | 302 | 17, to 30° below the horizon: 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22 | `airliner`, `widebody`, `quadjet`, `turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0` to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`) |
| Vessels | 208 | 13, to the horizon (a ship is never seen from below): 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25 | `cargo`, `tanker`, `passenger`, `highspeed`, `fishing`, `tug`, `sailing`, `pleasure`, `military`, `other` (the kinds of `vesselKind`, `src/data/vesselTypes.js`), `dredger`, `pilot` |
The sprites are neutral (light paint, grey shading, dark glass, a dark edge)
so each layer's tint multiplies them, as it does the flat glyphs. They are
exactly grey (`"grey": true`): the renderer keeps a sheet as grey and alpha,
reading its red channel, which halves its memory. The bake refuses a frame
that is not grey, and so does the step that writes the WebP. Every cell keeps
its outer 2 px transparent, so the renderer's mipmaps never pull in a
neighbour.
Thin subjects are thickened a little before their edge so they still read
20 to 30 px wide: the glider, UAV, light aircraft and helicopter, and every
vessel (the container ship, tanker and patrol boat most).
Vessels differ from aircraft in four ways:
- **Waterline.** A ship model's origin is its waterline. Each model is cut
there before it is rendered, so no hull below the water is drawn, even from
the horizon.
- **Paint.** The ship models are many colours (hull paint, decks,
containers). The vessel paint makes every colour a light grey, black hull
paint included, except the windows (a dark colour whose blue stands above
its red), which stay dark.
- **Beam.** Hulls are long and thin, so most are widened across the beam
(1.2 to 1.5 times; the trawler and tug as built). The side view keeps its
true height.
- **Sailboat.** The sailboat's mast is taller than its hull is long. Above
1.2 m it is squashed to 0.4 of its height, so the hull fills its cell from
above and the sail still reads from the side.
## Rebuilding
```
npm run build:aircraft-views # about 7 minutes
npm run build:vessel-views # about 4 minutes
npm run build:vessel-views -- --only tug,sailing --out /tmp/views
```
This needs Blender (`$BLENDER`, else `blender` on the `PATH`, else
`/Applications/Blender.app`). Each runs `scripts/build-view-sheet.mjs`, which
runs `scripts/bake-view-sheet.py --sheet aircraft|vessels` headless (one
script, with each sheet's layout, models, paint and adjustments). The bake
renders every frame with Cycles and refuses a frame whose pixels reach
within 2 px of its cell's edge. `build-view-sheet.mjs` then writes the PNG as
lossless WebP here with the manifest. With `--only`, the other subjects'
cells are left empty, so ship only a full bake. Cycles is not
bit-reproducible, so a rebuild changes the WebP's bytes slightly; rebuild a
sheet only to change it.
To review a bake, write a contact sheet per subject: its rings as rows, plus
a few frames at 40, 30 and 20 px in each tint the layers draw it with.
- Aircraft: over a dark sea, pale land and a mid satellite tone, in the
fleet, tracked and military tints.
- Vessels: over a dark sea, pale shallow water and a satellite ocean tone,
in white and the kind's colour.
```
node scripts/qa-view-sheet.mjs --manifest public/sprites/vessel-views.json [--out qa-shots/vessel-views]
```
+90
View File
@@ -0,0 +1,90 @@
{
"image": "aircraft-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 57,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25,
25,
24,
23,
22
],
"fill": 0.92,
"grey": true,
"subjects": {
"airliner": {
"first": 0,
"model": "aircraft/a320.glb",
"radiusM": 18.883
},
"widebody": {
"first": 302,
"model": "aircraft/b789.glb",
"radiusM": 32.121
},
"quadjet": {
"first": 604,
"model": "aircraft/b744.glb",
"radiusM": 37.959
},
"turboprop": {
"first": 906,
"model": "aircraft/at72.glb",
"radiusM": 14.14
},
"light": {
"first": 1208,
"model": "aircraft/c172.glb",
"radiusM": 5.825
},
"glider": {
"first": 1510,
"model": "aircraft/glider.glb",
"radiusM": 7.506
},
"fastjet": {
"first": 1812,
"model": "aircraft/t38.glb",
"radiusM": 7.408
},
"bizjet": {
"first": 2114,
"model": "aircraft/glf4.glb",
"radiusM": 17.211
},
"uav": {
"first": 2416,
"model": "aircraft/mq9.glb",
"radiusM": 9.811
},
"helicopter0": {
"first": 2718,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter1": {
"first": 3020,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter2": {
"first": 3322,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

+86
View File
@@ -0,0 +1,86 @@
{
"image": "vessel-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 39,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25
],
"fill": 0.92,
"grey": true,
"subjects": {
"cargo": {
"first": 0,
"model": "ships/container_ship.glb",
"radiusM": 160.913
},
"tanker": {
"first": 208,
"model": "ships/tanker.glb",
"radiusM": 130.314
},
"passenger": {
"first": 416,
"model": "ships/cruise_ship.glb",
"radiusM": 168.583
},
"highspeed": {
"first": 624,
"model": "ships/fast_ferry.glb",
"radiusM": 23.032
},
"fishing": {
"first": 832,
"model": "ships/trawler.glb",
"radiusM": 13.229
},
"tug": {
"first": 1040,
"model": "ships/tug.glb",
"radiusM": 16.418
},
"sailing": {
"first": 1248,
"model": "ships/sailboat.glb",
"radiusM": 8.358
},
"pleasure": {
"first": 1456,
"model": "ships/motor_yacht.glb",
"radiusM": 10.073
},
"military": {
"first": 1664,
"model": "ships/patrol.glb",
"radiusM": 36.28
},
"other": {
"first": 1872,
"model": "ships/generic_vessel.glb",
"radiusM": 21.828
},
"dredger": {
"first": 2080,
"model": "ships/dredger.glb",
"radiusM": 53.542
},
"pilot": {
"first": 2288,
"model": "ships/pilot_boat.glb",
"radiusM": 10.774
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

+678
View File
@@ -0,0 +1,678 @@
"""Bake a view sheet: each subject of a sheet (an aircraft class, a vessel
kind) seen from a sphere of directions, as one image of small shaded sprites.
blender -b --factory-startup --python scripts/bake-view-sheet.py -- \
--sheet aircraft|vessels --out <dir> [--cell 64] [--supersample 4]
[--only airliner,light] [--preview <dir>]
It writes `<name>.png` and its manifest `<name>.json` to `--out`, `<name>`
being the sheet's name (`aircraft-views`, `vessel-views`). The manifest names
the shipped image, `<name>.webp`, which `npm run build:aircraft-views` or
`npm run build:vessel-views` (scripts/build-view-sheet.mjs) makes from the
PNG (lossless) and writes to `public/sprites/` with the manifest.
The layers draw a contact with the frame that shows it from where the eye is
(`src/data/viewSheet.js` holds the same layouts and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's sheets and the shipped
manifests against it). A frame is an orthographic view of the subject's
fleet model (`public/models/fleet/`, nose or bow toward -X, +Y starboard, +Z
up), centred on the model's origin, the model's bounding sphere filling
`FILL` of the cell.
Directions. `d` is the unit vector from the subject to the eye in the
subject's own frame (forward, right, up), the subject lying flat on the
earth: up is the ground's normal, forward its course. Rings of frames lie
the sheet's `ring_step_deg` apart from straight above (ring 0, one frame)
down to its last ring (30 degrees below the horizon for aircraft, the horizon
for vessels). A ring holds the eye's bearings from dead ahead (first frame)
round the starboard side to dead astern (last frame); the port side is the
starboard frame mirrored, which is why the light is symmetric about the
subject's centre plane.
Roll. A frame's image up is where the subject's forward goes under the
smallest rotation that takes "up" to `d`: straight above, the nose points up
the image, and the roll then changes smoothly all the way round and below
(it has no meaning only from straight below, which no ring reaches).
The sprites are neutral (light paint, grey shading, dark glass and a dark
edge) so a layer's tint multiplies them, as it does the flat glyphs; every
pixel's red, green and blue are equal (`"grey": true` in the manifest), as
the renderer keeps the sheet as grey and alpha, and the bake refuses a frame
that is not. Each sheet has its paint ramp (`PAINTS`), and a subject may
have its own. A helicopter's body and blades are painted light as well (its
blades a solid light grey), and its rotor frames share one scale: each rotor
vertex counts at the farthest point of the circle it sweeps about the
rotor's axis. A vessel is cut at its waterline (its origin, z = 0) before it
is rendered, so no hull below the water is drawn and its bounding sphere is
of what floats; a subject's model may be widened across the beam (`beam`)
or squashed above a height (`squash_above`: a sailboat's mast). Thin
subjects are thickened before their edge (`bold_px`), and every cell keeps
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
refuses a frame that does not.
"""
import json
import math
import os
import struct
import sys
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheets (their layouts mirrored in src/data/viewSheet.js) -----------
# A sheet: its name (the files it writes), its rings of frames (each ring's
# frame count, from dead ahead round starboard to dead astern), its paint,
# whether its models are cut at the waterline, and its subjects, in the order
# of their blocks of frames. A subject is (name, model, options); options:
# rotor_deg a helicopter's rotor frame: the rotors turned this far
# paint its own paint ramp (a key of PAINTS)
# bold_px cell pixels it is thickened by before its edge, so thin
# wings, blades and hulls still read 20 to 30 px wide
# beam its model scaled across the beam by this much
# squash_above [z, k]: its model above z metres scaled up by k
AIRCRAFT = {
"name": "aircraft-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22],
"columns": 64,
"paint": "aircraft",
"waterline": False,
"subjects": [
("airliner", "aircraft/a320.glb", {}),
("widebody", "aircraft/b789.glb", {}),
("quadjet", "aircraft/b744.glb", {}),
("turboprop", "aircraft/at72.glb", {}),
("light", "aircraft/c172.glb", {"bold_px": 0.35}),
("glider", "aircraft/glider.glb", {"bold_px": 1.0}),
("fastjet", "aircraft/t38.glb", {}),
("bizjet", "aircraft/glf4.glb", {}),
("uav", "aircraft/mq9.glb", {"bold_px": 1.0}),
# The helicopter has one block for each rotor frame (rotorFrames.js).
("helicopter0", "helicopters/generic_heli.glb", {"rotor_deg": 15, "paint": "helicopter", "bold_px": 0.4}),
("helicopter1", "helicopters/generic_heli.glb", {"rotor_deg": 45, "paint": "helicopter", "bold_px": 0.4}),
("helicopter2", "helicopters/generic_heli.glb", {"rotor_deg": 75, "paint": "helicopter", "bold_px": 0.4}),
],
}
# Vessels: down to the horizon only, as a ship is never seen from below. The
# subjects are the hull kinds of vesselKind (src/data/vesselTypes.js), then
# the dredger (AIS 33) and the pilot boat (pilot, rescue, tender and
# anti-pollution craft).
VESSELS = {
"name": "vessel-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25],
"columns": 64,
"paint": "ship",
"waterline": True,
"subjects": [
("cargo", "ships/container_ship.glb", {"beam": 1.4, "bold_px": 1.0}),
("tanker", "ships/tanker.glb", {"beam": 1.4, "bold_px": 1.0}),
("passenger", "ships/cruise_ship.glb", {"beam": 1.4, "bold_px": 0.5}),
("highspeed", "ships/fast_ferry.glb", {"beam": 1.2, "bold_px": 0.5}),
("fishing", "ships/trawler.glb", {"bold_px": 0.5}),
("tug", "ships/tug.glb", {"bold_px": 0.5}),
("sailing", "ships/sailboat.glb", {"beam": 1.3, "bold_px": 0.5, "squash_above": [1.2, 0.4]}),
("pleasure", "ships/motor_yacht.glb", {"beam": 1.25, "bold_px": 0.5}),
("military", "ships/patrol.glb", {"beam": 1.5, "bold_px": 1.0}),
("other", "ships/generic_vessel.glb", {"beam": 1.3, "bold_px": 0.5}),
("dredger", "ships/dredger.glb", {"beam": 1.3, "bold_px": 0.5}),
("pilot", "ships/pilot_boat.glb", {"beam": 1.2, "bold_px": 0.5}),
],
}
SHEETS = {"aircraft": AIRCRAFT, "vessels": VESSELS}
# How much of a cell the model's bounding sphere spans.
FILL = 0.92
# Cells keep this many pixels at each edge clear: the renderer samples the
# sheet with mipmaps (to level 1), so a neighbour's pixels must not reach
# into a cell's footprint.
CLEAR_EDGE_PX = 2
FORWARD = Vector((-1.0, 0.0, 0.0))
RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions(sheet):
"""Every frame's (ring, index, d) with d in the model's axes."""
out = []
for ring, count in enumerate(sheet["rings"]):
alpha = math.radians(ring * sheet["ring_step_deg"])
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
FORWARD * (math.sin(alpha) * math.cos(phi))
+ RIGHT * (math.sin(alpha) * math.sin(phi))
+ UP * math.cos(alpha)
)
out.append((ring, i, d.normalized()))
return out
def frame_up(d):
"""A frame's image up: forward, turned as `UP` turns onto `d`."""
return (UP.rotation_difference(d) @ FORWARD).normalized()
# --- Scene -------------------------------------------------------------------
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"sheet": "aircraft",
"out": "public/sprites",
"cell": 64,
"supersample": 4,
"only": None,
"preview": None,
"samples": 48,
}
i = 0
while i < len(argv):
key = argv[i].lstrip("-")
if key not in opts:
raise SystemExit(f"unknown option {argv[i]}")
opts[key] = argv[i + 1]
i += 2
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
if opts["sheet"] not in SHEETS:
raise SystemExit(f"--sheet is one of {', '.join(SHEETS)}")
return opts
def setup_scene(render_px, samples):
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = samples
scene.cycles.use_denoising = False
scene.cycles.max_bounces = 3
scene.cycles.pixel_filter_type = "BOX"
scene.cycles.filter_width = 1.0
scene.render.film_transparent = True
scene.render.resolution_x = render_px
scene.render.resolution_y = render_px
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.image_settings.color_depth = "8"
scene.view_settings.view_transform = "Standard"
scene.view_settings.look = "None"
scene.display_settings.display_device = "sRGB"
# Sky: even light from every side, so the underside is lit and the
# wings shade the fuselage softly where they meet.
world = bpy.data.worlds.new("sky")
world.use_nodes = True
background = world.node_tree.nodes["Background"]
background.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
background.inputs["Strength"].default_value = SKY_STRENGTH
scene.world = world
# Sun: from above, leaning toward the nose, in the aircraft's centre
# plane (so a mirrored frame is lit as its twin).
sun_data = bpy.data.lights.new("sun", "SUN")
sun_data.energy = SUN_STRENGTH
sun_data.angle = math.radians(18)
sun = bpy.data.objects.new("sun", sun_data)
scene.collection.objects.link(sun)
lean = math.radians(28)
to_sun = (UP * math.cos(lean) + FORWARD * math.sin(lean)).normalized()
sun.rotation_euler = to_sun.to_track_quat("Z", "Y").to_euler()
# Fill: a weak light from the eye, so what faces the viewer is lighter
# than what turns away and a round body reads as round from any side.
fill_data = bpy.data.lights.new("fill", "SUN")
fill_data.energy = FILL_STRENGTH
fill_data.angle = math.radians(30)
fill = bpy.data.objects.new("fill", fill_data)
scene.collection.objects.link(fill)
camera_data = bpy.data.cameras.new("camera")
camera_data.type = "ORTHO"
camera_data.clip_start = 0.1
camera_data.clip_end = 10000
camera = bpy.data.objects.new("camera", camera_data)
scene.collection.objects.link(camera)
scene.camera = camera
return scene, camera, fill
# Paint by the model's own colour value (its largest channel, linear), as
# (value, grey) stops. Aircraft: glass and tyres stay dark, a livery's accent
# becomes mid grey, and every body colour a light paint, so a tint reads on
# any model. Ships: windows and the darkest fittings stay dark, and hull
# paint, decks and cargo all become light greys a little apart.
PAINTS = {
"aircraft": [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)],
"helicopter": [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)],
"ship": [(0.0, 0.62), (0.25, 0.78), (0.85, 0.95)],
}
# Glass by its colour, for a paint that lifts even black hull paint: a dark
# colour (value at most `value`) whose blue is at least `blue` and
# `blue_over_red` times its red (the ship models' windows) is painted `grey`.
GLASS = {"ship": {"value": 0.08, "blue": 0.025, "blue_over_red": 2.5, "grey": 0.07}}
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp, solid=None, glass=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = nodes["Principled BSDF"]
bsdf.inputs["Roughness"].default_value = 0.6
if solid is not None:
bsdf.inputs["Base Color"].default_value = (solid, solid, solid, 1.0)
return material
colour = nodes.new("ShaderNodeVertexColor")
colour.layer_name = "Color"
split = nodes.new("ShaderNodeSeparateColor")
links.new(colour.outputs["Color"], split.inputs["Color"])
red_green = nodes.new("ShaderNodeMath")
red_green.operation = "MAXIMUM"
links.new(split.outputs[0], red_green.inputs[0])
links.new(split.outputs[1], red_green.inputs[1])
value = nodes.new("ShaderNodeMath")
value.operation = "MAXIMUM"
links.new(red_green.outputs[0], value.inputs[0])
links.new(split.outputs[2], value.inputs[1])
ramp = nodes.new("ShaderNodeValToRGB")
elements = ramp.color_ramp.elements
while len(elements) < len(paint_ramp):
elements.new(0.5)
for element, (position, grey) in zip(elements, paint_ramp):
element.position = position
element.color = (grey, grey, grey, 1.0)
links.new(value.outputs[0], ramp.inputs["Fac"])
if glass is None:
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def math_node(operation, a, b, c=None):
node = nodes.new("ShaderNodeMath")
node.operation = operation
for i, x in enumerate((a, b, c)):
if x is None:
continue
if isinstance(x, (int, float)):
node.inputs[i].default_value = x
else:
links.new(x, node.inputs[i])
return node.outputs[0]
dark = math_node("LESS_THAN", value.outputs[0], glass["value"] + 1e-4)
blue = math_node("GREATER_THAN", split.outputs[2], glass["blue"] - 1e-4)
red_scaled = math_node("MULTIPLY", split.outputs[0], glass["blue_over_red"])
over_red = math_node(
"GREATER_THAN", math_node("SUBTRACT", split.outputs[2], red_scaled), -1e-4
)
is_glass = math_node("MULTIPLY", math_node("MULTIPLY", dark, blue), over_red)
ramp_grey = nodes.new("ShaderNodeSeparateColor")
links.new(ramp.outputs["Color"], ramp_grey.inputs["Color"])
to_glass = math_node("SUBTRACT", glass["grey"], ramp_grey.outputs[0])
grey = math_node("MULTIPLY_ADD", is_glass, to_glass, ramp_grey.outputs[0])
combine = nodes.new("ShaderNodeCombineColor")
for i in range(3):
links.new(grey, combine.inputs[i])
links.new(combine.outputs["Color"], bsdf.inputs["Base Color"])
return material
def model_parts(path):
"""The part table in a fleet model's root node (`render/modelParts.js`)."""
with open(path, "rb") as f:
data = f.read()
length = struct.unpack("<I", data[12:16])[0]
document = json.loads(data[20 : 20 + length])
for node in document.get("nodes", []):
parts = (node.get("extras") or {}).get("parts")
if parts:
return parts
return []
def gltf_to_blender(v):
"""A glTF (Y up) vector in Blender's axes (Z up)."""
return Vector((v[0], -v[2], v[1]))
def turn_rotors(mesh, parts, degrees, rotor_material):
"""Pose the rotors and bound each vertex over its entire rotation."""
part_of = mesh.data.attributes.get("_PART")
if part_of is None:
return {}
mesh.data.materials.append(rotor_material)
swept_radii = {}
to_world = mesh.matrix_world
to_local = to_world.inverted()
for index, part in enumerate(parts):
if part.get("kind") != "spin" or not part["name"].startswith("rotor"):
continue
pivot = gltf_to_blender(part["pivot"])
axis = gltf_to_blender(part["axis"]).normalized()
turn = Matrix.Rotation(math.radians(degrees), 4, axis)
move = to_local @ Matrix.Translation(pivot) @ turn @ Matrix.Translation(-pivot) @ to_world
if part_of.domain == "POINT":
members = [i for i, item in enumerate(part_of.data) if item.value == index]
else:
members = sorted(
{
mesh.data.loops[i].vertex_index
for i, item in enumerate(part_of.data)
if item.value == index
}
)
for i in members:
vertex = mesh.data.vertices[i]
relative = to_world @ vertex.co - pivot
axial = relative.dot(axis)
center = pivot + axial * axis
# The sweep lies in a plane perpendicular to the axis. Its
# farthest point adds the circle radius to the projected center.
radial = (relative - axial * axis).length
offset = (center - center.dot(axis) * axis).length
swept_radii[i] = math.hypot(center.dot(axis), offset + radial)
vertex.co = move @ vertex.co
for polygon in mesh.data.polygons:
if all(i in swept_radii for i in polygon.vertices):
polygon.material_index = 1
return swept_radii
def reshape(mesh, waterline, beam, squash_above):
"""Bring a mesh into the scene's axes, cut away what lies below the
waterline (z = 0) and scale it across the beam and above a height."""
world = mesh.matrix_world.copy()
mesh.parent = None
mesh.matrix_world = Matrix.Identity(4)
mesh.data.transform(world)
bm = bmesh.new()
bm.from_mesh(mesh.data)
if waterline:
bmesh.ops.bisect_plane(
bm,
geom=bm.verts[:] + bm.edges[:] + bm.faces[:],
dist=1e-4,
plane_co=(0.0, 0.0, 0.0),
plane_no=(0.0, 0.0, 1.0),
clear_inner=True,
)
for vertex in bm.verts:
vertex.co.y *= beam
if squash_above and vertex.co.z > squash_above[0]:
height, k = squash_above
vertex.co.z = height + (vertex.co.z - height) * k
bm.to_mesh(mesh.data)
bm.free()
def load_model(path, material, rotor_deg, rotor_material, waterline=False, options=None):
options = options or {}
before = set(bpy.data.objects)
bpy.ops.import_scene.gltf(filepath=path)
objects = [o for o in bpy.data.objects if o not in before]
meshes = [o for o in objects if o.type == "MESH"]
bpy.context.view_layer.update()
parts = model_parts(path) if rotor_deg is not None else []
beam = options.get("beam", 1.0)
squash_above = options.get("squash_above")
radius = 0.0
for mesh in meshes:
if waterline or beam != 1.0 or squash_above:
reshape(mesh, waterline, beam, squash_above)
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
for vertex in mesh.data.vertices:
distance = swept_radii.get(vertex.index)
if distance is None:
distance = (mesh.matrix_world @ vertex.co).length
radius = max(radius, distance)
return objects, radius
def aim(camera, fill, d, radius):
fill.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
up = frame_up(d)
right = up.cross(d).normalized()
rotation = Matrix((right, up, d)).transposed()
camera.matrix_world = Matrix.Translation(d * (radius * 4 + 10)) @ rotation.to_4x4()
camera.data.ortho_scale = 2 * radius / FILL
# --- Pixels ------------------------------------------------------------------
def read_pixels(path):
image = bpy.data.images.load(path)
width, height = image.size
pixels = np.array(image.pixels[:], dtype=np.float32).reshape(height, width, 4)
bpy.data.images.remove(image)
return pixels[::-1] # top row first
def dilate(alpha, radius):
out = alpha.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
shifted = np.zeros_like(alpha)
ys = slice(max(dy, 0), alpha.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), alpha.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), alpha.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), alpha.shape[1] + min(-dx, 0))
shifted[ys, xs] = alpha[yd, xd]
np.maximum(out, shifted, out=out)
return out
def disk_sum(values, radius):
"""Each pixel's sum of `values` over a disk of `radius` around it."""
out = values.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
ys = slice(max(dy, 0), values.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), values.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), values.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), values.shape[1] + min(-dx, 0))
out[ys, xs] += values[yd, xd]
return out
# Neutral, as the whole sheet is: the renderer keeps it as grey + alpha.
EDGE_RGB = np.array([0.045, 0.045, 0.045], dtype=np.float32)
EDGE_ALPHA = 0.62
def inside_mask(size, supersample):
"""1 within the disk that keeps CLEAR_EDGE_PX of the cell clear, fading
to 0 over half a cell pixel inside its rim. Only what the bake adds round
the model (its thickening and dark edge) is faded by it: the model's own
bounding sphere ends at FILL, inside it."""
cell = size / supersample
centre = size / 2
y, x = np.mgrid[0:size, 0:size] + 0.5
r = np.hypot(x - centre, y - centre) / supersample
outer = cell / 2 - CLEAR_EDGE_PX
return np.clip((outer - r) / 0.5, 0, 1).astype(np.float32)
def finish(pixels, supersample, bold_px=0.0):
"""Thicken the sprite by `bold_px` cell pixels, put a dark edge round it,
then bring it down to the cell by area."""
rgb = pixels[..., :3]
alpha = pixels[..., 3]
premultiplied = rgb * alpha[..., None]
mask = inside_mask(pixels.shape[0], supersample)
radius = round(supersample * bold_px)
if radius > 0:
# Under the model, its own colour spread outward: each new pixel the
# mean colour of the model round it.
grown = dilate(alpha, radius) * mask
weight = disk_sum(alpha, radius)
spread = disk_sum(premultiplied, radius) / np.maximum(weight, 1e-6)[..., None]
under = grown * (1 - alpha)
premultiplied = premultiplied + spread * under[..., None]
alpha = alpha + under
# About 0.9 cell pixels of edge.
halo = dilate(alpha, max(1, round(supersample * 0.9))) * EDGE_ALPHA * mask
out_alpha = alpha + halo * (1 - alpha)
premultiplied = premultiplied + EDGE_RGB * (halo * (1 - alpha))[..., None]
size = pixels.shape[0] // supersample
def area(a):
return a.reshape(size, supersample, size, supersample, -1).mean(axis=(1, 3))
small_alpha = area(out_alpha[..., None])[..., 0]
small = area(premultiplied)
colour = np.where(
small_alpha[..., None] > 1e-4, small / np.maximum(small_alpha[..., None], 1e-4), 0
)
return np.dstack([np.clip(colour, 0, 1), np.clip(small_alpha, 0, 1)])
# How far a frame's red, green and blue may differ (in 0..1) before the bake
# refuses it as not grey: rendering noise, never a colour.
GREY_TOLERANCE = 1.5 / 255
def to_grey(frame, name, n):
"""The frame with equal red, green and blue (their mean), refusing one
whose channels differ by more than rendering noise: the sheet ships as
grey (`"grey": true`), its red channel read as the grey."""
rgb = frame[..., :3]
lit = frame[..., 3] > 0
spread = (rgb.max(axis=2) - rgb.min(axis=2))[lit]
if spread.size and spread.max() > GREY_TOLERANCE:
raise SystemExit(
f"{name} frame {n}: not grey (its channels differ by "
f"{spread.max() * 255:.1f}/255); the sheet ships as grey"
)
grey = rgb.mean(axis=2, keepdims=True)
return np.dstack([np.repeat(grey, 3, axis=2), frame[..., 3:]])
def check_clear_edge(frame, name, n):
"""Refuse a frame with anything but transparent pixels near its edge."""
e = CLEAR_EDGE_PX
alpha = frame[..., 3]
band = np.concatenate(
[alpha[:e].ravel(), alpha[-e:].ravel(), alpha[:, :e].ravel(), alpha[:, -e:].ravel()]
)
if band.max() >= 0.5 / 255:
raise SystemExit(
f"{name} frame {n}: pixels within {e} px of the cell edge "
f"(alpha {band.max():.3f}); the fill leaves them no room"
)
def save_png(path, pixels):
height, width = pixels.shape[:2]
image = bpy.data.images.new("out", width, height, alpha=True)
image.alpha_mode = "STRAIGHT"
image.pixels.foreach_set(pixels[::-1].astype(np.float32).ravel())
image.filepath_raw = path
image.file_format = "PNG"
image.save()
bpy.data.images.remove(image)
# --- Bake --------------------------------------------------------------------
def main():
opts = args_after_dashes()
config = SHEETS[opts["sheet"]]
name_of_sheet = config["name"]
columns = config["columns"]
subjects = config["subjects"]
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
models = os.path.join(root, "public", "models", "fleet")
cell = opts["cell"]
supersample = opts["supersample"]
only = set(opts["only"].split(",")) if opts["only"] else None
scene, camera, fill = setup_scene(cell * supersample, opts["samples"])
materials = {
key: paint_material(ramp, glass=GLASS.get(key)) for key, ramp in PAINTS.items()
}
rotor_material = paint_material(None, solid=0.82)
directions = frame_directions(config)
frames = len(directions)
tmp = os.path.join(bpy.app.tempdir, "view-frame.png")
rows = math.ceil(len(subjects) * frames / columns)
sheet = np.zeros((rows * cell, columns * cell, 4), dtype=np.float32)
manifest = {
"image": f"{name_of_sheet}.webp",
"cellPx": cell,
"columns": columns,
"rows": rows,
"ringStepDeg": config["ring_step_deg"],
"rings": config["rings"],
"fill": FILL,
# Every pixel's red, green and blue are equal.
"grey": True,
"subjects": {},
}
for index, (name, model, options) in enumerate(subjects):
first = index * frames
manifest["subjects"][name] = {"first": first, "model": model}
if only and name not in only:
continue
objects, radius = load_model(
os.path.join(models, model),
materials[options.get("paint", config["paint"])],
options.get("rotor_deg"),
rotor_material,
config["waterline"],
options,
)
manifest["subjects"][name]["radiusM"] = round(radius, 3)
for n, (ring, i, d) in enumerate(directions):
aim(camera, fill, d, radius)
scene.render.filepath = tmp
bpy.ops.render.render(write_still=True)
frame = finish(read_pixels(tmp), supersample, options.get("bold_px", 0.0))
check_clear_edge(frame, name, n)
frame = to_grey(frame, name, n)
at = first + n
y = (at // columns) * cell
x = (at % columns) * cell
sheet[y : y + cell, x : x + cell] = frame
if opts["preview"]:
os.makedirs(opts["preview"], exist_ok=True)
save_png(
os.path.join(opts["preview"], f"{name}-r{ring}-{i:02d}.png"), frame
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {frames} frames, radius {radius:.2f} m", flush=True)
out = os.path.join(root, opts["out"]) if not os.path.isabs(opts["out"]) else opts["out"]
os.makedirs(out, exist_ok=True)
save_png(os.path.join(out, f"{name_of_sheet}.png"), sheet)
with open(os.path.join(out, f"{name_of_sheet}.json"), "w") as f:
json.dump(manifest, f, indent=1)
f.write("\n")
print(f"wrote {out}/{name_of_sheet}.png ({columns * cell}x{rows * cell})")
main()
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env node
// Writes src/data/homeCountries.js: each time zone's country, and where the
// opening stops over that country.
//
// node scripts/build-home-countries.mjs [path/to/zone.tab]
//
// Zones come from tzdata's zone.tab (macOS and most Linux systems ship it at
// /usr/share/zoneinfo/zone.tab), with the older names ICU still reports for
// some of them (Asia/Calcutta for Asia/Kolkata): a browser may give either.
// A country's point is the centroid of its largest part in the Natural Earth
// countries pack (the contiguous United States, mainland France), or the
// zone's own place where the pack has no such country.
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { geometryOf } from '../src/data/adminBoundaries.js';
const root = new URL('../', import.meta.url);
const zoneTab = process.argv[2] ?? '/usr/share/zoneinfo/zone.tab';
const pack = JSON.parse(
readFileSync(
new URL('src/data/local_data/natural_earth/countries.json', root),
'utf8',
),
);
const out = new URL('src/data/homeCountries.js', root);
const round = (value) => Math.round(value * 10) / 10;
/** ISO 6709 `±DDMM[SS]±DDDMM[SS]` → [lat, lon]. */
function iso6709(text) {
const [, lat, lon] = text.match(/^([+-]\d+)([+-]\d+)$/);
const part = (s, degreeDigits) => {
const sign = s[0] === '-' ? -1 : 1;
const d = s.slice(1);
const deg = Number(d.slice(0, degreeDigits));
const min = Number(d.slice(degreeDigits, degreeDigits + 2));
const sec = Number(d.slice(degreeDigits + 2) || 0);
return sign * (deg + min / 60 + sec / 3600);
};
return [part(lat, 2), part(lon, 3)];
}
const largest = new Map();
for (const feature of pack.features) {
if (feature.type !== 'Country' || !/^[A-Z]{2}$/.test(feature.iso2)) continue;
const geometry = geometryOf({ feature, decimals: pack.meta.decimals });
const held = largest.get(feature.iso2);
if (!held || geometry.areaKm2 > held.areaKm2)
largest.set(feature.iso2, geometry);
}
const zones = new Map();
const centres = new Map();
const icuName = (zone) => {
try {
return new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions()
.timeZone;
} catch {
return null;
}
};
for (const line of readFileSync(zoneTab, 'utf8').split('\n')) {
if (!line || line.startsWith('#')) continue;
const [country, place, zone] = line.split('\t');
zones.set(zone, country);
const icu = icuName(zone);
if (icu && icu !== zone && !zones.has(icu)) zones.set(icu, country);
if (centres.has(country)) continue;
const label = largest.get(country)?.label;
centres.set(
country,
label ? [round(label.lat), round(label.lon)] : iso6709(place).map(round),
);
}
const sortedEntries = (map) =>
[...map].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
const lines = [
'// Generated by scripts/build-home-countries.mjs. Do not edit by hand.',
'// Sources: tzdata zone.tab (public domain) and the Natural Earth countries',
'// pack in src/data/local_data/natural_earth (public domain).',
'',
'/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */',
'export const COUNTRY_CENTRES = {',
...sortedEntries(centres).map(
([country, [lat, lon]]) => ` ${country}: [${lat}, ${lon}],`,
),
'};',
'',
'/** Time zone (tzdata and ICU names) → ISO 3166 country. */',
'export const ZONE_COUNTRIES = {',
...sortedEntries(zones).map(
([zone, country]) => ` '${zone}': '${country}',`,
),
'};',
'',
];
writeFileSync(out, lines.join('\n'));
console.log(
`${fileURLToPath(out)}: ${centres.size} countries, ${zones.size} zones`,
);
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env node
/**
* build-view-sheet.mjs: bake a view sheet (aircraft or vessels) and ship it.
*
* Runs `scripts/bake-view-sheet.py` in Blender (headless) into a scratch
* directory, then writes the sheet to `public/sprites/` as
* `<name>.webp` (lossless WebP of the baked PNG) and `<name>.json` (its
* manifest): `aircraft-views` or `vessel-views`. See
* `public/sprites/README.md`.
*
* Run: node scripts/build-view-sheet.mjs --sheet aircraft|vessels
* [--only airliner,light] [--out public/sprites]
* (npm run build:aircraft-views, npm run build:vessel-views)
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
const SHEET = opt('--sheet', null);
if (SHEET !== 'aircraft' && SHEET !== 'vessels')
throw new Error('--sheet is aircraft or vessels');
// A bake of some subjects leaves the others' cells empty: it is for looking
// at, never for the sheet the app loads.
if (ONLY && !argv.includes('--out'))
throw new Error(
'--only bakes part of a sheet: give it its own --out, not public/sprites',
);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
const which = spawnSync('which', ['blender'], { encoding: 'utf8' });
if (which.status === 0 && which.stdout.trim()) return which.stdout.trim();
const mac = '/Applications/Blender.app/Contents/MacOS/Blender';
if (fs.existsSync(mac)) return mac;
throw new Error('no Blender: set BLENDER to its executable');
}
/**
* Refuse a sheet the manifest calls grey whose red, green and blue differ
* anywhere: the renderer reads its red channel as the grey.
*/
async function assertGrey(file) {
const { data, info } = await sharp(file)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
for (let i = 0; i < data.length; i += info.channels)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
const pixel = i / info.channels;
throw new Error(
`the sheet is not grey at (${pixel % info.width}, ${Math.floor(pixel / info.width)})`,
);
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'view-sheet-'));
try {
const bake = spawnSync(
blender(),
[
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'bake-view-sheet.py'),
'--',
'--sheet',
SHEET,
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
],
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' },
);
for (const line of bake.stdout.split('\n'))
if (/^(baked|wrote)\b/.test(line)) console.log(line);
if (bake.status !== 0) {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const [json] = fs.readdirSync(scratch).filter((f) => f.endsWith('.json'));
const name = path.basename(json, '.json');
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, json), 'utf8'),
);
const png = path.join(scratch, `${name}.png`);
if (manifest.grey) await assertGrey(png);
fs.mkdirSync(OUT, { recursive: true });
const webp = path.join(OUT, manifest.image);
await sharp(png)
.webp({ lossless: true, effort: 6, exact: true })
.toFile(webp);
fs.copyFileSync(path.join(scratch, json), path.join(OUT, json));
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
fs.rmSync(scratch, { recursive: true, force: true });
}
+65 -30
View File
@@ -68,7 +68,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1303,7 +1304,8 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js"
"src/layers/satellites/tiangongMounts.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1715,7 +1717,8 @@
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js"
"src/ui/liveControls.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -1919,7 +1922,8 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/scenes/storyTags.js",
"src/scenes/storyThumb.js"
"src/scenes/storyThumb.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
},
@@ -2086,7 +2090,9 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js"
"src/data/courseFromFixes.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2232,7 +2238,9 @@
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/approxDistance.js"
"src/data/approxDistance.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2390,7 +2398,9 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js"
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2521,7 +2531,8 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/sky/assets.js",
"src/render/cesium/cardPreviews.js"
"src/render/cesium/cardPreviews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2619,7 +2630,8 @@
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/time/frameWait.js"
"src/time/frameWait.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2771,7 +2783,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2894,7 +2907,8 @@
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
"src/layers/satellites/tiangongArticulation.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -2998,7 +3012,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3110,7 +3125,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3192,7 +3208,8 @@
"src/data/installationFeedback.js",
"src/ui/layerNames.js",
"src/render/cesium/zoomOutGuard.js",
"src/ui/statusText.js"
"src/ui/statusText.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3318,7 +3335,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3512,7 +3530,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3642,7 +3661,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -3735,7 +3755,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3847,7 +3868,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3922,7 +3944,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -4063,7 +4086,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -4303,7 +4327,6 @@
"src/render/contract/index.js",
"src/sources/sourceSlot.js",
"src/app/sources.js",
"src/app/openingIntro.js",
"src/app/startupChrome.js",
"src/app/stateChannel.js",
"src/app/surfaceServices.js",
@@ -5598,7 +5621,10 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6454,7 +6480,10 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js"
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6603,7 +6632,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -6717,7 +6747,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -7552,7 +7583,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
},
@@ -7682,7 +7714,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "kdbush"]
},
@@ -7994,7 +8027,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -8443,7 +8477,8 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/render/recession.js",
"src/render/modelParts.js"
"src/render/modelParts.js",
"src/data/viewSheet.js"
],
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
},
+382
View File
@@ -0,0 +1,382 @@
#!/usr/bin/env node
/**
* qa-aircraft-views.mjs: screenshots of the aircraft view sheet in the app.
*
* Seeds a grid of synthetic military contacts (every icon class down the
* rows, eight courses across) through a fetch shim, then photographs it from
* straight above, tilted from several sides and from below, so a person can
* check that each sprite shows its aircraft from where the camera is: the
* nose along the course, the far wing foreshortened, the underside from
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights|vessels] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
import fs from 'node:fs';
import path from 'node:path';
import puppeteer from 'puppeteer';
import { stubPlanespotters } from './qa-photo-stub.mjs';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const APP_URL = opt('--url', 'http://localhost:4173');
const OUT = path.resolve(opt('--out', 'qa-shots/views'));
const HEADFUL = argv.includes('--headful');
// `military` (amber, every class by type code), `flights` (white, the
// classes an ADS-B emitter category gives) or `vessels` (every hull kind by
// AIS ship type, at sea level).
const LAYER = opt('--layer', 'military');
const VESSELS = LAYER === 'vessels';
// The app's id of the layer.
const LAYER_ID = VESSELS ? 'ais-live-vessels' : LAYER;
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
// A type code for each icon class (aircraftClass.js).
const CLASSES = [
['airliner', 'A320'],
['widebody', 'C17'],
['quadjet', 'B744'],
['turboprop', 'C130'],
['light', 'C172'],
['glider', 'DISC'],
['fastjet', 'F16'],
['bizjet', 'GLF4'],
['uav', 'Q9'],
['helicopter', 'H60'],
];
// The classes a flight's emitter category gives (OpenSky has no type code).
const CATEGORIES = [
['airliner', 4],
['widebody', 6],
['light', 2],
['fastjet', 7],
['glider', 9],
['helicopter', 8],
];
// An AIS ship type for each hull kind (vesselTypes.js).
const HULLS = [
['cargo', 70],
['tanker', 80],
['passenger', 60],
['highspeed', 40],
['fishing', 30],
['tug', 52],
['sailing', 36],
['pleasure', 37],
['military', 35],
['other', 90],
['dredger', 33],
['pilot', 50],
];
const ROWS = VESSELS ? HULLS : LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
// Aircraft over Austin; vessels on open water in the North Sea.
const CENTRE = VESSELS ? { lon: 3.2, lat: 52.6 } : { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = VESSELS ? 0 : 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
COURSES.forEach((courseDeg, column) =>
contacts.push({
hex: `ee${row.toString(16)}${column.toString(16)}00`.slice(0, 6),
flight: `${klass.slice(0, 4).toUpperCase()}${courseDeg}`,
t: type,
klass,
courseDeg,
lon: CENTRE.lon + (column - (COURSES.length - 1) / 2) * STEP_DEG,
lat: CENTRE.lat - (row - (ROWS.length - 1) / 2) * STEP_DEG,
altFt: ALT_FT,
}),
),
);
// Each shot: where the camera looks from. `heading` is the way it looks
// (degrees clockwise from north), `pitch` down from level, `rangeKm` from
// the grid's centre at the contacts' height.
const SHOTS = [
{ name: '1-above', heading: 0, pitch: -90, rangeKm: 44 },
{ name: '2-tilt30-north', heading: 0, pitch: -60, rangeKm: 46 },
{ name: '3-tilt55-north', heading: 0, pitch: -35, rangeKm: 50 },
{ name: '4-tilt55-east', heading: 90, pitch: -35, rangeKm: 50 },
{ name: '5-tilt55-southwest', heading: 225, pitch: -35, rangeKm: 50 },
{ name: '6-tilt75-north', heading: 0, pitch: -15, rangeKm: 52 },
// From below, looking up at the grid; a vessel is never seen from there,
// so vessels get a shot from just above the water in its place.
VESSELS
? { name: '7-horizon-north', heading: 0, pitch: -5, rangeKm: 30 }
: { name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
];
// `--orbit`: the camera swung round the grid a little at a time, a frame
// each step, to watch the sprites turn from one view to the next.
const ORBIT_STEP_DEG = Number(opt('--orbit-step', 2));
const ORBIT_SHOTS = Array.from(
{ length: Math.floor(90 / ORBIT_STEP_DEG) + 1 },
(_, i) => ({
name: `orbit-${String(i).padStart(3, '0')}`,
heading: i * ORBIT_STEP_DEG,
pitch: Number(opt('--orbit-pitch', -35)),
rangeKm: 50,
settleMs: i === 0 ? 6000 : 900,
}),
);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
fs.mkdirSync(OUT, { recursive: true });
const browser = await puppeteer.launch({
headless: HEADFUL ? false : 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
...(GPU ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
'--disable-web-security',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--window-size=1500,1000',
],
});
const errors = [];
try {
const page = await browser.newPage();
await stubPlanespotters(page);
await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 2 });
page.on('console', (msg) => {
if (
msg.type() === 'error' &&
!/Failed to load resource/i.test(msg.text())
)
errors.push(msg.text());
});
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
if (BLOCK_SHEET) {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/[a-z]+-views\./.test(request.url())) request.abort();
else request.continue();
});
}
await page.evaluateOnNewDocument(
(seed) => {
const realFetch = window.fetch.bind(window);
// Each contact flies its course, slowly: a feed whose fixes stand
// still while claiming a track makes the layers work a heading out
// of no movement, and the contacts turn north over a run.
const SPEED_MPS = 6;
const started = Date.now();
const at = (c) => {
const flown = (SPEED_MPS * (Date.now() - started)) / 1000;
const course = (c.courseDeg * Math.PI) / 180;
return {
lat: c.lat + (flown * Math.cos(course)) / 111320,
lon:
c.lon +
(flown * Math.sin(course)) /
(111320 * Math.cos((c.lat * Math.PI) / 180)),
};
};
const json = (body) =>
new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
window.fetch = (input, init) => {
const url =
typeof input === 'string' ? input : (input && input.url) || '';
if (url.includes('/api/openai/hud-summary'))
return Promise.resolve(json({ summary: 'view QA' }));
if (url.includes('/api/military/track'))
return Promise.resolve(
json({ timestamp: Math.floor(Date.now() / 1000), trace: [] }),
);
if (url.includes('/api/military'))
return Promise.resolve(
json({
msg: 'No error',
now: Date.now(),
ac: (seed.layer === 'military' ? seed.contacts : []).map(
(c) => ({
hex: c.hex,
flight: c.flight,
...at(c),
alt_baro: c.altFt,
track: c.courseDeg,
gs: SPEED_MPS * 1.9438,
t: c.t,
r: `QA-${c.hex.slice(-3)}`,
ownOp: 'QA',
seen_pos: 0,
}),
),
}),
);
if (url.includes('/api/vessels') && seed.layer === 'vessels') {
const now = Date.now();
return Promise.resolve(
json({
rows: seed.contacts.map((c, i) => ({
...at(c),
name: c.flight,
mmsi: String(235000000 + i),
imo: '0',
type: String(c.t),
destination: 'QA',
length: 120,
beam: 20,
speed: SPEED_MPS * 1.9438,
course: c.courseDeg,
heading: c.courseDeg,
last_position_UTC: new Date(now).toISOString(),
last_position_epoch: Math.floor(now / 1000),
})),
source: 'AISStream',
status: 'live',
error: null,
refreshing: false,
newestPositionAt: now,
lastMessageAt: now,
silentForMs: 0,
reconnectAttempt: 0,
nextAttemptAt: null,
staleAfterMs: 120000,
watchdog: 'armed',
}),
);
}
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
const now = Math.floor(Date.now() / 1000);
return Promise.resolve(
json({
time: now,
states: seed.contacts.map((c) => [
c.hex,
c.flight,
'QA',
now,
now,
at(c).lon,
at(c).lat,
c.altFt * 0.3048,
false,
SPEED_MPS,
c.courseDeg,
0,
null,
null,
null,
false,
0,
c.t,
]),
}),
);
}
if (url.includes('/api/adsbdb/'))
return Promise.resolve(json({ found: false }));
return realFetch(input, init);
};
},
{ layer: LAYER, contacts },
);
console.log(`Loading ${APP_URL} ...`);
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForFunction(
() => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager,
{ timeout: 60000, polling: 200 },
);
const seeded = await page.evaluate(
async (name, centre) => {
const { dataManager, viewer } = window.__godsEyeView;
// Over the grid first: a layer may ask only for what is in view.
const Cartesian3 = viewer.camera.position.constructor;
viewer.camera.setView({
destination: Cartesian3.fromDegrees(centre.lon, centre.lat, 60000),
});
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) {
await layer.update(viewer);
await new Promise((resolve) => setTimeout(resolve, 500));
}
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
},
LAYER_ID,
CENTRE,
);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
`the ${LAYER} layer took ${seeded} of ${contacts.length} contacts`,
);
// Past the layer's render delay, so every contact is drawn.
await sleep(20000);
for (const shot of argv.includes('--orbit') ? ORBIT_SHOTS : SHOTS) {
await page.evaluate(
({ shot, centre, altM }) => {
const { viewer } = window.__godsEyeView;
const Cartesian3 = viewer.camera.position.constructor;
const heading = (shot.heading * Math.PI) / 180;
const pitch = (shot.pitch * Math.PI) / 180;
const range = shot.rangeKm * 1000;
// The eye sits `range` back along the way it looks.
const east = -range * Math.sin(heading) * Math.cos(pitch);
const north = -range * Math.cos(heading) * Math.cos(pitch);
const up = -range * Math.sin(pitch);
const lat = centre.lat + north / 111320;
const lon =
centre.lon +
east / (111320 * Math.cos((centre.lat * Math.PI) / 180));
viewer.camera.setView({
destination: Cartesian3.fromDegrees(
lon,
lat,
Math.max(50, altM + up),
),
orientation: { heading, pitch, roll: 0 },
});
viewer.scene.requestRender();
},
{ shot, centre: CENTRE, altM: ALT_FT * 0.3048 },
);
await sleep(shot.settleMs ?? 6000);
// The globe's own canvas, read right after a render: no HUD, dialogs
// or label overlays in the way.
const png = await page.evaluate(() => {
const { viewer } = window.__godsEyeView;
viewer.scene.render();
return viewer.scene.canvas.toDataURL('image/png');
});
const file = path.join(OUT, `${shot.name}.png`);
fs.writeFileSync(file, Buffer.from(png.split(',')[1], 'base64'));
console.log(` wrote ${file}`);
}
} finally {
await browser.close();
}
if (errors.length) {
console.log(`\nConsole errors (${errors.length}):`);
for (const error of errors.slice(0, 20)) console.log(` ${error}`);
process.exitCode = 1;
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env node
/**
* qa-view-sheet.mjs: contact sheets of a baked view sheet (aircraft or
* vessels), for reviewing a bake (`scripts/bake-view-sheet.py`) before it
* ships.
*
* For each subject it writes one image: its frames with the rings as rows
* (straight above at the top, the last ring at the bottom, each ring from
* dead ahead to dead astern), in white, over three grounds the subject is
* seen over. Under them, a few frames (above, oblique, abeam, and below or
* low on the horizon) shrunk to the sizes a contact is drawn at, in each
* tint the layers draw it with, to judge whether thin wings and hulls still
* read. Aircraft: a dark sea, pale land and a mid satellite tone; the fleet,
* tracked and military tints. Vessels: a dark sea, pale shallow water and a
* satellite ocean tone; white and the colour of each kind the subject is
* drawn for (`VESSEL_KIND_STYLES`).
*
* Run: node scripts/qa-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/<name>] [--zoom 2] [--sizes 40,30,20]
* [--only airliner,glider]
* `--sheet` defaults to the manifest's `image`, next to it.
*/
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
import { VESSEL_KIND_STYLES } from '../src/data/vesselTypes.js';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const MANIFEST = path.resolve(
opt('--manifest', 'public/sprites/aircraft-views.json'),
);
const ZOOM = Number(opt('--zoom', '2'));
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
const ONLY = opt('--only', '').split(',').filter(Boolean);
const GAP = 8;
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
const VESSELS = manifest.image.startsWith('vessel');
const OUT = path.resolve(
opt('--out', `qa-shots/${path.basename(manifest.image, '.webp')}`),
);
const WHITE = { name: 'white', rgb: [1, 1, 1] };
/** `#rrggbb` as 0..1 channels. */
const rgbOf = (css) =>
[1, 3, 5].map((i) => parseInt(css.slice(i, i + 2), 16) / 255);
/** Grounds a contact is seen over. */
const GROUNDS = VESSELS
? [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'shallows', css: '#8fc3c1' },
{ name: 'satellite', css: '#0f2e44' },
]
: [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The kinds a vessel shape that is not a kind of its own is coloured as: a
* vessel takes its kind's colour (`vesselKind`), whatever its shape. */
const SHAPE_KINDS = { dredger: ['other'], pilot: ['tug', 'military'] };
/** A subject's tints, multiplied into the neutral sprite as the layers do. */
const tintsOf = (name) =>
VESSELS
? [
WHITE,
...(SHAPE_KINDS[name] ?? [name]).map((kind) => ({
name: kind,
rgb: rgbOf(VESSEL_KIND_STYLES[kind].css),
})),
]
: [
WHITE,
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
const { cellPx: cell, columns, rings } = manifest;
const firsts = [];
rings.reduce((at, count) => (firsts.push(at), at + count), 0);
const widest = Math.max(...rings);
/** The ring nearest `offDeg` from straight above. */
const ringAt = (offDeg) =>
Math.min(rings.length - 1, Math.round(offDeg / manifest.ringStepDeg));
const last = rings.length - 1;
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and the last ring from
* below abeam or, if the last ring is the horizon, from the bow quarter. */
const PICKS = [
[0, 0],
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
last === ringAt(90)
? [last, Math.round((rings[last] - 1) / 4)]
: [last, Math.round((rings[last] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
const { data: pixels, info } = await sheet
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
/** One cell as raw RGBA, tinted. */
function cellPixels(index, tint) {
const out = Buffer.alloc(cell * cell * 4);
const left = (index % columns) * cell;
const top = Math.floor(index / columns) * cell;
for (let y = 0; y < cell; y++)
for (let x = 0; x < cell; x++) {
const from = ((top + y) * info.width + left + x) * 4;
const to = (y * cell + x) * 4;
for (let c = 0; c < 3; c++)
out[to + c] = Math.round(pixels[from + c] * tint.rgb[c]);
out[to + 3] = pixels[from + 3];
}
return out;
}
async function cellImage(index, tint, size) {
let image = sharp(cellPixels(index, tint), {
raw: { width: cell, height: cell, channels: 4 },
});
if (size !== cell) image = image.resize(size, size, { kernel: 'lanczos3' });
else if (ZOOM !== 1)
image = image.resize(cell * ZOOM, cell * ZOOM, { kernel: 'nearest' });
return image.png().toBuffer();
}
async function subjectSheet(name, first) {
const TINTS = tintsOf(name);
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
const stripH = Math.max(...SIZES) + GAP;
const blockH = panelH + GAP + TINTS.length * stripH;
const width = GROUNDS.length * (panelW + GAP) + GAP;
const height = blockH + 2 * GAP;
const layers = [];
for (const [g, ground] of GROUNDS.entries()) {
const x0 = GAP + g * (panelW + GAP);
layers.push({
input: {
create: {
width: panelW,
height: blockH,
channels: 4,
background: ground.css,
},
},
left: x0,
top: GAP,
});
// Rings as rows, white.
for (let ring = 0; ring < rings.length; ring++)
for (let i = 0; i < rings[ring]; i++)
layers.push({
input: await cellImage(first + firsts[ring] + i, WHITE, cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});
// The picked frames shrunk to drawn sizes, one row a tint.
for (const [t, tint] of TINTS.entries()) {
let x = x0 + GAP;
const y = GAP + panelH + GAP + t * stripH;
for (const [ring, index] of PICKS)
for (const size of SIZES) {
layers.push({
input: await cellImage(first + firsts[ring] + index, tint, size),
left: x,
top: y + (stripH - GAP - size),
});
x += size + 4;
}
}
}
const file = path.join(OUT, `${name}.png`);
await sharp({
create: { width, height, channels: 4, background: '#111111' },
})
.composite(layers)
.png()
.toFile(file);
return file;
}
fs.mkdirSync(OUT, { recursive: true });
for (const [name, entry] of Object.entries(manifest.subjects)) {
if (ONLY.length && !ONLY.includes(name)) continue;
const first = typeof entry === 'number' ? entry : entry.first;
console.log('wrote', await subjectSheet(name, first));
}
-281
View File
@@ -1,281 +0,0 @@
import { cameraOf } from '../render/rendererOf.js';
/**
* The opening: once the world has loaded, the loading screen's logo turns
* into the globe. The words fade and the logo glides to the centre; the eye's
* arcs fly at the viewer; the drawn planet in the pupil gives way to the real
* one, drawn the same size behind it; the real one spins and grows, slowing
* until it stops, the whole planet in view, over the start view (the
* visitor's country). Everything is timed from one clock, in ms.
*/
export const OPENING = Object.freeze({
/** The words fade and the logo moves to the centre. */
centreMs: 450,
// The rest is timed from the end of the move.
/** The arcs grow and fade. */
arcsMs: 700,
/** The background clears to the globe. */
veilMs: Object.freeze([200, 700]),
/** The drawn planet fades into the real one. */
pupilMs: Object.freeze([500, 1100]),
/** The camera's flight in. */
flightStartMs: 300,
flightMs: 4200,
/** How far the globe turns on the way in, degrees. */
spinDeg: 360,
});
const EARTH_RADIUS_M = 6371000;
// logo.svg: its viewBox width and the drawn planet's radius, in its units.
const LOGO_WIDTH = 775;
const PUPIL_RADIUS = 120.33;
/** Never start further out than this, metres. */
const MAX_FAR_HEIGHT_M = 4e8;
/** Openings in progress on this page. */
let playing = 0;
/**
* Whether an opening is playing: the far start shows the globe as a speck,
* which the globe-in-view recovery would otherwise turn the camera back to.
*/
export function openingPlaying() {
return playing > 0;
}
const clamp01 = (x) => Math.min(1, Math.max(0, x));
const easeInCubic = (x) => x ** 3;
const easeOutCubic = (x) => 1 - (1 - x) ** 3;
const easeInOutCubic = (x) =>
x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
const span = (t, [from, to]) => clamp01((t - from) / (to - from));
/**
* Where each part of the opening stands `t` ms after it starts.
* @param {number} t
*/
export function openingStage(t, timing = OPENING) {
const move = clamp01(t / timing.centreMs);
const after = t - timing.centreMs;
const arcs = easeInCubic(clamp01(after / timing.arcsMs));
const flight = clamp01((after - timing.flightStartMs) / timing.flightMs);
return {
/** The words' opacity. */
text: 1 - move,
/** How far the logo has moved to the centre, 0–1. */
centre: easeInOutCubic(move),
arcsScale: 1 + 5 * arcs,
arcsOpacity: 1 - arcs,
/** The loading screen's background opacity. */
veil: 1 - span(after, timing.veilMs),
pupilOpacity: 1 - span(after, timing.pupilMs),
/** The flight's progress, 0–1. */
flight,
done: flight >= 1,
};
}
/**
* The camera `flight` (0–1) of the way in: from `farHeight` over the
* equator, a turn of `spinDeg` west to east that slows to a stop over
* `target`, closing in on `target.height`.
*/
export function openingPose(
flight,
{ target, farHeight, spinDeg = OPENING.spinDeg },
) {
const f = clamp01(flight);
const closing = easeInOutCubic(f);
const height = Math.exp(
Math.log(farHeight) +
(Math.log(target.height) - Math.log(farHeight)) * closing,
);
const lon = target.lon + spinDeg * (1 - easeOutCubic(f));
return {
lon: ((((lon + 180) % 360) + 360) % 360) - 180,
lat: target.lat * closing,
height,
};
}
/**
* The globe's radius on screen, pixels, from `height` metres straight above
* it, through a lens of vertical angle `fovy` on a view `viewportHeight`
* pixels tall.
*/
export function globeRadiusPx(height, { fovy, viewportHeight }) {
const angle = Math.asin(EARTH_RADIUS_M / (EARTH_RADIUS_M + height));
return (Math.tan(angle) / Math.tan(fovy / 2)) * (viewportHeight / 2);
}
/** The height at which the globe's radius on screen is `radiusPx`. */
export function heightForGlobeRadius(radiusPx, { fovy, viewportHeight }) {
const tangent = (radiusPx * Math.tan(fovy / 2)) / (viewportHeight / 2);
return EARTH_RADIUS_M / Math.sin(Math.atan(tangent)) - EARTH_RADIUS_M;
}
/**
* Whether the page opens with the opening: not where motion is reduced, not
* on a Stories link (Stories opens its own view) and not with `?intro=0`.
*/
export function openingWanted(win = globalThis.window) {
if (!win) return false;
if (win.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
return false;
const params = new URLSearchParams(win.location?.search ?? '');
return !(
params.get('intro') === '0' ||
params.has('story') ||
params.has('stories')
);
}
/**
* Play the opening over `loadingScreen`, from where the camera stands (the
* start view). Returns null when it does not play; else `done`, which
* settles when the camera has stopped, and `cancel()`. A click, a key or the
* wheel skips to the start view; any other camera move stops it where it is. The loading
* screen is `hidden` once the real globe shows, or at once on a cancel.
* @param {{viewer: object, loadingScreen: HTMLElement, win?: Window,
* camera?: object}} options `camera` is the viewer's camera port unless given.
*/
export function playOpeningIntro({
viewer,
loadingScreen,
win = globalThis.window,
camera = null,
}) {
if (!openingWanted(win)) return null;
try {
camera ??= cameraOf(viewer);
} catch {
return null;
}
const target = camera.pose();
if (
!Number.isFinite(target?.height) ||
!Number.isFinite(target.lon) ||
!Number.isFinite(target.lat)
)
return null;
const doc = loadingScreen.ownerDocument;
const logo = loadingScreen.querySelector('.loader-logo');
const svg = logo?.querySelector('svg');
const part = (id) => svg?.querySelector(`#${id}`);
const arcs = [part('outer_eye'), part('inner_eye')].filter(Boolean);
// The drawn planet; the whole logo where it is an <img>.
const pupil = svg
? [part('globe'), part('globe_cage')].filter(Boolean)
: [logo].filter(Boolean);
loadingScreen.classList.add('opening');
playing += 1;
// The planet looks out of the middle of the eye again.
for (const element of pupil) element.style.transform = 'none';
const globe = part('globe');
const pupilRect = (globe ?? logo)?.getBoundingClientRect();
const view = (
doc.getElementById('cesiumContainer') ?? doc.documentElement
).getBoundingClientRect();
const viewportHeight = view.height || win.innerHeight;
const aspect = (view.width || win.innerWidth) / viewportHeight;
// Cesium's default lens: 60° across the wider side.
const fovy = Number.isFinite(target.fovy)
? target.fovy
: aspect > 1
? 2 * Math.atan(Math.tan(Math.PI / 6) / aspect)
: Math.PI / 3;
const lens = { fovy, viewportHeight };
const pupilRadius = pupilRect
? globe
? pupilRect.width / 2
: (pupilRect.width * PUPIL_RADIUS) / LOGO_WIDTH
: 20;
const farHeight = Math.min(
MAX_FAR_HEIGHT_M,
Math.max(target.height * 2, heightForGlobeRadius(pupilRadius, lens)),
);
const toCentre = pupilRect
? {
x: view.left + view.width / 2 - (pupilRect.left + pupilRect.width / 2),
y: view.top + view.height / 2 - (pupilRect.top + pupilRect.height / 2),
}
: { x: 0, y: 0 };
const startRadius = globeRadiusPx(farHeight, lens);
let driving = false;
const place = (pose, heading = 0, pitch = -Math.PI / 2) => {
driving = true;
try {
camera.setView({
destination: pose,
orientation: { heading, pitch, roll: 0 },
});
} finally {
driving = false;
}
};
let resolveDone;
const done = new Promise((resolve) => {
resolveDone = resolve;
});
let frame = 0;
let finished = false;
const hide = () => loadingScreen.classList.add('hidden');
const stopCommands = camera.onCommand?.(() => {
if (!driving) finish();
});
const inputs = ['pointerdown', 'wheel', 'keydown', 'touchstart'];
// The person's own input skips to the end; another camera move stops it.
const onInput = () => finish({ land: true });
for (const type of inputs)
win.addEventListener(type, onInput, { capture: true, passive: true });
function finish({ land = false } = {}) {
if (finished) return;
finished = true;
playing -= 1;
if (frame) win.cancelAnimationFrame(frame);
stopCommands?.();
for (const type of inputs)
win.removeEventListener(type, onInput, { capture: true });
if (land)
place(
{ lon: target.lon, lat: target.lat, height: target.height },
target.heading ?? 0,
target.pitch ?? -Math.PI / 2,
);
hide();
resolveDone();
}
const start = win.performance.now();
const step = () => {
frame = 0;
if (finished) return;
const stage = openingStage(win.performance.now() - start);
if (stage.done) {
finish({ land: true });
return;
}
const pose = openingPose(stage.flight, { target, farHeight });
place(pose);
const scale = globeRadiusPx(pose.height, lens) / startRadius;
loadingScreen.style.setProperty('--opening-text', stage.text);
loadingScreen.style.setProperty('--opening-veil', stage.veil);
if (logo)
logo.style.transform = `translate(${toCentre.x * stage.centre}px, ${
toCentre.y * stage.centre
}px) scale(${scale})`;
for (const element of arcs) {
element.style.transform = `scale(${stage.arcsScale})`;
element.style.opacity = stage.arcsOpacity;
}
for (const element of pupil) element.style.opacity = stage.pupilOpacity;
if (stage.pupilOpacity === 0) hide();
frame = win.requestAnimationFrame(step);
};
step();
return { done, cancel: () => finish() };
}
-184
View File
@@ -1,184 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Window } from 'happy-dom';
import {
OPENING,
globeRadiusPx,
heightForGlobeRadius,
openingPlaying,
openingPose,
openingStage,
openingWanted,
playOpeningIntro,
} from './openingIntro.js';
const LENS = { fovy: Math.PI / 4, viewportHeight: 800 };
const TARGET = { lon: 10.4, lat: 51.1, height: 23e6, heading: 0, pitch: -1 };
const LANDED = { lon: TARGET.lon, lat: TARGET.lat, height: TARGET.height };
const END_MS = OPENING.centreMs + OPENING.flightStartMs + OPENING.flightMs + 1;
test('the arcs fly out and the words fade before the globe arrives', () => {
const start = openingStage(0);
assert.equal(start.text, 1);
assert.equal(start.veil, 1);
assert.equal(start.pupilOpacity, 1);
assert.equal(start.flight, 0);
const centred = openingStage(OPENING.centreMs);
assert.equal(centred.text, 0);
assert.equal(centred.centre, 1);
const arcsGone = openingStage(OPENING.centreMs + OPENING.arcsMs);
assert.equal(arcsGone.arcsOpacity, 0);
assert.ok(arcsGone.arcsScale > 5);
const real = openingStage(OPENING.centreMs + OPENING.pupilMs[1]);
assert.equal(real.pupilOpacity, 0);
assert.equal(real.veil, 0);
assert.ok(real.flight > 0 && real.flight < 1);
assert.equal(openingStage(END_MS).done, true);
});
test('the flight turns west to east, slows and stops over the target', () => {
const far = 4e8;
const start = openingPose(0, { target: TARGET, farHeight: far });
assert.ok(Math.abs(start.height - far) < 1);
assert.equal(start.lat, 0);
const end = openingPose(1, { target: TARGET, farHeight: far });
assert.ok(Math.abs(end.lon - TARGET.lon) < 1e-9);
assert.ok(Math.abs(end.lat - TARGET.lat) < 1e-9);
assert.ok(Math.abs(end.height - TARGET.height) < 1e-3);
// Unwrapped longitude falls all the way (the camera moves west, so the
// surface turns east), fastest at first.
let previous = Infinity;
let previousStep = Infinity;
for (let i = 0; i <= 10; i++) {
const f = i / 10;
const unwrapped = TARGET.lon + OPENING.spinDeg * (1 - (1 - (1 - f) ** 3));
assert.ok(unwrapped <= previous);
if (i > 0) {
const step = previous - unwrapped;
assert.ok(step <= previousStep + 1e-9, 'the turn slows');
previousStep = step;
}
previous = unwrapped;
const pose = openingPose(f, { target: TARGET, farHeight: far });
assert.ok(pose.lon >= -180 && pose.lon < 180);
}
});
test('the far start draws the globe the size of the pupil', () => {
for (const radius of [12, 20, 64]) {
const height = heightForGlobeRadius(radius, LENS);
assert.ok(Math.abs(globeRadiusPx(height, LENS) - radius) < 1e-6);
}
assert.ok(globeRadiusPx(4e8, LENS) < globeRadiusPx(23e6, LENS));
});
test('reduced motion, Stories links and ?intro=0 open without it', () => {
const win = (search, reduced = false) => ({
location: { search },
matchMedia: () => ({ matches: reduced }),
});
assert.equal(openingWanted(win('')), true);
assert.equal(openingWanted(win('', true)), false);
assert.equal(openingWanted(win('?intro=0')), false);
assert.equal(openingWanted(win('?story=abc')), false);
assert.equal(openingWanted(win('?stories')), false);
assert.equal(openingWanted(win('?intro=1')), true);
});
// A loading screen and a camera port; the test runs the frames by hand.
function stage() {
const window = new Window({ width: 1280, height: 800 });
const doc = window.document;
doc.body.innerHTML = `
<div id="cesiumContainer"></div>
<div id="loading-screen"><span class="loader-logo"><svg>
<path id="outer_eye"/><path id="inner_eye"/>
<path id="globe"/><path id="globe_cage"/>
</svg></span></div>`;
const screen = doc.getElementById('loading-screen');
let now = 0;
let frames = [];
window.performance.now = () => now;
window.requestAnimationFrame = (fn) => frames.push(fn);
window.cancelAnimationFrame = () => {
frames = [];
};
window.matchMedia = () => ({ matches: false });
const views = [];
const commandListeners = new Set();
const camera = {
pose: () => ({ ...TARGET, fovy: Math.PI / 4 }),
setView(spec) {
views.push(spec);
for (const cb of commandListeners) cb({ kind: 'setView' });
},
onCommand(cb) {
commandListeners.add(cb);
return () => commandListeners.delete(cb);
},
};
return {
window,
screen,
views,
camera,
commandListeners,
play: () =>
playOpeningIntro({
viewer: {},
loadingScreen: screen,
win: window,
camera,
}),
advance(ms) {
now += ms;
const run = frames;
frames = [];
for (const fn of run) fn();
},
otherMove: () => {
for (const cb of [...commandListeners]) cb({ kind: 'flyTo' });
},
};
}
test('the opening runs to the start view, then hides the cover', async () => {
const s = stage();
const opening = s.play();
assert.ok(opening);
assert.equal(openingPlaying(), true);
assert.ok(s.screen.classList.contains('opening'));
assert.ok(s.views[0].destination.height > TARGET.height * 2, 'far start');
s.advance(OPENING.centreMs + OPENING.pupilMs[1]);
assert.ok(s.screen.classList.contains('hidden'));
s.advance(OPENING.flightMs);
await opening.done;
const last = s.views.at(-1);
assert.deepEqual(last.destination, LANDED);
assert.equal(last.orientation.pitch, TARGET.pitch);
assert.equal(openingPlaying(), false);
assert.equal(s.commandListeners.size, 0);
});
test("the person's input skips to the start view", async () => {
const s = stage();
const opening = s.play();
s.advance(2000);
s.window.dispatchEvent(new s.window.Event('keydown'));
await opening.done;
assert.deepEqual(s.views.at(-1).destination, LANDED);
assert.ok(s.screen.classList.contains('hidden'));
assert.equal(openingPlaying(), false);
});
test('another camera move stops it where it is', async () => {
const s = stage();
const opening = s.play();
s.advance(2000);
const count = s.views.length;
s.otherMove();
await opening.done;
s.advance(1000);
assert.equal(s.views.length, count, 'no more frames');
assert.ok(s.screen.classList.contains('hidden'));
});
+1 -15
View File
@@ -1,9 +1,6 @@
import { initFirstRunExperience } from '../firstRunExperience.js';
/**
* Reveal welcome controls only after restoration and the loading transition.
* `playOpening` plays the opening on a bare address (src/app/openingIntro.js).
*/
/** Reveal welcome controls only after restoration and the loading transition. */
export function startApplicationChrome({
loadingScreen,
styleManager,
@@ -11,11 +8,9 @@ export function startApplicationChrome({
signal,
initializeWelcome = initFirstRunExperience,
initializeSettings,
playOpening = null,
}) {
let disposed = false;
let firstRun;
let opening = null;
let revealTimer;
let resolveDelay;
const minimumDelay = new Promise((resolve) => {
@@ -34,14 +29,6 @@ export function startApplicationChrome({
})
.then(() => {
if (disposed || signal.aborted) return;
// A bare address opens with the opening; welcome waits for its end.
opening = styleManager.hasShareState
? null
: playOpening?.({ viewer: styleManager.viewer, loadingScreen });
if (opening) {
void opening.done.then(revealFirstRun);
return;
}
loadingScreen.classList.add('hidden');
loadingScreen.addEventListener('transitionend', revealFirstRun, {
once: true,
@@ -57,7 +44,6 @@ export function startApplicationChrome({
);
return async () => {
disposed = true;
opening?.cancel();
clearTimeout(delayTimer);
clearTimeout(revealTimer);
resolveDelay();
+2 -4
View File
@@ -22,7 +22,6 @@ import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
import { createRecentImageryPanel } from '../ui/recentImagery.js';
import { createDataLibrary } from '../library/controller.js';
import { flyToLibraryExtent } from '../library/camera.js';
import { openingPlaying } from './openingIntro.js';
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
import { localGeoJsonServices } from './localGeojsonServices.js';
@@ -89,9 +88,8 @@ export function createApplicationTools({
installGlobeInViewRecovery(viewer, {
// The scope mask hides everything outside its keyhole.
keyholeRadius: () => (isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0),
// An authored scene frames its own shots, holds included, and the
// opening starts with the globe as a speck.
paused: () => sceneDirector.running || openingPlaying(),
// An authored scene frames its own shots, holds included.
paused: () => sceneDirector.running,
}),
);
onSceneDirector?.(sceneDirector);
+42 -12
View File
@@ -33,6 +33,7 @@ import {
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { rotorFrame, rotorTurns } from './rotorFrames.js';
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
@@ -436,6 +437,8 @@ function fixedDelay(ms) {
* Where a host-supplied placement draws a live contact at a wall time,
* written into `out` (`placeAircraftAt`), or null when it does not place
* it; none without a placement.
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
* URL resolver, for the aircraft view sheet's image.
*/
export function createAircraftIcons({
state,
@@ -453,10 +456,14 @@ export function createAircraftIcons({
afterSettle = () => {},
onForget = () => {},
placeAt = null,
resolveAsset = (url) => url,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** Whether the renderer draws icons along their course from the aircraft
* view sheet (`aircraftViews.js`), set when the draw set is made. */
let views = false;
/**
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
* frame each was last drawn at, and the frame it was last judged at
@@ -544,9 +551,9 @@ export function createAircraftIcons({
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
});
const capabilities = rendererOf(viewer)?.capabilities ?? null;
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
state._icons = createContactIcons(set, { capabilities });
return set.id;
}
@@ -555,6 +562,7 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
views = false;
rotors.clear();
planFrom.clear();
easeEnds.clear();
@@ -962,19 +970,26 @@ export function createAircraftIcons({
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
* one it switches to up close), size, scale and scale by distance. The
* tracked contact's own icon is drawn with this too, so selecting a contact
* changes its colour and nothing else.
* changes its colour and nothing else. Drawn along its course
* (`alongCourse`) on a renderer that draws view sheets, a kind with
* rendered views draws from the aircraft view sheet, with no near image
* (`aircraftViews.js`); otherwise it is the flat glyph.
* @param {string} icao24
* @param {object} [info] Its record.
* @returns {{image: string, imageLod: {near: string, switchPx: number},
* @param {number} [frame] A helicopter's rotor frame.
* @param {{alongCourse?: boolean}} [options]
* @returns {{image: string|{views: string, first: number},
* imageLod: {near: string, switchPx: number}|undefined,
* size: [number, number], scale: number, scaleByDistance: object}}
*/
function _fleetLook(
icao24,
info = state.records.data.get(icao24),
frame = _rotorFrameOf(icao24, info, Date.now()),
{ alongCourse = false } = {},
) {
const rendering = parts.rendering;
return {
const look = {
image: aircraftIcon(
rendering._iconKind(icao24, info?.klass),
FLEET_ICON_PX,
@@ -992,6 +1007,17 @@ export function createAircraftIcons({
scale: rendering._fleetBillboardScale(icao24),
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
};
return withAircraftView(look, {
views,
kind: rendering._iconKind(icao24, info?.klass),
frame,
rotationMode: alongCourse ? 'course' : undefined,
});
}
/** Whether contacts drawn along their course draw from the view sheet. */
function _drawsViews() {
return views;
}
/**
@@ -1051,6 +1077,7 @@ export function createAircraftIcons({
id,
state.records.data.get(id),
frame,
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
);
icons.update(id, { image, imageLod });
}
@@ -1064,6 +1091,11 @@ export function createAircraftIcons({
const rendering = parts.rendering;
const info = state.records.data.get(icao24);
const tracked = icao24 === state._trackedIcao;
// A helicopter's rotor frame, chosen once for its look and its rotor.
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
// A ground station's mast stands upright; every other glyph turns
// along its course.
const station = info?.klass === 'station';
const cockpitDot =
state._cockpitContactMode &&
!tracked &&
@@ -1079,21 +1111,18 @@ export function createAircraftIcons({
rotationMode: 'screen',
}
: {
..._fleetLook(icao24, info),
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
color: rgba(rendering._fleetBillboardColor(icao24, info)),
rotationMode: 'course',
};
// A ground station's mast stands upright.
if (!cockpitDot && info?.klass === 'station') {
if (!cockpitDot && station) {
look.rotationMode = 'screen';
look.rotation = 0;
}
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
icons.update(icao24, look);
// An airborne helicopter drawn as its glyph turns its rotor.
const frame = cockpitDot
? undefined
: _rotorFrameOf(icao24, info, Date.now());
const frame = cockpitDot ? undefined : heliFrame;
if (frame === undefined || !rotorTurns(_rotorState(info))) {
// A tracked helicopter that lands shows the still frame at once.
if (rotors.delete(icao24) && tracked)
@@ -1176,6 +1205,7 @@ export function createAircraftIcons({
_focusIcons,
_applyIconPresentation,
_fleetLook,
_drawsViews,
_turnRotors,
_rotorsTurning,
_addIcon,
+180
View File
@@ -481,3 +481,183 @@ 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,
);
});
/**
* An icon layer on a renderer that does (or does not) draw view sheets,
* over contacts `records` (by id), all held at one place.
*/
function viewsFixture(
records,
{ viewSheets = true, kinds = {}, resolveAsset } = {},
) {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer, {
capabilities: new Set(viewSheets ? ['viewSheets'] : []),
});
const state = {
_viewer: viewer,
now: () => Date.now(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (id, klass) => kinds[id] ?? klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1.25,
_cockpitContactColor: () => [1, 0, 0, 1],
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
resolveAsset,
});
icons._createIcons(viewer);
const here = fromDegrees(0, 30, 300);
for (const id of records.keys()) {
state._icons.put(
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons, registered: draw.viewSheets, here, unbind };
}
test('with view sheets, every aircraft class draws from the sheet along its course, with no near image', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const records = new Map([
['p1', { klass: 'airliner' }],
['p2', { klass: 'glider' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, icons, registered, unbind } = viewsFixture(records);
t.after(unbind);
assert.deepEqual(registered, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftViewRef('airliner'));
assert.equal(p1.imageLod, undefined);
assert.equal(p1.rotationMode, 'course');
// Everything else is as the flat glyph draws it.
assert.deepEqual(p1.size, [20, 20]);
assert.equal(p1.scale, 1.25);
assert.deepEqual(p1.color, [1, 1, 1, 1]);
assert.equal(p1.scaleByDistance.nearValue, 3);
assert.equal(state._icons.item('p2').image, aircraftViewRef('glider'));
assert.equal(
state._icons.item('h1').image,
aircraftViewRef('helicopter', ROTOR_STILL_FRAME),
);
// The plain fleet look (the tracked icon's sizing, a screen-rotated
// caller) stays the flat glyph.
assert.equal(
icons._fleetLook('p1').image,
aircraftIcon('airliner', FLEET_ICON_PX),
);
assert.equal(
icons._fleetLook('p1', undefined, undefined, { alongCourse: true }).image,
aircraftViewRef('airliner'),
);
assert.equal(icons._drawsViews(), true);
icons._disposeIcons();
assert.equal(icons._drawsViews(), false);
});
test('without view sheets the icons are the flat glyphs with their near image, as before', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['p1', { klass: 'airliner' }]]);
const { state, icons, registered, unbind } = viewsFixture(records, {
viewSheets: false,
});
t.after(unbind);
assert.deepEqual(registered, [], 'no sheet is registered');
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftIcon('airliner', FLEET_ICON_PX));
assert.equal(p1.imageLod.near, aircraftIcon('airliner', 192));
assert.equal(p1.rotationMode, 'course');
assert.equal(icons._drawsViews(), false);
});
test('with view sheets, the TR-3B, airport vehicles and ground stations stay flat', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['x1', { klass: 'airliner' }],
['v1', { klass: 'vehicle' }],
['s1', { klass: 'station' }],
]);
const { state, unbind } = viewsFixture(records, {
kinds: { x1: 'tr3b' },
});
t.after(unbind);
assert.equal(
state._icons.item('x1').image,
aircraftIcon('tr3b', FLEET_ICON_PX),
);
assert.ok(state._icons.item('x1').imageLod);
assert.equal(
state._icons.item('v1').image,
aircraftIcon('vehicle', FLEET_ICON_PX),
);
const mast = state._icons.item('s1');
assert.equal(mast.image, aircraftIcon('station', FLEET_ICON_PX));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('with view sheets, an airborne helicopter turns its rotor through the sheet’s three blocks', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
const { state, icons, unbind } = viewsFixture(records);
t.after(unbind);
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now());
const item = state._icons.item('h1');
assert.equal(item.imageLod, undefined);
seen.add(item.image);
}
assert.deepEqual(
new Set(seen),
new Set([0, 1, 2].map((frame) => aircraftViewRef('helicopter', frame))),
);
});
test('the layer registers the view sheet at its own asset URL', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const { registered, unbind } = viewsFixture(
new Map([['p1', { klass: 'airliner' }]]),
{ resolveAsset: (url) => `/gev/${url.replace(/^\//, '')}` },
);
t.after(unbind);
assert.equal(registered.length, 1);
assert.equal(registered[0][0], AIRCRAFT_VIEWS.id);
assert.equal(registered[0][1].image, '/gev/sprites/aircraft-views.webp');
});
test('a view carries the contact’s flat glyph as its fallback', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['p1', { klass: 'turboprop' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, unbind } = viewsFixture(records);
t.after(unbind);
assert.equal(
state._icons.item('p1').image.fallback,
aircraftIcon('turboprop', FLEET_ICON_PX),
);
assert.equal(
state._icons.item('h1').image.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
+138
View File
@@ -0,0 +1,138 @@
/**
* @module data/aircraftViews
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
* contact's icon draws from. Each aircraft class is rendered there from a
* sphere of camera angles; a renderer with the `viewSheets` capability lays
* the icon flat on the earth along its course and draws the view that
* matches where the eye is, so an oblique contact looks solid instead of
* like a paper cut-out. Only an icon drawn along its course
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
* airport vehicles, ground stations) keep their flat glyph as well.
*/
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import {
aircraftIcon,
FLEET_ICON_PX,
ROTOR_FRAMES,
ROTOR_STILL_FRAME,
} from './aircraftIcons.js';
/** The renderer capability that draws view sheets. */
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
/** Kinds drawn from the sheet with one block each (helicopters have three). */
const STILL_KINDS = new Set([
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
]);
/** One frozen image ref per block, so equal refs are the same object. */
const refs = new Map();
/**
* The ref of the block at `first`, with the flat glyph of `kind` (and its
* rotor `frame`) as its fallback: what the renderer draws until the sheet
* has loaded, and for good if it cannot load.
*/
function refAt(first, kind, frame) {
let ref = refs.get(first);
if (!ref) {
ref = Object.freeze({
views: AIRCRAFT_VIEWS.id,
first,
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
});
refs.set(first, ref);
}
return ref;
}
/**
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
* id, the first cell of the kind's block and its flat glyph (drawn while
* the sheet loads, or if it fails), or null for a kind with no views.
* @param {string} kind An icon kind (`rendering._iconKind`).
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame otherwise, as `aircraftIcon` takes it).
* @returns {{views: string, first: number, fallback: string}|null}
*/
export function aircraftViewRef(kind, frame) {
const subjects = AIRCRAFT_VIEWS.subjects;
if (kind === 'helicopter') {
const f =
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME;
const first = subjects[`helicopter${f}`];
return Number.isInteger(first) ? refAt(first, kind, f) : null;
}
if (!STILL_KINDS.has(kind)) return null;
const first = subjects[kind];
return Number.isInteger(first) ? refAt(first, kind) : null;
}
/** Whether an icon image is a view-sheet ref. */
export function isAircraftViewRef(image) {
return Boolean(image) && typeof image === 'object' && 'views' in image;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the aircraft view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerAircraftViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
if (!registered.has(drawPort)) {
const sheet = AIRCRAFT_VIEWS.sheet;
drawPort.views(AIRCRAFT_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
/**
* An icon's look drawn from the view sheet where it can be: with views on,
* the item drawn along its course and the kind rendered, the image is the
* view ref and there is no near image (`imageLod: undefined`, so an update
* clears it); otherwise the look as given, the very same object.
* @template {{image: unknown, imageLod?: unknown}} T
* @param {T} look
* @param {object} options
* @param {boolean} options.views Whether the renderer draws views
* (`registerAircraftViews`).
* @param {string} options.kind The icon kind.
* @param {number} [options.frame] A helicopter's rotor frame.
* @param {string} [options.rotationMode] How the item is rotated.
* @returns {T}
*/
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
if (!views || rotationMode !== 'course') return look;
const ref = aircraftViewRef(kind, frame);
if (!ref) return look;
return { ...look, image: ref, imageLod: undefined };
}
+175
View File
@@ -0,0 +1,175 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
aircraftViewRef,
isAircraftViewRef,
registerAircraftViews,
VIEW_SHEETS_CAPABILITY,
withAircraftView,
} from './aircraftViews.js';
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
const STILL_KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
];
test('every aircraft class draws its own block of the view sheet', () => {
for (const kind of STILL_KINDS)
assert.deepEqual(
aircraftViewRef(kind),
{
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects[kind],
fallback: aircraftIcon(kind, FLEET_ICON_PX),
},
kind,
);
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
assert.equal(
new Set(firsts).size,
STILL_KINDS.length,
'no two share a block',
);
assert.equal(
aircraftViewRef('airliner'),
aircraftViewRef('airliner'),
'one ref per block, so an unchanged image writes nothing',
);
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
});
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
assert.equal(ROTOR_FRAMES, 3);
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
const ref = aircraftViewRef('helicopter', frame);
assert.equal(
ref.first,
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
`frame ${frame}`,
);
assert.equal(
ref.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
`its fallback is the glyph of rotor frame ${frame}`,
);
}
assert.equal(
aircraftViewRef('helicopter').fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
for (const frame of [undefined, -1, 3, 1.5, NaN])
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
});
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
for (const kind of [
'tr3b',
'tr3bHot',
'vehicle',
'station',
'jet',
'',
undefined,
])
assert.equal(aircraftViewRef(kind), null, String(kind));
assert.equal(
aircraftViewRef('airliner', 1).first,
0,
'a frame means nothing to a fixed wing',
);
});
test('a view ref is told apart from flat images', () => {
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
for (const image of [
'data:image/svg+xml;base64,AAA',
null,
undefined,
{ atlas: 'a', slot: 's' },
])
assert.equal(isAircraftViewRef(image), false, String(image));
});
test('the sheet is registered once per draw port, only with the capability', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
assert.equal(registerAircraftViews(port, new Set()), false);
assert.equal(registerAircraftViews(port, null), false);
assert.equal(calls.length, 0, 'nothing registered without the capability');
assert.equal(registerAircraftViews(port, caps), true);
assert.equal(registerAircraftViews(port, caps), true);
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const other = { views: (id) => calls.push([id]) };
assert.equal(registerAircraftViews(other, caps), true);
assert.equal(calls.length, 2, 'a second port registers its own');
assert.equal(
registerAircraftViews({}, caps),
false,
'a port without views()',
);
assert.equal(registerAircraftViews(null, caps), false);
});
test('a look takes the view only when views are on and it is drawn along its course', () => {
const look = {
image: 'flat',
imageLod: { near: 'near', switchPx: 30 },
size: [20, 20],
scale: 1.5,
};
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
const viewed = withAircraftView(look, on);
assert.deepEqual(viewed, {
image: aircraftViewRef('airliner'),
imageLod: undefined,
size: [20, 20],
scale: 1.5,
});
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
assert.equal(look.image, 'flat', 'the look given is left as it was');
assert.equal(withAircraftView(look, { ...on, views: false }), look);
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
assert.equal(
withAircraftView(look, { ...on, rotationMode: undefined }),
look,
);
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
assert.equal(
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
aircraftViewRef('helicopter', 2),
);
});
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
assert.equal(calls.length, 1);
const [id, sheet] = calls[0];
assert.equal(id, AIRCRAFT_VIEWS.id);
assert.equal(
sheet.image,
'https://cdn.example/app/sprites/aircraft-views.webp',
);
assert.deepEqual(
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
{ ...AIRCRAFT_VIEWS.sheet },
'the layout as it is',
);
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
});
-695
View File
@@ -1,695 +0,0 @@
// Generated by scripts/build-home-countries.mjs. Do not edit by hand.
// Sources: tzdata zone.tab (public domain) and the Natural Earth countries
// pack in src/data/local_data/natural_earth (public domain).
/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */
export const COUNTRY_CENTRES = {
AD: [42.5, 1.6],
AE: [23.9, 54.3],
AF: [33.8, 66],
AG: [17.1, -61.8],
AI: [18.2, -63.1],
AL: [41.1, 20.1],
AM: [40.3, 44.9],
AO: [-12.3, 17.6],
AQ: [-80.6, 20.8],
AR: [-35.2, -65.1],
AS: [-14.3, -170.7],
AT: [47.6, 14.1],
AU: [-25.6, 134.4],
AW: [12.5, -70],
AX: [60.2, 19.9],
AZ: [40.3, 47.7],
BA: [44.2, 17.8],
BB: [13.2, -59.6],
BD: [23.9, 90.2],
BE: [50.6, 4.6],
BF: [12.3, -1.8],
BG: [42.8, 25.2],
BH: [26.1, 50.5],
BI: [-3.4, 29.9],
BJ: [9.6, 2.3],
BL: [17.9, -62.8],
BM: [32.3, -64.8],
BN: [4.5, 114.6],
BO: [-16.7, -64.7],
BQ: [12.2, -68.3],
BR: [-10.8, -53.1],
BS: [24.7, -78],
BT: [27.4, 90.4],
BW: [-22.2, 23.8],
BY: [53.5, 28],
BZ: [17.2, -88.7],
CA: [57.9, -102.4],
CC: [-12.2, 96.9],
CD: [-2.9, 23.6],
CF: [6.6, 20.5],
CG: [-0.8, 15.2],
CH: [46.8, 8.2],
CI: [7.6, -5.6],
CK: [-21.2, -159.8],
CL: [-35.4, -71.2],
CM: [5.7, 12.7],
CN: [36.6, 103.8],
CO: [3.9, -73.1],
CR: [10, -84.2],
CU: [21.6, -79],
CV: [15.1, -23.6],
CW: [12.2, -69],
CX: [-10.4, 105.7],
CY: [34.9, 33],
CZ: [49.7, 15.3],
DE: [51.1, 10.4],
DJ: [11.8, 42.6],
DK: [56.2, 9.4],
DM: [15.4, -61.4],
DO: [18.9, -70.5],
DZ: [28.1, 2.7],
EC: [-1.4, -78.4],
EE: [58.7, 25.8],
EG: [26.5, 29.9],
EH: [24.2, -12.2],
ER: [15.4, 38.8],
ES: [40.4, -3.6],
ET: [8.6, 39.6],
FI: [64.5, 26.3],
FJ: [-17.8, 178],
FK: [-51.7, -58.8],
FM: [6.9, 158.2],
FO: [62.1, -7],
FR: [46.6, 2.5],
GA: [-0.6, 11.8],
GB: [53.9, -2.5],
GD: [12.1, -61.7],
GE: [42.2, 43.5],
GF: [4.9, -52.3],
GG: [49.5, -2.6],
GH: [8, -1.2],
GI: [36.1, -5.3],
GL: [74.8, -41.4],
GM: [13.4, -15.4],
GN: [10.4, -10.9],
GP: [16.2, -61.5],
GQ: [1.6, 10.5],
GR: [39.5, 22.6],
GS: [-54.4, -36.7],
GT: [15.7, -90.4],
GU: [13.4, 144.8],
GW: [12.1, -14.9],
GY: [4.8, -59],
HK: [22.4, 114.2],
HN: [14.8, -86.6],
HR: [45.2, 16.4],
HT: [18.9, -72.7],
HU: [47.2, 19.4],
ID: [-0.2, 114],
IE: [53.2, -8.1],
IL: [31.4, 35],
IM: [54.2, -4.5],
IN: [22.9, 79.6],
IO: [-7.3, 72.4],
IQ: [33, 43.7],
IR: [32.6, 54.3],
IS: [65, -18.6],
IT: [43.5, 12.2],
JE: [49.2, -2.1],
JM: [18.2, -77.3],
JO: [31.2, 36.8],
JP: [36.7, 138],
KE: [0.6, 37.8],
KG: [41.5, 74.5],
KH: [12.7, 104.9],
KI: [1.9, -157.4],
KM: [-11.7, 43.3],
KN: [17.3, -62.8],
KP: [40.2, 127.2],
KR: [36.5, 127.9],
KW: [29.3, 47.6],
KY: [19.3, -81.3],
KZ: [48.2, 67.3],
LA: [18.5, 103.7],
LB: [33.9, 35.9],
LC: [13.9, -61],
LI: [47.1, 9.5],
LK: [7.6, 80.7],
LR: [6.5, -9.3],
LS: [-29.6, 28.2],
LT: [55.3, 23.9],
LU: [49.8, 6.1],
LV: [56.9, 24.9],
LY: [27, 18],
MA: [29.8, -8.4],
MC: [43.7, 7.4],
MD: [47.2, 28.5],
ME: [42.8, 19.2],
MF: [18.1, -63.1],
MG: [-19.4, 46.7],
MH: [7.1, 171.2],
MK: [41.6, 21.7],
ML: [17.3, -3.5],
MM: [21.2, 96.5],
MN: [46.8, 103.1],
MO: [22.1, 113.6],
MP: [15.2, 145.7],
MQ: [14.6, -61.1],
MR: [20.3, -10.3],
MS: [16.7, -62.2],
MT: [35.9, 14.4],
MU: [-20.3, 57.6],
MV: [4.2, 73.5],
MW: [-13.2, 34.3],
MX: [23.9, -102.5],
MY: [3.6, 114.7],
MZ: [-17.3, 35.5],
NA: [-22.1, 17.2],
NC: [-21.3, 165.5],
NE: [17.4, 9.4],
NF: [-29, 168],
NG: [9.6, 8.1],
NI: [12.8, -85],
NL: [52.3, 5.6],
NO: [64.2, 14],
NP: [28.2, 83.9],
NR: [-0.5, 166.9],
NU: [-19, -169.9],
NZ: [-44, 170.5],
OM: [20.6, 56.1],
PA: [8.5, -80.1],
PE: [-9.2, -74.4],
PF: [-17.7, -149.4],
PG: [-6.6, 144.3],
PH: [16, 121.4],
PK: [29.9, 69.3],
PL: [52.1, 19.4],
PM: [47, -56.3],
PN: [-24.4, -128.3],
PR: [18.2, -66.5],
PS: [31.9, 35.3],
PT: [39.7, -8],
PW: [7.5, 134.6],
PY: [-23.2, -58.4],
QA: [25.3, 51.2],
RE: [-20.9, 55.5],
RO: [45.9, 25],
RS: [44.2, 20.8],
RU: [61.7, 99.1],
RW: [-2, 29.9],
SA: [24.1, 44.5],
SB: [-9.6, 160.2],
SC: [-4.7, 55.5],
SD: [16, 29.9],
SE: [62.8, 16.7],
SG: [1.4, 103.8],
SH: [-16, -5.7],
SI: [46.1, 14.8],
SJ: [78, 16],
SK: [48.7, 19.5],
SL: [8.6, -11.8],
SM: [43.9, 12.4],
SN: [14.4, -14.5],
SO: [4.8, 45.7],
SR: [4.1, -55.9],
SS: [7.3, 30.3],
ST: [0.2, 6.6],
SV: [13.7, -88.9],
SX: [18, -63.1],
SY: [35, 38.5],
SZ: [-26.6, 31.5],
TC: [21.8, -71.7],
TD: [15.3, 18.6],
TF: [-49.3, 69.5],
TG: [8.5, 1],
TH: [15.1, 101],
TJ: [38.5, 71],
TK: [-9.4, -171.2],
TL: [-8.8, 125.9],
TM: [39.1, 59.4],
TN: [34.1, 9.5],
TO: [-21.2, -175.2],
TR: [39, 35.4],
TT: [10.4, -61.3],
TV: [-8.5, 179.2],
TW: [23.8, 121],
TZ: [-6.3, 34.8],
UA: [49.2, 31.3],
UG: [1.3, 32.4],
UM: [5.9, -162.1],
US: [39.5, -99.1],
UY: [-32.8, -56],
UZ: [41.8, 63.1],
VA: [41.9, 12.5],
VC: [13.3, -61.2],
VE: [7.1, -66.2],
VG: [18.4, -64.6],
VI: [17.7, -64.8],
VN: [16.7, 106.3],
VU: [-15.2, 166.9],
WF: [-13.3, -176.2],
WS: [-13.6, -172.4],
YE: [15.9, 47.5],
YT: [-12.8, 45.2],
ZA: [-29, 25.2],
ZM: [-13.5, 27.8],
ZW: [-19, 29.9],
};
/** Time zone (tzdata and ICU names) → ISO 3166 country. */
export const ZONE_COUNTRIES = {
'Africa/Abidjan': 'CI',
'Africa/Accra': 'GH',
'Africa/Addis_Ababa': 'ET',
'Africa/Algiers': 'DZ',
'Africa/Asmara': 'ER',
'Africa/Asmera': 'ER',
'Africa/Bamako': 'ML',
'Africa/Bangui': 'CF',
'Africa/Banjul': 'GM',
'Africa/Bissau': 'GW',
'Africa/Blantyre': 'MW',
'Africa/Brazzaville': 'CG',
'Africa/Bujumbura': 'BI',
'Africa/Cairo': 'EG',
'Africa/Casablanca': 'MA',
'Africa/Ceuta': 'ES',
'Africa/Conakry': 'GN',
'Africa/Dakar': 'SN',
'Africa/Dar_es_Salaam': 'TZ',
'Africa/Djibouti': 'DJ',
'Africa/Douala': 'CM',
'Africa/El_Aaiun': 'EH',
'Africa/Freetown': 'SL',
'Africa/Gaborone': 'BW',
'Africa/Harare': 'ZW',
'Africa/Johannesburg': 'ZA',
'Africa/Juba': 'SS',
'Africa/Kampala': 'UG',
'Africa/Khartoum': 'SD',
'Africa/Kigali': 'RW',
'Africa/Kinshasa': 'CD',
'Africa/Lagos': 'NG',
'Africa/Libreville': 'GA',
'Africa/Lome': 'TG',
'Africa/Luanda': 'AO',
'Africa/Lubumbashi': 'CD',
'Africa/Lusaka': 'ZM',
'Africa/Malabo': 'GQ',
'Africa/Maputo': 'MZ',
'Africa/Maseru': 'LS',
'Africa/Mbabane': 'SZ',
'Africa/Mogadishu': 'SO',
'Africa/Monrovia': 'LR',
'Africa/Nairobi': 'KE',
'Africa/Ndjamena': 'TD',
'Africa/Niamey': 'NE',
'Africa/Nouakchott': 'MR',
'Africa/Ouagadougou': 'BF',
'Africa/Porto-Novo': 'BJ',
'Africa/Sao_Tome': 'ST',
'Africa/Tripoli': 'LY',
'Africa/Tunis': 'TN',
'Africa/Windhoek': 'NA',
'America/Adak': 'US',
'America/Anchorage': 'US',
'America/Anguilla': 'AI',
'America/Antigua': 'AG',
'America/Araguaina': 'BR',
'America/Argentina/Buenos_Aires': 'AR',
'America/Argentina/Catamarca': 'AR',
'America/Argentina/Cordoba': 'AR',
'America/Argentina/Jujuy': 'AR',
'America/Argentina/La_Rioja': 'AR',
'America/Argentina/Mendoza': 'AR',
'America/Argentina/Rio_Gallegos': 'AR',
'America/Argentina/Salta': 'AR',
'America/Argentina/San_Juan': 'AR',
'America/Argentina/San_Luis': 'AR',
'America/Argentina/Tucuman': 'AR',
'America/Argentina/Ushuaia': 'AR',
'America/Aruba': 'AW',
'America/Asuncion': 'PY',
'America/Atikokan': 'CA',
'America/Bahia': 'BR',
'America/Bahia_Banderas': 'MX',
'America/Barbados': 'BB',
'America/Belem': 'BR',
'America/Belize': 'BZ',
'America/Blanc-Sablon': 'CA',
'America/Boa_Vista': 'BR',
'America/Bogota': 'CO',
'America/Boise': 'US',
'America/Buenos_Aires': 'AR',
'America/Cambridge_Bay': 'CA',
'America/Campo_Grande': 'BR',
'America/Cancun': 'MX',
'America/Caracas': 'VE',
'America/Catamarca': 'AR',
'America/Cayenne': 'GF',
'America/Cayman': 'KY',
'America/Chicago': 'US',
'America/Chihuahua': 'MX',
'America/Ciudad_Juarez': 'MX',
'America/Coral_Harbour': 'CA',
'America/Cordoba': 'AR',
'America/Costa_Rica': 'CR',
'America/Coyhaique': 'CL',
'America/Creston': 'CA',
'America/Cuiaba': 'BR',
'America/Curacao': 'CW',
'America/Danmarkshavn': 'GL',
'America/Dawson': 'CA',
'America/Dawson_Creek': 'CA',
'America/Denver': 'US',
'America/Detroit': 'US',
'America/Dominica': 'DM',
'America/Edmonton': 'CA',
'America/Eirunepe': 'BR',
'America/El_Salvador': 'SV',
'America/Fort_Nelson': 'CA',
'America/Fortaleza': 'BR',
'America/Glace_Bay': 'CA',
'America/Godthab': 'GL',
'America/Goose_Bay': 'CA',
'America/Grand_Turk': 'TC',
'America/Grenada': 'GD',
'America/Guadeloupe': 'GP',
'America/Guatemala': 'GT',
'America/Guayaquil': 'EC',
'America/Guyana': 'GY',
'America/Halifax': 'CA',
'America/Havana': 'CU',
'America/Hermosillo': 'MX',
'America/Indiana/Indianapolis': 'US',
'America/Indiana/Knox': 'US',
'America/Indiana/Marengo': 'US',
'America/Indiana/Petersburg': 'US',
'America/Indiana/Tell_City': 'US',
'America/Indiana/Vevay': 'US',
'America/Indiana/Vincennes': 'US',
'America/Indiana/Winamac': 'US',
'America/Indianapolis': 'US',
'America/Inuvik': 'CA',
'America/Iqaluit': 'CA',
'America/Jamaica': 'JM',
'America/Jujuy': 'AR',
'America/Juneau': 'US',
'America/Kentucky/Louisville': 'US',
'America/Kentucky/Monticello': 'US',
'America/Kralendijk': 'BQ',
'America/La_Paz': 'BO',
'America/Lima': 'PE',
'America/Los_Angeles': 'US',
'America/Louisville': 'US',
'America/Lower_Princes': 'SX',
'America/Maceio': 'BR',
'America/Managua': 'NI',
'America/Manaus': 'BR',
'America/Marigot': 'MF',
'America/Martinique': 'MQ',
'America/Matamoros': 'MX',
'America/Mazatlan': 'MX',
'America/Mendoza': 'AR',
'America/Menominee': 'US',
'America/Merida': 'MX',
'America/Metlakatla': 'US',
'America/Mexico_City': 'MX',
'America/Miquelon': 'PM',
'America/Moncton': 'CA',
'America/Monterrey': 'MX',
'America/Montevideo': 'UY',
'America/Montserrat': 'MS',
'America/Nassau': 'BS',
'America/New_York': 'US',
'America/Nome': 'US',
'America/Noronha': 'BR',
'America/North_Dakota/Beulah': 'US',
'America/North_Dakota/Center': 'US',
'America/North_Dakota/New_Salem': 'US',
'America/Nuuk': 'GL',
'America/Ojinaga': 'MX',
'America/Panama': 'PA',
'America/Paramaribo': 'SR',
'America/Phoenix': 'US',
'America/Port-au-Prince': 'HT',
'America/Port_of_Spain': 'TT',
'America/Porto_Velho': 'BR',
'America/Puerto_Rico': 'PR',
'America/Punta_Arenas': 'CL',
'America/Rankin_Inlet': 'CA',
'America/Recife': 'BR',
'America/Regina': 'CA',
'America/Resolute': 'CA',
'America/Rio_Branco': 'BR',
'America/Santarem': 'BR',
'America/Santiago': 'CL',
'America/Santo_Domingo': 'DO',
'America/Sao_Paulo': 'BR',
'America/Scoresbysund': 'GL',
'America/Sitka': 'US',
'America/St_Barthelemy': 'BL',
'America/St_Johns': 'CA',
'America/St_Kitts': 'KN',
'America/St_Lucia': 'LC',
'America/St_Thomas': 'VI',
'America/St_Vincent': 'VC',
'America/Swift_Current': 'CA',
'America/Tegucigalpa': 'HN',
'America/Thule': 'GL',
'America/Tijuana': 'MX',
'America/Toronto': 'CA',
'America/Tortola': 'VG',
'America/Vancouver': 'CA',
'America/Whitehorse': 'CA',
'America/Winnipeg': 'CA',
'America/Yakutat': 'US',
'Antarctica/Casey': 'AQ',
'Antarctica/Davis': 'AQ',
'Antarctica/DumontDUrville': 'AQ',
'Antarctica/Macquarie': 'AU',
'Antarctica/Mawson': 'AQ',
'Antarctica/McMurdo': 'AQ',
'Antarctica/Palmer': 'AQ',
'Antarctica/Rothera': 'AQ',
'Antarctica/Syowa': 'AQ',
'Antarctica/Troll': 'AQ',
'Antarctica/Vostok': 'AQ',
'Arctic/Longyearbyen': 'SJ',
'Asia/Aden': 'YE',
'Asia/Almaty': 'KZ',
'Asia/Amman': 'JO',
'Asia/Anadyr': 'RU',
'Asia/Aqtau': 'KZ',
'Asia/Aqtobe': 'KZ',
'Asia/Ashgabat': 'TM',
'Asia/Atyrau': 'KZ',
'Asia/Baghdad': 'IQ',
'Asia/Bahrain': 'BH',
'Asia/Baku': 'AZ',
'Asia/Bangkok': 'TH',
'Asia/Barnaul': 'RU',
'Asia/Beirut': 'LB',
'Asia/Bishkek': 'KG',
'Asia/Brunei': 'BN',
'Asia/Calcutta': 'IN',
'Asia/Chita': 'RU',
'Asia/Colombo': 'LK',
'Asia/Damascus': 'SY',
'Asia/Dhaka': 'BD',
'Asia/Dili': 'TL',
'Asia/Dubai': 'AE',
'Asia/Dushanbe': 'TJ',
'Asia/Famagusta': 'CY',
'Asia/Gaza': 'PS',
'Asia/Hebron': 'PS',
'Asia/Ho_Chi_Minh': 'VN',
'Asia/Hong_Kong': 'HK',
'Asia/Hovd': 'MN',
'Asia/Irkutsk': 'RU',
'Asia/Jakarta': 'ID',
'Asia/Jayapura': 'ID',
'Asia/Jerusalem': 'IL',
'Asia/Kabul': 'AF',
'Asia/Kamchatka': 'RU',
'Asia/Karachi': 'PK',
'Asia/Kathmandu': 'NP',
'Asia/Katmandu': 'NP',
'Asia/Khandyga': 'RU',
'Asia/Kolkata': 'IN',
'Asia/Krasnoyarsk': 'RU',
'Asia/Kuala_Lumpur': 'MY',
'Asia/Kuching': 'MY',
'Asia/Kuwait': 'KW',
'Asia/Macau': 'MO',
'Asia/Magadan': 'RU',
'Asia/Makassar': 'ID',
'Asia/Manila': 'PH',
'Asia/Muscat': 'OM',
'Asia/Nicosia': 'CY',
'Asia/Novokuznetsk': 'RU',
'Asia/Novosibirsk': 'RU',
'Asia/Omsk': 'RU',
'Asia/Oral': 'KZ',
'Asia/Phnom_Penh': 'KH',
'Asia/Pontianak': 'ID',
'Asia/Pyongyang': 'KP',
'Asia/Qatar': 'QA',
'Asia/Qostanay': 'KZ',
'Asia/Qyzylorda': 'KZ',
'Asia/Rangoon': 'MM',
'Asia/Riyadh': 'SA',
'Asia/Saigon': 'VN',
'Asia/Sakhalin': 'RU',
'Asia/Samarkand': 'UZ',
'Asia/Seoul': 'KR',
'Asia/Shanghai': 'CN',
'Asia/Singapore': 'SG',
'Asia/Srednekolymsk': 'RU',
'Asia/Taipei': 'TW',
'Asia/Tashkent': 'UZ',
'Asia/Tbilisi': 'GE',
'Asia/Tehran': 'IR',
'Asia/Thimphu': 'BT',
'Asia/Tokyo': 'JP',
'Asia/Tomsk': 'RU',
'Asia/Ulaanbaatar': 'MN',
'Asia/Urumqi': 'CN',
'Asia/Ust-Nera': 'RU',
'Asia/Vientiane': 'LA',
'Asia/Vladivostok': 'RU',
'Asia/Yakutsk': 'RU',
'Asia/Yangon': 'MM',
'Asia/Yekaterinburg': 'RU',
'Asia/Yerevan': 'AM',
'Atlantic/Azores': 'PT',
'Atlantic/Bermuda': 'BM',
'Atlantic/Canary': 'ES',
'Atlantic/Cape_Verde': 'CV',
'Atlantic/Faeroe': 'FO',
'Atlantic/Faroe': 'FO',
'Atlantic/Madeira': 'PT',
'Atlantic/Reykjavik': 'IS',
'Atlantic/South_Georgia': 'GS',
'Atlantic/St_Helena': 'SH',
'Atlantic/Stanley': 'FK',
'Australia/Adelaide': 'AU',
'Australia/Brisbane': 'AU',
'Australia/Broken_Hill': 'AU',
'Australia/Darwin': 'AU',
'Australia/Eucla': 'AU',
'Australia/Hobart': 'AU',
'Australia/Lindeman': 'AU',
'Australia/Lord_Howe': 'AU',
'Australia/Melbourne': 'AU',
'Australia/Perth': 'AU',
'Australia/Sydney': 'AU',
'Europe/Amsterdam': 'NL',
'Europe/Andorra': 'AD',
'Europe/Astrakhan': 'RU',
'Europe/Athens': 'GR',
'Europe/Belgrade': 'RS',
'Europe/Berlin': 'DE',
'Europe/Bratislava': 'SK',
'Europe/Brussels': 'BE',
'Europe/Bucharest': 'RO',
'Europe/Budapest': 'HU',
'Europe/Busingen': 'DE',
'Europe/Chisinau': 'MD',
'Europe/Copenhagen': 'DK',
'Europe/Dublin': 'IE',
'Europe/Gibraltar': 'GI',
'Europe/Guernsey': 'GG',
'Europe/Helsinki': 'FI',
'Europe/Isle_of_Man': 'IM',
'Europe/Istanbul': 'TR',
'Europe/Jersey': 'JE',
'Europe/Kaliningrad': 'RU',
'Europe/Kiev': 'UA',
'Europe/Kirov': 'RU',
'Europe/Kyiv': 'UA',
'Europe/Lisbon': 'PT',
'Europe/Ljubljana': 'SI',
'Europe/London': 'GB',
'Europe/Luxembourg': 'LU',
'Europe/Madrid': 'ES',
'Europe/Malta': 'MT',
'Europe/Mariehamn': 'AX',
'Europe/Minsk': 'BY',
'Europe/Monaco': 'MC',
'Europe/Moscow': 'RU',
'Europe/Oslo': 'NO',
'Europe/Paris': 'FR',
'Europe/Podgorica': 'ME',
'Europe/Prague': 'CZ',
'Europe/Riga': 'LV',
'Europe/Rome': 'IT',
'Europe/Samara': 'RU',
'Europe/San_Marino': 'SM',
'Europe/Sarajevo': 'BA',
'Europe/Saratov': 'RU',
'Europe/Simferopol': 'UA',
'Europe/Skopje': 'MK',
'Europe/Sofia': 'BG',
'Europe/Stockholm': 'SE',
'Europe/Tallinn': 'EE',
'Europe/Tirane': 'AL',
'Europe/Ulyanovsk': 'RU',
'Europe/Vaduz': 'LI',
'Europe/Vatican': 'VA',
'Europe/Vienna': 'AT',
'Europe/Vilnius': 'LT',
'Europe/Volgograd': 'RU',
'Europe/Warsaw': 'PL',
'Europe/Zagreb': 'HR',
'Europe/Zurich': 'CH',
'Indian/Antananarivo': 'MG',
'Indian/Chagos': 'IO',
'Indian/Christmas': 'CX',
'Indian/Cocos': 'CC',
'Indian/Comoro': 'KM',
'Indian/Kerguelen': 'TF',
'Indian/Mahe': 'SC',
'Indian/Maldives': 'MV',
'Indian/Mauritius': 'MU',
'Indian/Mayotte': 'YT',
'Indian/Reunion': 'RE',
'Pacific/Apia': 'WS',
'Pacific/Auckland': 'NZ',
'Pacific/Bougainville': 'PG',
'Pacific/Chatham': 'NZ',
'Pacific/Chuuk': 'FM',
'Pacific/Easter': 'CL',
'Pacific/Efate': 'VU',
'Pacific/Enderbury': 'KI',
'Pacific/Fakaofo': 'TK',
'Pacific/Fiji': 'FJ',
'Pacific/Funafuti': 'TV',
'Pacific/Galapagos': 'EC',
'Pacific/Gambier': 'PF',
'Pacific/Guadalcanal': 'SB',
'Pacific/Guam': 'GU',
'Pacific/Honolulu': 'US',
'Pacific/Kanton': 'KI',
'Pacific/Kiritimati': 'KI',
'Pacific/Kosrae': 'FM',
'Pacific/Kwajalein': 'MH',
'Pacific/Majuro': 'MH',
'Pacific/Marquesas': 'PF',
'Pacific/Midway': 'UM',
'Pacific/Nauru': 'NR',
'Pacific/Niue': 'NU',
'Pacific/Norfolk': 'NF',
'Pacific/Noumea': 'NC',
'Pacific/Pago_Pago': 'AS',
'Pacific/Palau': 'PW',
'Pacific/Pitcairn': 'PN',
'Pacific/Pohnpei': 'FM',
'Pacific/Ponape': 'FM',
'Pacific/Port_Moresby': 'PG',
'Pacific/Rarotonga': 'CK',
'Pacific/Saipan': 'MP',
'Pacific/Tahiti': 'PF',
'Pacific/Tarawa': 'KI',
'Pacific/Tongatapu': 'TO',
'Pacific/Truk': 'FM',
'Pacific/Wake': 'UM',
'Pacific/Wallis': 'WF',
};
+2 -2
View File
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
* and the renderer's (about 45, the view sheet's layout among them), with
* room for drivers that keep constants in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
+6
View File
@@ -100,6 +100,12 @@ export const ICON_RECEDES = 4;
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/**
* The row's image is a subject of the set's view sheet
* ({@link module:viewSheet}): its far image is the subject's first cell, and
* the renderer draws the frame that shows it from the eye.
*/
export const ICON_VIEWS = 16;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
+20 -5
View File
@@ -15,8 +15,14 @@
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
* icons are, so the renderer draws the view of the aircraft that matches
* the eye and tracking a contact does not flatten it.
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
import { isAircraftViewRef } from './aircraftViews.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
@@ -105,18 +111,21 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const alongCourse =
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
...(alongCourse
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
@@ -132,7 +141,9 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
written.size[0] === item.size[0] &&
written.size[1] === item.size[1] &&
written.scale === item.scale &&
written.rotationMode === item.rotationMode &&
written.rotation === item.rotation &&
written.course === item.course &&
sameColor(written.color, item.color)
)
return;
@@ -146,13 +157,17 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string} target.image
* @param {string|{views: string, first: number}} target.image A flat
* glyph, or a view-sheet image (drawn along `course`).
* @param {{near: string, switchPx: number}} [target.imageLod] The
* sharper image it switches to once drawn larger than `switchPx`.
* sharper image a flat glyph switches to once drawn larger than
* `switchPx`.
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite Read each frame.
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => number} [target.course] Degrees clockwise from north;
* required with a view-sheet image, which only draws along a course.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
+49
View File
@@ -199,3 +199,52 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
assert.ok(Object.isFrozen(stale));
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
});
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
const { aircraftViewRef } = await import('./aircraftViews.js');
const { viewer, draw, tick } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
let course = 45;
let rotations = 0;
icon.show({
id: 'abc123',
image: aircraftViewRef('airliner'),
imageLod: { near: 'near', switchPx: 30 },
sprite: SPRITE,
position: () => ({ x: 1, y: 2, z: 3 }),
rotation: () => {
rotations++;
return 0.5;
},
course: () => course,
color: () => [0, 1, 1, 1],
});
const set = draw.find('flights-tracked-icon:');
tick();
const item = set.items.get('abc123');
assert.equal(item.image, aircraftViewRef('airliner'));
assert.equal('imageLod' in item, false);
assert.equal(item.rotationMode, 'course');
assert.equal(item.course, 45);
assert.equal('rotation' in item, false);
assert.equal(rotations, 0, 'no screen rotation is projected');
assert.deepEqual(item.size, [28, 28]);
const writes = set.writes;
tick();
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
course = 50;
tick();
assert.equal(set.items.get('abc123').course, 50);
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
tick();
const flat = set.items.get('abc123');
assert.equal(flat.rotationMode, 'screen');
assert.equal(flat.rotation, 0.5);
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
assert.equal('course' in flat, false);
icon.dispose();
});
+53 -2
View File
@@ -59,9 +59,9 @@ const VESSEL_KIND_RULES = [
['fishing', /fishing|trawler/i],
[
'military',
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search\W+(?:and\W+|&\W*)?rescue/i,
],
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
['tug', /tug|tow|pilot|tender|supply|service|anti\W?pollution/i],
['sailing', /sail/i],
['pleasure', /pleasure|yacht/i],
];
@@ -116,6 +116,57 @@ export function vesselKind(type) {
return kind;
}
/**
* Hull shapes drawn within a kind, where an AIS ship type has a hull of its
* own: a dredger (AIS 33, otherwise `other`), and the small workboats that
* are neither tugs nor patrol craft, drawn as a pilot boat (AIS 50 pilot,
* 51 search and rescue, 53 port tender, 54 anti-pollution). In order: the
* first that matches.
*/
const VESSEL_SHAPE_RULES = [
['dredger', /dredg/i],
[
'pilot',
/pilot|\bsar\b|search\W+(?:and\W+|&\W*)?rescue|port\W?tender|anti\W?pollution/i,
],
];
/** Every hull shape {@link vesselShape} names: the kinds, then the rest. */
export const VESSEL_SHAPES = Object.freeze([
'cargo',
'tanker',
'passenger',
'highspeed',
'fishing',
'tug',
'sailing',
'pleasure',
'military',
'other',
...VESSEL_SHAPE_RULES.map(([shape]) => shape),
]);
const SHAPE_MEMO = new Map();
/**
* The hull a vessel is shown as from the eye's angle (the vessel view
* sheet, `vesselViews.js`): its own where its AIS type has one, else its
* kind's ({@link vesselKind}). Its colour is always its kind's.
* @param {string} type Raw AIS type.
* @returns {string} One of `VESSEL_SHAPES`.
*/
export function vesselShape(type) {
const text = normalizeVesselType(type);
let shape = SHAPE_MEMO.get(text);
if (shape !== undefined) return shape;
shape =
VESSEL_SHAPE_RULES.find(([, pattern]) => pattern.test(text))?.[0] ??
vesselKind(type);
if (SHAPE_MEMO.size >= KIND_MEMO_MAX) SHAPE_MEMO.clear();
SHAPE_MEMO.set(text, shape);
return shape;
}
/**
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
+74
View File
@@ -0,0 +1,74 @@
/**
* @module data/vesselViews
* @description Which block of the vessel view sheet (`viewSheet.js`) a
* vessel's icon draws from. Each hull shape (`vesselShape`, vesselTypes.js)
* is rendered there from a sphere of camera angles, from straight above
* down to the horizon; a renderer with the `viewSheets` capability lays the icon
* flat on the water along its course and draws the view that matches where
* the eye is, so a ship seen at an oblique angle looks solid instead of
* like a flat hull. An aid to navigation keeps its upright buoy.
*/
import { VESSEL_VIEWS } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import { VESSEL_KINDS } from './vesselTypes.js';
/** One frozen image ref per shape and kind, so equal refs are the same. */
const refs = new Map();
/**
* The view image of a vessel: `{views, first, fallback}`, the sheet's id,
* the first cell of its hull shape's block and its kind's flat hull sprite
* (drawn while the sheet loads, or if it fails). A shape the sheet does not
* hold draws its kind's block, and a kind it does not hold `other`'s.
* @param {string} shape One of `VESSEL_SHAPES` (`vesselShape`).
* @param {string} [kind] One of `VESSEL_KINDS` (`vesselKind`); the shape
* itself by default.
* @returns {{views: string, first: number, fallback: string}}
*/
export function vesselViewRef(shape, kind = shape) {
const held = (name) => Number.isInteger(VESSEL_VIEWS.subjects[name]);
const flat = VESSEL_KINDS.includes(kind) ? kind : 'other';
const subject = held(shape) ? shape : held(flat) ? flat : 'other';
const key = `${subject}|${flat}`;
let ref = refs.get(key);
if (!ref) {
ref = Object.freeze({
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[subject],
fallback: vesselSprite(flat),
});
refs.set(key, ref);
}
return ref;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the vessel view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerVesselViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.('viewSheets')) return false;
if (!registered.has(drawPort)) {
const sheet = VESSEL_VIEWS.sheet;
drawPort.views(VESSEL_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { registerVesselViews, vesselViewRef } from './vesselViews.js';
import { VESSEL_VIEWS, viewLayout } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import {
VESSEL_KINDS,
VESSEL_SHAPES,
vesselKind,
vesselShape,
} from './vesselTypes.js';
test('VESSEL_VIEWS holds a block for every hull shape, each on the sheet', () => {
const layout = viewLayout(VESSEL_VIEWS.sheet);
assert.equal(layout.frames, VESSEL_VIEWS.frames);
// To the horizon and no further: a ship is never seen from below.
assert.equal(
(VESSEL_VIEWS.sheet.rings.length - 1) * VESSEL_VIEWS.sheet.ringStepDeg,
90,
);
// Every shape, in order, a block each: the ten kinds, then the rest.
assert.deepEqual(Object.keys(VESSEL_VIEWS.subjects), [...VESSEL_SHAPES]);
assert.deepEqual(
VESSEL_SHAPES.slice(0, VESSEL_KINDS.length).toSorted(),
[...VESSEL_KINDS].sort(),
);
VESSEL_SHAPES.forEach((shape, i) =>
assert.equal(VESSEL_VIEWS.subjects[shape], i * VESSEL_VIEWS.frames, shape),
);
assert.ok(
VESSEL_SHAPES.length * VESSEL_VIEWS.frames <=
VESSEL_VIEWS.sheet.columns * VESSEL_VIEWS.sheet.rows,
);
});
test('every AIS ship type, 0 to 99, draws a shape the sheet holds, in its kind’s colour', () => {
// ITU-R M.1371: the families by their tens, and the types with a hull of
// their own.
const shapeOf = (code) => vesselShape(String(code));
const kindOf = (code) => vesselKind(String(code));
for (let code = 0; code < 100; code++) {
assert.ok(Number.isInteger(VESSEL_VIEWS.subjects[shapeOf(code)]), code);
assert.ok(VESSEL_KINDS.includes(kindOf(code)), code);
}
const drawn = (codes, shape, kind = shape) =>
codes.forEach((code) =>
assert.deepEqual([shapeOf(code), kindOf(code)], [shape, kind], code),
);
const tens = (ten) => Array.from({ length: 10 }, (_, i) => ten * 10 + i);
drawn(tens(7), 'cargo');
drawn(tens(8), 'tanker');
drawn(tens(6), 'passenger');
drawn(tens(4), 'highspeed');
drawn([30], 'fishing');
drawn([31, 32, 52], 'tug');
drawn([36], 'sailing');
drawn([37], 'pleasure');
drawn([35, 55], 'military');
drawn([33], 'dredger', 'other');
// Pilot, port tender and anti-pollution craft are service boats (the
// tug's colour); search and rescue is a patrol colour. One small hull.
drawn([50, 53, 54], 'pilot', 'tug');
drawn([51], 'pilot', 'military');
// Wing-in-ground craft, diving and medical vessels, the reserved and
// spare codes and "other": the plain hull.
drawn(
[0, 1, 19, ...tens(2), 34, 38, 39, 56, 57, 58, 59, ...tens(9)],
'other',
);
// A feed that names the type in words draws the same shapes.
assert.equal(vesselShape('Dredger'), 'dredger');
assert.equal(vesselShape('Pilot Vessel'), 'pilot');
assert.equal(vesselShape('Search and Rescue'), 'pilot');
// However the words are joined, the hull and the colour are the code's.
for (const text of ['Search & Rescue', 'Search-and-rescue', 'SAR'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'military'],
text,
);
for (const text of ['Anti Pollution', 'Anti-pollution', 'Port Tender'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'tug'],
text,
);
assert.equal(vesselShape('Tug'), 'tug');
assert.equal(vesselShape('Container Ship'), 'cargo');
assert.equal(vesselShape(''), 'other');
});
test('a vessel draws its shape’s block of the sheet, with its kind’s flat hull to fall back on', () => {
for (const kind of VESSEL_KINDS) {
const ref = vesselViewRef(kind);
assert.deepEqual(ref, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[kind],
fallback: vesselSprite(kind),
});
assert.ok(Object.isFrozen(ref));
// One object a shape and kind: an unchanged icon is seen as unchanged.
assert.equal(vesselViewRef(kind), ref);
}
// A shape within a kind: its own block, its kind's flat hull.
assert.deepEqual(vesselViewRef('pilot', 'tug'), {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
assert.notEqual(
vesselViewRef('pilot', 'tug'),
vesselViewRef('pilot', 'military'),
);
assert.equal(
vesselViewRef('dredger', 'other').first,
VESSEL_VIEWS.subjects.dredger,
);
// A shape the sheet does not hold: its kind's block, then `other`'s.
assert.equal(
vesselViewRef('hovercraft', 'highspeed'),
vesselViewRef('highspeed'),
);
assert.equal(vesselViewRef('submarine'), vesselViewRef('other'));
assert.equal(vesselViewRef(undefined), vesselViewRef('other'));
});
test('the sheet is registered once a port, at the layer’s asset URL, on a renderer that draws views', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const views = new Set(['viewSheets']);
const resolve = (url) => `/gev${url}`;
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(calls.length, 1);
assert.equal(calls[0][0], VESSEL_VIEWS.id);
assert.deepEqual(calls[0][1], {
...VESSEL_VIEWS.sheet,
image: '/gev/sprites/vessel-views.webp',
});
// No capability, no port, or a port without `views`: flat hulls.
assert.equal(registerVesselViews(port, new Set(), resolve), false);
assert.equal(registerVesselViews(port, null), false);
assert.equal(registerVesselViews(null, views), false);
assert.equal(registerVesselViews({}, views), false);
});
+295
View File
@@ -0,0 +1,295 @@
/**
* @module viewSheet
* @description A view sheet: one image of small sprites showing a subject
* (an aircraft class) from a sphere of directions, and the maths that picks
* the sprite for where the eye is. Plain JavaScript and GLSL: no DOM, no
* engine. `scripts/bake-view-sheet.py` bakes the aircraft and
* vessel sheets to their layouts here; a renderer with the `viewSheets`
* capability draws them.
*
* **Frames.** A subject lies flat on the earth: up is the ground's normal,
* forward its course. `d` is the direction from the subject to the eye in
* the subject's own axes `[forward, right, up]`. A sheet holds each subject
* as a block of consecutive cells, row-major: rings of frames `ringStepDeg`
* apart, from straight above (ring 0) downward, ring `k` holding `rings[k]`
* frames from the eye dead ahead, round the right side, to dead astern. The
* left side is the right-side frame mirrored, so a sheet's subjects and
* their light are symmetric about their centre plane.
*
* **Roll.** A frame's image up is {@link frameUp}: forward, turned by the
* smallest rotation that takes up onto the frame's direction. Straight
* above, the nose points up the image; the roll then changes smoothly all
* the way round and below. It has no meaning only from straight below, so a
* sheet's last ring stays short of that.
*
* **Between frames.** The frame nearest the eye's direction is drawn
* ({@link viewFrame}), as a card standing where its subject is, square to
* the frame's own direction: seen from a little to one side it is tilted
* (foreshortened and turned) as the subject itself would be, until the next
* frame is the nearer. Frames are not blended.
*/
/** Rings a sheet may hold (the shader's uniform array); even. */
export const VIEW_RINGS_MAX = 18;
/** The aircraft classes' view sheet (`public/sprites/aircraft-views.json`). */
export const AIRCRAFT_VIEWS = Object.freeze({
id: 'aircraft-views',
sheet: Object.freeze({
image: '/sprites/aircraft-views.webp',
cellPx: 64,
columns: 64,
rows: 57,
ringStepDeg: 7.5,
rings: Object.freeze([
1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22,
]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 302,
/** Each subject's first cell. */
subjects: Object.freeze({
airliner: 0,
widebody: 302,
quadjet: 604,
turboprop: 906,
light: 1208,
glider: 1510,
fastjet: 1812,
bizjet: 2114,
uav: 2416,
helicopter0: 2718,
helicopter1: 3020,
helicopter2: 3322,
}),
});
/**
* The vessel hull shapes' view sheet (`public/sprites/vessel-views.json`):
* from straight above down to the horizon, a ship never being seen from
* below.
*/
export const VESSEL_VIEWS = Object.freeze({
id: 'vessel-views',
sheet: Object.freeze({
image: '/sprites/vessel-views.webp',
cellPx: 64,
columns: 64,
rows: 39,
ringStepDeg: 7.5,
rings: Object.freeze([1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 208,
/**
* Each hull shape's first cell (`vesselShape`, vesselTypes.js): the ten
* hull kinds, then the shapes drawn within a kind.
*/
subjects: Object.freeze({
cargo: 0,
tanker: 208,
passenger: 416,
highspeed: 624,
fishing: 832,
tug: 1040,
sailing: 1248,
pleasure: 1456,
military: 1664,
other: 1872,
dredger: 2080,
pilot: 2288,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
* ringStepDeg: number, rings: readonly number[], grey?: boolean}} sheet
* @returns {{columns: number, rows: number, ringStepRad: number,
* rings: number[], firsts: number[], frames: number}}
*/
export function viewLayout(sheet) {
const whole = (n) => Number.isInteger(n) && n > 0;
if (!sheet || typeof sheet.image !== 'string' || !sheet.image)
throw new TypeError('a view sheet needs its image URL');
if (!whole(sheet.cellPx) || !whole(sheet.columns) || !whole(sheet.rows))
throw new TypeError(
'a view sheet needs whole cellPx, columns and rows above 0',
);
const { rings, ringStepDeg } = sheet;
if (
!Array.isArray(rings) ||
rings.length < 1 ||
rings.length > VIEW_RINGS_MAX ||
!rings.every(whole)
)
throw new TypeError(
`a view sheet needs 1 to ${VIEW_RINGS_MAX} rings of whole frame counts`,
);
if (rings[0] !== 1)
throw new TypeError("a view sheet's first ring is the one frame above");
if (
!(ringStepDeg > 0) ||
!Number.isFinite(ringStepDeg) ||
(rings.length - 1) * ringStepDeg >= 180
)
throw new TypeError("a view sheet's rings stop short of straight below");
const firsts = [];
let frames = 0;
for (const count of rings) {
firsts.push(frames);
frames += count;
}
return {
columns: sheet.columns,
rows: sheet.rows,
ringStepRad: (ringStepDeg * Math.PI) / 180,
rings: [...rings],
firsts,
frames,
};
}
/**
* The frame that shows a subject from `d`.
* @param {ReturnType<typeof viewLayout>} layout
* @param {readonly [number, number, number]} d Toward the eye, as
* `[forward, right, up]`; any length above 0.
* @returns {{frame: number, ring: number, index: number, mirrored: boolean}}
* `frame` counts from the subject's first cell; `mirrored` draws it flipped
* left to right (the eye on the left side).
*/
export function viewFrame(layout, d) {
const length = Math.hypot(d[0], d[1], d[2]);
const up = length > 0 ? Math.min(1, Math.max(-1, d[2] / length)) : 1;
const ring = Math.min(
layout.rings.length - 1,
Math.floor(Math.acos(up) / layout.ringStepRad + 0.5),
);
const span = layout.rings[ring] - 1;
const side = Math.abs(d[1]);
const bearing = side + Math.abs(d[0]) > 0 ? Math.atan2(side, d[0]) : 0;
const index = span > 0 ? Math.floor((bearing / Math.PI) * span + 0.5) : 0;
return {
frame: layout.firsts[ring] + index,
ring,
index,
mirrored: d[1] < 0,
};
}
/**
* The direction a frame shows its subject from: a unit `[forward, right,
* up]`, on the right side (or the left, mirrored).
*/
export function frameDirection(layout, ring, index, mirrored = false) {
const off = ring * layout.ringStepRad;
const span = layout.rings[ring] - 1;
const turn = span > 0 ? (index / span) * Math.PI : 0;
return [
Math.sin(off) * Math.cos(turn),
Math.sin(off) * Math.sin(turn) * (mirrored ? -1 : 1),
Math.cos(off),
];
}
/**
* A frame's image up, for the unit direction `d` it shows its subject from:
* forward, turned as up turns onto `d`. A unit `[forward, right, up]`,
* perpendicular to `d`.
*/
export function frameUp(d) {
const k = 1 / Math.max(1 + d[2], 1e-6);
return [1 - d[0] * d[0] * k, -d[0] * d[1] * k, -d[0]];
}
/**
* A sheet's layout as the shader's uniforms: `grid`, and `rings` as one
* vector for each two rings (`[frames, first, frames, first]`).
*/
export function viewUniforms(layout) {
const rings = [];
for (let k = 0; k < VIEW_RINGS_MAX; k += 2)
rings.push([
layout.rings[k] ?? 1,
layout.firsts[k] ?? 0,
layout.rings[k + 1] ?? 1,
layout.firsts[k + 1] ?? 0,
]);
return {
grid: [
layout.columns,
layout.rows,
layout.ringStepRad,
layout.rings.length,
],
rings,
};
}
/**
* {@link viewFrame}, {@link frameDirection} and {@link frameUp} in GLSL, over `u_viewGrid` (columns, rows, ring step in radians, rings) and
* `u_viewRings` (each ring's frames and first frame, two rings a vector).
*/
export const VIEW_SHEET_GLSL = /* glsl */ `
uniform vec4 u_viewGrid;
uniform vec4 u_viewRings[${VIEW_RINGS_MAX / 2}];
// A ring's frames and its first frame, from the subject's first cell.
vec2 viewRing(float ring) {
vec4 pair = u_viewRings[int(ring * 0.5)];
return ring - 2.0 * floor(ring * 0.5) < 0.5 ? pair.xy : pair.zw;
}
// The frame that shows a subject from d (unit, toward the eye, as forward,
// right, up): its ring, its index in the ring, and 1 when it is drawn
// mirrored (the eye on the left side).
vec3 viewNearest(vec3 d) {
float ring = clamp(
floor(acos(clamp(d.z, -1.0, 1.0)) / u_viewGrid.z + 0.5),
0.0, u_viewGrid.w - 1.0);
float span = viewRing(ring).x - 1.0;
float side = abs(d.y);
float bearing = side + abs(d.x) > 0.0 ? atan(side, d.x) : 0.0;
return vec3(
ring,
span > 0.0 ? floor(bearing / 3.141592653589793 * span + 0.5) : 0.0,
d.y < 0.0 ? 1.0 : 0.0);
}
// The direction a frame shows its subject from (toward the eye, as forward,
// right, up; flip 1 for the left side) and the frame's image up.
void viewFrameAxes(float ring, float index, float flip, out vec3 toEye, out vec3 up) {
float span = viewRing(ring).x - 1.0;
float off = ring * u_viewGrid.z;
float turn = span > 0.0 ? index / span * 3.141592653589793 : 0.0;
toEye = vec3(
sin(off) * cos(turn),
sin(off) * sin(turn) * (1.0 - 2.0 * flip),
cos(off));
float k = 1.0 / max(1.0 + toEye.z, 1.0e-6);
up = vec3(1.0 - toEye.x * toEye.x * k, -toEye.x * toEye.y * k, -toEye.x);
}
`;
/**
* Reading a view sheet's cells in a fragment shader: `viewCell(cell, uv,
* lod)` is the colour of a cell at `uv` (0..1 across it, v down) and that
* level of detail, nothing outside it, from `u_views` over `u_viewGrid`.
*/
export const VIEW_SHEET_FRAGMENT_GLSL = /* glsl */ `
uniform sampler2D u_views;
uniform vec4 u_viewGrid;
vec4 viewCell(float cell, vec2 uv, float lod) {
float at = floor(cell + 0.5);
float row = floor((at + 0.5) / u_viewGrid.x);
float column = at - row * u_viewGrid.x;
vec2 inside = step(vec2(0.0), uv) * step(uv, vec2(1.0));
vec4 color = textureLod(
u_views, (vec2(column, row) + clamp(uv, 0.0, 1.0)) / u_viewGrid.xy, lod);
return color * (inside.x * inside.y);
}
`;
+429
View File
@@ -0,0 +1,429 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
VESSEL_VIEWS,
frameDirection,
frameUp,
viewFrame,
viewLayout,
viewUniforms,
VIEW_RINGS_MAX,
} from './viewSheet.js';
const layout = viewLayout(AIRCRAFT_VIEWS.sheet);
const RAD = Math.PI / 180;
const HORIZON = 12; // the ring at 90° from straight above
/** The pinned layout: rings 7.5° apart, 302 frames a subject. */
const RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22];
const FIRSTS = [
0, 1, 5, 12, 22, 35, 51, 69, 89, 111, 134, 158, 183, 208, 233, 257, 280,
];
/** A unit `[forward, right, up]` `offDeg` from straight above, at `bearingDeg`
* from dead ahead toward the right side. */
function direction(offDeg, bearingDeg) {
const off = offDeg * RAD;
const bearing = bearingDeg * RAD;
return [
Math.sin(off) * Math.cos(bearing),
Math.sin(off) * Math.sin(bearing),
Math.cos(off),
];
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const mirror = (v) => [v[0], -v[1], v[2]];
const near = (a, b, eps = 1e-9) =>
a.every((value, i) => Math.abs(value - b[i]) < eps);
/** The smallest rotation taking up onto `d`, applied to forward (Rodrigues). */
function rotatedForward(d) {
const up = [0, 0, 1];
const forward = [1, 0, 0];
const axis = cross(up, d);
const sin = Math.hypot(...axis);
const cos = dot(up, d);
if (sin < 1e-12) return forward;
const k = axis.map((value) => value / sin);
const kxv = cross(k, forward);
const kv = dot(k, forward);
return forward.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
}
test('viewLayout gives the aircraft sheet each ring’s first frame', () => {
assert.deepEqual(layout.rings, RINGS);
assert.deepEqual(layout.firsts, FIRSTS);
assert.equal(layout.frames, 302);
assert.equal(layout.columns, 64);
assert.equal(layout.rows, 57);
assert.equal(layout.ringStepRad, 7.5 * RAD);
assert.notEqual(layout.rings, AIRCRAFT_VIEWS.sheet.rings, 'a copy');
});
test('viewLayout refuses a sheet it cannot draw', () => {
const sheet = AIRCRAFT_VIEWS.sheet;
const bad = [
null,
{ ...sheet, image: '' },
{ ...sheet, image: undefined },
{ ...sheet, cellPx: 63.5 },
{ ...sheet, columns: 0 },
{ ...sheet, rows: -32 },
{ ...sheet, rings: [] },
{ ...sheet, rings: 'many' },
{ ...sheet, rings: Array(VIEW_RINGS_MAX + 1).fill(1) },
{ ...sheet, rings: [3, 5] },
{ ...sheet, rings: [1, 2.5] },
{ ...sheet, rings: [1, 0] },
{ ...sheet, ringStepDeg: 0 },
{ ...sheet, ringStepDeg: -15 },
{ ...sheet, ringStepDeg: Number.NaN },
{ ...sheet, ringStepDeg: Infinity },
// A ring straight below, or past it.
{ ...sheet, rings: [1, 4, 4, 1], ringStepDeg: 60 },
{ ...sheet, rings: Array(13).fill(1), ringStepDeg: 15 },
];
for (const sheetGiven of bad)
assert.throws(
() => viewLayout(sheetGiven),
TypeError,
JSON.stringify(sheetGiven),
);
// Short of straight below, and the most rings there may be, are drawn.
assert.equal(viewLayout({ ...sheet, rings: Array(12).fill(1) }).frames, 12);
assert.equal(
viewLayout({
...sheet,
rings: Array(VIEW_RINGS_MAX).fill(1),
ringStepDeg: 10,
}).rings.length,
VIEW_RINGS_MAX,
);
});
test('straight above is frame 0, whatever the course', () => {
assert.deepEqual(viewFrame(layout, [0, 0, 1]), {
frame: 0,
ring: 0,
index: 0,
mirrored: false,
});
assert.equal(viewFrame(layout, [0, 0, 42]).frame, 0, 'any length');
assert.equal(viewFrame(layout, direction(3.7, 135)).frame, 0);
assert.equal(viewFrame(layout, [0, 0, 0]).frame, 0, 'no direction: above');
});
test('on the horizon, dead ahead, abeam and astern are the first, middle and last frames of ring 12', () => {
const first = layout.firsts[HORIZON];
const ahead = viewFrame(layout, [1, 0, 0]);
assert.deepEqual(ahead, {
frame: first,
ring: 12,
index: 0,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [0, 1, 0]), {
frame: first + 12,
ring: 12,
index: 12,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [-1, 0, 0]), {
frame: first + 24,
ring: 12,
index: 24,
mirrored: false,
});
});
test('the left side draws the right side’s frame mirrored', () => {
for (const [off, bearing] of [
[30, 40],
[90, 90],
[105, 170],
[60, 1],
]) {
const right = viewFrame(layout, direction(off, bearing));
const left = viewFrame(layout, mirror(direction(off, bearing)));
assert.equal(left.frame, right.frame, `${off}/${bearing}`);
assert.equal(right.mirrored, false);
assert.equal(left.mirrored, true);
}
// Exactly on the centre plane it is not mirrored.
assert.equal(viewFrame(layout, [1, 0, 0]).mirrored, false);
assert.equal(viewFrame(layout, [1, -0, 0]).mirrored, false);
});
test('below the last ring the eye takes the last ring', () => {
const last = layout.rings.length - 1;
for (const off of [120, 126, 135, 170, 180]) {
const view = viewFrame(layout, direction(off, 90));
assert.equal(view.ring, last, `${off}°`);
}
assert.equal(viewFrame(layout, [0, 0, -1]).frame, layout.firsts[last]);
});
test('frames round to the nearest, between rings and between bearings', () => {
// Rings are 7.5° apart: 3.75° from straight above is between ring 0 and 1.
assert.equal(viewFrame(layout, direction(3.7, 0)).ring, 0);
assert.equal(viewFrame(layout, direction(3.8, 0)).ring, 1);
assert.equal(viewFrame(layout, direction(86.2, 0)).ring, 11);
assert.equal(viewFrame(layout, direction(86.3, 0)).ring, 12);
// The horizon ring's 25 frames are 7.5° of bearing apart.
assert.equal(viewFrame(layout, direction(90, 3.7)).index, 0);
assert.equal(viewFrame(layout, direction(90, 3.8)).index, 1);
assert.equal(viewFrame(layout, direction(90, 176.2)).index, 23);
assert.equal(viewFrame(layout, direction(90, 176.3)).index, 24);
// Ring 1's 4 frames are 60° apart.
assert.equal(viewFrame(layout, direction(7.5, 29.9)).index, 0);
assert.equal(viewFrame(layout, direction(7.5, 30.1)).index, 1);
});
test('frameDirection is where viewFrame finds each frame of the sheet', () => {
let frames = 0;
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-12, 'unit');
const view = viewFrame(layout, d);
assert.equal(view.ring, ring, `${ring}/${index}`);
assert.equal(view.index, index, `${ring}/${index}`);
assert.equal(view.frame, layout.firsts[ring] + index);
// A frame on the centre plane is its own mirror image: either way
// draws it.
if (Math.abs(d[1]) > 1e-12) assert.equal(view.mirrored, mirrored);
}
frames++;
}
assert.equal(frames, AIRCRAFT_VIEWS.frames);
});
test('frameUp is a unit vector across the view, forward from straight above, and turns as the smallest rotation does', () => {
assert.ok(near(frameUp([0, 0, 1]), [1, 0, 0]), 'nose up the image');
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++)
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
const up = frameUp(d);
const at = `${ring}/${index}${mirrored ? ' mirrored' : ''}`;
assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9, `unit at ${at}`);
assert.ok(Math.abs(dot(up, d)) < 1e-9, `across the view at ${at}`);
assert.ok(
near(up, rotatedForward(d)),
`the smallest rotation at ${at}`,
);
// Mirroring the eye mirrors the image's up.
assert.ok(near(frameUp(mirror(d)), mirror(up)), `mirrored at ${at}`);
}
// On the horizon, abeam: the nose still points up the image.
assert.ok(near(frameUp([0, 1, 0]), [1, 0, 0]));
// Dead ahead on the horizon: the image's up is straight down the aircraft.
assert.ok(near(frameUp([1, 0, 0]), [0, 0, -1]));
});
test('viewUniforms packs the layout as the shader reads it', () => {
const { grid, rings } = viewUniforms(layout);
assert.deepEqual(grid, [64, 57, 7.5 * RAD, 17]);
// Two rings a vector: each ring's frames and its first frame.
assert.equal(rings.length, VIEW_RINGS_MAX / 2);
const pairs = [];
for (let k = 0; k < RINGS.length; k += 2)
pairs.push([RINGS[k], FIRSTS[k], RINGS[k + 1] ?? 1, FIRSTS[k + 1] ?? 0]);
assert.deepEqual(rings.slice(0, pairs.length), pairs);
for (const pair of rings.slice(pairs.length))
assert.deepEqual(pair, [1, 0, 1, 0], 'padding');
});
test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet', () => {
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(
frames,
sheet.rings.reduce((a, b) => a + b, 0),
);
assert.equal(frames, 302);
assert.equal(sheet.cellPx * sheet.columns, 4096);
assert.equal(sheet.cellPx * sheet.rows, 3648);
assert.equal(sheet.grey, true, 'kept as grey and alpha');
const firsts = Object.values(subjects);
firsts.forEach((first, i) => {
assert.equal(first, i * frames, 'in order, one block after another');
assert.equal(first % frames, 0);
assert.ok(first + frames <= sheet.columns * sheet.rows, 'on the sheet');
});
assert.ok(Object.isFrozen(AIRCRAFT_VIEWS));
assert.ok(Object.isFrozen(sheet));
assert.ok(Object.isFrozen(sheet.rings));
assert.ok(Object.isFrozen(subjects));
});
const BAKE = new URL('../../scripts/bake-view-sheet.py', import.meta.url);
/** The sheets the bake script bakes: its config name, the layout it must
* match, the files it ships and the size the layout pins. */
const SHEETS = [
{
config: 'AIRCRAFT',
views: AIRCRAFT_VIEWS,
name: 'aircraft-views',
frames: 302,
size: [4096, 3648],
},
{
config: 'VESSELS',
views: VESSEL_VIEWS,
name: 'vessel-views',
frames: 208,
size: [4096, 2496],
},
];
/** A sheet's entry in the bake script: `NAME = { ... }`. */
function bakeConfig(script, config) {
const block = new RegExp(`^${config} = \\{([\\s\\S]*?)^\\}`, 'm').exec(
script,
);
assert.ok(block, `${config} in the bake script`);
const field = (key) => {
const match = new RegExp(`^\\s*"${key}": (.+),$`, 'm').exec(block[1]);
assert.ok(match, `${config}.${key} in the bake script`);
return JSON.parse(match[1]);
};
const names = [...block[1].matchAll(/^\s*\("(\w+)", "([\w/.]+)"/gm)];
return {
field,
names: names.map((m) => m[1]),
models: names.map((m) => m[2]),
};
}
for (const { config, views, name, frames, size } of SHEETS) {
test(`${views.id} is pinned: ${frames} frames a subject, ${size.join(' × ')} px`, () => {
const { sheet } = views;
assert.equal(views.frames, frames);
assert.equal(viewLayout(sheet).frames, frames);
assert.equal(sheet.cellPx * sheet.columns, size[0]);
assert.equal(sheet.cellPx * sheet.rows, size[1]);
assert.equal(sheet.image, `/sprites/${name}.webp`);
assert.equal(sheet.grey, true);
});
test(`the bake script lays ${views.id} out as the layout says`, () => {
const { field, names } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(field('name'), name);
assert.equal(field('ring_step_deg'), sheet.ringStepDeg);
assert.deepEqual(field('rings'), [...sheet.rings]);
assert.equal(field('columns'), sheet.columns);
assert.deepEqual(
names,
Object.keys(subjects),
'the same subjects in order',
);
// The script's rows: as many as its subjects' blocks take.
assert.equal(
Math.ceil((names.length * frames) / sheet.columns),
sheet.rows,
);
});
const manifestUrl = new URL(
`../../public/sprites/${name}.json`,
import.meta.url,
);
test(`the baked manifest matches ${views.id}`, () => {
// Shipped with the app: a missing manifest fails, it does not skip.
assert.ok(existsSync(manifestUrl), `public/sprites/${name}.json`);
const manifest = JSON.parse(readFileSync(manifestUrl, 'utf8'));
const { models } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(manifest.cellPx, sheet.cellPx);
assert.equal(manifest.columns, sheet.columns);
assert.equal(manifest.rows, sheet.rows);
assert.equal(manifest.ringStepDeg, sheet.ringStepDeg);
assert.deepEqual(manifest.rings, [...sheet.rings]);
assert.equal(manifest.grey, true);
assert.equal(manifest.image, `${name}.webp`);
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
Object.entries(subjects).forEach(([subject, first], i) => {
assert.equal(manifest.subjects[subject].first, first, subject);
assert.equal(manifest.subjects[subject].model, models[i], subject);
assert.ok(manifest.subjects[subject].radiusM > 0, `${subject} baked`);
});
});
const sheetUrl = new URL(
`../../public/sprites/${name}.webp`,
import.meta.url,
);
test(`the shipped ${name}.webp is the size the layout says, grey, and clear at every cell’s edge`, async () => {
assert.ok(existsSync(sheetUrl), `public/sprites/${name}.webp`);
const { default: sharp } = await import('sharp');
const { sheet, subjects } = views;
const { data, info } = await sharp(fileURLToPath(sheetUrl))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
assert.equal(info.width, sheet.columns * sheet.cellPx);
assert.equal(info.height, sheet.rows * sheet.cellPx);
const at = (x, y) => (y * info.width + x) * 4;
// Grey: the renderer reads the red channel as the grey.
for (let i = 0; i < data.length; i += 4)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2])
assert.fail(`not grey at pixel ${i / 4}`);
// Each used cell keeps its outer 2 px transparent (the mipmaps), and
// has something in it.
const used = Object.keys(subjects).length * frames;
const c = sheet.cellPx;
for (let n = 0; n < used; n++) {
const left = (n % sheet.columns) * c;
const top = Math.floor(n / sheet.columns) * c;
let drawn = 0;
for (let y = 0; y < c; y++)
for (let x = 0; x < c; x++) {
const alpha = data[at(left + x, top + y) + 3];
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) drawn += alpha;
else if (alpha !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
assert.ok(drawn > 0, `cell ${n} is empty`);
}
});
}
test('in the bake’s axes (nose −X, starboard +Y, up +Z) a frame has the same up and direction', () => {
// The bake turns forward by Blender's rotation_difference(UP, d), in its
// own axes, which are mirrored from [forward, right, up]: the smallest
// rotation is the same rotation in either.
const toBake = (v) => [-v[0], v[1], v[2]];
const minimal = (from, to, v) => {
const axis = cross(from, to);
const sin = Math.hypot(...axis);
const cos = dot(from, to);
if (sin < 1e-12) return v;
const k = axis.map((value) => value / sin);
const kxv = cross(k, v);
const kv = dot(k, v);
return v.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
};
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
const d = frameDirection(layout, ring, index);
const bakeUp = minimal([0, 0, 1], toBake(d), toBake([1, 0, 0]));
assert.ok(near(toBake(frameUp(d)), bakeUp), `${ring}/${index}`);
}
});
/** A blend's weight by frame (a frame listed twice counts once, summed). */
-52
View File
@@ -1,52 +0,0 @@
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
import { START_VIEW } from './camera.js';
/**
* The visitor's country, guessed from the browser's time zone and, for a zone
* that belongs to no country (UTC), the region of a preferred language
* ("en-GB"). Nothing leaves the browser. Null when neither names one.
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
* @returns {string|null} ISO 3166 code, e.g. 'DE'
*/
export function homeCountry({
timeZone = currentTimeZone(),
languages = globalThis.navigator?.languages ?? [],
} = {}) {
const byZone = ZONE_COUNTRIES[timeZone];
if (byZone) return byZone;
for (const language of languages) {
const region = regionOf(language);
if (region && COUNTRY_CENTRES[region]) return region;
}
return null;
}
/**
* The start view over the visitor's country: the planet from `base.height`,
* looking straight down on the country's centre. `base` where the country is
* unknown.
* @param {{timeZone?: string|null, languages?: readonly string[],
* base?: {lon: number, lat: number, height: number}}} [where]
*/
export function homeCountryView({ base = START_VIEW, ...where } = {}) {
const centre = COUNTRY_CENTRES[homeCountry(where)];
if (!centre) return base;
const [lat, lon] = centre;
return Object.freeze({ lon, lat, height: base.height });
}
function currentTimeZone() {
try {
return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
} catch {
return null;
}
}
function regionOf(language) {
try {
return new Intl.Locale(language).region ?? null;
} catch {
return null;
}
}
-53
View File
@@ -1,53 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { homeCountry, homeCountryView } from './homeCountry.js';
import { START_VIEW } from './camera.js';
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
test('the time zone names the country, in its tzdata or ICU name', () => {
assert.equal(homeCountry({ timeZone: 'Europe/Berlin', languages: [] }), 'DE');
assert.equal(homeCountry({ timeZone: 'Asia/Kolkata', languages: [] }), 'IN');
assert.equal(homeCountry({ timeZone: 'Asia/Calcutta', languages: [] }), 'IN');
assert.equal(homeCountry({ timeZone: 'Europe/Kiev', languages: [] }), 'UA');
assert.equal(
homeCountry({ timeZone: 'America/Chicago', languages: ['de-DE'] }),
'US',
'the zone outranks the language',
);
});
test("a zone of no country falls back to a language's region", () => {
assert.equal(
homeCountry({ timeZone: 'UTC', languages: ['fr', 'en-GB'] }),
'GB',
);
assert.equal(homeCountry({ timeZone: 'Etc/UTC', languages: ['ru'] }), null);
assert.equal(homeCountry({ timeZone: null, languages: [] }), null);
});
test('the start view looks down on the country from the planet height', () => {
const view = homeCountryView({ timeZone: 'Asia/Tokyo', languages: [] });
assert.deepEqual(
[view.lat, view.lon, view.height],
[...COUNTRY_CENTRES.JP, START_VIEW.height],
);
assert.equal(
homeCountryView({ timeZone: 'UTC', languages: [] }),
START_VIEW,
'unknown: the default start',
);
});
test('every zone has a country with a centre on the globe', () => {
for (const [zone, country] of Object.entries(ZONE_COUNTRIES)) {
const centre = COUNTRY_CENTRES[country];
assert.ok(centre, `${zone} → ${country}`);
const [lat, lon] = centre;
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, country);
}
// Countries whose largest part is not where their centroid would be.
const [usLat, usLon] = COUNTRY_CENTRES.US;
assert.ok(usLat > 30 && usLat < 45 && usLon > -110 && usLon < -85);
const [frLat, frLon] = COUNTRY_CENTRES.FR;
assert.ok(frLat > 42 && frLat < 50 && frLon > -2 && frLon < 8);
});
+2 -1
View File
@@ -21,11 +21,12 @@ const PIN_TURN_DEG = 0.1;
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
* planned, and settling a grounded contact puts it straight onto the floor.
*/
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
const icons = createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'flights',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -948,7 +948,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1130,6 +1135,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+34 -15
View File
@@ -1,5 +1,9 @@
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
aircraftViewRef,
registerAircraftViews,
} from '../../data/aircraftViews.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
@@ -13,6 +17,7 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
@@ -148,6 +153,9 @@ export function createLocalAdsbLayer({
* @type {{markers: object, rings: object}|null}
*/
let sets = null;
/** Whether the renderer draws markers from the aircraft view sheet
* (`aircraftViews.js`), set at `init`. */
let views = false;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -355,31 +363,36 @@ export function createLocalAdsbLayer({
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright.
* ground station's mast upright. On a renderer that draws view sheets, a
* kind with rendered views is drawn from the sheet along its course;
* every other marker is its flat glyph turned on screen.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
const frame =
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined;
const view = views ? aircraftViewRef(kind, frame) : null;
return {
id: marker.id,
pos: marker.position,
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
image: view ?? aircraftIcon(kind, undefined, frame),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
...(view
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
: {
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
}),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -773,6 +786,11 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
const draw = drawOf(viewer);
views = registerAircraftViews(
draw,
rendererOf(viewer)?.capabilities ?? null,
resolveAsset,
);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
@@ -872,6 +890,7 @@ export function createLocalAdsbLayer({
models = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
views = false;
viewer = null;
void receiver.destroy?.();
},
+58
View File
@@ -223,6 +223,7 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds,
services: { ...services, ...options.services },
now: () => clock.now,
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
});
layer.init(viewer);
await layer.enable();
@@ -319,6 +320,63 @@ test('local aircraft use their class silhouette at one size in magenta', async (
assert.equal(detectable.type, 'AIR');
});
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { drillPick: () => [] },
capabilities: new Set(['viewSheets']),
});
fakeInput(viewer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer },
resolveAsset: (url) => `/gev${url}`,
});
t.after(() => layer.destroy());
// Registered once, at the layer's own asset URL.
assert.deepEqual(draw.viewSheets, [
[
AIRCRAFT_VIEWS.id,
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
],
]);
receiver.set({
aircraft: [
record({ trackDeg: 0 }),
record({ icao: 'a0b702', category: 'A7' }),
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
const icon = iconOf(draw, 'local-adsb:abc123');
assert.equal(icon.image, aircraftViewRef('airliner'));
assert.equal(icon.rotationMode, 'course');
assert.equal(icon.course, 0);
assert.equal('rotation' in icon, false);
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(
iconOf(draw, 'local-adsb:a0b702').image,
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
'the rotor turns through the sheet',
);
const vehicle = iconOf(draw, 'local-adsb:a0c001');
assert.equal(vehicle.image, aircraftIcon('vehicle'));
assert.equal(vehicle.rotationMode, 'screen');
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+2 -1
View File
@@ -8,11 +8,12 @@ import {
} from './policy.js';
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
return createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'military',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -396,7 +396,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1087,6 +1092,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+2 -18
View File
@@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => {
};
await assert.rejects(
searchHls({
box: { west: -181, south: 0, east: -179, north: 1 },
box: { west: 179, south: 0, east: -179, north: 1 },
fetchImpl,
}),
/±180/,
/dateline/,
);
await assert.rejects(
searchHls({ box: BOX, now: 'never', fetchImpl }),
@@ -251,22 +251,6 @@ 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}` }));
+4 -9
View File
@@ -581,8 +581,6 @@ 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
@@ -590,8 +588,6 @@ export function createRecentImageryLayer({
: (slotId === 'a') !== _swapped
? 'left'
: 'right',
availableBoxes,
emptyBoxes,
});
} else {
renderer.hideSlot(slotId);
@@ -901,22 +897,21 @@ 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],
);
// 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();
if (drapesChanged && !pruned && !followed) syncRender();
notify('thumbnail');
if (pruned || followed || drapesChanged || moved) notify();
if (pruned || followed || drapesChanged) notify();
});
syncHost();
if (_box && !_candidates.length) void runSearch();
+1 -428
View File
@@ -1,10 +1,6 @@
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';
@@ -18,16 +14,11 @@ import {
SPLIT_PUBLISH_MS,
createRecentImageryLayer,
} from './index.js';
import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { createImageryBoxPreview } from './rendering.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import {
BOX,
CANDIDATES,
FIJI_BOX,
boxToolFakes,
candidate,
fakeCatalog,
@@ -1573,424 +1564,6 @@ 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],
+24 -93
View File
@@ -72,11 +72,13 @@ 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;
@@ -85,11 +87,6 @@ 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] = [
@@ -108,45 +105,8 @@ function normalizeBox(box) {
}
/**
* 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.
* 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.
* @param {object} box Degrees box.
* @returns {{ width: number, height: number }}
*/
@@ -156,7 +116,7 @@ export function boxSideKm(box) {
const midLat = (normalized.south + normalized.north) / 2;
return {
width:
lonSpanDeg(normalized.west, normalized.east) *
(normalized.east - normalized.west) *
KM_PER_DEG_LAT *
Math.cos(toRadians(midLat)),
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
@@ -166,11 +126,9 @@ export function boxSideKm(box) {
const refuse = (reason, message) => ({ ok: false, reason, message });
/**
* 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.
* Validate a selection box for the catalog and the tile providers.
* @param {object} box Degrees box.
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
*/
export function validateBox(box) {
const normalized = normalizeBox(box);
@@ -178,6 +136,8 @@ 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
@@ -186,7 +146,7 @@ export function validateBox(box) {
'polar',
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
);
if (lonSpanDeg(west, east) === 0 || north === south)
if (east === west || 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)
@@ -223,9 +183,7 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
}
/**
* 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.
* The centre of a box that does not cross the dateline, in degrees.
* @param {object} box Degrees box.
* @returns {{ lon: number, lat: number } | null}
*/
@@ -233,18 +191,14 @@ export function boxCentre(box) {
const normalized = normalizeBox(box);
if (!normalized) return null;
return {
lon: wrapLon(
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
),
lon: (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. 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.
* widens by 1/cos(lat)); null when the result would not validate.
* @param {number} lon Degrees.
* @param {number} lat Degrees.
* @param {number} [sideKm]
@@ -253,19 +207,16 @@ 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: wrapLon(lon - halfLon),
west: lon - halfLon,
south: clampLat(lat - halfLat),
east: wrapLon(lon + halfLon),
east: lon + halfLon,
north: clampLat(lat + halfLat),
});
return result.ok ? result.box : null;
@@ -498,31 +449,15 @@ 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 = [
[project(west), south],
[project(east), south],
[project(east), north],
[project(west), north],
[project(centre.lon), centre.lat],
[west, south],
[east, south],
[east, north],
[west, north],
[(west + east) / 2, (south + north) / 2],
];
return samples.every(([lon, lat]) =>
footprints.some((ring) =>
pointInPolygon(
lon,
lat,
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
),
),
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
)
? 'full'
: 'partial';
@@ -671,10 +606,6 @@ 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,
+9 -120
View File
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
import {
boxFromPin,
lonSpanDeg,
nonCrossingBoxes,
boxFromRectangle,
boxSideKm,
coverageFor,
@@ -53,20 +51,11 @@ function hls(product, day, clouds, extra = {}) {
return { ...groupGranulesByDay(granules)[0], ...extra };
}
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
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: 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',
reason({ west: 179, south: 0, east: -179, north: 1 }),
'dateline',
);
assert.equal(
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
@@ -81,6 +70,10 @@ test('validateBox refuses polar, degenerate, invalid and oversized boxes, and ac
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,
@@ -144,14 +137,10 @@ 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; a dateline box uses the short arc', () => {
test('box width is the longitude span at the mid-latitude, never the shortest 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);
@@ -160,13 +149,6 @@ test('box width is the longitude span at the mid-latitude; a dateline box uses t
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', () => {
@@ -185,12 +167,7 @@ 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(181, 0), null, 'longitude out of range');
assert.equal(
boxFromPin(0, 0, 400000),
null,
'half-width of 90 degrees or more',
);
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
});
@@ -321,34 +298,6 @@ 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]),
@@ -480,17 +429,6 @@ 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', () => {
@@ -499,52 +437,3 @@ 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);
});
+24 -97
View File
@@ -1,7 +1,7 @@
/**
* 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.
* 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.
* 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,13 +15,7 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { markBaseTileset } from '../../render/baseTilesets.js';
import { drawOf } from '../../render/rendererOf.js';
import {
PRODUCTS,
boxKey,
gibsTemplate,
lonSpanDeg,
nonCrossingBoxes,
} from './model.js';
import { PRODUCTS, gibsTemplate } from './model.js';
const SLOT_IDS = ['a', 'b'];
const SPLITS = new Set(['left', 'right', 'none']);
@@ -35,27 +29,8 @@ function clampAlpha(value) {
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
}
/** 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)));
}
const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* Admit a tile request while the semaphore has room. A request that finds
@@ -102,7 +77,7 @@ export function createRecentImageryRenderer({
let host = NO_HOST;
let destroyed = false;
const admission = { limit: maxTileRequests, inFlight: 0 };
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
const owned = { a: null, b: null };
const admit = admitTileRequests(admission, requestRender);
@@ -130,53 +105,36 @@ export function createRecentImageryRenderer({
const record = owned[slotId];
if (!record) return false;
owned[slotId] = null;
for (const layer of record.layers) layer.remove();
record.layer.remove();
return true;
}
function applyLook(record) {
for (const layer of record.layers) {
layer.alpha = record.alpha;
layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
record.layer.alpha = record.alpha;
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
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,
};
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 };
applyLook(owned[slotId]);
return true;
}
return {
/**
* 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.
* Drape a candidate into a slot. The same candidate on the same host only
* updates its look; anything else replaces the slot's layer.
* @param {'a'|'b'} slotId
* @param {object} candidate
* @param {object} box Degrees box.
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
* @returns {boolean} Whether a layer is now draped for the slot.
*/
showSlot(
slotId,
candidate,
box,
{
alpha = 1,
splitDirection = 'none',
availableBoxes = null,
emptyBoxes = null,
} = {},
{ alpha = 1, splitDirection = 'none' } = {},
) {
if (destroyed || !candidate?.key || !box) return false;
if (!host.globe) {
@@ -185,52 +143,21 @@ 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 &&
parts.length
boxKey(current.box) === boxKey(box)
) {
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
) {
if (current.alpha !== look.alpha || current.split !== look.split) {
Object.assign(current, look);
applyLook(current);
requestRender('recent-imagery-look');
}
return true;
}
const removed = removeOwned(slotId);
if (!mount(slotId, { candidate, parts, ...look })) {
if (removed) requestRender('recent-imagery-hide');
return false;
}
removeOwned(slotId);
mount(slotId, { candidate, box, ...look });
requestRender('recent-imagery-show');
return true;
},
@@ -294,7 +221,7 @@ export function createRecentImageryRenderer({
return out;
},
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
/** Number of layers this renderer owns (never above two). */
ownedCount() {
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
},
@@ -320,11 +247,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) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
Boolean(box) && box.east > box.west && box.north > box.south;
/** A box with no extent draws nothing: a press that has not moved yet. */
const hasExtent = (box) =>
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
Boolean(box) && (box.east > box.west || box.north > box.south);
/**
* The box tool's preview: the box being dragged, a translucent fill and a
+1 -210
View File
@@ -5,9 +5,7 @@ import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { boxKey, nonCrossingBoxes } from './model.js';
import { BOX, FIJI_BOX } from './testDoubles.mjs';
import { BOX } from './testDoubles.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
@@ -273,210 +271,3 @@ 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();
});
+11 -152
View File
@@ -1,107 +1,10 @@
import { searchHls } from './catalog.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;
}
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
/**
* 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),
@@ -109,68 +12,24 @@ 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 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,
},
),
),
const response = await fetchImpl(
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box,
width: size,
height: size,
}),
{ signal },
);
signal?.throwIfAborted();
// 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'),
});
return response;
},
getTileTemplate: (product, day) => tileTemplate(product, day),
};
+10 -253
View File
@@ -1,20 +1,13 @@
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) => {
@@ -23,263 +16,27 @@ 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');
// 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(calls[0][1].signal, controller.signal);
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({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
await assert.rejects(source.getThumbnail({}, {}, { 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);
});
-7
View File
@@ -16,13 +16,6 @@ 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. */
+8 -43
View File
@@ -1,6 +1,6 @@
/**
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
* candidate day. 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,28 +8,16 @@
* 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 { boxKey, thumbnailOrder } from './model.js';
import { createRecentImagerySource, dataPresent } from './source.js';
import { thumbnailOrder } from './model.js';
import { createRecentImagerySource } 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]
*/
@@ -102,22 +90,18 @@ 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 = dataPresent(response);
const present = String(
response.headers?.get?.('Data-Present') ?? '',
).toLowerCase();
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
if (present === 'false') {
status = 'empty';
@@ -133,11 +117,7 @@ export function createThumbnailLoader({
} catch (error) {
if (controller.signal.aborted || error?.name === 'AbortError')
cancelled = true;
else {
status = 'error';
availableBoxes = error?.presentBoxes ?? availableBoxes;
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
}
else status = 'error';
} finally {
inFlight -= 1;
entry.loading = false;
@@ -149,17 +129,6 @@ 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;
@@ -227,8 +196,6 @@ export function createThumbnailLoader({
status: 'unknown',
objectUrl: null,
acquisitionTime: null,
availableBoxes: null,
emptyBoxes: null,
loading: false,
controller: null,
touched: 0,
@@ -305,7 +272,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, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
*/
get(key) {
const entry = entries.get(key);
@@ -314,8 +281,6 @@ export function createThumbnailLoader({
status: entry.status,
objectUrl: entry.objectUrl,
acquisitionTime: entry.acquisitionTime,
availableBoxes: entry.availableBoxes,
emptyBoxes: entry.emptyBoxes,
loading: entry.loading,
};
},
+7 -74
View File
@@ -1,9 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createThumbnailLoader } from './thumbnails.js';
import { createRecentImagerySource } from './source.js';
import { nonCrossingBoxes } from './model.js';
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
import { BOX, response, settle } from './testDoubles.mjs';
const candidate = (product, day) => ({
key: `${product}:${day}`,
product,
day,
});
/** A fetch whose responses the test releases, in any order. */
function fakeFetch() {
@@ -64,8 +68,6 @@ 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');
@@ -335,75 +337,6 @@ 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');
+72 -2
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createVesselLayer } from './index.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { VESSEL_VIEWS } from '../../data/viewSheet.js';
// Following the world clock on a renderer that moves icons along motion
// segments on its own clock, each vessel's icon is drawn along its track
@@ -10,7 +12,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
@@ -35,6 +37,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
clearOverlaySource: noop,
},
geoid: {},
...(fleet ? { fleet } : null),
sprites: {},
focus: {
focusNowMs: () => 0,
@@ -68,7 +71,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
);
return { layer, viewer, icons };
return { layer, viewer, icons, draw };
}
const T = 1_000_000;
@@ -282,3 +285,70 @@ test('going live, a vessel a live update has drawn since stays where that drew i
assert.deepEqual(icons().items.get(id).pos, visual.position);
}
});
test('on a renderer that draws view sheets a vessel is a view of its hull, an aid still its buoy', (t) => {
const { layer, viewer, icons, draw } = setup(t, {
capabilities: new Set(['motionSegments', 'viewSheets']),
fleet: { resolveAsset: (url) => `/gev${url}` },
});
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
{ ...row(minuteFixes), mmsi: '222', type: '36' },
{ ...row(minuteFixes), mmsi: '333', type: '50' },
{ ...row(minuteFixes), mmsi: '993672001', type: 'Port Hand Mark' },
]);
// The sheet, once, at the layer's asset URL.
assert.deepEqual(draw.viewSheets, [
[
VESSEL_VIEWS.id,
{ ...VESSEL_VIEWS.sheet, image: '/gev/sprites/vessel-views.webp' },
],
]);
const set = icons();
const cargo = set.items.get('111');
assert.deepEqual(cargo.image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.cargo,
fallback: vesselSprite('cargo'),
});
assert.equal(cargo.rotationMode, 'course', 'a view lies along its course');
assert.equal(cargo.imageLod, undefined);
assert.equal(set.items.get('222').image.first, VESSEL_VIEWS.subjects.sailing);
// A pilot boat: its own hull from the sheet, a service boat's flat hull.
assert.deepEqual(set.items.get('333').image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
const buoy = set.items.get('993672001');
assert.equal(buoy.image, aidSprite());
assert.equal(buoy.rotationMode, 'screen');
});
test('without view sheets a vessel keeps its flat hull', (t) => {
const { layer, viewer, icons, draw } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
]);
assert.deepEqual(draw.viewSheets, []);
assert.equal(icons().items.get('111').image, vesselSprite('cargo'));
});
test('a vessel is drawn larger near than far, under an aircraft at every range, and recedes toward the horizon', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
// The fastest step of a vessel's own scale.
{ ...row(minuteFixes), type: 'Cargo', speed: 20 },
]);
const set = icons();
assert.deepEqual(set.spec.recede, {}, "the renderer's own recession");
const item = set.items.get('111');
const curve = item.scaleByDistance;
const px = (value) => item.size[0] * item.scale * value;
assert.ok(px(curve.nearValue) > px(1), 'larger up close than it was');
// An aircraft icon: 20 px, three times that near and half of it far, over
// the same range (aircraftIconLayer.js).
assert.deepEqual([curve.near, curve.far], [1000, 8000000]);
assert.ok(px(curve.nearValue) < 20 * 3);
assert.ok(px(curve.farValue) < 20 * 0.5);
});
+56 -12
View File
@@ -44,8 +44,13 @@ import {
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { vesselPartState } from '../../data/modelPartDrivers.js';
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
import {
isAidToNavigation,
vesselKind,
vesselShape,
} from '../../data/vesselTypes.js';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { registerVesselViews, vesselViewRef } from '../../data/vesselViews.js';
import { cssColor } from '../../render/color.js';
import { KNOT_MPS } from '../../data/units.js';
@@ -61,6 +66,19 @@ const HIDDEN_FOLLOW_MS = 250;
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
const SHIP_ICON_PX = 32;
/**
* How a vessel or aid sprite's size follows its range from the eye, on the
* aircraft icons' range (`aircraftIconLayer.js`): half as large again up
* close, where a hull's shape reads; as it was drawn before at some
* 1,000 km; and a third from 8,000 km out. Under an aircraft's icon at every
* range, so a world of ships is a field of small marks.
*/
const SHIP_SCALE_BY_DISTANCE = Object.freeze({
near: 1000,
nearValue: 1.5,
far: 8000000,
farValue: 0.35,
});
let instances = 0;
@@ -228,6 +246,7 @@ export function createRendering({
advanceSpriteFocus,
focusAlphaNeedsWrite,
spriteFocusAtRest,
nearFarScalarValueAtDistance,
} = services.focus;
const {
holdContinuousRender,
@@ -265,12 +284,22 @@ export function createRendering({
const capabilities = rendererOf(viewer)?.capabilities ?? null;
iconMotion = capabilities?.has('motionSegments') === true;
segmentsWere = segmentsOn();
// On a renderer that draws view sheets a vessel is the view of its
// hull from where the eye is, not the flat hull.
iconViews = registerVesselViews(
drawOf(viewer),
capabilities,
services.fleet?.resolveAsset,
);
const set = drawOf(viewer).icons({
id: `ais-vessels:${++instances}`,
// Translucent, as its billboards were: overlapping chevrons keep
// their outlines rather than the first one's fill.
blend: 'translucent',
horizonCull: true,
// Toward the horizon a vessel shrinks and fades, as an aircraft does
// (the renderer's defaults, which are the aircraft sets').
recede: {},
drawOrder: spriteDrawOrder?.('ais') ?? 0,
...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null),
});
@@ -286,6 +315,8 @@ export function createRendering({
// segments on its own clock.
let iconSet = null;
let iconMotion = false;
// Whether a vessel's icon is drawn from the vessel view sheet.
let iconViews = false;
// Whether the icons last moved on the renderer's clock.
let segmentsWere = false;
// The record drawn under each icon id, for replanning an id.
@@ -381,6 +412,7 @@ export function createRendering({
state.icons?.dispose();
state.icons = null;
iconSet = null;
iconViews = false;
iconRecords.clear();
planFrom.clear();
replannedAtMs = -Infinity;
@@ -430,6 +462,7 @@ export function createRendering({
// Tinted by type; selection changes neither the colour nor the size.
color: shipTint(record),
scale: shipScale(record),
scaleByDistance: SHIP_SCALE_BY_DISTANCE,
// An aid's buoy stands upright on screen; a vessel turns with course.
rotationMode: aid ? 'screen' : 'course',
rotation: 0,
@@ -529,18 +562,22 @@ export function createRendering({
}
/**
* The sprite a vessel is drawn as: the white hull of its kind
* (`vesselKind`), bow up so the row's course turns it to its heading, or
* for an aid to navigation the buoy. The layer tints it
* (`shipTint`), so each shape takes one icon-atlas slot.
* The sprite a vessel is drawn as: on a renderer that draws view sheets,
* the view of its kind's hull (`vesselKind`) from where the eye is
* (`vesselViews.js`), with the flat hull to fall back on; else the flat
* white hull, bow up so the row's course turns it to its heading. An aid
* to navigation is the buoy either way. The layer tints it (`shipTint`).
* @param {Object} record - Vessel record.
* @returns {string} SVG data URL.
* @returns {string|{views: string, first: number, fallback: string}} SVG
* data URL, or a view of the vessel sheet.
*/
function shipIcon(record) {
return isAidToNavigation(record)
? aidSprite()
: vesselSprite(vesselKind(record.type));
if (isAidToNavigation(record)) return aidSprite();
const kind = vesselKind(record.type);
return iconViews
? vesselViewRef(vesselShape(record.type), kind)
: vesselSprite(kind);
}
/**
@@ -1308,18 +1345,25 @@ export function createRendering({
!focusAlphaNeedsWrite(icons.focus(id), 1, params)
)
continue;
const cameraDistance = cameraDistanceFor(position);
// The sprite's half size as drawn at that range.
const half =
(item.scale ?? 1) *
(nearFarScalarValueAtDistance?.(item.scaleByDistance, cameraDistance) ??
1) *
0.5;
const focus = advanceSpriteFocus(sprite, {
// Hidden/far-side icons still finish any pending release so the active
// count remains truthful and they cannot reappear with stale dim alpha.
screenPosition: visual.visible ? screenPositionFor(position) : null,
cameraDistance: cameraDistanceFor(position),
cameraDistance,
nowMs,
target,
params,
// Vessel artwork is 32 px before scale. Including the ambient
// chevron's own rendered extent prevents edge-overlap misses.
spriteHalfWidthPx: item.size[0] * (item.scale ?? 1) * 0.5,
spriteHalfHeightPx: item.size[1] * (item.scale ?? 1) * 0.5,
spriteHalfWidthPx: item.size[0] * half,
spriteHalfHeightPx: item.size[1] * half,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
+40 -5
View File
@@ -37,7 +37,8 @@ import { alongLength } from '../../geo/polyline.js';
import { clusterScreenPoints } from '../../geo/screenCluster.js';
import { provideUnboundDraw } from '../rendererOf.js';
import { blobUrl, listenerList, toCartesian, uncaught } from './common.js';
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createGpuIcons, gpuIconCapabilities } from './gpuIcons.js';
import { viewLayout } from '../../data/viewSheet.js';
import { blendHost } from './setBlend.js';
import { createModelSets } from './drawModels.js';
import { materialTexture } from './internals.js';
@@ -714,7 +715,7 @@ const animating = (record) => record.gpu?.animating();
export function createCesiumDraw({
scene,
report,
capabilities = new Set(GPU_ICON_CAPABILITIES),
capabilities = new Set(gpuIconCapabilities(scene)),
requestRender: requestFrame = null,
date = null,
now = () => performance.now(),
@@ -1129,6 +1130,7 @@ export function createCesiumDraw({
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
viewsOf: (id) => viewSheets.get(id),
requestRender: (reason) => {
if (!live()) return;
if (requestFrame) requestFrame(reason);
@@ -1146,9 +1148,9 @@ export function createCesiumDraw({
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
gpu.check(list, record.spec);
gpu.check(list, record.spec, record);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec);
if (!replacing) gpu.check(record.items.values(), record.spec, record);
record.gpu = gpu.attach(record);
record.billboards = null;
record.billboardHost = null;
@@ -1670,6 +1672,9 @@ export function createCesiumDraw({
// when its icon is drawn, and registering an atlas again swaps the images
// of the icons that drew from it.
const atlases = new Map();
// View sheets icons draw subjects of, by id (`viewSheets`): each as its
// image and checked layout, a new object whenever it is registered.
const viewSheets = new Map();
/** The blob each material or quad draws, held while it lives (`holdImage`). */
const heldBlobs = new WeakMap();
@@ -6024,6 +6029,32 @@ export function createCesiumDraw({
}
if (changed) scene.requestRender();
},
...(capabilities.has('viewSheets')
? {
views(id, sheet) {
viewSheets.set(
id,
Object.freeze({
image: sheet.image,
layout: viewLayout(sheet),
grey: sheet.grey === true,
}),
);
let changed = false;
for (const record of sets.values())
if (
record.kind === 'icons' &&
record.gpu &&
record.views === id
) {
record.gpu.reviews();
setsVersion += 1;
changed = true;
}
if (changed) scene.requestRender();
},
}
: {}),
};
return {
@@ -6148,7 +6179,11 @@ provideUnboundDraw((viewer) => {
const part = createCesiumDraw({
scene,
report: uncaught,
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
capabilities: new Set([
...gpuIconCapabilities(scene),
'fields',
'modelParts',
]),
});
unboundParts.set(part.port, part);
const offs = [
+36
View File
@@ -8873,3 +8873,39 @@ test('a disposed set, and every set once the port is disposed, does nothing on l
restore();
}
});
test('a draw port registers view sheets only with viewSheets, each port its own', async () => {
const { PORTS } = await import('../contract/index.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
assert.equal(PORTS.draw.views, 'viewSheets', 'an optional port method');
const report = (error) => assert.fail(error);
const without = createCesiumDraw({
scene: fakeScene(),
report,
capabilities: new Set(['motionSegments']),
});
assert.equal(typeof without.port.views, 'undefined');
// Two viewers: a sheet registered on one is not drawn by the other.
const one = createCesiumDraw({ scene: fakeScene(), report });
const two = createCesiumDraw({ scene: fakeScene(), report });
assert.equal(typeof one.port.views, 'function');
const view = {
id: 'a',
pos: { ...Cesium.Cartesian3.fromDegrees(4, 52, 1000) },
image: { views: AIRCRAFT_VIEWS.id, first: AIRCRAFT_VIEWS.subjects.uav },
size: [20, 20],
rotationMode: 'course',
course: 0,
};
const setOne = one.port.icons({ id: 'views:one' });
const setTwo = two.port.icons({ id: 'views:two' });
setOne.set([view]);
setTwo.set([view]);
one.port.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const rowsOne = one.sets.get('views:one').gpu.set;
const rowsTwo = two.sets.get('views:two').gpu.set;
assert.equal(rowsOne.imageFar(rowsOne.row('a')), AIRCRAFT_VIEWS.subjects.uav);
assert.equal(rowsTwo.imageFar(rowsTwo.row('a')), -1, 'not on this port');
setOne.dispose();
setTwo.dispose();
});
+122 -13
View File
@@ -31,6 +31,14 @@
* root's larger `width`/`height`, as a billboard rasterises it), any other
* image at the item's larger side.
*
* A view (`{views, first}`, `viewSheets`) is not in that atlas: its sheet is
* a texture of its own, and its row draws the frame that shows its subject
* from the eye (`data/viewSheet.js`), lying flat on the ground along its
* course. Until the sheet is registered and loaded, and if it cannot load,
* the row draws the view's `fallback` image along its course (nothing
* without one). A set draws views from one sheet; a view of another is
* refused.
*
* Choices the contract leaves open, taken conservatively:
* - `horizonCull` judges each row no lower than `ICON_CULL_HEIGHT_M` above
* the ellipsoid, as the layers drawing their own icon sets do for sea
@@ -53,6 +61,7 @@ import {
ICON_GROUND_RELATIVE,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import {
writeArcSegment,
@@ -77,6 +86,26 @@ export const GPU_ICON_CAPABILITIES = Object.freeze([
'courseGlide',
]);
/**
* The capabilities GPU icon sets bring on `scene`: `viewSheets` too, but on
* WebGL 1, where a set that draws views could not also draw what its rows
* read from their extras (a display range, a fade, an offset), and a layer
* that uses those would lose its icons to the sheet.
* @param {object} [scene] A Cesium scene; none (a test's) is taken as WebGL 2.
*/
export function gpuIconCapabilities(scene) {
return scene?.context?.webgl2 === false
? [...GPU_ICON_CAPABILITIES]
: [...GPU_ICON_CAPABILITIES, 'viewSheets'];
}
/** Whether an image is a subject of a view sheet (`{views, first}`). */
const isView = (image) => typeof image?.views === 'string';
/** Whether a subject's block of frames, from its first cell, is in `layout`. */
const blockFits = (first, layout) =>
first + layout.frames <= layout.columns * layout.rows;
const nonZero = (v) =>
Boolean(v) && (v.x !== 0 || v.y !== 0 || (v.z ?? 0) !== 0);
@@ -204,10 +233,12 @@ function rasterPxOf(url, item) {
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* viewsOf?: (id: string) => ({image: string, layout: object}|undefined),
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it.
* noting that the set draws from it; `peekImage` only reads it;
* `viewsOf` reads a registered view sheet (undefined while it is not).
*/
export function createGpuIcons({
scene,
@@ -216,9 +247,15 @@ export function createGpuIcons({
toColor,
imageOf,
peekImage,
viewsOf = () => undefined,
requestRender,
}) {
const can = (capability) => capabilities.has(capability);
/** Whether a view's frames are in its sheet (true while not registered). */
const viewFits = (view) => {
const sheet = viewsOf(view.views);
return !sheet || blockFits(view.first, sheet.layout);
};
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
@@ -228,7 +265,10 @@ export function createGpuIcons({
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.pickProxy ||
item.imageLod
item.imageLod ||
// A view turns along its course: an item that does not is not asked
// for its image here.
(item.rotationMode === 'course' && isView(item.image))
)
return true;
}
@@ -236,13 +276,33 @@ export function createGpuIcons({
}
/** Refuse what a GPU icon set cannot draw, before anything changes. */
function check(items, spec = {}) {
function check(items, spec = {}, record = null) {
// Atlas slots these items would take anew: they must all fit.
const fresh = new Set();
// The one sheet the set draws views from: its record's, else the first
// of these items'.
let sheet = record?.views ?? null;
for (const item of items) {
const refuse = (what) => {
throw new Error(`the Cesium renderer's GPU icons have no ${what}`);
};
if (isView(item.imageLod?.near)) refuse('views as near images');
if (isView(item.image?.fallback)) refuse('views as fallbacks');
if (isView(item.image)) {
if (!can('viewSheets')) refuse('view sheets');
if (!Number.isInteger(item.image.first) || item.image.first < 0)
throw new TypeError("a view's first cell is a whole number from 0");
if (!viewFits(item.image))
throw new RangeError("a view's frames run past its sheet");
if (item.rotationMode !== 'course')
refuse("views but along a course (rotationMode: 'course')");
if (item.imageLod) refuse('imageLod for a view');
sheet ??= item.image.views;
if (item.image.views !== sheet)
refuse(
`views from two sheets in a set (${sheet}, ${item.image.views})`,
);
}
if (item.offsetScalesByDistance && nonZero(item.pixelOffset))
refuse('pixel offsets scaled by distance');
// What a row reads from its extras texture, which WebGL 1 has not.
@@ -258,7 +318,12 @@ export function createGpuIcons({
if (item.rotationMode === 'screen' && (item.rotation ?? 0) !== 0)
refuse('screen rotation on WebGL 1');
}
for (const given of [item.image, item.imageLod?.near]) {
for (const given of [
// A view is not in the atlas; the image it falls back to is.
isView(item.image) ? item.image.fallback : item.image,
item.imageLod?.near,
]) {
if (given === undefined) continue;
// An atlas slot as what it holds now (none yet draws once it does).
const image =
typeof given?.atlas === 'string' ? peekImage(given) : given;
@@ -316,6 +381,7 @@ export function createGpuIcons({
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
views: () => (record.views ? (viewsOf(record.views) ?? null) : null),
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
pickObject: (id, _set, primitive) => ({
@@ -411,14 +477,34 @@ export function createGpuIcons({
const added = row < 0;
if (added) row = set.add(item.id);
const [width = 0, height = 0] = item.size ?? [];
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
const view = isView(item.image);
if (view) {
// Its subject's first cell, once its sheet is registered, and the
// slot of the image drawn in its place until the sheet has loaded.
// (A subject past the sheet, registered since, draws no cell.)
record.views ??= item.image.views;
const sheet = viewsOf(item.image.views);
const first =
sheet && blockFits(item.image.first, sheet.layout)
? item.image.first
: -1;
const fallback =
item.image.fallback === undefined
? -1
: slotOf(item.image.fallback, item);
set.setImage(row, first, fallback);
set.setImageSwitch(row, 0);
} else {
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
}
set.setFlag(row, ICON_VIEWS, view);
set.setSize(row, width, height);
set.setScale(row, item.scale ?? 1);
set.setAlpha(row, item.alpha ?? 1);
@@ -747,11 +833,21 @@ export function createGpuIcons({
reatlas(id) {
const drawing = [];
for (const item of record.items.values())
if (item.image?.atlas === id || item.imageLod?.near?.atlas === id)
if (
item.image?.atlas === id ||
item.image?.fallback?.atlas === id ||
item.imageLod?.near?.atlas === id
)
drawing.push(item);
if (fresh) return sync();
for (const item of drawing) writeRow(item);
},
/** Rewrite the rows drawing views, once their sheet is registered. */
reviews() {
if (fresh) return sync();
for (const item of record.items.values())
if (isView(item.image)) writeRow(item);
},
/**
* After a frame: sample the ground under clamped rows' segment ends,
* from `budget` (`{ends, surface}`, spent). Whether a row's ground
@@ -879,6 +975,19 @@ export function createGpuIcons({
let loading = false;
for (let row = 0; row < set.count; row++) {
if (!set.shown(row)) continue;
if (set.flags(row) & ICON_VIEWS) {
// Its sheet, or while that is not drawn, the image it falls
// back to.
const views = host.viewsState();
if (views === 'ready' && set.imageFar(row) >= 0) continue;
const fallback = set.imageNear(row);
if (fallback < 0) {
if (views === 'failed') return 'failed';
loading = true;
} else if (iconAtlas.failed(fallback)) return 'failed';
else if (!iconAtlas.ready(fallback)) loading = true;
continue;
}
for (const slot of [set.imageFar(row), set.imageNear(row)]) {
if (slot < 0) continue;
if (iconAtlas.failed(slot)) return 'failed';
+259
View File
@@ -3,13 +3,16 @@ import * as Cesium from 'cesium';
import test from 'node:test';
import { createCesiumDraw } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { IconSetPrimitive } from './iconSetPrimitive.js';
import { MAX_ICON_SLOTS } from '../../data/iconAtlas.js';
import {
ICON_CULL_LIFT,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import { AIRCRAFT_VIEWS, viewLayout } from '../../data/viewSheet.js';
import {
iconCourse,
iconPosition,
@@ -1187,3 +1190,259 @@ test('a live motion clock reads the date the draw port is given', () => {
0.1,
);
});
/** An item drawn from the aircraft view sheet's subject at `first`. */
const viewIcon = (id, first = AIRCRAFT_VIEWS.subjects.widebody, extra = {}) =>
icon(id, {
image: { views: AIRCRAFT_VIEWS.id, first },
rotationMode: 'course',
course: 30,
...extra,
});
test('a view takes its set onto the GPU, its row flagged and drawing its subject’s first cell once the sheet is registered', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:views' });
set.set([viewIcon('a')]);
assert.ok(scene.added[0] instanceof IconSetPrimitive, 'a GPU icon set');
const { set: s } = rows(part, 'gpu:views');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.flags(a) & ICON_ROTATES, ICON_ROTATES, 'along its course');
assert.equal(s.imageFar(a), -1, 'its sheet not registered yet: not drawn');
const host = part.sets.get('gpu:views').host;
assert.equal(host._views(), null);
const before = part.version();
const renders = scene.renders;
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.widebody);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0, 'one image at any size');
assert.ok(part.version() > before);
assert.ok(scene.renders > renders, 'a frame is asked for');
const sheet = host._views();
assert.equal(sheet.image, AIRCRAFT_VIEWS.sheet.image);
assert.deepEqual(
sheet.layout.firsts,
viewLayout(AIRCRAFT_VIEWS.sheet).firsts,
);
assert.equal(sheet.layout.frames, AIRCRAFT_VIEWS.frames);
// Registered again: a new sheet the host reads afresh.
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.notEqual(host._views(), sheet);
// A row added once it is registered draws at once.
set.upsert([viewIcon('b', AIRCRAFT_VIEWS.subjects.helicopter2)]);
assert.equal(s.imageFar(s.row('b')), AIRCRAFT_VIEWS.subjects.helicopter2);
set.dispose();
});
test('a row switching between a view and a flat image changes its flag and its image', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-flat' });
set.set([viewIcon('a')]);
const { set: s } = rows(part, 'gpu:view-flat');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
set.upsert([
icon('a', {
rotationMode: 'course',
course: 30,
imageLod: { near: 'ship-large.png', switchPx: 60 },
}),
]);
assert.equal(s.row('a'), a, 'the same row');
assert.equal(s.flags(a) & ICON_VIEWS, 0, 'flat');
assert.ok(s.imageFar(a) >= 0, 'an atlas slot');
assert.notEqual(s.imageNear(a), s.imageFar(a));
assert.equal(s.imageSwitch(a), 60);
set.upsert([viewIcon('a', AIRCRAFT_VIEWS.subjects.glider)]);
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS, 'a view again');
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.glider);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0);
set.dispose();
});
test('a view’s fallback is the atlas image its row draws until the sheet is', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-fallback' });
const view = (first) => ({
views: AIRCRAFT_VIEWS.id,
first,
fallback: 'glyph.png',
});
set.set([{ ...viewIcon('a'), image: view(AIRCRAFT_VIEWS.subjects.light) }]);
const { set: s } = rows(part, 'gpu:view-fallback');
const a = s.row('a');
// Not registered: no cell yet, its fallback's slot as its near image.
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.imageFar(a), -1);
const slot = s.imageNear(a);
assert.ok(slot >= 0, 'the fallback has an atlas slot');
assert.equal(s.imageSwitch(a), 0);
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.light);
assert.equal(s.imageNear(a), slot, 'kept for a sheet that fails to load');
// A view cannot be what a view falls back to.
assert.throws(
() =>
set.upsert([
{
...viewIcon('b'),
image: {
views: AIRCRAFT_VIEWS.id,
first: 0,
fallback: {
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects.widebody,
},
},
},
]),
/views as fallbacks/,
);
assert.equal(s.row('b'), -1, 'refused, changing nothing');
set.dispose();
});
test('a GPU icon set refuses, changing nothing, views it cannot draw', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
draw.views('other-views', AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-refuse' });
set.set([viewIcon('a')]);
const refused = [
[viewIcon('b', 1.5), /first cell is a whole number/],
[viewIcon('b', -1), /first cell is a whole number/],
[
viewIcon('b', String(AIRCRAFT_VIEWS.frames)),
/first cell is a whole number/,
],
// The last block that fits ends at the sheet's last cell; one cell on
// runs past.
[
viewIcon(
'b',
AIRCRAFT_VIEWS.sheet.columns * AIRCRAFT_VIEWS.sheet.rows -
AIRCRAFT_VIEWS.frames +
1,
),
/run past its sheet/,
],
[viewIcon('b', 0, { rotationMode: 'screen' }), /views but along a course/],
[viewIcon('b', 0, { rotationMode: undefined }), /views but along a course/],
[
viewIcon('b', 0, { imageLod: { near: 'ship.png', switchPx: 30 } }),
/imageLod for a view/,
],
[
icon('b', {
motion: { kind: 'hold' },
imageLod: {
near: { views: AIRCRAFT_VIEWS.id, first: 0 },
switchPx: 30,
},
}),
/views as near images/,
],
[
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
/views from two sheets/,
],
];
for (const [item, pattern] of refused)
assert.throws(() => set.upsert([item]), pattern, JSON.stringify(item));
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:view-refuse').set.count, 1);
// Two sheets in one write to a fresh set.
const fresh = draw.icons({ id: 'gpu:view-two' });
assert.throws(
() =>
fresh.set([
viewIcon('a'),
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
]),
/views from two sheets/,
);
assert.equal(fresh.size(), 0);
});
test('without viewSheets the draw port has no views(), and refuses a view', () => {
const { part, draw } = drawOver({
capabilities: new Set(['motionSegments', 'columns']),
});
assert.equal('views' in draw, false);
const set = draw.icons({ id: 'gpu:no-views' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
assert.throws(() => set.upsert([viewIcon('b')]), /no view sheets/);
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:no-views').set.count, 1);
// A set of billboards refuses one too: it cannot take it onto the GPU.
const billboards = draw.icons({ id: 'gpu:no-views-billboards' });
assert.throws(() => billboards.set([viewIcon('a')]), /no view sheets/);
assert.equal(billboards.size(), 0);
});
test('a view sheet is checked when it is registered', () => {
const { draw } = drawOver();
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, rings: [2, 3] }),
TypeError,
);
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, image: '' }),
TypeError,
);
});
test('view rows load with their sheet: loading until it is ready, failed when it cannot load', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-load' });
set.set([viewIcon('a')]);
const record = part.sets.get('gpu:view-load');
assert.equal(record.gpu.imageState(), 'loading', 'no sheet registered');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(record.host.viewsState(), 'loading', 'registered, not drawn');
assert.equal(record.gpu.imageState(), 'loading');
// Node has no Image: the sheet's texture cannot load on this context.
record.host._syncViews({});
assert.equal(record.host.viewsState(), 'failed');
assert.equal(record.gpu.imageState(), 'failed');
// A hidden view row waits on nothing.
set.upsert([viewIcon('a', undefined, { show: false })]);
assert.equal(record.gpu.imageState(), 'settled');
set.dispose();
});
test('view sheets are offered on WebGL 2, not on WebGL 1', () => {
// A row that draws views is on the GPU, where WebGL 1 has no extras: a
// layer whose icons carry a display range would lose them to the sheet.
assert.ok(
gpuIconCapabilities({ context: { webgl2: true } }).includes('viewSheets'),
);
assert.ok(gpuIconCapabilities().includes('viewSheets'), 'no scene: a test');
const webgl1 = gpuIconCapabilities({ context: { webgl2: false } });
assert.equal(webgl1.includes('viewSheets'), false);
assert.deepEqual(webgl1, ['columns', 'motionSegments', 'courseGlide']);
});
test('a view registered past the sheet after its row was written draws no cell', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-late' });
// Accepted while its sheet is unknown: a block that runs one cell past
// the end of the sheet.
const { columns, rows: sheetRows } = AIRCRAFT_VIEWS.sheet;
set.set([viewIcon('a', columns * sheetRows - AIRCRAFT_VIEWS.frames + 1)]);
const { set: s } = rows(part, 'gpu:view-late');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(s.row('a')), -1, 'no cell: its fallback, or nothing');
set.dispose();
});
+281 -20
View File
@@ -20,6 +20,17 @@
* above, taken between the heights under its segment's two ends. On WebGL 1
* the extras are not drawn (the draw port refuses rows that need them).
*
* A row flagged `ICON_VIEWS` draws from the set's view sheet
* ({@link module:viewSheet}), a texture of its own, in place of the atlas
* (on WebGL 2; the shader has none of it on WebGL 1): it lies flat on the
* ground, forward along its course, and draws the frame nearest the eye's
* direction, mirrored for the eye on its left. The frame is a card standing
* at the row's anchor, square to the frame's own direction, so between
* frames the sprite is tilted (foreshortened and turned) as its subject is,
* with no blending of frames; the row's quad stays upright on screen. Until the
* sheet has loaded it draws its near image from the atlas, turned along its
* course as any row, if it has one.
*
* This module is the one place the icon sets touch Cesium's renderer internals.
*/
import * as Cesium from 'cesium';
@@ -29,6 +40,7 @@ import {
ICON_CULL_HEIGHT_M,
ICON_CULL_LIFT,
ICON_EXTRA_TEXELS,
ICON_VIEWS,
STYLE_STRIDE,
} from '../../data/iconSet.js';
import {
@@ -39,6 +51,13 @@ import {
NEAR_IMAGE_DEVICE_PX,
} from '../../data/iconAtlas.js';
import { recedeFrame, recedeParams } from '../recession.js';
import { rawTexture, webglContext } from './internals.js';
import {
VIEW_RINGS_MAX,
VIEW_SHEET_FRAGMENT_GLSL,
VIEW_SHEET_GLSL,
viewUniforms,
} from '../../data/viewSheet.js';
/** The parameters the uniforms hold while the set does not recede. */
const NO_RECEDE = recedeParams({});
@@ -84,6 +103,7 @@ uniform vec3 u_recessionFloors; // scale, alpha, combined alpha
uniform vec4 u_slots[ICON_SLOTS]; // ICON_SLOTS: as many as the context addresses
uniform float u_cull; // 1: hide rows past the ellipsoid's horizon
uniform float u_pickPass; // 1 while drawing for a pick
uniform float u_viewsReady; // 1 once the set's view sheet is loaded
#ifdef ICON_EXTRAS
uniform highp sampler2D u_extras; // ICON_EXTRA_TEXELS texels a row, ICON_EXTRA_ROWS rows a line
#endif
@@ -93,12 +113,42 @@ out vec4 v_color;
out vec4 v_pickColor;
out float v_proxy;
out float v_overDepth; // 1 for a row drawn over depth, on the near plane
out float v_views; // 1 for a row drawn from the view sheet
#ifdef ICON_VIEW_SHEETS
// A view row's frame: its cell in the sheet (v_uv is then this corner's
// place in that cell, not in the atlas).
out float v_viewCell;
#endif
// The row's anchor in clip space before screen offsets, for effects that wrap
// main() (sonar) and must not change geometry or picks.
vec4 iconAnchorClip = vec4(0.0, 0.0, 0.0, -1.0);
${ICON_SEGMENT_GLSL}
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_GLSL}
// Where a corner of the row's quad falls in a frame's cell (0..1 across it,
// v down). The frame is a card standing at the row's anchor, square to the
// direction it shows its subject from: the corner (offset, in the eye's
// axes) is carried along the eye's ray onto that card, so a frame seen from
// a little off its direction is tilted (foreshortened and turned) as its
// subject is, until the next frame is the nearer.
// axes takes the subject's forward, right and up to the eye's axes; cardHalf
// is the card's half size, in the offset's units.
vec2 viewCardUv(float ring, float index, float flip, mat3 axes, vec3 offset, vec3 ray, vec2 cardHalf) {
vec3 toEye;
vec3 up;
viewFrameAxes(ring, index, flip, toEye, up);
vec3 normal = axes * toEye;
vec3 cardUp = axes * up;
vec3 cardRight = cross(cardUp, normal);
// The ray meets the card head on, or nearly: never edge on.
vec3 on = offset - ray * (dot(offset, normal) / min(dot(ray, normal), -0.2));
vec2 at = vec2(dot(on, cardRight), dot(on, cardUp)) / cardHalf;
return vec2(0.5 + 0.5 * (flip > 0.5 ? -at.x : at.x), 0.5 - 0.5 * at.y);
}
#endif
bool iconFlag(float flags, float bit) {
return mod(floor(flags / bit), 2.0) == 1.0;
@@ -127,6 +177,10 @@ void main() {
v_color = vec4(0.0);
v_proxy = 0.0;
v_overDepth = 0.0;
v_views = 0.0;
#ifdef ICON_VIEW_SHEETS
v_viewCell = 0.0;
#endif
gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn
float flags = style1.z;
@@ -195,11 +249,25 @@ void main() {
bool nearImage = style3.x > 0.0
? glyphPx / czm_pixelRatio > style3.x
: glyphPx > ${NEAR_IMAGE_DEVICE_PX.toFixed(1)};
// A view row's far image is its subject's first cell in the view sheet,
// its near image the atlas slot drawn in its place while the sheet is not
// registered or loaded.
bool views = false;
vec2 viewUv = vec2(0.0);
float slot = nearImage ? style1.y : style1.x;
if (iconFlag(flags, ${ICON_VIEWS.toFixed(1)})) {
#ifdef ICON_VIEW_SHEETS
views = u_viewsReady > 0.5 && style1.x >= 0.0;
#endif
slot = views ? style1.x : style1.y;
}
if (slot < 0.0) return; // no image set
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
vec4 rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
vec4 rect = vec4(0.0, 0.0, 1.0, 1.0);
if (!views) {
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
}
vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner;
vec2 shift = vec2(0.0);
@@ -222,15 +290,44 @@ void main() {
vec3 east = dot(horizontal, horizontal) > 1.0 ? normalize(vec3(horizontal, 0.0)) : vec3(0.0, 1.0, 0.0);
vec3 north = cross(up, east);
vec3 forward = east * sin(course) + north * cos(course);
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
#ifdef ICON_VIEW_SHEETS
if (views) {
// A view lies flat on the ground, forward along its course, and draws
// the frame nearest the eye's direction. Its quad stays upright on
// screen; the frame is put on it where its card falls.
vec3 right = cross(forward, up);
vec3 toEye = normalize(-rte);
vec3 frame = viewNearest(
vec3(dot(toEye, forward), dot(toEye, right), dot(toEye, up)));
// The subject's axes in the eye's (x right, y up, z back).
mat3 axes = transpose(mat3(u_cameraRight, u_cameraUp, cross(u_cameraRight, u_cameraUp))) *
mat3(forward, right, up);
// This corner, square to the eye's ray (the eye's right and up, turned
// as its back turns onto the ray): a card facing the eye then fills
// the quad wherever on screen it is, without the stretch a wide view
// gives what is off its centre.
vec3 ray = normalize(positionEC.xyz);
vec3 turned = vec3(0.0, 0.0, 1.0) - ray;
vec3 offset =
(vec3(1.0, 0.0, 0.0) + turned * (ray.x / turned.z)) * halfSize.x +
(vec3(0.0, 1.0, 0.0) + turned * (ray.y / turned.z)) * halfSize.y;
viewUv = viewCardUv(
frame.x, frame.y, frame.z, axes, offset, ray,
style0.xy * (scale * distanceScale * 0.5));
v_viewCell = slot + viewRing(frame.x).y + frame.y;
} else
#endif
{
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
}
}
}
#ifdef ICON_EXTRAS
@@ -267,22 +364,39 @@ void main() {
v_overDepth = 1.0;
}
v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_uv = views
? viewUv
: mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_views = views ? 1.0 : 0.0;
v_color = vec4(color.rgb, color.a * alpha);
}
`;
const FRAGMENT_SHADER = /* glsl */ `
uniform sampler2D u_atlas;
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_FRAGMENT_GLSL}
in float v_viewCell;
#endif
in vec2 v_uv;
in vec4 v_color;
in vec4 v_pickColor;
in float v_proxy;
in float v_overDepth;
in float v_views;
void main() {
vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv));
vec4 color = texture(u_atlas, v_uv);
#ifdef ICON_VIEW_SHEETS
// How small the sheet's cells are drawn (v_uv runs 0..1 across a view
// row's cell), worked out for every row so the cell can be read inside
// the branch.
vec2 texels = v_uv * (float(textureSize(u_views, 0).x) / max(u_viewGrid.x, 1.0));
float lod = log2(max(max(length(dFdx(texels)), length(dFdy(texels))), 1.0e-6));
if (v_views > 0.5) color = viewCell(v_viewCell, v_uv, lod);
#endif
color = czm_gammaCorrect(color);
color *= czm_gammaCorrect(v_color);
// A pick proxy is picked wherever it covers, drawn or not.
if (v_proxy > 0.5) color = vec4(1.0);
@@ -308,6 +422,100 @@ void main() {
}
`;
/** The coarsest mip level a view sheet is sampled at (half-size cells). */
const VIEW_SHEET_MAX_LOD = 1;
/** Each context's view sheet textures, by URL. */
const sheetTextures = new WeakMap();
/**
* A view sheet's image as a texture on `context`, loaded once however many
* icon sets draw from it: `{state, texture}`, `state` going from `loading`
* to `ready` (its `texture` set) or `failed`. `onChange` runs when it does.
* Mipmapped where the context can (to `VIEW_SHEET_MAX_LOD`), so a sprite
* drawn smaller than its cell stays smooth; a cell's transparent margin
* keeps its neighbours out. The texture lives as long as its context.
* A sheet larger than the context's textures fails, as one that cannot load.
* @param {object} context A Cesium Context.
* @param {string} url
* @param {() => void} [onChange]
* @param {boolean} [grey] The sheet's pixels are grey: kept as one channel
* and alpha.
*/
export function viewSheetTexture(context, url, onChange, grey = false) {
let byUrl = sheetTextures.get(context);
if (!byUrl) sheetTextures.set(context, (byUrl = new Map()));
const key = `${grey ? 'grey' : 'colour'}|${url}`;
let entry = byUrl.get(key);
if (!entry) {
entry = { state: 'loading', texture: null, listeners: new Set() };
byUrl.set(key, entry);
const settle = (state) => {
entry.state = state;
for (const listener of entry.listeners) listener();
entry.listeners.clear();
};
if (typeof Image === 'undefined') settle('failed');
else {
const image = new Image();
image.decoding = 'async';
// A cross-origin image would taint the upload.
image.crossOrigin = 'anonymous';
image.onload = () => {
if (context.isDestroyed?.()) return;
// This context's own limit (Cesium's is the last context's made).
const gl = webglContext({ context });
const limit = gl.getParameter(gl.MAX_TEXTURE_SIZE);
if (Math.max(image.naturalWidth, image.naturalHeight) > limit) {
console.warn(
`[iconSetPrimitive] View sheet is larger than this context's textures (${limit} px): ${url}`,
);
settle('failed');
return;
}
const mipmapped = context.webgl2 === true;
entry.texture = new Cesium.Texture({
context,
source: image,
// A grey sheet as its grey (its red) and alpha: half the memory.
pixelFormat: grey
? Cesium.PixelFormat.LUMINANCE_ALPHA
: Cesium.PixelFormat.RGBA,
flipY: false,
sampler: new Cesium.Sampler({
wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE,
wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE,
minificationFilter: mipmapped
? Cesium.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR
: Cesium.TextureMinificationFilter.LINEAR,
magnificationFilter: Cesium.TextureMagnificationFilter.LINEAR,
}),
});
if (mipmapped) {
entry.texture.generateMipmap();
// No coarser than this: past it a cell's transparent margin is
// under a texel, and its neighbours would show at its edges.
gl.bindTexture(gl.TEXTURE_2D, rawTexture(entry.texture));
gl.texParameterf(
gl.TEXTURE_2D,
gl.TEXTURE_MAX_LOD,
VIEW_SHEET_MAX_LOD,
);
gl.bindTexture(gl.TEXTURE_2D, null);
}
settle('ready');
};
image.onerror = () => {
console.warn(`[iconSetPrimitive] View sheet failed to load: ${url}`);
settle('failed');
};
image.src = url;
}
}
if (onChange && entry.state === 'loading') entry.listeners.add(onChange);
return entry;
}
/**
* How many atlas slots the icon shader addresses on `context`: as many as
* the vertex uniform limit leaves room for (Cesium's ContextLimits, which
@@ -344,7 +552,9 @@ const EARTH_BOUNDS = new Cesium.BoundingSphere(
* Cesium's `BlendOption.TRANSLUCENT` billboards are, in place of an opaque
* pass and a translucent one (by default never). `pickObject` builds a row's pick object around the
* `primitive` drill picks hide it by (by default `{ id, iconSet, meta,
* primitive }`).
* primitive }`). `views` gives the view sheet the set's view rows draw from
* (`{image, layout, grey}`, `layout` as `viewLayout` returns; null: none),
* the same object until the sheet changes.
*/
export class IconSetPrimitive {
constructor({
@@ -355,9 +565,22 @@ export class IconSetPrimitive {
recede,
translucent,
pickObject,
views,
}) {
this.set = set;
this.renderTime = renderTime;
this._requestRender = requestRender ?? null;
// The set's view sheet: what it was last read as, its texture's entry
// and its layout as uniforms.
this._views = views ?? (() => null);
this._viewsFrom = null;
this._viewEntry = null;
this._viewGrid = new Cesium.Cartesian4();
this._viewRings = Array.from(
{ length: VIEW_RINGS_MAX / 2 },
() => new Cesium.Cartesian4(1, 0, 1, 0),
);
this._blank = null;
this._cull = cull ?? (() => true);
// The set's `recede`, and the parameters last made from it.
this._recede = recede ?? (() => null);
@@ -410,7 +633,11 @@ export class IconSetPrimitive {
u_recession: () => primitive._recession,
u_recessionFloors: () => primitive._recessionFloors,
u_slots: () => primitive._slotUniform,
u_atlas: () => primitive._texture,
u_atlas: () => primitive._texture ?? primitive._blank,
u_views: () => primitive._viewEntry?.texture ?? primitive._blank,
u_viewsReady: () => (primitive._viewEntry?.texture ? 1 : 0),
u_viewGrid: () => primitive._viewGrid,
u_viewRings: () => primitive._viewRings,
u_extras: () => primitive._extras,
u_cull: () => (primitive._cull() ? 1 : 0),
u_pickPass: () => primitive._pickPass,
@@ -431,7 +658,10 @@ export class IconSetPrimitive {
return;
const context = frameState.context;
this._syncAtlas(context);
if (!this._texture) return;
this._syncViews(context);
// Nothing to draw from yet: no atlas image packed, no view sheet.
if (!this._texture && !this._viewEntry) return;
this._blank = context.defaultTexture;
// Read as the commands run, which they do right after this update.
this._pickPass = frameState.passes.pick ? 1 : 0;
const renderTime = this.renderTime(frameState);
@@ -485,6 +715,31 @@ export class IconSetPrimitive {
Cesium.Cartesian4.unpack(iconAtlas.rects, slot * 4, this._slots[slot]);
}
/** Follow the set's view sheet: its layout's uniforms and its texture. */
_syncViews(context) {
const sheet = this._views();
if (sheet === this._viewsFrom) return;
this._viewsFrom = sheet;
this._viewEntry = null;
if (!sheet) return;
const { grid, rings } = viewUniforms(sheet.layout);
Cesium.Cartesian4.fromArray(grid, 0, this._viewGrid);
rings.forEach((pair, k) =>
Cesium.Cartesian4.fromArray(pair, 0, this._viewRings[k]),
);
this._viewEntry = viewSheetTexture(
context,
sheet.image,
() => this._requestRender?.(),
sheet.grey === true,
);
}
/** The set's view sheet: `none`, `loading`, `failed` or `ready`. */
viewsState() {
return this._viewEntry?.state ?? (this._views() ? 'loading' : 'none');
}
_allocate(context) {
const set = this.set;
this._destroyBuffers();
@@ -749,12 +1004,16 @@ export class IconSetPrimitive {
_createCommands(context) {
this._slotCount = contextIconSlots(context);
this._slotUniform = this._slots.slice(0, this._slotCount);
// View sheets are drawn on WebGL 2 only (as the draw port offers them):
// on WebGL 1 the shader is as it was without them.
const viewDefines = context?.webgl2 ? ['ICON_VIEW_SHEETS'] : [];
const programFor = (pass) =>
Cesium.ShaderProgram.fromCache({
context,
vertexShaderSource: new Cesium.ShaderSource({
defines: [
`ICON_SLOTS ${this._slotCount}`,
...viewDefines,
...(this._extras
? [
'ICON_EXTRAS',
@@ -766,12 +1025,14 @@ export class IconSetPrimitive {
sources: [VERTEX_SHADER],
}),
fragmentShaderSource: new Cesium.ShaderSource({
defines:
pass === 'opaque'
defines: [
...viewDefines,
...(pass === 'opaque'
? ['OPAQUE']
: pass === 'translucent'
? ['TRANSLUCENT']
: [],
: []),
],
sources: [FRAGMENT_SHADER],
}),
attributeLocations: ATTRIBUTE_LOCATIONS,
+2 -2
View File
@@ -18,7 +18,7 @@ import { createControlledCamera } from './controlledCamera.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import { createCesiumCredits } from './credits.js';
import { createCesiumDraw } from './draw.js';
import { GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { createCesiumEffects } from './effects.js';
import { renderNow, willDraw } from './frame.js';
import { createCesiumGlobe } from './globe.js';
@@ -100,7 +100,7 @@ export function cesiumCapabilities(scene, only) {
...(scene?.screenSpaceCameraController && scene?.preRender
? ['keepEarthFramed']
: []),
...GPU_ICON_CAPABILITIES,
...gpuIconCapabilities(scene),
// Icon sets cluster on screen, on billboards and the GPU (`draw.js`).
'cluster',
'styles',
+1
View File
@@ -18,6 +18,7 @@ test('capabilities follow what the scene supports', () => {
'columns',
'motionSegments',
'courseGlide',
'viewSheets',
'cluster',
'styles',
'bloom',
+2
View File
@@ -207,6 +207,8 @@ export type Capability =
| 'fields'
/** Rate-limited course easing (`IconItem.courseGlide`). */
| 'courseGlide'
/** Icons drawn from a sheet of views, by where the eye is (`ViewSheet`). */
| 'viewSheets'
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
| 'lineAgeFade'
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
+47 -1
View File
@@ -154,10 +154,48 @@ export interface Placed {
disableDepthTest?: number;
}
/** An image an icon draws: a URL, a slot in a shared atlas, or generated. */
/**
* `viewSheets`: one image of small sprites that show subjects from a sphere
* of directions, registered with `DrawPort.views`. An icon whose image is a
* view (`{views, first}`) lies flat on the ground, forward along its course,
* and is drawn as the sprite that shows it from where the eye is.
*
* The image is a grid of square cells, `cellPx` a side, `columns` across and
* `rows` down. A subject is a block of consecutive cells, row-major from its
* `first`: rings of frames `ringStepDeg` apart, from straight above (ring 0,
* one frame) downward, short of straight below; ring `k` holds `rings[k]`
* frames, from the eye dead ahead of the subject, round its right side, to
* dead astern. The eye on its left side draws the right side's frame
* mirrored. A frame's up is the subject's forward, turned by the smallest
* rotation that takes its up onto the frame's direction. The frame nearest
* the eye's direction is drawn, as a card square to its own direction, so
* between frames it is tilted as its subject is (`data/viewSheet.js` holds
* the maths).
*/
export interface ViewSheet {
/** The sheet's URL. */
image: string;
cellPx: number;
columns: number;
rows: number;
ringStepDeg: number;
/** Frames in each ring; the first is 1. At most 18 rings. */
rings: readonly number[];
/**
* The sheet's pixels are grey (red, green and blue equal): a renderer may
* keep it as one channel and alpha.
*/
grey?: boolean;
}
/**
* An image an icon draws: a URL, a slot in a shared atlas, generated, or
* (`viewSheets`, icons only) a subject of a view sheet by its first cell.
*/
export type ImageRef =
| string
| { atlas: string; slot: string }
| { views: string; first: number; fallback?: ImageRef }
| { svg: string }
| { blob: Blob }
| { canvas: HTMLCanvasElement | OffscreenCanvas; key: string };
@@ -211,6 +249,12 @@ export interface CourseGlide {
}
export interface IconItem extends Placed {
/**
* A view (`{views, first}`) needs `rotationMode: 'course'` and takes no
* `imageLod`; a set draws views from one sheet. Until its sheet is
* registered and loaded, and if that cannot load, it draws its `fallback`
* (any image but a view) along its course, or nothing without one.
*/
image: ImageRef;
/** Drawn size in CSS pixels. */
size: [width: number, height: number];
@@ -752,4 +796,6 @@ export interface DrawPort {
on(event: 'clampState', cb: (state: 'draped' | 'overlay') => void): Off;
/** Register an atlas of images icons refer to by slot. */
atlas(id: string, images: Record<string, ImageRef>): void;
/** `viewSheets`: register a sheet of views icons refer to by id. */
views?(id: string, sheet: ViewSheet): void;
}
+2
View File
@@ -41,6 +41,7 @@ export const CAPABILITIES = Object.freeze([
'meshes',
'fields',
'courseGlide',
'viewSheets',
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
@@ -174,6 +175,7 @@ export const PORTS = deepFreeze({
['quads', 'quads'],
['meshes', 'meshes'],
['field', 'fields'],
['views', 'viewSheets'],
]),
camera: Object.fromEntries([
...required(
+6
View File
@@ -23,6 +23,7 @@ import {
} from '../recession.js';
import { CLEAR_WEATHER, mergeWeather } from '../weather.js';
import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { viewLayout } from '../../data/viewSheet.js';
import { createStubCamera } from './camera.js';
import { motionPosition } from '../motion/iconMotion.js';
import { computeViewRectangle } from './viewRectangle.js';
@@ -704,6 +705,11 @@ export function createStubRenderer(options = {}) {
};
},
};
if (capabilities.has('viewSheets'))
draw.views = (id, sheet) => {
viewLayout(sheet); // refused as a renderer refuses it
log('draw', 'views', [id]);
};
if (capabilities.has('models'))
draw.models = (spec) => makeSet('models', spec);
if (capabilities.has('quads')) draw.quads = (spec) => makeSet('quads', spec);
-3
View File
@@ -1,11 +1,8 @@
import { createApplicationControls } from '../app/controls.js';
import { getStandaloneCatalog } from './catalog.js';
import { homeCountryView } from '../homeCountry.js';
export function createStandaloneControls(options) {
return createApplicationControls({
catalog: options?.catalog ?? getStandaloneCatalog(),
// The planet over the visitor's country; the title's logo goes back here.
startView: homeCountryView(),
...options,
});
}
-2
View File
@@ -1,10 +1,8 @@
import { startApplicationChrome } from '../app/startupChrome.js';
import { playOpeningIntro } from '../app/openingIntro.js';
import { initKeySetup } from '../keySetup.js';
export function startStandaloneChrome(options) {
return startApplicationChrome({
initializeSettings: initKeySetup,
playOpening: playOpeningIntro,
...options,
});
}
+1 -60
View File
@@ -10,7 +10,7 @@ const source = readFileSync(
.replace(/^import .*;\n/gm, '')
.replace('export function', 'function');
function fixture({ playOpening, hasShareState = false } = {}) {
function fixture() {
const timers = new Map();
const listeners = new Map();
const events = [];
@@ -44,10 +44,7 @@ function fixture({ playOpening, hasShareState = false } = {}) {
addEventListener: (type, listener) => listeners.set(type, listener),
removeEventListener: (type) => listeners.delete(type),
},
playOpening,
styleManager: {
hasShareState,
viewer: 'viewer',
initialRestorePromise: new Promise((resolve) => {
restored = resolve;
}),
@@ -127,59 +124,3 @@ test('shutdown during the cover transition cancels the listener and fallback', a
f.fire(900);
assert.deepEqual(f.events, ['hidden', 'settings:destroy']);
});
function openingStub(events) {
let land;
const calls = [];
const play = (options) => {
calls.push(options);
events.push('opening');
return {
done: new Promise((resolve) => {
land = resolve;
}),
cancel: () => events.push('opening:cancel'),
};
};
return { play, calls, land: () => land() };
}
test('a bare address plays the opening, and welcome waits for its end', async () => {
const events = [];
const opening = openingStub(events);
const f = fixture({ playOpening: opening.play });
f.events.push = (value) => events.push(value);
f.restored();
f.fire(1000);
await flush();
assert.deepEqual(events, ['opening']);
assert.equal(opening.calls[0].viewer, 'viewer');
f.fire(900);
assert.deepEqual(events, ['opening'], 'no fallback timer while it plays');
opening.land();
await flush();
assert.deepEqual(events, ['opening', 'welcome']);
await f.stop();
assert.ok(events.includes('opening:cancel'));
});
test('a shared view opens without the opening', async () => {
const events = [];
const opening = openingStub(events);
const f = fixture({ playOpening: opening.play, hasShareState: true });
f.restored();
f.fire(1000);
await flush();
assert.equal(opening.calls.length, 0);
assert.deepEqual(f.events, ['hidden']);
await f.stop();
});
test('without an opening to play the cover hides as before', async () => {
const f = fixture({ playOpening: () => null });
f.restored();
f.fire(1000);
await flush();
assert.deepEqual(f.events, ['hidden']);
await f.stop();
});
+7
View File
@@ -8,6 +8,8 @@ import { bindRenderer } from '../render/rendererOf.js';
export function fakeDrawPort() {
const sets = new Map();
// Every `views(id, sheet)` call, in order.
const viewSheets = [];
const make = (kind) => (spec) => {
const live = sets.get(spec.id);
if (live && !live.disposed)
@@ -97,6 +99,11 @@ export function fakeDrawPort() {
clampState: () => 'draped',
on: () => () => {},
atlas() {},
/** The `views(id, sheet)` registrations, in order, as `[id, sheet]`. */
viewSheets,
views(id, sheet) {
viewSheets.push([id, sheet]);
},
};
}
+5 -7
View File
@@ -31,6 +31,11 @@ export const getRecentImagery = defineTool({
requires: ['imagery'],
async run(args, { services, signal }) {
const area = await resolveArea(args.area, { services, signal });
if (area.west > area.east)
throw new ToolError(
'invalid_arguments',
'The area must not cross the antimeridian',
);
if (
Math.abs(area.south) > MAX_LATITUDE ||
Math.abs(area.north) > MAX_LATITUDE
@@ -50,13 +55,6 @@ export const getRecentImagery = defineTool({
east: area.east,
north: area.north,
};
// Worldview Snapshots rejects a west > east BBOX, so a dateline area can
// never produce the image this tool returns: refuse before searching.
if (box.west > box.east)
throw new ToolError(
'invalid_arguments',
'The area must not cross the antimeridian',
);
let latest;
try {
latest = await services.imagery.latest({ box, signal });
+1 -23
View File
@@ -82,30 +82,8 @@ test('overview fallback, empty results and invalid areas are reported', async ()
);
await assert.rejects(
none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }),
/too large for imagery/,
/antimeridian/,
);
const crossing = imagery({
candidate: {
product: 'S30',
day: '2026-10-01',
cloud: { min: 1, max: 2 },
coverage: 'full',
},
reason: 'clear',
errors: [],
});
const wrapped = composeCatalog({
tools: coreTools,
services: { imagery: crossing },
});
await assert.rejects(
wrapped.call('get_recent_imagery', {
area: { bbox: [179, 0, -179, 1] },
}),
/must not cross the antimeridian/,
);
assert.equal(crossing.snapshots.length, 0);
assert.equal(crossing.boxes.length, 0);
await assert.rejects(
none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }),
/±85° latitude/,
+4 -11
View File
@@ -48,20 +48,13 @@ export function initImageryBoxTool({
let lease = null;
let releaseCamera = null;
const dragBox = () => {
if (!anchor) return null;
const lo = Math.min(anchor.lon, corner.lon);
const hi = Math.max(anchor.lon, corner.lon);
// Corners more than half the globe apart are the short way round, over
// the dateline: west gets the larger longitude, east the smaller.
const crosses = hi - lo > 180;
return {
west: crosses ? hi : lo,
const dragBox = () =>
anchor && {
west: Math.min(anchor.lon, corner.lon),
south: Math.min(anchor.lat, corner.lat),
east: crosses ? lo : hi,
east: Math.max(anchor.lon, corner.lon),
north: Math.max(anchor.lat, corner.lat),
};
};
const preview = createPreview(viewer, dragBox);
const setPreview = (visible) => preview.setVisible(visible);
-38
View File
@@ -10,7 +10,6 @@ import {
IMAGERY_BOX_POINTER_OWNER,
initImageryBoxTool,
} from './imageryBoxTool.js';
import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js';
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
@@ -210,40 +209,3 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
assert.equal(f.tool.start(), false);
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
});
test('a drag across the dateline is the short box, not a box round the world', async () => {
const pickWorld = (_viewer, nx, ny) =>
ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny };
const f = fixture({ pickWorld });
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
assert.deepEqual(f.cancels, []);
assert.equal(f.boxes.length, 1);
const { west, east } = f.boxes[0];
assert.ok(west > east, `west ${west} is east of east ${east}`);
assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span');
await f.tool.destroy();
});
test('a drag whose short arc is still over the size limit is refused as too large', async () => {
const pickWorld = (_viewer, nx, ny) => ({
lon: nx < 0.5 ? 100 : -100,
lat: ny,
});
const refused = [];
const f = fixture({
pickWorld,
onCancel: (reason, message, box) => refused.push({ reason, message, box }),
});
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
assert.equal(f.boxes.length, 0);
const { reason, message, box } = refused.at(-1);
assert.equal(reason, 'too-large');
assert.deepEqual([box.west, box.east], [100, -100], 'the short arc');
assert.equal(lonSpanDeg(box.west, box.east), 160);
assert.equal(message, validateBox(box).message);
await f.tool.destroy();
});
+5 -27
View File
@@ -22,7 +22,6 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
import {
PRODUCTS,
hhmm,
nonCrossingBoxes,
wvsSnapshotUrl,
} from '../layers/recentImagery/model.js';
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
@@ -136,20 +135,6 @@ function coverageText(coverage) {
return t('unknown');
}
/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */
function shownCoverage(candidate, box) {
const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {};
const halves = nonCrossingBoxes(box).length;
if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial';
if (
status !== 'present' ||
!Array.isArray(availableBoxes) ||
availableBoxes.length >= halves
)
return candidate.coverage;
return 'unknown';
}
function cloudText(candidate) {
if (candidate.thumbnail?.status === 'empty') return t('no imagery');
if (!candidate.cloud) return t('cloud unknown');
@@ -531,9 +516,6 @@ export function createRecentImageryPanel({
function exportsView() {
const ab = snapshot.mode === 'ab';
const crossing = Boolean(
snapshot.box && snapshot.box.west > snapshot.box.east,
);
return [
{
id: 'export',
@@ -543,12 +525,10 @@ export function createRecentImageryPanel({
label: ab
? t('EXPORT {slot}', { slot: slotId.toUpperCase() })
: t('EXPORT'),
title: crossing
? t('Select one side of the dateline')
: ab
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
: t('Download the image as a PNG'),
disabled: crossing || !exportTarget(slotId) || exporting.has(slotId),
title: ab
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
: t('Download the image as a PNG'),
disabled: !exportTarget(slotId) || exporting.has(slotId),
reserved: slotId === 'b' ? !ab : undefined,
onClick: () => void exportImage(slotId),
})),
@@ -586,9 +566,7 @@ export function createRecentImageryPanel({
}),
);
times.push(
t('Coverage {coverage}', {
coverage: coverageText(shownCoverage(focus, snapshot.box)),
}),
t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }),
);
lines.push({ id: 'acquired', text: times.join(' · ') });
(focus.granules || []).forEach((granule, index) => {
-50
View File
@@ -5,11 +5,9 @@ import assert from 'node:assert/strict';
import { assertSameNode } from '../testSupport/domAssert.mjs';
import { readFileSync } from 'node:fs';
import { createRecentImageryPanel } from './recentImagery.js';
import { nonCrossingBoxes } from '../layers/recentImagery/model.js';
import { createRecentImageryLayer } from '../layers/recentImagery/index.js';
import {
BOX,
FIJI_BOX,
fakeCatalog,
fakeController,
fakeRenderer,
@@ -979,29 +977,6 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX
await settle();
assert.equal(await f.readout.exportImage('a'), true);
assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/);
// A dateline box is drawn on the map, but Worldview rejects a crossing BBOX.
const before = f.fetches.length;
f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 });
f.catalog.resolveLast();
await settle();
assert.notEqual(
f.byId('ri-notice-text').textContent,
'Select one side of the dateline',
'the drawn box is not a warning until an export is tried',
);
const crossingExport = f.byAction('export-a');
assert.equal(crossingExport.disabled, true, 'EXPORT is off up front');
assert.equal(crossingExport.title, 'Select one side of the dateline');
assert.equal(await f.readout.exportImage('a'), false);
assert.equal(
f.byId('ri-notice-text').textContent,
'Export failed · A snapshot cannot cross the dateline',
);
assert.equal(
f.fetches.length,
before,
'export does not request a crossing BBOX',
);
f.layer.setMode('ab');
assert.deepEqual(
[
@@ -1065,31 +1040,6 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to
assert.equal(article.dataset.open, 'false');
});
test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => {
const f = fixture();
f.layer.enable();
f.layer.setBox(FIJI_BOX);
f.catalog.resolveLast();
await settle();
assert.match(f.byId('ri-details').textContent, /Coverage full/);
const get = f.thumbnails.get;
const [west, east] = nonCrossingBoxes(FIJI_BOX);
f.thumbnails.get = (key) => ({
...get(key),
availableBoxes: [west],
emptyBoxes: [east],
});
f.thumbnails.probe(f.snap().focus.key, 'present');
assert.match(f.byId('ri-details').textContent, /Coverage partial/);
f.thumbnails.get = (key) => ({
...get(key),
availableBoxes: [west],
emptyBoxes: [],
});
f.thumbnails.probe(f.snap().focus.key, 'present');
assert.match(f.byId('ri-details').textContent, /Coverage unknown/);
});
test('the body scroll position survives renders even when DOM mutations reset it', async () => {
const f = fixture();
await f.ready();
+6 -13
View File
@@ -13,11 +13,11 @@ const REFUSALS = [
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
'That point cannot anchor a box', // layers/recentImagery/index.js
...[
{ west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap
{ west: 10, south: 80, east: 20, north: 89 },
{ west: 10, south: 10, east: 10, north: 20 },
{ west: 10, south: 10, east: 200, north: 20 },
{ west: Number.NaN, south: 10, east: 20, north: 20 },
{ west: 170, south: 10, east: -170, north: 20 }, // dateline
{ west: 10, south: 80, east: 20, north: 89 }, // polar
{ west: 10, south: 10, east: 10, north: 20 }, // degenerate
{ west: 10, south: 10, east: 200, north: 20 }, // longitude range
{ west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite
].map((box) => {
const result = validateBox(box);
assert.equal(result.ok, false);
@@ -27,14 +27,7 @@ const REFUSALS = [
test('en: refusals stay English', () => {
setLocale('en');
for (const text of REFUSALS) {
const shown = localizeNotice(text);
// Size refusals are rewritten with a non-breaking space before the unit.
const expected = / km wide/.test(text)
? text.replaceAll(' km', '\u00a0km')
: text;
assert.equal(shown, expected);
}
for (const text of REFUSALS) assert.equal(localizeNotice(text), text);
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
});
-29
View File
@@ -431,35 +431,6 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
}
}
/* The opening (src/app/openingIntro.js) sets these each frame. */
#loading-screen.opening {
background: color-mix(
in srgb,
var(--bg-dark) calc(var(--opening-veil, 1) * 100%),
transparent
);
}
#loading-screen.opening .loader-logo {
animation: none;
will-change: transform;
}
#loading-screen.opening .loader-logo svg {
overflow: visible;
}
#loading-screen.opening .loader-logo svg > path {
transform-box: fill-box;
transform-origin: center;
}
#loading-screen.opening h2,
#loading-screen.opening .loader-status {
animation: none;
opacity: var(--opening-text, 1);
}
.loader-content h2 {
font-family: var(--font-mono);
font-size: 18px;
+11 -11
View File
@@ -17,12 +17,7 @@
* @module voice/imageryActions
*/
import {
PRODUCTS,
boxCentre,
boxSideKm,
rankLatest,
} from '../layers/recentImagery/model.js';
import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js';
import {
displacedLayerResult,
watchExplicitLayerOff,
@@ -208,14 +203,19 @@ export async function findImagery(
`No area "${args.areaId}" on this page — call resolve_area again.`,
);
const [west, south, east, north] = record.bbox;
if (west > east)
return fail(
'DATELINE',
`${record.name} crosses the date line; the imagery box needs one side of it.`,
);
// 30 m pixels over a landmark-sized area show a handful of blobs: a small
// area gets the layer's own 10 km box around its centre instead.
// west > east is the short arc across the date line. The layer's helpers
// measure and centre it.
const { width, height } = boxSideKm({ west, south, east, north });
const small = width < 5 && height < 5;
const small =
(north - south) * 111 < 5 &&
(east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) <
5;
box = small
? { pin: boxCentre({ west, south, east, north }) }
? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } }
: { west, south, east, north };
areaName = record.name;
} else if (where === 'point') {
+4 -27
View File
@@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their
assert.equal(unknown.code, 'AREA_UNKNOWN');
});
test('a mixed antimeridian area is searched as its short-arc box', async () => {
test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => {
const square = (w, s, e, n) => [
[w, s],
[e, s],
@@ -251,7 +251,6 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
[178, 1],
[178, 0],
];
const layer = fakeLayer();
const store = createAreaStore();
const area = store.put({
geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]],
@@ -259,33 +258,11 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
source: 'osm',
});
assert.deepEqual(area.bbox, [178, 0, -174, 1]);
const result = await findImagery(deps(layer, { area }).value, {
const result = await findImagery(deps(fakeLayer(), { area }).value, {
areaId: area.areaId,
});
assert.equal(result.ok, true, 'the guard is lifted');
assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], {
west: 178,
south: 0,
east: -174,
north: 1,
});
});
test('a small area across the date line is pinned at its short-arc centre', async () => {
const layer = fakeLayer();
await findImagery(
deps(layer, {
area: {
areaId: 'd',
name: 'Dateline Islet',
bbox: [179.998, 0, -179.998, 0.01],
},
}).value,
{ areaId: 'd' },
);
const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt');
assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`);
assert.equal(lat, 0.005);
assert.equal(result.ok, false);
assert.equal(result.code, 'DATELINE');
});
test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => {