diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 541af11364..412bf5da86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,6 +106,16 @@ jobs: - name: Street Level gate with Mapillary fixtures run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173 + - name: The whole application on the stub renderer, with no Cesium loaded + run: | + mkdir -p qa-artifacts + npm run qa:stub-boot -- --json qa-artifacts/stub-boot.json + + - name: The renderer contract's logic checks on Cesium, headless + run: | + mkdir -p qa-artifacts + npm run qa:conformance -- --json qa-artifacts/conformance.json + - name: Preview server log if: failure() run: cat preview.log diff --git a/.prettierignore b/.prettierignore index 2b2cc755a1..9e1a01ef80 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,6 +9,8 @@ coverage pinokio/ENVIRONMENT pinokio/.installed src/data/local_data/ +# Written by scripts/record-camera-goldens.mjs and compared byte for byte. +src/render/conformance/goldens/ *.geojson *.geojsonl diff --git a/CHANGELOG.md b/CHANGELOG.md index f49dad02be..995beef5e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,120 @@ ## [Unreleased] +- A double-click on the map no longer follows or zooms to what is under + it. The globe's own double-click did that for some layers' markers and + shapes (earthquakes, cyclones, air quality, news, cables, places and + others); following something is a click, as for aircraft and ships. The + Cockpit's double-click and a drawing's finishing double-click are + unchanged (samehkhamis). +- Aircraft no longer jump ahead or back, and their trails no longer kink, + when the feed is late. The civil and military layers draw as far behind + real time as their feed is late (the 90th percentile of recent report + lags plus 5 s, at least 30 s civil and 15 s military, at most five + minutes), so an aircraft is placed between two real reports rather than + dead reckoned past them; the delay changes slowly, and the icons, the + renderer's live clock, labels, the HUD, detection, the tracked camera and + the trail all read the same one. Between two reports an aircraft flies + one smooth curve that leaves each report along its track, sent to the + renderer as `arc` segments; its trail is its reports joined along that + same curve, so the icon always sits on it. A late report a coasting + aircraft missed is eased onto, at most 30% faster than it flies; past + its newest report an aircraft coasts straight on (samehkhamis). +- The Display panel has a Sky group on a renderer with a sky to set: the + atmosphere, day and night (sun lighting by scene time), the sun, the + moon, the stars and the Milky Way's brightness. The choice is kept for the + next visit; what is not set stays as the renderer draws it (samehkhamis). +- The renderer contract no longer ties a renderer's look to the default + renderer's: `globe.sky` switches parts of the sky on and off, while how + the sky, atmosphere, haze, lighting, tone mapping and exposure look is + the renderer's own. `globe.weather`'s `clouds` is the fraction of the sky + covered, as observed; clouds are placed by scene time and the wind and + shade the ground under them where the sun lights it. New conformance + check `globe.weather.sceneTime` (samehkhamis). +- Selecting an aircraft, a vessel, a train or a transit vehicle no longer + makes it bigger: it keeps the size and form it had and changes colour (a + transit vehicle only widens its dark ring). A click on an aircraft, a + vessel or a train no longer moves the camera to a new framing either: the + camera keeps its distance and viewing angle, the contact slides to the + centre over one second, and the camera then follows it from there (a + vessel, which is never followed, is left centred). A + follow target asks for this glide with `transitionS` (renderer contract, + conformance check `camera.follow.transition`); without it a follow frames + at once, as before. An aircraft chosen by voice, search or a shared link + is still framed as before (samehkhamis). +- The renderer contract's `models` capability draws the procedural fleet + models: a model item can carry its glTF bytes (`gltf`, drawn without a + fetch), a per-axis stretch (`axisScale`), a colour for its tinted parts + (`maskColor`) and a cut below its origin (`clip: 'belowOrigin'`, a hull at + the waterline). Aircraft, military, local ADS-B, vessel, transit and rail + models are drawn through it (samehkhamis). +- A tracked aircraft's trail no longer draws a straight line from its track + history across a landing or take-off that was not seen: a parked or + taxiing aircraft whose history ends in the air (often its previous flight) + starts its trail on the ground (samehkhamis). +- Aircraft from adsb.lol that report no ground track (parked or taxiing + slowly) now face their reported true heading instead of north, so parked + models line up with their gates (samehkhamis). +- A renderer can draw weather: the `weather` capability adds `globe.weather`, + with clouds, fog, haze, rain and snow (each 0 to 1) and the wind they drift + on. `./render/weather` and `./weather/effects` export the shared rules and + the strengths of a weather observation. The Cesium renderer does not draw + weather (samehkhamis). +- Groups of toggles, sliders and notes can be added to the Display panel + under Effects, with `publishDisplayGroup` from `./ui/display/groups` + (samehkhamis). +- The globe opens at planet level, the whole Earth in view, instead of + flying in to Austin. A shared link still flies from + there to its view. The `startView` option of `createApplicationControls` + starts it somewhere else, a city for instance (longitude, latitude and + height, and heading and pitch in degrees) (samehkhamis). - An application's own tool can take the pointer as Draw does, and its click handlers can yield while a tool holds it, as the layers' do (`pointer` from `createApplicationTools`) (samehkhamis, #1641). +- `gods-eye-view/annotations` no longer reaches Cesium: the world annotation + renderer draws its areas, building columns, routes, arrows, rings and + markers through the renderer's draw port (the Cesium renderer now drapes + arrows, draws clamped rings by camera height and pulses shape alpha), and + samples a building's ground through the height service. A click on a + world mark now hits its draw set (`meta: { annotation: id }`) rather than + an entity. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog` + no longer reach Cesium: the weather shells and the wind layer's colour + shell and flow draw through the renderer's `draw.field` (`rasterShell` and + `windStreamlines`, which the Cesium renderer now draws), and the wind + relief is the globe port's `hillshade` surface shading. The flow animates + as before, and still falls back to the canvas where the renderer refuses + it. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its + pointer events from the renderer's input port and its picks from the query + port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and + `pickAt`'s result, are the renderer contract's `Hit`; positions are plain + `{ x, y }`; `HANDLER_EVENT_TYPES` is gone. Cesium's own picks stay on + `event.native` (and `event.pick` and `event.pickWindow`). A viewer with no + renderer bound needs `gods-eye-view/render/cesium/unbound` + loaded once first (samehkhamis). +- `gods-eye-view/application/operations` no longer reaches Cesium: ground + snapping and mesh floor sampling ask the renderer's globe, camera and query + ports, and see through the caller's draw sets by id (the raw + `excludeObjects` option and exclusion callbacks are gone). A viewer with no + renderer bound needs `gods-eye-view/render/cesium/unbound` + loaded once first, or location framing throws and snaps answer nothing + (samehkhamis). +- `gods-eye-view/layers/traffic` (and `gods-eye-view/application/sources`, + which reaches it) no longer reaches Cesium: the layer keys cached road + heights by the globe port's `surfaceVersion()` and waits on + `isSettled('surface')`. Heat-lines are always asked for draped; a renderer + that cannot drape draws them over the surface instead of the layer + dropping them. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- Where the Cesium renderer cannot drape (a WebGL context without depth + textures), every draped line now draws over the surface, as the renderer + contract asks: along the surface's curve between its positions, in its + colour where the surface hides it, hidden past the horizon. Segment colours + are dropped (it draws in its style colour) and it runs from its first shown + segment to its last (samehkhamis). ## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language @@ -788,7 +899,7 @@ - Stop one retired bikeshare feed from reporting the whole layer as failed. City feeds are fetched independently, but failure was recorded in a single - flag that only a successful *activation* cleared — and an already-loaded city + flag that only a successful _activation_ cleared — and an already-loaded city never activates again. A dead feed re-entering camera range therefore latched LOAD FAILED permanently over a map still drawing every other city's stations. Failure is now tracked per city: a city that fails beside others still @@ -1064,7 +1175,7 @@ photo a click opens, and the cones, by each photo's projection and upload date. KartaView's SINCE is the upload date (all its server can filter by); a note under the slider says so while KartaView is lit (`sinceBasis: - 'upload'` in the provider contract). +'upload'` in the provider contract). Mapillary's line coverage and sequence cones are now shared by both (`lineCoverage.js`, `sequenceCones.js`). @@ -1642,6 +1753,7 @@ Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347). Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351). + - New Fire Perimeters layer (Events group): live NIFC WFIGS interagency wildfire incident perimeters as ground-clamped polygons with a containment-colored fire line, refreshed every 5 minutes from the public @@ -1918,7 +2030,6 @@ of current runtime behavior, see [`docs/CURRENT-STATE.md`](docs/CURRENT-STATE.md ### Other changes - - Add ECMWF IFS model selection to Wind (#464, thanks @beneduzi), with model-scoped forecast-step caches, cancellation of replaced requests, and separate issue/valid timestamps. - Add bounded Director feature actions with accessible controls, explicit camera/layer admission and cancellation; restore pack geometry on same-shot seek. Preserve existing scenes and content attribution. @@ -2727,4 +2838,3 @@ represent previously published GitHub Releases. ## [0.1.0] — 2026-02-09 - Initial project version. - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5ef1d7f8e3..438f9da14d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -139,6 +139,7 @@ The highest-leverage places to jump in: - **Vue 3 + Pinia for the interface,** [CesiumJS](https://cesium.com/platform/cesiumjs/) for the globe and [Vite](https://vitejs.dev/) to build. See [Building UI](#building-ui). - **Assembly lives in `src/app/`; standalone defaults live in `src/standalone/`.** UI controllers live in `src/ui/`, layer factories in `src/layers/`, portable sources in `src/sources/`, and application operations in `src/services/`. Existing `src/data/.js` entries retain compatibility; new code belongs with its focused owner. +- **Reach the renderer through its contract** ([docs/RENDERER-CONTRACT.md](docs/RENDERER-CONTRACT.md#moving-code-onto-the-contract)): `findDraw`, `findCamera` and the other ports in `src/render/rendererOf.js`, not Cesium or the viewer's `scene`, `camera` or `entities`. Two ratchet tests hold this: only files on `src/render/cesiumAllowList.json` may import Cesium, and `src/render/viewerAccessAllowList.json` caps the viewer accesses each other file still makes. Neither list may grow; when you port code off them, shrink them (`node scripts/viewer-access-baseline.mjs` lowers the second). - Sources acquire records; renderers own Cesium resources. Import `gods-eye-view/layers//source` when only a source factory is needed. Common voice controls consume the session interface; protocol adapters own connection details. - **Secrets stay server-side.** Anything needing a private key goes through a local proxy under `server/providers/`. The browser only ever sees the Google Maps key (which you restrict) and ephemeral tokens. - `docs/CURRENT-STATE.md` is the authoritative runtime reference — read it first. diff --git a/README.md b/README.md index 4177b24f8e..ea347a7399 100644 --- a/README.md +++ b/README.md @@ -527,7 +527,7 @@ More reconstructions, interviews and press: [godseyeview.ai/press](https://godse How the globe handles live data: - **World-stable icons.** Aircraft and ships point along their _true real-world heading_ at every camera angle — tracked or not, looking straight down or across the horizon — via per-frame screen-space course projection. No spinning, no viewport-locking. -- **Smooth motion from choppy data.** Live feeds arrive every 15–30s; the globe renders one interval behind real time and interpolates between known fixes. Dead reckoning fills the gaps. +- **Smooth motion from choppy data.** Live feeds arrive every 15–30s, often minutes late; the globe renders as far behind real time as the feed is late (at least one interval) and draws each aircraft along a smooth curve between its known fixes. Dead reckoning fills the gaps. - **Honest satellites.** SGP4 propagation with orbit rings that stay locked to their satellites via GMST realignment — no drift, no per-second flicker. - **Sits on the real ground.** Entity heights are aligned to work with Google 3D tiles, so aircraft park on aprons and cameras stand on street corners instead of floating. - **Caching and request budgets.** An OpenSky credit governor, a TomTom daily tile budget, and disk-cached TLEs reduce repeated requests. These controls do not replace provider quotas or billing controls. @@ -544,7 +544,7 @@ src/ ├── voice/ # OpenAI Realtime session + 30 voice tools ├── layers/ # Layer components — weather, wind, cyclones, transit, ALPR, … ├── data/ # One module per layer + orchestration + context store -│ ├── iconOrientation.js # Screen-projected headings + horizon cull +│ ├── iconOrientation.js # Horizon backdrop for labels (headings: screenRotation.js) │ └── local_data/ # Bundled datasets (per-folder provenance) └── scenes/ # Cinematic scene director ``` diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index f796c62396..de7c4f2ea2 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -62,6 +62,14 @@ layer's hexagon grid; the complete resolved dependency inventory remains in - Source: - License: MIT +## kdbush + +- Package: `kdbush` 4.0.2 (the screen index that groups points drawn too + close together into clusters) +- Author: Copyright (c) 2018, Vladimir Agafonkin +- Source: +- License: ISC + ## H3 (h3-js) - Package: `h3-js` 4.4.0 (the GNSS Integrity layer's H3 hexagon cells) diff --git a/changelog.d/870-hidden-contact-dr.md b/changelog.d/870-hidden-contact-dr.md deleted file mode 100644 index aab55229e0..0000000000 --- a/changelog.d/870-hidden-contact-dr.md +++ /dev/null @@ -1,4 +0,0 @@ -- Reduce dead-reckoning work for flights already hidden behind the horizon. - Hidden contacts update on a staggered one-in-13-ticks rotation (about once a - second) while visible contacts and contacts with fleet models retain the full - update path (Wilmer Alzate, #870). diff --git a/dev/conformance/index.html b/dev/conformance/index.html new file mode 100644 index 0000000000..16d48a5372 --- /dev/null +++ b/dev/conformance/index.html @@ -0,0 +1,114 @@ + + + + + + Renderer conformance + + + +
+

Renderer conformance

+ + + + + + +
+
+
+
+
+
+ + + diff --git a/dev/conformance/main.js b/dev/conformance/main.js new file mode 100644 index 0000000000..a1fb6c48a2 --- /dev/null +++ b/dev/conformance/main.js @@ -0,0 +1,256 @@ +/** + * The conformance page: runs the logic suite in the browser, and draws the + * reference scenes on a renderer to check them against the stored + * references (or record new ones). Driven by hand or through the + * chrome-devtools MCP; `window.conformance` exposes the same actions. + */ +import { + DEFAULT_TOLERANCE, + runConformance, +} from '../../src/render/conformance/index.js'; +import { + REFERENCE_SCENES, + sceneSupport, +} from '../../src/render/conformance/scenes.js'; +import { + compareImages, + drawScene, + referenceName, +} from '../../src/render/conformance/visual.js'; +import { createStubHarness } from '../../src/render/stub/harness.js'; +import { toEcef } from '../../src/render/stub/math.js'; +import { createCesiumSceneRenderer } from '../../src/render/cesium/sceneRenderer.js'; +import { + CESIUM_CHECKS, + createCesiumHarness, +} from '../../src/render/cesium/harness.js'; + +const REFERENCES = '/src/render/conformance/goldens/visual/'; +const SAVE = '/__conformance/references/'; +const ctx = { + toEcef, + assets: { + model: '/models/fleet/aircraft/c172.glb', + // Not served: the model failure check loads it. + missingModel: '/models/conformance-missing.glb', + }, +}; +const $ = (id) => document.getElementById(id); +const status = (text) => ($('status').textContent = text); + +const RENDERERS = { + cesium: () => createCesiumSceneRenderer({ container: $('stage') }), +}; + +const HARNESSES = { + stub: () => [createStubHarness('stub (browser)'), {}], + cesium: () => [ + createCesiumHarness({ + model: ctx.assets.model, + missingModel: ctx.assets.missingModel, + }), + { only: (id) => CESIUM_CHECKS.has(id) }, + ], +}; + +/** + * Runs the logic suite on `which`; `all` runs every check, listed or not; + * `only` (check ids) runs just those of them. + */ +async function runLogic(which = 'stub', { all = false, only } = {}) { + status(`running the logic suite on ${which}…`); + const [harness, options] = HARNESSES[which](); + const listed = all ? () => true : (options.only ?? (() => true)); + const report = await runConformance(harness, { + only: (id) => listed(id) && (!only || only.includes(id)), + }); + $('logicResults').innerHTML = + `

${report.harness}: ${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped

+ ${report.results + .filter((r) => r.status !== 'pass') + .map( + (r) => + ``, + ) + .join('')}
${r.status}${r.id}${escape(r.detail ?? '')}
`; + status(''); + return { + passed: report.passed, + failed: report.failed, + skipped: report.skipped, + failures: report.results.filter((r) => r.status === 'fail'), + skips: report.results.filter((r) => r.status === 'skip'), + }; +} + +const escape = (s) => + s.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]); + +async function pixels(blob) { + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const g = canvas.getContext('2d'); + g.drawImage(bitmap, 0, 0); + return g.getImageData(0, 0, bitmap.width, bitmap.height); +} + +// Object URLs shown for the current run, revoked when the next one starts. +let objectUrls = []; +function objectUrl(blob) { + const url = URL.createObjectURL(blob); + objectUrls.push(url); + return url; +} + +async function toUrl(imageData) { + const canvas = new OffscreenCanvas(imageData.width, imageData.height); + canvas.getContext('2d').putImageData(imageData, 0, 0); + return objectUrl(await canvas.convertToBlob()); +} + +/** The views the stored manifest lists, or none. */ +async function storedViews() { + try { + const res = await fetch(REFERENCES + 'manifest.json', { + cache: 'no-store', + }); + return res.ok ? ((await res.json()).views ?? []) : []; + } catch { + return []; + } +} + +async function reference(name) { + const res = await fetch(REFERENCES + name, { cache: 'no-store' }); + return res.ok && res.headers.get('content-type')?.startsWith('image/') + ? res.blob() + : null; +} + +/** Draws every scene; records references or compares against them. */ +async function runScenes({ record = false, only } = {}) { + const which = $('renderer').value; + const renderer = await RENDERERS[which](); + const results = []; + $('views').innerHTML = ''; + for (const url of objectUrls) URL.revokeObjectURL(url); + objectUrls = []; + try { + for (const scene of REFERENCE_SCENES) { + if (only && !only.includes(scene.id)) continue; + const unsupported = sceneSupport(scene, renderer, ctx); + if (unsupported) { + results.push({ scene: scene.id, status: 'skip', detail: unsupported }); + continue; + } + status(`${scene.id}…`); + // A scene the renderer refuses fails alone; the others still draw. + try { + await drawScene(renderer, scene, ctx, async (view, capture, settle) => { + const name = referenceName(scene.id, view.name); + const figure = document.createElement('figure'); + $('views').append(figure); + if (settle.state !== 'settled') { + const detail = `${settle.state}: ${settle.blockers.join(', ')}`; + results.push({ + scene: scene.id, + view: view.name, + status: 'fail', + detail, + }); + figure.innerHTML = `
${name}: ${escape(detail)}
`; + return; + } + if (record) { + const res = await fetch(SAVE + name, { + method: 'PUT', + body: capture, + }); + results.push({ + scene: scene.id, + view: view.name, + status: res.ok ? 'recorded' : 'fail', + detail: res.ok ? undefined : `save ${res.status}`, + }); + figure.innerHTML = `
${name}: recorded
`; + return; + } + const refBlob = await reference(name); + if (!refBlob) { + results.push({ + scene: scene.id, + view: view.name, + status: 'fail', + detail: 'no reference', + }); + figure.innerHTML = `
${name}: no reference
`; + return; + } + const [actual, expected] = await Promise.all([ + pixels(capture), + pixels(refBlob), + ]); + const diff = new Uint8ClampedArray(actual.data.length); + const outcome = compareImages(actual, expected, { diff }); + results.push({ + scene: scene.id, + view: view.name, + status: outcome.match ? 'pass' : 'fail', + diffFraction: outcome.diffFraction, + solidPixels: outcome.solidPixels, + mismatchedPixels: outcome.mismatchedPixels, + ...(outcome.reason ? { detail: outcome.reason } : {}), + }); + const diffUrl = outcome.reason + ? '' + : await toUrl(new ImageData(diff, actual.width, actual.height)); + figure.innerHTML = `
+
${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}
`; + }); + } catch (error) { + results.push({ + scene: scene.id, + status: 'fail', + detail: String(error?.message ?? error), + }); + } + } + if (record) { + // A partial recording keeps the other scenes' entries. + const kept = only + ? (await storedViews()).filter( + (view) => !only.some((id) => view.startsWith(`${id}-`)), + ) + : []; + const recorded = results + .filter((r) => r.status === 'recorded') + .map((r) => referenceName(r.scene, r.view)); + await fetch(SAVE + 'manifest.json', { + method: 'PUT', + body: + JSON.stringify( + { + renderer: which, + size: { + width: renderer.canvas.width, + height: renderer.canvas.height, + }, + views: [...kept, ...recorded], + }, + null, + 2, + ) + '\n', + }); + } + } finally { + renderer.destroy(); + status(''); + } + return results; +} + +$('logic').onclick = () => runLogic('stub'); +$('logicCesium').onclick = () => runLogic('cesium'); +$('check').onclick = () => runScenes(); +$('record').onclick = () => runScenes({ record: true }); +window.conformance = { runLogic, runScenes }; diff --git a/dev/stub-app/main.js b/dev/stub-app/main.js new file mode 100644 index 0000000000..ecd9e8607f --- /dev/null +++ b/dev/stub-app/main.js @@ -0,0 +1,60 @@ +/** + * The whole application on the stub renderer (`src/render/stub`), with only + * the contract's required members: the proof that the application runs on + * those members alone, and needs no code that knows which renderer it is. + * `scripts/qa-stub-boot.mjs` serves the application's page with this entry + * in place of `src/main.js`, boots it headless, runs its data layers and + * checks that no Cesium module loads. + * + * The stub runs nothing on its own: each animation frame here ticks it once. + * `window.__stubBoot` exposes the application and the renderer it made. + */ +import { createStandaloneApplication } from '../../src/standalone/application.js'; +import { createStubRendererPlugin } from '../../src/render/stub/index.js'; + +const renderers = []; + +/** Tick a renderer once per animation frame until it is destroyed. */ +function drive(renderer) { + const step = () => { + if (!renderers.includes(renderer)) return; + renderer.testing.tick(); + requestAnimationFrame(step); + }; + requestAnimationFrame(step); +} + +// The required tier, no capability at all; `?capabilities=all` gives the +// stub every capability, to see what the layers draw with them. +const allCapabilities = + new URLSearchParams(location.search).get('capabilities') === 'all'; + +const plugin = createStubRendererPlugin( + allCapabilities ? {} : { capabilities: [] }, + (renderer) => { + renderers.push(renderer); + const destroy = renderer.destroy.bind(renderer); + renderer.destroy = () => { + renderers.splice(renderers.indexOf(renderer), 1); + destroy(); + }; + drive(renderer); + }, +); + +const application = createStandaloneApplication({ + renderer: plugin, + allowQaRegistration: true, +}); + +window.__stubBoot = { + application, + renderers, + started: application.start().then( + () => ({ ok: true }), + (error) => { + console.error('Stub application failed to start:', error); + return { ok: false, error: String(error?.stack || error) }; + }, + ), +}; diff --git a/docs/APPLICATION.md b/docs/APPLICATION.md index 33036f31af..10673fd07f 100644 --- a/docs/APPLICATION.md +++ b/docs/APPLICATION.md @@ -43,7 +43,11 @@ await app.destroy(); ``` The example's containers and three remaining constructors are supplied by the -consumer. The viewer helper preserves the standalone viewer's render settings; +caller. The standalone scene also returns `trimStaleCommands()`, which drops +the draw commands the Cesium scene keeps after a turned-off layer stops drawing; +the application tools call it one frame after each layer disable. A scene +without it keeps those commands, and so the layer's memory, until they are +overwritten. The viewer helper preserves the standalone viewer's render settings; it neither selects map sources nor reads keys. Supply a visible credit container and retain all attribution required by the chosen sources. Cesium is external to this export: the consuming build must provide the same instance used elsewhere @@ -81,6 +85,119 @@ constructed component objects; the component instances themselves remain mutable `ready` means all constructors have returned. Background feed activity and the standalone share-restoration result keep their existing separate contracts. +## Pointer input + +`gods-eye-view/input` exports `inputFor(viewer)`, the scene's one input +dispatcher. Every layer and tool takes its pointer input from it, and so can +the caller: one pointer handler per viewer, and a click picked once and +handed to every subscriber. + +```js +import { inputFor } from 'gods-eye-view/input'; + +const input = inputFor(viewer); +const off = input.onClick((event) => { + if (event.ownerId === 'flights') showFlight(event.id); +}); +// Later: +off(); +``` + +`onClick` runs while no tool holds the pointer (the draw tool, the imagery +box), so a vertex placed on an aircraft is not also a click on it. Its event +reads lazily; a subscriber that reads nothing costs no pick: + +| Member | What it is | +| -------------------- | ------------------------------------------------------------------------- | +| `screenPosition` | Where the user clicked, in CSS pixels; for DOM and overlay hit-tests | +| `position` | Where that lands in the pick buffer (corrected under sensor styles) | +| `gesture` | `{ travelPx, durationMs }` of the press, to tell a click from a drag | +| `topHit` | The renderer's `Hit` on top at `position`, or `null` for the map itself | +| `drawHit` | `topHit` when it is an item of a draw set, else `null` | +| `hit` | `topHit`, or on a coarse pointer the contact under a surface pick | +| `id`, `ownerId` | The hit's pick id and the layer that registered it, or `null` | +| `meta` | The hit's own metadata, when it carries any | +| `surface` | Whether the hit is the map itself | +| `drill(limit)` | The draw-set `Hit`s under the click, shared by every subscriber | +| `windowHit(w, h)` | `{ id, drawHit, surface }` of a pick over a `w`×`h` window | +| `ground()` | The world position under the click, or `null` over the sky | +| `native` | The renderer adapter's own `{ pick, pickWindow(w, h), drill(limit) }` | +| `pick`, `pickWindow` | `native.pick` and `native.pickWindow`, for code bound to the engine picks | + +A hit is the renderer contract's `Hit` (`src/render/contract/query.d.ts`). +Something drawn outside the renderer's draw port is a `Hit` with `set: ''`, +named by the adapter. Positions are plain `{ x, y }` objects. The dispatcher +takes its pointer events from the renderer's input port and its picks from +its query port, so a viewer with no renderer bound needs the Cesium adapter's +factories loaded (`gods-eye-view/render/cesium/unbound`), or `inputFor` throws. + +`onPointer(type, fn, { lease })` subscribes to `down`, `move`, `up`, `click` +or `dblclick`; with a lease it runs only while that lease is current. A tool +takes its lease with `claimPointer(ownerId, { onLost })` from the same export +(and gives it back with `releasePointer(lease)`), which also keeps every +ambient subscriber off its clicks; `isPointerFree()` and `pointerOwner()` +report who holds it. The newest claim takes over, as on the renderer's input +port: the tool holding the pointer has its `onLost` called once and turns +itself off, and its late release frees nothing. `suspendCamera(reason)` and `suppressStockClicks()` return their +own release: camera input and the viewer's stock select and double-click-track +come back when the last hold is released, so two holders cannot undo each +other. The renderer's input port owns the camera controller's `enableInputs`: a direct +write (Cesium's camera flights make one when they start and end) is kept, but +reads true only while no hold is out. A caller-supplied `createScene` that creates its own viewer registers +`defer(() => inputFor(viewer).destroy())` right after it; the standalone scene +does this and returns the dispatcher as `scene.input`. + +## Height queries + +`gods-eye-view/queries/heights` exports `heightsOf(viewer)`, the one place +height queries go. Layers, tools and the camera ask it instead of asking the +renderer's query port (`sampleHeight`, `sampleHeightNow`, `clampToSurface`) +or the scene themselves, so how the renderer answers heights can change +without touching them. Pass the viewer the renderer is bound to, not its +scene. A viewer with no renderer bound is answered by the Cesium adapter's +fallback once the caller has loaded `gods-eye-view/render/cesium/unbound`; +until then, every query answers `null`. + +```js +import { heightsOf } from 'gods-eye-view/queries/heights'; + +const heights = heightsOf(viewer); +const ground = heights.now({ lon, lat }, { exclude: [ownSetId] }); +if (ground !== null) place(ground); +``` + +| Member | What it answers | +| ----------------------------- | ------------------------------------------------------------------------- | +| `now(point, opts)` | Height in metres from what is loaded, or `null` | +| `clampNow(position, opts)` | The ECEF `{ x, y, z }` moved onto the drawn surface, or `null` | +| `batch(points, opts)` | A promise of heights once the most detailed tiles stream; `null` per miss | +| `clampBatch(positions, opts)` | A promise of clamped `{ x, y, z }` copies; `null` per miss | +| `supported()` | `{ surface, clamp }`: whether the drawn surface can be queried at all | + +A point is `{ lon, lat }` in degrees or `{ longitude, latitude }` in radians. +`against: 'surface'` (the default) reads what is drawn, 3D tiles and globe; +`against: 'terrain'` reads the loaded terrain alone; `against: 'tiles'` the +tiles without the globe. Both `surface` and `tiles` include draw sets drawn +with `includeInHeightQueries`; `clampNow` and `clampBatch` always clamp to +the surface. `exclude` lists draw set ids to see through, of those drawn with +`includeInHeightQueries`; every other draw set is seen through already. Every +miss is `null`, and every caller treats it as one; `batch` and `clampBatch` +reject when the query itself fails. Without depth-texture support the Cesium +renderer answers no `surface` or `tiles` height; `now` still answers +`terrain` from the loaded tiles, while `batch` misses terrain too. + +## Cesium internals + +The app reaches private Cesium fields only through +`src/render/cesium/internals.js`, one named helper per field (the main and +offscreen pick views, a billboard's collection, a cluster's point collection, +the widget's render-loop latch, the WebGL context and whether a camera flight +is under way). `internals.test.mjs` fails when the installed Cesium stops +declaring one of them, and when a private field is reached anywhere else. +Imagery that rations its tile requests states the policy as a hook with +`withTileRequestHook(provider, { requestImage, credit })` from +`src/render/cesium/tileRequests.js`, which leaves the provider untouched. + ## Standalone wiring `src/main.js` reads the existing browser configuration and starts diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index e7105aae32..44d598cac2 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -33,12 +33,13 @@ export inventory. Use declared exports rather than reaching into internal files. | `src/layers//` | Source acquisition, records and Cesium resources with explicit controller/renderer owners | | `src/sources/` | Portable protocols and source contracts; request state belongs to each factory instance | | `src/services/` | Supplied application operations; scene construction owns caches and cancellation | +| `src/render/` | The renderer contract, the stub renderer, the conformance suite and Cesium renderer pieces | | `src/voice/` | Portable action schemas/session, common controls, action execution and separate protocol adapters | | `server/providers/` | Node route factories, process-scoped provider caches and shutdown cleanup | | `server/standalone/` | Environment, local settings writes and server composition | See [application construction](APPLICATION.md) and the -[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces. +[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces, and the [renderer contract](RENDERER-CONTRACT.md) for what a renderer provides. ## Import direction gates @@ -470,6 +471,13 @@ release listeners; pending action feedback is limited to its current owner. rendering, HUD and share operations. `src/standalone/controls.js` provides the running application's instances. The shell imports no standalone bootstrap or concrete live layer implementation. +The shell reaches the renderer through its ports alone, and loads no +renderer: given a viewer with no renderer bound, load +`./render/cesium/unbound` once first, which also provides the celestial +ring's precise ICRF rotation (`src/sky/icrf.js`; until then the ring uses +the TEME approximation). Whether Cockpit's aircraft is an entity of the +viewer's own is the `viewerDrawsEntity` service's to say; the application +scene supplies it. Panel layout, position/drag, notices, recording and deferred UI work have separate owners with synchronous cleanup. Existing scene, share and HUD engines retain their entry points. `ui/styles` loads the ordered stylesheet entry; component @@ -507,6 +515,15 @@ perform no network requests and discover no additional modules. standard sources and their setup/fallback policy. The standalone facade wires these to the application's render governor. +`maps/imagery`, `maps/terrain` and `maps/3d` are the Cesium renderer's +(`src/render/cesium/`). `maps/controller` and `maps/defaults` are +Cesium-free: they make their scene changes and build their providers +through the map engine the renderer provides as it loads +(`src/maps/engine.js`). The application's renderer provides it; with a +viewer with no renderer bound, load `./render/cesium/unbound` once first, or pass the +engine as the controller's and `createDefaultMapSources`' `engine` option. +Without one, constructing a controller throws, naming that export. + A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`. Each source has a user-facing `descriptor`, availability/reason, and either an `imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`. @@ -571,6 +588,13 @@ separate from standalone setup. Scene construction returns these operations; the catalog and controls use the same surface owner. Layers still own their individual ground-snap caches and model resources. +The entry is Cesium-free: ground snapping and mesh floor sampling ask the +renderer's globe (`isSettled`), camera (`pose`) and query (heights) ports, and +see through the caller's draw sets by id. A viewer with no renderer bound needs +the Cesium adapter's factories loaded (`gods-eye-view/render/cesium/unbound`) +first; until then the snap and the sampler answer nothing and location framing +throws, naming that export. + Terrain cancellation rejects late replies before caching, clears floor queues and removes the map-stack listener. Annotation lookup caches are instance-owned and cleared on cancellation. Geometry selection and floor policies are unchanged. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index a176aae753..811e2a1fd6 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -12,16 +12,17 @@ north. While anything moves (a layer in motion, the camera, a followed contact), the globe draws at the display's own refresh rate; there is no fixed 60 FPS cap. -The idle render governor (`src/renderGovernor.js`) caps a parked scene at -`IDLE_FRAME_RATE` (60) ticks a second, because Cesium still runs the clock, -data sources and update listeners on every animation frame even when it skips -the draw; the viewer starts at that cap until the governor is installed. The -camera holds continuous render from `moveStart` to `moveEnd`, and samples its +The Cesium frame port (`src/render/cesium/ports.js`, its `idleFps`) caps a +parked scene at `IDLE_FRAME_RATE` (60, `src/renderGovernor.js`) ticks a +second while no hold is out, because Cesium still runs the clock, data sources +and update listeners on every animation frame even when it skips the draw; the +viewer starts at that cap until the frame port takes over. Through the idle +render governor, the camera port holds continuous render from `moveStart` to `moveEnd`, and samples its pose every 250 ms in between, so a camera drifting by rounding errors (no `moveEnd`) is released after half a second at rest and held again if it moves. The world clock holds continuous render while it plays away from the live edge (not while it steps or waits for data), so playback draws at the display's rate too. Waits that used to count frames (a followed contact's first -position, a shared follow view, a trail's temporary copy) count drawn time +position, a shared follow view) count drawn time through `src/time/frameWait.js`, at most 100 ms a frame, so they last the same at any refresh rate and a background tab does not use them up. @@ -101,7 +102,7 @@ does nothing, wherever it starts. Rotation drags that start on the planet, and zoom, are unchanged. How much of the frame shows the planet's surface is measured by casting a 32×18 grid of view rays at the ellipsoid; while the scope mask is on (the default) only the rays inside its keyhole count, since the mask -hides or dims the rest. Voice tilt and in-place turns of a free 3D camera above +hides or dims the rest. Voice tilt and in-place turns of a free camera above 1,000 km stop when about a tenth of the frame still shows the surface (or about as much as it showed when it started), never less than about 1% of the visible frame, and a view that already shows less only keeps or gains what it has. A @@ -132,7 +133,7 @@ Views with more surface than that, such as the oblique orbital Director shots, are left as they are, and so are tracked or locked cameras, a camera flight in progress, a Director scene while it plays (holds included), a pointer held down on the globe (a drag held still; with several fingers down, until the -last is released) and the 2D and Columbus modes; a check a flight, scene or +last is released); a check a flight, scene or held pointer defers runs once it ends. A release outside the window that the page never sees counts as given once the window loses focus, the page is hidden, the canvas loses the pointer's capture, or the pointer moves with no @@ -143,6 +144,11 @@ it is until the next move. A voice turn requested while the camera is tracked is judged by the pose voice's release of the follow camera will leave, before that release, so a refused turn keeps the tracking. +The app draws only the 3D globe: the renderer it draws through has no 2D or +Columbus view. Voice tilt, in-place turns and the move-end recovery above are +written for that globe alone and carry no check for the other scene modes, +which in Cesium's 2D and Columbus views made them do nothing. + Analyst region queries resolve unique Natural Earth names offline without geocoding, so Gold Coast and Ivory Coast name the West African natural regions. Duplicate names require a geocoded containment anchor; when several entries for @@ -1019,9 +1025,10 @@ resources and subscriptions. The globe relief helper is enabled with Wind and released when Wind is disabled. It uses terrain vertex normals for view-directed shading, falling back to global globe-curvature shading when normals are unavailable; the fallback does not show local hillshade. Neither mode -adds elevation data or represents sunlight. Relief declines to replace an -existing globe material, restores the prior empty material only while still -owning it, and leaves later owners intact. +adds elevation data or represents sunlight. Relief is the globe port's +`hillshade` surface shading: the renderer never replaces a globe material +someone else holds (it waits until that one is gone), gives the globe back +when Wind is disabled, and leaves later owners intact. Source acquisition retains deadlines, body budgets, disconnect cancellation, per-model/field singleflight caching and one-minute failure backoff. Application catalog construction owns each instance. @@ -1225,7 +1232,7 @@ Keyless terrain tiles retry when Re:Earth throttles them. The browser fetches `terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no proxy in this repository sees those requests (`/api/terrain/heights` is the separate point-height endpoint), and the upstream edge answers zoom-out bursts -with HTTP 429 under load. `src/maps/terrain.js` hands Cesium a `Resource` +with HTTP 429 under load. `src/render/cesium/mapTerrain.js` hands Cesium a `Resource` whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms doubling to a 15 s cap, with every retry waiting behind one shared cooldown @@ -1600,7 +1607,9 @@ unchanged. Polled layer refreshes and the HUD's camera readout pause while the page is hidden. An app embedded inline in a panel keeps both running, because the panel's host can report the page as hidden while it is on screen. This is the -same rule the render loop follows (`keepPanelRendering` in `app/embed.js`). +same rule the render loop follows (`keepPanelRendering` in +`render/cesium/panelRendering.js`, which the Cesium plugin hands the +application and the application scene hands the embed views). Application scene setup owns request services, terrain/floor caches and annotation lookup state. Controls, layers and voice share those owners, and cancellation @@ -1760,15 +1769,19 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. -Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames. +Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. Traffic and bikeshare expose factories through `./layers/traffic` and `./layers/bikeshare`. Traffic separates road requests, ingestion, animation, flow matching, styling, viewport lifecycle and development timing. Each source owns its decoded flow cache; cancelled bodies cannot refill it. Bikeshare separates its city registry, station source, parsing, rendering, selection and -proximity lifecycle. Existing standalone sources, live/simulated labels, road -budgets, station availability and polling behavior are retained. +proximity lifecycle; its station dots and selected-station highlight are two +renderer draw sets and it no longer reaches Cesium, so a caller handing it a +Cesium viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Existing standalone sources, +live/simulated labels, road budgets, station availability and polling behavior +are retained. Installations and proximity context now expose `./layers/installations` and `./layers/awareness` factories. Each owns its records, selection, presentation, @@ -1787,7 +1800,17 @@ a fresh winning record. Dense removal clears only its own provenance, and a fresh core rebuild or lifecycle reset replaces the corresponding ownership. Source adapters retain the existing CelesTrak and Launch Library endpoints; standalone entries provide scene services and the satellite dependency. +The satellites layer draws through the renderer's draw port and no longer +reaches Cesium: the dots are one point set moved in a single write a frame, the +tracked satellite's dot a set of its own drawn where the follow camera framed +it, and the orbit rings a line set dimmed behind the globe and turned with the +Earth each second. A caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. The mission factory separates paths, replay, camera, panel, overlays and placement. +Its markers, lines, live rings and pad zone are renderer draw sets, and it +follows a mission through the camera port, so a caller handing it a Cesium +viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Launch Library pad coordinates retain unknown values: missing fields use the reported location coordinates when available, and launches without a known pad position stay off the map. Genuine zero coordinates remain valid. Undisclosed @@ -1808,10 +1831,16 @@ and scene services. Disable and teardown cancel pending refreshes; malformed snapshots preserve the last good display. Refresh restoration keeps selection identity without announcing a new user selection. Source/label, LOD thresholds, card limits, fire identities, altitude placement and analyst records are retained. +The layer draws its fire glows through the renderer's draw port and no longer +reaches Cesium; a caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. Earthquake rendering is exposed through `./layers/earthquakes`. The layer owns -its entities and request lifecycle; the application supplies the overlay host -and snapshot source. The standalone adapter keeps the existing USGS daily feed, +its renderer draw set and request lifecycle and no longer reaches Cesium; the +application supplies the overlay host and snapshot source. A caller handing +it a Cesium viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. `depthColor` returns a renderer +colour `[r, g, b, a]` and `depthAccent` its CSS. The standalone adapter keeps the existing USGS daily feed, M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or destroying the layer cancels pending work and ignores late results. While on, the layer registers its quakes of magnitude 6 and up @@ -1822,6 +1851,21 @@ feed's place, cut to 40 characters (`earthquakeMarkLabel` in `src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon Islands`, or `M6.4` with no place). +Air quality (`./layers/air-quality`) draws its station discs as one renderer +draw set of ground-clamped fills and reads the view through the camera port; it +no longer reaches Cesium, so a caller handing it a Cesium viewer, +with no renderer bound, loads the `./render/cesium/unbound` export once +first. + +Cockpit (`./ui/cockpit`) flies the camera through the camera port on the frame +port's `preUpdate`, with the shared geo maths, and no longer loads the Cesium +camera factory: a caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first, or its +controller throws naming it. Whether the aircraft it flies still draws comes +from its `trackedEntityDrawn` service (the shell asks the entity's record, +and the application scene's `viewerDrawsEntity` for an entity of the viewer's +own); without one, Cockpit takes the aircraft as drawn. + ## Rendered-mesh floor readings — November 9, 2026 On the photoreal stack the shared floor (`cachedGroundFloor`) answers from @@ -1846,12 +1890,26 @@ directly under a deck or a roof overhang reads the structure above it, and a vehicle between readings takes the nearest one, so its floor steps where the nearest reading changes. +The sampler and the aircraft ground snap (`src/services/groundSnap.js`) reach +the renderer only through its ports: the camera's `pose()` for the probe +height gate, the globe's `isGlobeVisible()` (the sampler runs only with +the globe hidden) and `isSettled('surface')` (sampler) and +`isSettled('tiles')` with `isSettled('surface')` (snap) for whether the tiles +have streamed, and the query +port's heights, seeing through the caller's draw sets by id. Cockpit's ground +probe names the tracked contact's icon and model sets, which the flights and +military layers keep on its entity record (`groundSets`). + ## Vessel components and sources `src/data/aisLiveVessels.js` assembles `createVesselLayer` from the `./layers/vessels` package entry. The factory owns feed lifecycle, keyed records, rendering, selection, trails and cards in separate components. The standalone entry supplies its AISStream source, scene services and existing row limits. +Its ship icons are one renderer icon draw set (held motion, course rotation, +focus emphasis, horizon cull) and the entry no longer reaches Cesium, so a +caller handing it a Cesium viewer, with no renderer bound, +loads the `./render/cesium/unbound` export once first. Incomplete observations retain missing keyed vessels for at most five minutes since their last accepted receipt, within the renderer's row budget (plus the @@ -1907,31 +1965,29 @@ A tracked civil or military aircraft's trail (`src/data/trailContinuity.js`) lif the pen, drawing nothing, between two points more than 48 minutes or over 1,500 kt apart (a parked aircraft within 0.1 nm keeps one line for up to three hours) and at a waypoint with no altitude; a ground waypoint is drawn on the ground. The head joins the -aircraft only within 150 km. Each trail keeps up to 2,000 points, a full day of history -at one fix per minute plus the live session; past that the oldest recorded points go -first, and the oldest reports only once none are left. The renderer +aircraft only within 150 km. Each trail keeps up to 2,000 reports, a full day of history +at one fix per minute plus the live session; past that the oldest go first. The renderer (`src/data/trailRenderer.js`) freezes every chunk of 128 points except the newest into static geometry, so a long trail costs about as much per frame as a short one; `scripts/qa-trail-freeze.mjs` checks that a freeze never shows a blank frame. -While an aircraft is tracked, its trail between reports is the path its icon was -drawn along: the displayed position is recorded about once a second or every 150 m -(`recordTrailPoint`). Recorded points are thinned by shape: one stays only where -dropping it would move the line more than 30 m across the track or in height from any -position it stood for, or leave a straight piece longer than 10 km, so straight flight -adds a vertex every 10 km at most and a turn keeps its curve. A recorded point that -would turn the line back sharper than 120° over a short step is dropped. Reports stay -in the trail as anchors, in time order. Recorded points never join two reports that are -not one flight under the 48-minute and 1,500 kt rules; the points between them go and -nothing is recorded across such a pair. A report for a time the display has already -passed replaces what was drawn after it, and nothing is recorded until the icon has -eased onto it, so the line reads arc, report, corrected path. History from before tracking started, and the backfill, run report to report. +A trail holds the aircraft's reports and nothing else, in time order: what the icon was +drawn at between them is never kept, so a late report cannot leave a kink. Between two +reports that are one flight and both carry a track, the icon is drawn along, and the +trail drawn through, one curve (`src/data/fixCurve.js`): a biarc, two constant-rate +turns sent to the renderer as contract `arc` segments, passing through both reports and +leaving each along its reported track, so the icon sits on its trail with no offset. +Pairs with no track, slower than 40 m/s, or with a track more than 75° off the line +between them are joined straight. The trail samples the curve at least every degree of +turn. History from before tracking started, and the backfill, run report to report the +same way. The trail never runs past the icon or through its 3D model, and the head runs from the newest kept point outside the model to the icon (to the model's tail when the model is -the visual). A contact with no new report coasts along its reported track for 5 minutes -past its last real report, at no more than 1,500 kt and never below known ground, then stops; +the visual). A contact with no new report coasts straight on along its reported track for 5 minutes +past its last real report (no turn: a turn rate measured over earlier reports outlives +the turn), at no more than 1,500 kt and never below known ground, then stops; one that went quiet on the ground, or within 150 m of a known ground floor, holds at its last -report, records nothing and draws no head (with the ground unknown, a low barometric +report and draws no head (with the ground unknown, a low barometric altitude alone does not hold it). The hold-or-coast choice is made once per report (`staleHoldsForFix` in `src/data/motionModel.js`), and the forward fix built when a repeated position carries new speed or course follows the same rules and is never a trail report. A live report @@ -2275,10 +2331,13 @@ hidden; tilted past the Earth's limb neither the sensor nor the swath reads. A swath is confirmed only on the operator's, an agency's (ESA's eoPortal included) or an academic page for its platform. From 16×, with flat imagery on the globe (not Google 3D tiles) and the view at -nadir, every 2 s the view asks the base imagery layer for the tiles it will -need 5 to 20 s ahead along the ground track (`prefetchImageryAhead` in -`src/ui/cockpitOrbitalView.js`), so the browser has them cached when the -view arrives. The level is the one Cesium will draw there +nadir, every 2 s the Cesium renderer asks the base imagery layer for the +tiles the view will need 5 to 20 s ahead along the ground track, so the +browser has them cached when the view arrives. The renderer works this from +its own camera (`preloadImageryAhead` in +`src/render/cesium/imageryLookAhead.js`): a vertical field of view as narrow +as an orbital view's at 16× for the camera's height, a look straight down, +and the camera's own motion over the ground, which gives the track. The level is the one Cesium will draw there (`imageryLevelForView` in `src/cockpitOrbital.js`, following Cesium's own choice: the terrain level whose error spans at most the globe's maximum screen-space error, then the imagery level whose texels are nearest that @@ -2288,7 +2347,7 @@ at the lowest priority, so a request is declined while the imagery server's slots are taken by the tiles on screen and is the first dropped when the scheduler is full (a declined or dropped tile is asked for again later, one that failed to load is not); it remembers the last 512 tiles asked for and does not ask for those again, starts over on another base map (cancelling the old map's -pending requests), and cancels the requests still pending on exit. Across the track it samples the centre line, a third +pending requests), and when the view widens (below 16× or on exit) cancels the requests still pending and forgets the tiles asked for. Across the track it samples the centre line, a third out and the frame's edges. While tilted off nadir the view looks away from the track, and with the world clock more than a minute from now (paused or played back) it will not pass where the look-ahead points, so nothing is @@ -2544,6 +2603,14 @@ owners. Tuner calculations have a pure entry, with existing layer exports preserved. Destruction removes listeners and state subscriptions before ending tuning; a delayed Enable result cannot reveal or refocus removed controls. +The stations, their clusters and the selected marker draw through the +renderer's draw port, and the layer no longer reaches Cesium. Stations drawn +too close together on screen stand behind one cluster dot, grouped as the +default renderer's entity clustering grouped them (`geo/screenCluster.js`, +42 px, three or more), reclustered as the camera moves and when the filter +changes. A caller handing the layer a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. + ## Giroc / Webcam Romania CCTV source pack `config/cctv_sources.romania.json` is an optional single-camera pack for Giroc, @@ -2692,7 +2759,7 @@ and a Denver coordinate underground. Search now resolves the application's ground-floor elevation (bounded wait, same ellipsoidal datum) before framing and warms the cell; after landing, `src/cameraGroundGuard.js` samples the rendered surface under the target and the camera once tiles stream in and lifts the eye -to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls and direct camera flights), layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners. `scripts/qa-context-arrivals.mjs` types Camp Mabry +to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls), any other caller moving the camera or starting a flight before a retry, layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners; the guard compares the pose it started on rather than wrapping camera methods. `scripts/qa-context-arrivals.mjs` types Camp Mabry and a Denver coordinate and requires at least 60 m clearance. ## Layer panel ownership @@ -2707,10 +2774,11 @@ provides its confirmed toggle, taxa presets and fixed-order, nonempty legend. ## Sky background -`src/sky/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale +`src/render/cesium/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with -a TEME fallback while Cesium's IAU 2006 tables load. Bundled assets and +a TEME fallback while Cesium's IAU 2006 tables load. The precise rotation reaches +Cesium-free code (the celestial ring) through `src/sky/icrf.js`. Bundled assets and their provenance are documented in `src/data/local_data/sky/README.md`. Anime fades out the Milky Way with its style intensity to avoid cel-shaded @@ -2747,7 +2815,7 @@ during viewer construction, before any tile builds a draw command. When the globe stops drawing, the scene chrome says so instead of leaving a black globe behind working controls. `installRenderFailureNotice()` -(`src/ui/renderFailure.js`) listens for Cesium's `renderError` and the canvas' +(`src/render/cesium/renderFailure.js`) listens for Cesium's `renderError` and the canvas' `webglcontextlost`, logs the error, and publishes a notice that `RenderFailure.vue` shows as an alert dialog with focus on its first action. The app's viewer uses `showRenderLoopErrors: false`, so Cesium's dead-end @@ -2801,11 +2869,14 @@ remain unchanged. ## Visual effects ownership -VisualEffects owns style-stage creation, crossfades, animation scheduling, bloom -and sharpen. Display supplies actions and renders settings; effect execution has -no DOM dependency. Existing presets and the 500 ms transition remain unchanged. -Stopping the controller revokes animation before asynchronous UI teardown; final -destruction removes its stages and restores the borrowed bloom configuration. +VisualEffects keeps the records of the styles, their crossfades, bloom and +sharpen, and drives them through the renderer's effects port: it defines each +preset there as a style, and the renderer runs the passes and animates the +animated ones. Display supplies actions and renders settings; effect execution +has no DOM dependency. Existing presets and the 500 ms transition remain +unchanged. Stopping the controller revokes animation before asynchronous UI +teardown; final destruction removes its styles and turns bloom and sharpen off, +and the renderer restores the scene's bloom configuration when it goes. Snow is no longer a visual preset. A share link that names it, in either the long or compact form, opens on Normal and drops the Snow shader parameters. A view passed to embed mode or `show_in_gods_eye_view`, and a saved scene shot, @@ -3681,9 +3752,14 @@ which embeds the MAP_KEY. windows reuse the active load. Disabling or returning Contacts to passive mode clears its anchor; passive refreshes cannot reclaim it. Background repaints refresh context records without publishing a new selection. - Installation tiles decode only the `landuse` layer. Reloads keep the Cesium - entities of sites whose geometry is unchanged, so outlines and fills do not - blink. While Contacts has a subject, the layer loads a window around it + Installation tiles decode only the `landuse` layer. The site dots, the + selected site's dot (a set of its own, so selecting one redraws no other), + their ground outlines and the selected site's fill are renderer draw sets; + reloads keep the drawn items of sites whose geometry is unchanged, so + outlines and fills do not blink. The layer no longer reaches + Cesium; a caller handing it a Cesium viewer, with no + renderer bound, loads the `./render/cesium/unbound` export once first. + While Contacts has a subject, the layer loads a window around it instead of the camera view (100 km half-width at mid latitudes, shrinking so it fits 16 z9 tiles), moves it only after the subject travels 20 km, and ignores camera `moveEnd`; clearing the subject returns to the viewport. The @@ -3840,9 +3916,12 @@ which embeds the MAP_KEY. > so a turned-off layer's entities stayed reachable (Data Centers kept 116 > MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`, > requests one frame through `governorRequestRender` after every layer -> disable and then trims those arrays. It reads private Cesium fields; -> `src/sceneCommandRelease.test.mjs` pins them and fails if Cesium renames -> them or changes which passes it truncates. +> disable and then has `src/render/cesium/sceneCommandRelease.js` (handed +> handed over by the Cesium plugin through `src/app/scene.js`) trim those +> arrays. It reads private Cesium +> fields through `src/render/cesium/internals.js`; +> `src/render/cesium/sceneCommandRelease.test.mjs` pins them and fails if +> Cesium renames them or changes which passes it truncates. > **2026-08-08 — performance waves 1+2:** the app idles via an explicit render > governor (`src/renderGovernor.js` — hold/release from every per-frame @@ -4250,7 +4329,7 @@ isCurrent })` gates BOTH halves of the map-stack switch, which is its only > tunnels. Every other layer > is untouched: aircraft, vessels and satellites draw their markers over the > scene on purpose and keep their labels over it. The test runs on the GPU -> (`src/data/sceneOcclusionProbe.js`): one occlusion query per contact, +> (`src/render/cesium/sceneOcclusionProbe.js`): one occlusion query per contact, > repeated every 100 to 200 ms, answered a frame or two later, with nothing > read back from the GPU and so no stall. A contact hides as soon as a > "hidden" answer arrives and returns 600 ms after its last one, which keeps @@ -4687,18 +4766,22 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > it, and narrow screens retain Cesium's surface with an internal > scroller. The title, close control, links, and persistent Google/Cesium line > remain unchanged and visible. -> - **Distant-aircraft recession:** both civilian and military billboard fleets +> - **Distant-aircraft recession:** both civilian and military icon sets > retain their locked class/ground scale and `NearFarScalar`, then multiply a -> limb-relative taper in the existing ~12 Hz tick. The taper is 1 below 0.5× +> limb-relative taper. The sets say so themselves (`SetSpec.recede`, with +> the tuning as its parameters, sent again when the tuning changes), and the +> renderer works the taper out each frame from `render/recession`. The +> taper is 1 below 0.5× > geometric limb distance and smoothsteps to 0.45 scale plus a 0.35 alpha-haze > factor at the limb. That treatment eases continuously back to identity from > 3,500–4,500 km camera height, avoiding a globe-view threshold pop. These > values, the start ratio, blend band, composed floor, and write epsilon remain > runtime tunings. No aircraft is count-culled or made fully transparent. -> Focus emphasis and limb haze multiply at one deadband-gated write site, and -> their product is clamped to 0.20 before freshness alpha is applied. Ambient -> fleet models receive that same composed alpha; class/ground/cockpit repaints -> preserve the current limb scale instead of dropping it for a tick. +> Focus emphasis and limb haze multiply, and their product is clamped to +> 0.20 before freshness alpha is applied. Ambient fleet models receive that +> same composed alpha, worked out on each fleet tick from the camera then +> and written again once it moves by more than 0.005; their set itself does +> not recede. Under the IR boost they draw at full alpha. > - **Focus-aware contact de-emphasis:** civilian/military aircraft and > satellites publish the selected target's padded screen bounds and camera > distance from the same per-frame position cache already consumed by their @@ -4785,10 +4868,13 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > untracking, so a stationary slow press on a plane still selects it. Escape > still releases tracking in place. The 200 px feel needs close-range field > verification; fleet model sizing remains unchanged. -> - **Deterministic sprite stacking:** contact collections reassert the stable -> bottom-to-top order CCTV, FIRMS, bikeshare, AIS, military, then civilian -> flights after every relevant layer init/enable and immediately after FIRMS -> lazily registers its detection sprites. Always-visible contact +> - **Deterministic sprite stacking:** contact sets are made at draw orders +> (`SetSpec.drawOrder`, from `spriteDrawOrder`) that stack them bottom to +> top as CCTV, FIRMS, bikeshare, transit, directions, AIS, military, then +> civilian flights on top, whichever layer was turned on first; picks +> name the topmost first. The orders are negative, so every overlay at the +> default order (selection highlights, route endpoints, the tracked plane) +> still draws over all of them. Always-visible contact > depth settings are unchanged. Cesium OIT weighted blending may soften strict > alpha layering on some GPUs, so the ordering remains a real-browser check. > - **Deterministic card stacking:** CCTV, FIRMS, vessel, and tracked-target @@ -4945,8 +5031,14 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > celestial ring, annotations SVG, missions frame tick, and traffic). > - **World-label accounting:** All intended label/card migrations use the > shared host. The former native `LabelGraphics` exception for cable reference -> labels was retired on 2026-08-18; cable text may render over tile geometry, -> so **zero native world-label creation sites remain**. The mission replay DOM vehicle, awareness +> labels was retired on 2026-08-18; cable text may render over tile geometry. +> The Directions A/B letters (`directions-markers` source) and data-pack media +> labels (a pooled `data-pack-labels:` source per pack resource, through +> the pack handle's `label`) moved to the host on 2026-11-04, and +> `src/noCesiumLabels.test.mjs` no longer keeps an allow-list, so **zero +> native world-label creation sites remain**. A media pack shown without an +> `overlayHost` fails to load rather than drawing a native label. The mission +> replay DOM vehicle, awareness > compass, annotation SVG callouts, and host-owned detection isolation target > are explicit exceptions; the awareness ring and cockpit contact pips are > non-text out-of-scope surfaces. Annotation callout text, geometry, leaders, @@ -4994,7 +5086,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > ambient-label host source. Its getter reads the point's own position, which > moves every frame, eliminating the former second ISS > propagation. Satellite tracking continues to publish exactly one protected -> tracked-lane card through `gevLabelModel` and `_trackedDisplayCached`; the +> tracked-lane card through its entity record's `labelModel` and `_trackedDisplayCached`; the > tracked entity is point-only. Tracking ISS suppresses the ambient entry and > untracking restores it, preventing duplicate ISS text. Disable, orbit-text > preference changes, catalog rebuild, and destroy clear/hide the source. @@ -5009,7 +5101,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Phase 5 tracked civil aircraft label:** A tracked flight's Cesium entity > is a billboard-only camera target with no native label. The flight source > retains callsign/registration fallback, flight-level/altitude, speed, stale -> state, airline/type, and plausible-route formatting in `gevLabelModel`; the +> state, airline/type, and plausible-route formatting in the entity record's `labelModel`; the > one protected tracked-lane host card renders that complete model. Its > position getter reads only `_trackedDisplayCached`, the same authoritative > Cartesian already consumed by the tracked visual and camera, and never @@ -5119,8 +5211,11 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Tracked-readout ownership:** `trackedReadout.js` is now a presentation-model > bridge only; it owns no canvas, projection, post-render listener, layout, > keyhole fade, or paint path. Civilian flights, military flights, satellites, -> and mapped installations write explicit `gevLabelModel` objects and expose -> `gevDisplayPosition` getters backed by their layer-owned frame/display cache. +> and mapped installations write explicit `labelModel` objects and +> `displayPosition` getters, backed by their layer-owned frame/display cache, +> into the app's entity records (`src/data/entityRecords.js`), never onto the +> Cesium entity. A layer's private per-entity state goes in its own store from +> `createEntityStore()` (ALPR markers: `src/layers/alpr/markerState.js`). > Selected AIS vessels continue using the vessel source's protected selected > card, so they do not create a duplicate tracked readout. The host registers > the active readout in the protected tracked lane with a zero ambient quota; @@ -5531,8 +5626,8 @@ centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap; nearby views share whole-degree cache keys, and a minute poll refreshes data. Counts and bands cover visited views over 30 minutes, including regions now off screen. Cells are H3 resolution-4 hexagons, gpsjam.org's grid, keyed by their H3 -index (`gnssCellKey`) and drawn from `cellToBoundary` (via `h3-js`) as one ground -primitive of polygons, rebuilt only when a cell or band changes; a cell across the +index (`gnssCellKey`) and drawn from `cellToBoundary` (via `h3-js`) as clamped +polygons in one shapes set of the draw port, redrawn only when a cell or band changes; a cell across the antimeridian is drawn with its longitudes unwrapped around its centre. As on gpsjam.org there is no minimum aircraft count: every cell with an aircraft is shown, and the one-aircraft discount is the only small-sample guard. @@ -6022,13 +6117,14 @@ the same navigation authority as every other camera destination. given; re-arming for the other endpoint reuses that lease rather than asking for a second claim, and every release names the lease, so a superseded instance can never free the claim its replacement holds. The claim is held until -the click that uses it has finished being dispatched — every layer binds its -own handler to the same canvas and they all run inside one browser event, so a -claim dropped the instant the endpoint is placed would hand the rest of that -same click to the ambient handlers bound after this one. It is returned on the -next tick after placement, and immediately on cancel, Escape, CLEAR, disable -and destroy; if another tool already holds it nothing is armed and the row says -so. Maneuver-dot selection is an ordinary ambient handler and yields while any +the click that uses it has finished being dispatched: the input dispatcher +checks the claim once per click, before any subscriber runs, but DOM canvas +listeners (the evidence cards) still see the same browser event afterwards, so +a claim dropped the instant the endpoint is placed would hand them that click. +It is returned on the next tick after placement, and immediately on cancel, Escape, CLEAR, disable +and destroy. The newest claim takes over: arming takes the pointer from a tool +holding it, which is told and turns itself off, and a newer tool taking it +disarms the layer as Escape would. Maneuver-dot selection is an ordinary ambient handler and yields while any tool holds the pointer. FLY runs through the UI shell's immediate-navigation facade — the same camera authority validated voice destinations use — and is handed the shared ground-floor read and corridor warm, so the dolly does not @@ -6223,11 +6319,27 @@ synchronizes visible playback before its next frame. Playback reserves numeric scratch before the first sample, including unknown heights, and reuses caller-owned sample and segment storage. -**Scene work.** Stationary and animated billboards use separate, adjacent -collections above CCTV and Bikeshare. Traffic, Bikeshare and Transit share camera -sensitivity claims; the original sensitivity returns after the last release. -Visibility checks combine the camera frustum and ellipsoid occlusion at no more -than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals +**Scene work.** Stationary and animated vehicles are two draw-port icon sets +(`transit::still` and `transit::moving`), made at adjacent draw orders +from the sprite order (`spriteDrawOrder`), above CCTV and Bikeshare. Each marker +is a plain record (position, show, image, size, colour, rotation); a frame +writes the changed ones to their set in one batched upsert, markers taken out +in one task go in one removal, and a marker that starts or stops moving moves +between the sets. The renderer moves and turns an icon without restyling it. +Rotation is computed in screen space through the query port's projection +(`perspectiveCourseRotation`), as before. Clicks read the draw-port hit. The +layer no longer reaches Cesium, so a caller handing it a Cesium viewer, +with no renderer bound, loads the `./render/cesium/unbound` export +once first. Transit listens to the camera port at its own `changed` threshold +(0.05); the port measures each listener separately, so no layer changes +another's camera trigger. +Visibility checks combine the camera port's frustum and the query port's +ellipsoid occlusion at no more than 4 Hz; missing map bounds do not admit the +globe's far side. Whether the globe is the bare ellipsoid is asked of the +height service at the camera's subpoint each time the globe's surface +changes; the answer comes asynchronously, the last one holds until then, and +floors are read again when it flips. +Camera arrivals rebuild an unprepared or cold marker corridor during that visibility sweep, adopt a loaded surface, and update both heightPending and surfaceReady diagnostics. A resolved display sample clears its pending-height gate without waiting for a poll. Frame work @@ -6258,7 +6370,8 @@ it does not establish Google 3D acceptance. The full run samples completed frames at 1920×1080 CSS pixels, records DPR, and measures moving fleets of 800 and 3,000 vehicles with 128 fixes each and DETECT on. Street/metro targets are respectively: transit frame CPU p95 ≤1/4 ms, frame -interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame, and retained +interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame (counted by +`src/render/cesium/uploadProbe.js` for the two marker sets), and retained heap growth ≤24/48 MiB. The 3,000-vehicle CPU budget is 4 ms (recorded browser measurement 3.4 ms); the 800-vehicle budget stays at 1 ms (measured 0.9 ms). Transit-authored frame allocation is ≤8 KiB/frame at both fleets, attributed @@ -6896,7 +7009,7 @@ silently demoting every later lookup for the session. - The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected. - The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies. -- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. +- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved. - `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width. - The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility. - Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. Outside Cyber, the two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. Cyber keeps its separately framed mode buttons, its red panel titles, and in layout-focus a framed, centred standby card over its radar art. @@ -6907,7 +7020,7 @@ silently demoting every later lookup for the session. - On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification. - A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated. - Contacts rows and the Cockpit Contact counts name each cohort's provider: the source of the last snapshot, marked `FALLBACK` or `STALE` as its layer row would be. A poll in flight keeps the mark, where the layer row shows `LOADING`. A flight snapshot from the adsb.lol regional fallback reads `adsb.lol · FALLBACK`, not `OpenSky`. -- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for, drawn as an unpickable primitive rather than an entity so a click or tap on its edge reaches the contact underneath (headless viewers without a primitive collection get a static entity instead); it is rebuilt when the subject moves. Three dim sonar pulses (3 px with a 1 px dark outline, same colours, at most 60% opacity) grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius. One unpickable 250 km disc draws both the pulse lines and the gradient, its shader reading the pulse radii and opacities each frame, so a click or tap near a pulse still reaches the contact underneath; the disc follows the subject by a model-matrix rotation and is rebuilt only after the subject moves 20 km, and not at all while the pulses rest. While the camera is below the disc's 2.5 km height, where it would sweep across the sky, the pulses rest: the disc is hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the disc and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one render request 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`), so they repaint at about 12.5 fps and never beat the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or in a scene without primitives or preRender and postRender hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. +- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline whose outer 1 px, half a pixel on each side, is a dark halo around a 3 px Context-blue core, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. Fronts and band are fixed in the world, so they step every 80 ms however many frames are drawn and look the same whether the camera moves or not; crossing the 2.5 km rim height shows or hides them at once. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. - For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop. - Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff. - Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk. @@ -6923,8 +7036,8 @@ silently demoting every later lookup for the session. ### Motion & Symbology Correctness (June 10, 2026) -- **Flights (commercial + military)** render one poll interval behind real time (30s/15s) and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The display latency is an intentional product decision — do not "fix" it away. The fleet dead-reckons at ~12Hz (1m² write gating); a contact already hidden behind the horizon whose last position still is re-reckons on a staggered one-in-13-ticks rotation (about once a second) instead, so the worldwide feed's ~13k contacts no longer cost a full pass when well under 1% are on screen. Anything that position puts in view, and any contact with a fleet model, takes the full pass immediately, and hidden-inclusive proximity queries read positions at most about a second old; aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.” -- **World-space headings at every angle** (`src/data/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder. +- **Flights (commercial + military)** render behind real time and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The delay (`src/data/displayDelay.js`) follows how late the feed is: the 90th percentile of the newest 256 lags (a report's receipt time less the same contact's previous report time) plus 5 s, never under the layer's floor (30 s civil, 15 s military) nor over five minutes, so the anonymous OpenSky feed, whose reports arrive about 90 s old every 30 s, draws about two minutes behind. Before 16 lags, first reports' ages plus a poll interval stand in. The delay moves toward that aim by at most 0.2 s per second up and 0.05 s per second down (an aim within 2 s leaves it be), and takes it at once only while nothing is drawn; deliveries following the world clock, or replacing the world at another time, leave it alone and draw with no delay. Every consumer (icons, the renderer's live motion clock, labels, HUD, detection, the tracked camera and trail) reads the one delay. When a newer report puts a moving contact elsewhere than it is drawn (it was coasting past its newest report), it eases onto the new path over at least 3 s, at most 30% faster than its speed and within 20 s, from where it would have been that frame; more than 5 km off, it jumps. The display latency is an intentional product decision — do not "fix" it away. The whole fleet dead-reckons at ~12Hz (1m² write gating); aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.” +- **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder. - **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them. - **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode. - **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. @@ -7576,8 +7689,8 @@ request viewbox and continues searching without that geographic preference. - UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone. - **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too. -- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the Cesium handler, the preview data source, the borrowed click actions and the `window.__gevDrawTool` handle. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam. -- **The pointer, for an application's own tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner)` takes the pointer as Draw does and returns its lease, or `null` while another tool holds it; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. An owner without a name in `pointerOwnerNames.js` is named by its id when another tool reports who holds the pointer. +- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band, dashed behind the surface too through the line's `depthFail` style, and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam. +- **The pointer, for any other tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner, { onLost })` takes the pointer as Draw does, from any tool holding it, and returns its lease; `onLost` is called once when a newer claim takes it, and the tool turns itself off there; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. - **Row actions are an application's own.** `createApplicationTools({ drawMarkActions })` hands `initDrawTool` buttons for drawn areas' and lines' rows; the standalone shell passes none, so the open-source build shows no new button and makes no new request. Each action (`drawMarkActions` in `src/annotations/drawMarks.js`) is `{ id, icon, label(name), shapes: ['area', 'line'], accepts?(geometry, shape), run({ id, shape, name, title, geometry }) }`: the icon a Material Symbols name, the label worded by the application, `name` the person's own and `title` the row's (the name, else `Area` or `Line · 950 m`), the geometry `drawMarkGeometry`'s `[lon, lat]` `Polygon` (closed; a `MultiPolygon` for an area handle with several parts) or `LineString`, longitudes wrapped into [-180, 180]. A pin, and a shape that crosses the antimeridian or has a part that cannot be given whole, has no geometry and is offered nothing. Malformed actions and repeated ids are dropped once, at construction. What `run` returns or resolves to is a note under the row (`role=status`; past 200 characters it is cut at a word with an ellipsis); the row is busy (`aria-disabled`, no second press) until it settles, a rejection or a throw clears the note and is logged (so an action words its own refusals and resolves with them), and a shape's note goes with the shape, so a late answer never lands on a removed one. - Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins. - **A vertex is a lon/lat, and the mark is DRAPED.** Clicks are picked through `pickWorldFromScreen` — one of two scene helpers the annotation resolver factory (`src/annotations/resolver.js`) exposes alongside `sampleGroundHeight`, so the app has ONE depth-aware pick cascade rather than a second written beside it — which returns the height the pick landed on as well as the coordinate, so the live preview hangs on the roof or hillside under the pointer instead of sinking to sea level. The world renderer draws areas and routes with `clampToGround`, so the height is dropped at finish in one place (`finishSpec`) rather than being carried downstream and discarded silently: what you get is the outline you drew, lying on the surface beneath it. @@ -7587,9 +7700,10 @@ request viewbox and continues searching without that geographic preference. - **Measurements and centres are computed on unwrapped longitudes** (`unwrapLongitudes` / `wrapLongitude` in `drawMode.js`, used by `ringAreaM2`, `ringCentroid` and the engine's manual-area anchor). A ~50,000 m² rectangle straddling the antimeridian reads its 0.002° width as 359.998° under raw arithmetic: it measured thousands of square kilometres and anchored on the Greenwich meridian, half a world from the shape. Path length was already safe — haversine is periodic in the longitude delta — and a test pins that so a "fix" cannot break it. - **Bounds.** One shape holds at most `MAX_VERTICES` = 512 points; two clicks within 0.5 m are one vertex (that is what makes a double-click finish without leaving a stray point); a vertex that is not a finite on-globe coordinate is refused. A shape that encloses nothing is refused rather than placed: three collinear points are not an area and a line under a metre long is not a line, and the hint says which. - Drawn-area measures round before choosing m², ha or km², so 9,999.6 m² displays as `1.0 ha`, not `10000 m²`, and 999,960 m² as `1.00 km²`, not `100.0 ha`. -- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`) and **every** ambient scene selection handler — the shared tracking click gesture behind flights, military and CCTV, plus vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers and the CCTV calibration gizmo — returns before picking. A vertex over an aircraft is a vertex, not a selection. -- **The claim is a LEASE.** `claimPointer(owner)` returns an opaque token or `null`; `releasePointer(lease)` takes that token. A second claim fails even under the same owner name, because two live instances of one tool — an old one mid-teardown and its replacement — are two owners; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease now releases nothing. -- **Cesium's own click actions are borrowed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. Both are removed for the session and restored, as the same function objects, when it ends or the tool is destroyed. +- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`), and the scene's input dispatcher (`src/input/dispatcher.js`) hands its clicks, moves and double clicks to the draw tool's leased subscriptions only: **every** ambient subscriber — flights, military, CCTV and its calibration gizmo, vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers — is skipped for that event before anything is picked. A vertex over an aircraft is a vertex, not a selection. +- The input dispatcher no longer reaches Cesium. It takes its pointer events from the renderer's input port (`findInput`, `src/render/rendererOf.js`) and its picks, drills and ground points from the query port, with positions as plain `{x, y}`. A click's hits are the contract's `Hit`; something drawn outside the draw port is a `Hit` with `set: ''` that the Cesium adapter names (`src/render/cesium/nativeClick.js`), which also hangs the engine's own picks on `event.native` (`pick`, `pickWindow`, `drill`, through the follow helper) for layers still bound to them. The adapter's pick reuses the query port's pass for the same pixel, window and frame, so an empty click still costs one pick pass; a sky click makes no depth pass unless a globe tile is on its ray. A touch tap's contact search drills Cesium's own picks, eight deep, so something drawn outside the draw port still stops it or is found by it. +- **The claim is a LEASE, and the newest claim takes over.** `claimPointer(owner, { onLost })` returns an opaque token; `releasePointer(lease)` takes that token. A second claim, even under the same owner name, ends the lease out, and its holder's `onLost` is called once, after the new lease holds the pointer: Draw turns off as if toggled off (the half-drawn shape and preview go, the stock clicks come back), the imagery box cancels, and Directions disarms. Two live instances of one tool — an old one mid-teardown and its replacement — are two owners, so the replacement wins; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease releases nothing. This is the renderer contract's rule (`input.claimPointer`), and the two are one: each scene's input dispatcher bridges its renderer's input port (`bridgePointer`), so the port holds a lease while a tool holds the pointer (the port is not free), and a claim made on the port itself takes over from the tool like any newer claim. That lease takes no press itself: the dispatcher decides who hears each event when it arrives, as each layer's own handler used to (a click reaches ambient selection only if no tool holds the pointer then, and a tool's subscribers only while its lease is current), and Cesium's own select and double-click follow run unless the tool holds them off (`suppressStockClicks`: Draw and the imagery box do, Directions does not). +- **Cesium's own click actions are suppressed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. The tool takes the dispatcher's `suppressStockClicks()` hold for the session; both actions come back, as the same function objects, when the last hold is released (the imagery box takes the same hold). - **Enter belongs to whatever has the keyboard.** The finish key is taken only from the canvas and the page body. With a control focused — Clear, a shape button — Enter activates that control, as a keyboard user expects; it does not quietly finish the shape. - Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`. - The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`. @@ -7614,14 +7728,14 @@ request viewbox and continues searching without that geographic preference. - Only a new head costs REST calls: one recursive tree and one commit. An optional `GITHUB_TOKEN` raises the REST limit. - After an upstream outage, a successful branch-head check clears the error and pushes a recovered catalog even when the commit is unchanged. Cached products stay in place; subsequent healthy unchanged checks stay silent. - The new catalog goes to `.gev-cache/ghostmaps/catalog.json` and to every open page over server-sent events (`/api/ghostmaps/events`, 25 s heartbeat, at most 64 subscribers). Default products are downloaded at once. - - The layer reloads only products whose blob changed. The new edition's data source is added before the old one is removed. A product that leaves the catalog leaves the globe. + - The layer reloads only products whose blob changed. The new edition's draw sets are added before the old ones are removed. A product that leaves the catalog leaves the globe. - The row reads `LIVE` while the stream is open. A five-minute catalog read is the backstop. - **Files.** `/api/ghostmaps/file/{product}` serves only catalog products. Files are downloaded by commit-pinned raw URLs, so a CDN cannot return an older edition. They are cached on disk by blob sha, and blobs no current product uses are pruned. A request whose `?v=` names the current blob is `immutable`. Repository paths never reach the page. - **Source ownership.** The application catalog receives `sources['s2-ghostmaps']` through the shared source contracts; an omitted or null source stays unavailable without opening a stream or fetching. The standalone source factory supplies the same-origin implementation and accepts replacements. Packed-image URLs are released on cancelled or failed product construction, and remain owned by a successfully loaded product until it is removed. - **Voice and locales.** S2 can be toggled through its registered id and aliases. The model already sees the S2 GhostMaps brand in the id, and compact alias-hint separators keep the complete voice prompt within its existing 52,000-character limit; accepted aliases are unchanged. The row and reports are translated in Spanish, Russian and Simplified Chinese. -- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into one `CustomDataSource` per product. - - Points become ground-clamped billboards with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. - - Lines and polygon outlines are ground-clamped polylines. +- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into renderer draw sets (icons, lines and shapes) per product edition. The layer no longer reaches Cesium, so a caller handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. + - Points become ground-clamped icons with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. + - Lines and polygon outlines are ground-clamped lines; polygon fills are ground-clamped shapes. - Styles, StyleMaps and inline styles are honoured. Icons come only from images packed in the same KMZ and at most 512 KB. Anything else uses a per-product round marker. - Network links, overlays, models and remote hrefs are never followed. Hidden placemarks are skipped. Bounds are 20,000 placemarks and 250,000 positions per product. - **Reports.** Clicking a marker opens a card with the product, folder, edition date and the placemark's report fields. `src/layers/ghostMaps/records.js` reads ArcGIS popup tables as text only: `` and internal fields are dropped and values are capped. Description markup is never inserted into the page. The first `http(s)` research link opens from the card. The card is `stateless`, so it comes and goes with the click, as CCTV cards do. It is also `horizonCull`ed, so it hides when its marker turns behind the planet. Picks are registered under `s2-ghostmaps`. @@ -7630,14 +7744,15 @@ request viewbox and continues searching without that geographic preference. ### Import Your Own Files (October 2026) - UTILITIES ▸ **Import** reads GeoJSON (`.geojson`/`.json`), KML, KMZ and GPX from the picker or a file drop anywhere in the app. Each file gets show/hide, Fly-to and Remove controls. GeoJSON and GPX use the row's color; KML/KMZ retain their styles and show a hatched swatch. The file bytes remain on the device for the page session. Rendered overlays can appear in map screenshots sent through voice or other existing screenshot tools. -- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 against loaded terrain and, in the nearby camera footprint on photoreal maps, `clampToHeightMostDetailed`, then draw in one owned native BillboardCollection per file, with static positions and no per-frame point Entity visualizer or clamping callbacks. Point metadata remains in `dataSource.importedEntities` for framing/style inspection; non-point geometry stays in the normal source collection. Pin collections mount only after source admission, follow file show/hide, and are destroyed on removal. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy. +- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 through the height service: the loaded terrain's height (0 on the bare ellipsoid, whose coarse tiles can sag far below it) and, in the nearby camera footprint on photoreal maps, the mesh height (`clampBatch`). They then draw as static icons in the file's own draw sets (pins, lines and shapes), with no per-frame clamping callbacks. GeoJSON lines and polygon edges follow rhumb lines, split into steps of at most half a degree. Each file's sets mount only after admission, follow its show/hide, and are removed with it. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy. - **Navigation.** Row Fly-to uses `runImmediateNavigation('file', …)`; Cockpit can refuse it and existing follow/track ownership is released first. Automatic Fly-to is stamped when a batch is submitted and reasserted before flying. Pointer/wheel gestures and newer navigation supersede it, including time spent in the queue. Framing uses every finite visible point/path/polygon-hole/wall vertex plus rotated overlay bounds, with viewport-aware range and a nadir view. The target uses available terrain/cached ground height and the ground guard on arrival. Empty footprints never fall back to deferred `viewer.flyTo`. -- **Clock.** Imports expose no source clock and no entity availability. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged. -- **Input handling.** Coordinates and GeoJSON geometry types are checked before Cesium allocation. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits. -- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, native labels and descriptions are removed, and generated pins share one lossless image URL per canvas. +- **Clock.** Imports keep no clock and no time ranges: everything in a file draws at all times. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged. +- **Input handling.** Coordinates and GeoJSON geometry types are checked before anything is drawn. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits. +- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, labels and descriptions are removed; only a short plain name reaches a drawn item. The default pins are shared SVG images. - **Bounds.** File size ≤50 MiB; inflated KMZ ≤120 MiB; ≤20,000 entities (including multipart children and Folder containers); ≤250,000 positions; ≤2,000 normalized style definitions and distinct image links; ≤12 files per session. Exact repeated styles share definitions without changing inheritance or inline overrides. Files of 20–30 MB fit the byte budget, subject to geometry/image limits. Refusals name a reason and batches continue; with multiple failures the hint shows the first reason. -- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes data sources, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import. -- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, native style/image equivalence, large-file painted output and frame times. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules. +- **Code layout.** `src/data/geoFileImport.js` reads, bounds and sanitizes the files. `src/data/geoImportFeatures.js` turns the sanitized KML or GeoJSON into plain features (pins, lines, walls, polygons and ground overlays) with the styles Cesium's KML and GeoJSON loaders gave them: icon, scale, colour, heading and hot spot; line and polygon colours and widths; extruded or clamped geometry. `src/data/geoImportPins.js` draws those features through the renderer's draw port (`drawOf`), settles ground pins through the height service and frames the file for Fly-to. None of the three reaches Cesium, so the Cesium allow-list is empty. `src/data/geoImportShared.js` holds the error, limits, deadline and feature names they use. +- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes each file's draw sets, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import. +- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, that what the import draws matches Cesium's own `KmlDataSource` reading of the same file (positions, scale, heading, colours, widths, fills), large-file painted output and frame times. The QA scripts read what a file drew through `window.__gevGeoImport.drawn(id)`. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules. ### Recent Imagery (September 2026) @@ -7652,7 +7767,7 @@ pins and share links already supply complete boxes. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. - **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **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). @@ -7681,7 +7796,7 @@ pins and share links already supply complete boxes. - Fleet model eligibility is distance-based with on-screen priority and hard caps (`MODEL_MAX`, `MODEL_MAX_ALL`) to avoid draw-call explosions. Each model owns its own `modelMatrix`; shared scratch matrices are forbidden because they caused stacking/flicker. - Tracked aircraft use standalone model primitives driven from the already-settled dead-reckoned display position, while the tracked Cesium entity remains billboard-backed so `viewer.trackedEntity` always has a ready bounding sphere. - Flights and military layers mirror the same tracking invariants: no warm-up freeze/jump, altitude-scaled framing, trail head glued to the displayed plane, no pull-out when switching targets, and no cross-layer orphan when switching between commercial and military tracks. -- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. Arrival-rotation checks observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget that sits inside the one-second idle fallback, rather than assuming the 80 ms fleet cadence fits inside four rendered frames; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers. +- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. The harness reads what the app draws through its own seams: what the camera follows through `src/data/followed.js`, icons from the draw port's icon sets as the renderer holds them, and models by their `{set, id}` pick ids. Arrival-rotation checks read the drawn rows' course (the icon sets turn each icon along it on the GPU every frame, so there is no CPU rotation pass to repair a stale nose) and observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers. ### TR-3B conversion Easter egg (August 2026) @@ -7970,6 +8085,76 @@ easier to meet (detection is now on more often), but does not create it. above and the DISPLAY-rail entry below (was `OFF`). - Style shader starting params: CRT/NVG/FLIR pixelation `1.2` (just above the native `1.0` floor); thermal/FLIR ships an optional Ironbow "Predator" palette (`palette` uniform, default `0` = accurate grayscale). +## Renderer contract + +`src/render/contract/` types the renderer contract, version `0`: nine ports +(frame, globe, draw, camera, query, input, effects, credits and quality), +plus the renderer itself. `PORTS` lists every member at run time, and +`contract.test.mjs` keeps that list and the types in step. +`src/render/stub/` is a renderer that draws nothing, with the default +camera's exact maths. `src/render/conformance/` is the suite: logic checks +in Node, plus camera traces recorded from Cesium's own `Camera` into +`goldens/camera.json`. It also holds the reference scenes, whose views are +checked against `goldens/visual/` on the `/dev/conformance/` page. +`npm run qa:conformance` runs the logic checks on the Cesium renderer in +headless Chromium, in CI too. After `destroy()` the Cesium renderer's +handles do nothing, and `renderOnce` and `capture` reject. See +[RENDERER-CONTRACT.md](RENDERER-CONTRACT.md). + +### The application and its renderer + +The application starts on whichever `RendererPlugin` it is given +(`createStandaloneApplication({ renderer })`), and on Cesium when none is. +`src/app/scene.js` loads the Cesium adapter (`src/render/cesium/application.js`) +only then, with `import()`; the standalone page starts that load as it +starts, beside its own setup. Outside `src/render/` no code reaches a +renderer's own objects: the record of files that still did, +`src/render/viewerAccessAllowList.json`, is empty. + +- What every layer and tool is handed is the scene object + (`createSceneHost`), bound to the renderer: its container, and whether it + is destroyed. Everything else goes through the renderer's ports. +- What a renderer's own plugin adds beside the contract (stale draw-command + trims, inline panel drawing, the zoom-out guard, its own map engine, the + detection overlay's occlusion probe, what QA scripts read) it hands through `src/render/applicationHooks.js`; the + application uses each where given and does without where not. + Renderer-only startup (Cesium's free-look limit, credit keyboard access) + runs in that plugin's `create`. +- The map stacks switch through the plugin's map engine, else the globe + port (`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, Cesium + ion imagery as `world` imagery, terrain as `world` terrain, or the + ellipsoid where no keyless terrain is offered, and photoreal as the port's + photoreal base. A photoreal base that fails to come back leaves the globe + shown. +- The renderer follows its container's size (`Renderer.resize`, from a + `ResizeObserver`). +- The credits: the Cesium renderer's plugin says it shows them in a display + of its own (`ownCreditDisplay`; `#cesium-credits`), which it keeps. On the + stub, the application shows what the credits port lists in its own line + at the bottom left (`#gev-credits`, `src/ui/creditsView.js`): the inline + credits on the line, the rest (the layers' data credits among them) in + the "Data attribution" list it opens, a keyboard button with Escape to + close. + +`npm run qa:stub-boot` boots the whole application on the stub with only +the contract's required members (`dev/stub-app/main.js`, served in place of +`src/main.js` on the application's own page), headless. It fails if +the credits line is not shown or its list is empty, if Cesium's code is +requested (the one stylesheet `vite-plugin-cesium` links +into every page is reported), on any page or console error, or if a data +layer (flights, military aircraft, transit, traffic, CCTV, AIS vessels, +weather radar and satellite, wind, satellites, FIRMS, wildlife, shipwrecks, +news) fails to turn on or off. A +feed's failed response (no key, no network) is reported, not failed; +`--strict` also fails a layer that drew nothing, and `--all-capabilities` +gives the stub every capability. CI runs it in the browser job. + +`src/geo/` (export `./geo`) is the Cesium-free maths: WGS84, ECEF and +geodetic conversions, surface normals and east-north-up frames, as plain +`{x, y, z}` objects. It follows Cesium's formulas step for step, and +`geo.test.mjs` checks it against Cesium. The stub renderer's maths is built +on it. + ## Operational Notes - **Earthquake discs are STATIC geometry.** Every quake is a `CLAMP_TO_GROUND` @@ -8226,8 +8411,9 @@ easier to meet (detection is now on more often), but does not create it. Every failed read cancels its body and aborts its owned request, including declared and streaming byte-cap failures. - Development captures opened with `?trafficDebug=1` mint an interaction anchor - from the exact `camera.changed` event that arms each debounced load, then emit - scheduling-correlated User Timing entries for production `response.json`, road + from the exact camera-port `changed` event that arms each debounced load, + then emit scheduling-correlated User Timing entries for production + `response.json`, road parse, dot construction, heat-line rebuild, and next-post-render boundaries. Every trace is paired with the exact camera-change that scheduled its load; mismatches are counted drops. Cesium's `moveEnd` remains a diagnostic @@ -8562,6 +8748,25 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security Policy unchanged. Ion attribution and Bing's per-tile credits are preserved; other ion imagery assets continue through the SDK's standard ion factory. +The imagery, terrain and 3D factories are the Cesium renderer's +(`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the +package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point +there). The catalog, the default registry and the controller are +Cesium-free: they reach those factories, and the scene operations a +switch makes (imagery layers, terrain, the globe's visibility, tilesets), +through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The +Cesium plugin hands the application its own engine with each renderer it makes +(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`), +and the application scene loads the photoreal base through it too. A renderer +whose plugin hands none switches through its globe port +(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world +imagery as `world` imagery, photoreal as the port's photoreal base (turned off +while hidden, on again when shown), and world terrain, or without a key +Re:Earth's keyless terrain as `quantizedMesh` terrain at its URL +(`src/maps/keylessTerrain.js`), as the Cesium engine draws it; a renderer +without the `terrain` capability keeps the ellipsoid. A viewer with no renderer bound gets the Cesium engine, with the +other unbound ports, from the package's `./render/cesium/unbound` export. + The controller accepts other source registries without adding provider branches. Each instance caches source construction, ignores superseded scene changes and releases imagery layers/listeners on replacement. Destroy invalidates pending @@ -8629,7 +8834,12 @@ product's next frame until that frame loads (for at most eight seconds), so every frame shows. Hidden documents, reduced motion and unavailable imagery hosts suspend products. Re-enabling or restoring a host joins the retained history target. The wind row explicitly says -“Forecast · does not follow history” while the observed clock is in history mode. +“Forecast · does not follow history” while the observed clock is in history mode, +unless a host follows the world clock for `wind` (`weatherClock.follows('wind')`): +its source then follows the timeline and the row says nothing of it. In history +mode, frame ages and the “Source observations delayed” status are measured from +the timeline time rather than the wall clock, and the timeline readout shows the +time alone; live, they count from now as before. The Weather panel's frame time shows the newest frame and its age while live (each product's newest, suspended products included), and the timeline time alone at a past time. diff --git a/docs/DIRECTOR-DATA-PACKS.md b/docs/DIRECTOR-DATA-PACKS.md index bf64efd0bf..3c223e33f9 100644 --- a/docs/DIRECTOR-DATA-PACKS.md +++ b/docs/DIRECTOR-DATA-PACKS.md @@ -95,6 +95,11 @@ registry of source functions. Each receives `{ path, signal, maxBytes }` and returns `{ bytes: Uint8Array, mimeType }`. Custom transports must honor the signal, bound reads and return the real MIME type. They remain application code, not scene document fields. Without registrations, referenced sources fail closed. +A standalone `SceneDirector` also passes `dataPacks.overlayHost`, the +world-overlay host that draws pack world text such as a media pack's label (an +object with `setEntries(sourceId, entries)` and `clearSource(sourceId)`); +without it a media pack fails to load. `createApplicationTools` passes the +application's shared host. The portable session receives format adapters separately. Each adapter receives `{ pack, asset, anchors, signal }` and returns a resource with an idempotent diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index aa8cd05587..f8f9b48623 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -31,8 +31,9 @@ const layers = createInfrastructureLayers({ | `overlayHost.clearSource` | `(sourceId)`; remove that source's overlay entries | | `registerEntityContext` | `(entity, metadata)`; register selectable feature metadata, including the owning layer and data source | | `selectEntityContext` | `(entity)`; select that registered feature | -| `clearSelectedEntityContextForLayer` | `(layerId)`; clear selection only if owned by this layer | -| `removeEntityContextsForLayer` | `(layerId)`; remove records owned by the layer on destruction or failed setup | +| `clearSelectedEntityContextForLayer` | `(layerId, { evicted })`; clear selection only if owned by this layer; `evicted` when its feature left the data | +| `removeEntityContextsForLayer` | `(layerId, { retainIds })`; remove records owned by the layer on destruction or failed setup, or those a new feature set no longer has | +| `getSelectedEntityContext` | optional; `()` the selected record, so `replaceFeatures` keeps a selection the new set still has | | `governorRequestRender` | `(reason)`; request a frame through the existing render scheduler | Each returned layer supports `init(viewer)`, `enable(viewer)`, `disable(viewer)`, @@ -45,18 +46,43 @@ Callbacks must be ready before enable and remain usable through destruction. Disable retains the loaded dataset for reuse and clears selection and listeners. Concurrent enables share one load. Destroy is permanent, aborts pending fetches, -discards late results, and clears the owned data source, context records, overlays, +discards late results, and clears the owned draw sets, context records, overlays, input handler and listeners. The layer never creates an application context store, overlay host, viewer, or render scheduler. The consumer must resolve one compatible Cesium installation shared with its viewer; it must not bundle separate copies. +The layers draw, size their stems and fly the camera through the renderer's +ports. A viewer the application has bound a renderer to needs nothing more; a +Cesium viewer with no renderer bound loads +`gods-eye-view/render/cesium/unbound` once first; until then the layer reports +an error naming it, as it does for a dataset it cannot load. +A selected feature is the context record its draw item carries as `meta`; the +layer no longer sets the viewer's `selectedEntity`. +Features keep their own simplestyle `fill`, `fill-opacity`, `stroke`, +`stroke-opacity`, `stroke-width`, `marker-color` and `marker-size`, given as +hex, `rgb()` or `hsl()` colours or by the CSS colour names the default renderer +knows (it has no `rebeccapurple`, and spells `lavenderblush` `lavendar_blush`); +a `marker-symbol` is stamped on the pin as the default renderer stamped it: a +one-character string as bold upper-case text, any other value as the Maki icon +of that id from the renderer's assets, the plain pin when the icon cannot be +loaded. The assets are found as the renderer finds them from a page script: the +`CESIUM_BASE_URL` global, else the folder `Cesium.js` is loaded from; a +page bundling Cesium as modules sets `CESIUM_BASE_URL` for icon pins. Polygons with heights are drawn at them, outlined; points with +heights stand their pin on the stem's tip. Edges follow rhumb lines. + `gods-eye-view/infrastructure/geojson` exports the lower-level `createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay -helpers. `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers. +helpers. Its options also take `loadFeatures({ signal })`, a loader resolving to +GeoJSON features in place of `url`, and `featureColor(properties)`, a CSS colour +per feature for its fill, stem, dot, pin and label accent. The layer it returns +also has `dropCachedFeatures()`, so the next `enable` loads again, and +`replaceFeatures(viewer, features)`, which draws a new feature set in place of +the current one: the current one stays drawn until the new one is built, and +stays if that fails (the call then rejects). `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers. Consumers use the package exports, which do not import standalone application globals. Dataset files and source/license notices remain under `src/data/local_data/`. -Their input counts are 4,352 datacenter features and 704 dam features. Cesium may -expand multipart geometries into multiple entities; entity and stem counts are -different measurements. This change does not refresh or relicense the datasets. +Their input counts are 4,352 datacenter features and 704 dam features. A multipart +geometry draws as several parts, each with its own stem; part and stem counts are +different measurements from feature counts. This change does not refresh or relicense the datasets. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index d8354709df..8b33ce6244 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -34,7 +34,8 @@ hardware-rendered overlay scenes. These frame rates were measured when the globe was capped at 60 FPS. It now draws at the display's refresh rate while anything moves and ticks at most 60 -times a second when parked (`src/renderGovernor.js`). +times a second when parked (the Cesium frame port's idle rate, +`IDLE_FRAME_RATE` in `src/renderGovernor.js`). The initial-settle measurement is the more useful launch reference because it includes the first visual and data settling window. All three samples reached diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md new file mode 100644 index 0000000000..9b055c2269 --- /dev/null +++ b/docs/RENDERER-CONTRACT.md @@ -0,0 +1,746 @@ +# Renderer contract + +The renderer contract is what the application asks of a 3D renderer. The +Cesium renderer draws the application through it, and the stub renderer +stands in for it in tests. The contract is version `0`. Today the application +still drives Cesium directly; later work moves the layers onto the contract +one family at a time. + +The package exports these modules: + +| Export | What it is | +| ------------------------------------ | -------------------------------------------------------------------------------------- | +| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | +| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | +| `gods-eye-view/render/camera/events` | The camera port's events: `changed` per listener, `moveStart`/`moveEnd`, command hooks | +| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | + +The pieces that do not depend on Cesium are exported too, each with its +own `.d.ts`: + +- `gods-eye-view/render/input/router`: the input port's leases and routing; +- `gods-eye-view/render/stub/camera`, `.../stub/viewRectangle` and + `.../stub/harness`: the stub's camera, its view rectangle and its + conformance harness; +- `gods-eye-view/render/motion`: where a moving icon is drawn at a time; +- `gods-eye-view/render/vectorBase`: the vector base painter; +- `gods-eye-view/render/iconSegment`: icon motion segments; +- `gods-eye-view/render/recession`: how a set that recedes shrinks and + fades its items toward the limb; +- `gods-eye-view/render/windStreamlines`: the wind field's streamlines; +- `gods-eye-view/geo/screenCluster`: screen-space clustering. + +`src/render/neutralExports.test.mjs` checks that each is declared, that its +names match what it exports, that it type-checks under strict TypeScript and +that it imports no Cesium. + +A camera controller takes the camera events from `render/camera/events` +and the geodesy it needs (`geodesicAt`, `horizonFrom` and the rest) from +`gods-eye-view/geo`, so it measures and fires exactly as the stub does. `CameraControllerFactory` +(`camera.d.ts`) types such a controller: what it is given (`NativeCamera`) +and what it gives back (the camera port and its two frame steps). + +## Ports + +A renderer is created by a `RendererPlugin` (`{ id, create(options) }`). It +exposes nine ports, each typed in its own file in `src/render/contract/`: + +| Port | File | Covers | +| --------- | -------------- | ----------------------------------------------------------------------- | +| `frame` | `frame.d.ts` | The render-on-demand loop, frame phases, continuous holds, scene time | +| `globe` | `globe.d.ts` | Base (photoreal, terrain, vector, imagery), imagery layers, split, sky | +| `draw` | `draw.d.ts` | Draw sets: icons, points, lines, shapes, models, quads, meshes, fields | +| `camera` | `camera.d.ts` | Pose, views, flights, `lookAt`, follow, user controls, events, matrices | +| `query` | `query.d.ts` | Picks, projection, rays, heights | +| `input` | `input.d.ts` | Pointer events with their pick made, leases, stock behaviours | +| `effects` | `effects.d.ts` | Screen styles, bloom, sharpen, screen modulation | +| `credits` | `credits.d.ts` | Data credits owed | +| `quality` | `quality.d.ts` | Quality knobs, device facts, frame signals | + +Version `0` is still being shaped, and not only by additions. Members +were removed or replaced (among them `camera.move`, `look`, +`rotateAround` and `zoom`, now step views placed with `setView`; +`query.sampleHeightNowMany`; `input.ctrlWheelZoom`, now the `ctrlWheel` +zoom input), `depthFailColor` and `depthFailDash` became one `depthFail` +style, and quality settings became detail only. The Cesium port and the +stub follow those changes. + +Some members and options were added to version `0` later. Each is +optional: + +- `globe.isGlobeVisible()` (capability `globeVisibility`) reads back whether + the globe surface is shown, for code that holds only the scene. +- `camera.followFrame()` (capability `followFrame`) reads the frame the eye + is placed in, as a column-major 4×4 matrix to ECEF: a follow's own frame + (east-north-up, or the orbit frame `autodetect` chose), a `lookAt` + target's east-north-up frame, or the identity. `setView` keeps that frame + while it places a world pose. A share link's follow offset is + re-expressed in it, satellites included. +- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that + changes whenever what surface heights answer against changes (base, + terrain or photoreal route swapped, the globe shown or hidden) and never + otherwise (not on camera moves or tile loads), so the application can key cached + heights by it. `isSettled('surface')` says whether that surface has + loaded what is in view; a renderer without it answers `surface` as `base`. +- `SurfaceShading` is `hillshade`: view-lit shading of the drawn terrain's + own relief (the ellipsoid's curvature where terrain has no normals) that + only darkens, at most `strength` opacity. The Cesium port draws it as a + globe material it takes only while no one else holds the globe's + material. +- Fields: `windStreamlines` takes `alpha` (changed without a rebuild) and + `paused`; `rasterShell` replaces `detailWindow` with + `detail: {image, rectangle}`, a sharper image drawn in place of the base + one, and says how shells stack, blend and update. `FieldHandle.on('drawn')` + says once per spec or `update` that it is drawn, never while hidden. These + change `fields` itself rather than add to it, so the renderer follows + them where it lists `fields`. The Cesium adapter lists `fields` and + draws `rasterShell` and `windStreamlines`. It reads the grid's samples as + points, the first column at `rectangle.west` and the first row at + `rectangle.north`, rows running south. Over the whole globe its paths + wrap east and west; over part of it they seed inside the rectangle, + equal-area, and stop at its edges. +- `ModulationSector` gains `radius` and `floor` and says what it modulates: + icons, points and models dimmed toward `floor` outside the band, the map, + lines and shapes as they are, picks unchanged. Its pass is named + `screenModulation`. This changes `screenModulation` itself; only the stub + lists it, and the Cesium adapter does not draw it yet. +- `camera.on('changed', cb, { threshold })` measures each listener by its + own threshold under the capability `cameraChangeThreshold`; a renderer + without it fires every `changed` listener at 0.5. +- A line item's `depthFail` style, solid or dashed, draws the parts behind + the surface (the Draw tool's rubber band is dashed there too); without one + they are hidden. +- A solid line's `outline.widthPx` is the outline's whole width, half on + each side, inside the line's own width: an 8 px line with a 4 px outline + is 2 px of outline, 4 px of colour and 2 px of outline, as Cesium draws + it. The check `draw.lines.outline` pins it. +- A shape's `lit` chooses shading by the renderer's fixed light (true) or a + flat colour (false); omitted, extruded shapes are lit and the rest flat, + as before. The Cesium port lights unclamped shapes only + (clamped ones drape unlit). The `shapes-lit` scene draws both. +- `SetSpec.recede` (`RecedeSpec`, for icon and model sets) makes a set's + items shrink and fade toward the globe's limb, replacing the icon item's + own `recede` flag. Its parameters (each optional: where receding starts + as a share of the limb's distance, the scale and haze reached at the + limb, the least focus × haze draws with, and the eye heights over which + it all eases off for a view of the whole globe) and the maths are + `render/recession`'s, so the renderer draws exactly those factors: an icon + draws at its scale times the scale factor, and an icon or model at its + alpha times `max(combinedAlphaFloor, focus × haze)`. `ModelItem.focus` + dims a model as `IconItem.focus` dims an icon. It changes live + (`setOptions`). The Cesium port draws a receding icon set on the GPU, + the factors worked out in its shader, and fades a receding model set's + models each frame before the scene draws, writing a model's colour again + once its focus and haze move by more than 0.005. The check + `draw.sets.recede` makes and changes both kinds, and + `draw.sets.recede.models` reads a receding model's pixels: at focus 0.25 + it draws faded, and a `combinedAlphaFloor` of 1, set live, brings it back. +- `SetSpec.drawOrder` stacks sets drawn over depth: a higher one draws over + a lower one and is picked first; equal ones keep the order they were + made in. The Cesium port stacks opaque icons and points by it; + translucent ones blend order-independently there. +- A rectangle shape's `rotation` (radians counter-clockwise) turns it about + its centre in longitude and latitude, as a KML ground overlay turns, and + its image fill turns with it. The Cesium port drapes image fills too, each + on a ground primitive of its own. +- `camera.controls.keepEarthFramed` (capability `keepEarthFramed`) stops + the user's outward zooms at a whole-Earth view (about 40,000 km, or + higher where a camera command left the eye) and, from high up, turns the + view down toward the globe so the whole Earth stays in frame; camera + commands are not held to it and end its turn. The Cesium port eases the + view until the Earth's limb is 8° below its centre line above 300 km + (`zoomOutGuard.js`). The application turns it on where a renderer has it. +- `query.occlusionTest()` (capability `occlusionTest`) tests many points + against the depth of the frames drawn without waiting for the GPU; the + detection overlay leaves out the street vehicles it finds hidden. The + Cesium port builds its test with `gods-eye-view/render/occlusion` + (`createDepthOcclusionTest`, given a `DepthSource`: depth packed into + RGBA8 or a depth texture, standard or logarithmic, with the view it was + drawn from). +- `RendererPlugin.applicationHooks(renderer)` hands the application what + lies beside the contract (`ApplicationHooks`); see + [The application and its renderer](#the-application-and-its-renderer). +- `frame.renderNow()` throws when the frame fails to draw. With + `{ifDue: true}` it runs one tick of the loop now, as the loop's own would + (camera flight, input, clock), and draws only a frame that is due. + +The Cesium port lists `gpuTiming` where its context has +`EXT_disjoint_timer_query_webgl2`: while anyone listens to frame signals, +each drawn frame is timed on the GPU from `preRender` to `postRender`, and a +signal carries `gpuMs` of the newest frame whose timing has come back (a +frame or more late; a disjoint timing is dropped). Without the extension it +answers `gpuTiming: 'none'` and lists no capability. The check +`quality.signals.gpuTiming` pins both. + +The Cesium port lists `modelAtmosphere`: Cesium scatters drawn models +through the atmosphere in the same stage as its distance fog, so models take +it while `globe.sky`'s `fog` is on. + +`weather` adds `globe.weather`: clouds, fog, haze, rain and snow drawn +around the view, each a strength from 0 to 1, with the wind they drift on. +`src/render/weather.js` (exported as `./render/weather`) keeps and clamps +them (`mergeWeather`), and `./weather/effects` +turns a weather observation into strengths (`deriveWeatherEffectProfile`). +The application sets none, and the Cesium port does not list it. The strengths say what +is observed (`clouds` is the fraction of the sky covered), not how it is +drawn: the renderer draws clouds, fog and haze its own way, with clouds +placed by scene time and the wind, and shading the ground under them where +the sun lights it. The checks `globe.weather`, `globe.weather.drawn` and +`globe.weather.sceneTime` (pixel checks) pin it. + +How the sky, atmosphere, haze, lighting and the frame's tone mapping and +exposure look is the renderer's own: `globe.sky` switches parts on and +off, and no check compares colours. With +`atmosphere`, `fog` and `lighting` off and clear weather a renderer applies +none of its look, so the checks that read an exact colour (`bareSky` in +`checks/ports.js`) set that sky first. The +reference images under `src/render/conformance/goldens/visual/` are the +Cesium renderer's own, for checking it against itself. + +The Cesium port lists `followAutodetect`: an `autodetect` follow is +Cesium's own AUTODETECT tracking frame, east-north-up on a still or slow +target and an orbit frame (x along the inertial motion, z up) on a fast +one. The stub's is a frame along the ground track, so an autodetect +`viewFrom` reads differently on each; the check `camera.follow.autodetect` +pins what both share (the range kept, north-up when still, the frame on the +target standing up). + +A follow target's `transitionS` makes the first framing a move instead of a +jump: from its first frame the eye is in the target's frame, and over +`transitionS` seconds of wall time it goes from where it stood to +`viewFrom`, by the one rule in `src/render/camera/followTransition.js` +(its offset and its view each turned and eased with smoothstep, the view +ending on the target with no roll). The Cesium port, the stub and a camera +controller import that rule rather than restating it. The tracked aircraft +and followed trains use it with a `viewFrom` taken from the camera +at the click: the eye's own view direction at its own range from the target, +so neither changes and only the eye's place moves, sliding the target to the +centre. The check `camera.follow.transition` pins it. + +The Cesium port draws clamped shapes of every kind. A clamped outline is a +draped line (a ground polyline a ring, under the shape's pick id; an outlined +clamped shape is rebuilt on any change; a pulsing one pulses through its line's +material, as an image fill pulses through its image material's colour). What +a ground primitive cannot drape stands on the surface unclamped, the surface +read when the set is built: an extruded shape from the lowest surface height +under it up to its `extrudeHeight`, a wall with its foot on the surface under +each position and its heights above it, and an image fill where the scene +cannot drape materials (no depth textures). The check `draw.shapes.clamped` +draws each. + +The Cesium port takes every kind of `ImageRef` wherever an image is drawn +(icons on billboards and on the GPU, line patterns, shape fills, quads and +raster shells): a URL, SVG, a blob (by an object URL made once per blob, +revoked once the blob itself has been collected; a material drawing a blob, +a quad's among them, holds it while it lives, since a material loads its image +on its first draw, even after the atlas slot it came from has a new one; a +quad given another source lets the old blob go with its old material, once the +frame has drawn), a +keyed canvas, and an atlas slot as the image it holds (an icon waits for an +unregistered slot; anything else refuses it). The check `draw.icons.images` +draws each kind on still icons and in a set that recedes. + +Icon sets with `cluster` (`ClusterSpec`) cluster the same way on every +renderer: `clusterScreenPoints` (`src/geo/screenCluster.js`) over the shown +icons in front of the eye and above the horizon, in the set's order, boxed at +their drawn size, the last pass's clusters kept. A cluster draws one icon at +the mean of its members' positions in place of its members (`icon(count)`, +else a default badge with the count, at the seed's size). A pick on it +answers one hit a member, seed first, each with the member's own `set`, `id` +and `meta` and the cluster's position, so `pick` gives the seed and +`drillPick` every member. Clusters are made again in the frames drawn after +the camera moves or the set changes, never on a timer. The Cesium port draws +a set's cluster icons in a billboard collection of their own and hides the +members' billboards. A set on the GPU (`columns`, a set that recedes, or moving, +proxy-picked or level-of-detail icons) clusters its rows where their segments +(and ground) put them at the frame's motion-clock time, hiding the members' +rows; while rows still move it clusters again every frame. The checks +`draw.icons.cluster` and `draw.motion.cluster` (members coming to rest on +their segments) draw a cluster, pick it, and part it by moving in. + +Icon sets on the Cesium GPU path draw what its billboards draw: pixel offsets, `bottom` and `top` anchors, screen and axis +rotations (turned as Cesium's billboards turn), `fadeByDistance`, +`displayRange`, and `clampGround` / `relativeGround` heights. Each row reads +these from a float texture by instance, so the 16 vertex attributes hold; +WebGL 1 has no such fetch and refuses them. A clamped row stands on the +ground taken between the heights under its segment's two ends, sampled after +a frame draws, 256 ends a frame across the port's sets: loaded terrain first, +then (but for `clampTo: 'terrain'`) the drawn surface, eight a frame. They are +sampled again when the globe's tiles finish loading and, clamped to more than +terrain, every 5 s. The check `draw.motion.look` draws each on a moving icon. + +A set's `blend` holds for every kind of set: omitted, opaque parts draw +opaque with depth writes and translucent ones blend without; `opaque` draws +every item opaque, its alpha ignored, with depth writes; `translucent` blends +every item without depth writes, even at alpha 1; `additive` adds each item's +colour times its alpha, without depth writes and still depth-tested. It +changes live (`setOptions`, from the next frame; models do not load again). +The Cesium port builds billboards and points in Cesium's blend options, and +turns every set's draw commands to its blend each frame before the scene +sorts them (`src/render/cesium/setBlend.js`): additive ones draw after every +opaque command and before the translucent pass, which blends +order-independently and would undo the addition; ground commands keep their +pass and stencil and only blend differently. The checks `draw.sets.blend` +(points, icons, lines, shapes) and `draw.models.blend` read the pixels. + +A model item may bring its glTF bytes (`gltf`): the renderer builds it from +them and never fetches its `url`, which stays the model's identity, so a +model set loaded up front (the procedural fleet models, GLBs compressed with +`EXT_meshopt_compression` and `KHR_mesh_quantization`) is never fetched +mid-session. `axisScale` stretches a model along its own glTF axes on top of +`scale` (a hull drawn at its reported beam), `maskColor` paints a colour +where the model's `_TINT` vertex attribute marks it (a vehicle in its route's +colour), and `clip: 'belowOrigin'` draws only what is above the horizontal +plane through its position (a hull above its waterline). Each changes live. +The Cesium port passes the bytes as the model's `gltf` with its url as the +base path, scales its model matrix along the axes Cesium's glTF axis +correction turns them to, paints the mask in a custom shader per colour +(unlit under `unlit` shading, left out under `thermal`), and clips with a +clipping plane through the model's origin. The checks `draw.models.bytes` +and `draw.models.fleet` cover them. + +The Cesium port draws timed imagery (`imageryFrames`): a layer given a timed +source hides its own imagery and draws each frame its clock shows as a Cesium +imagery layer just above it (in `blend` mode the later frame over the earlier +at its share of the way, as a layer's `alpha` blends), with the next +`prefetch` frames (1 by default) loading unseen at alpha 0. A video source is +seen every 250 ms of each segment (at most 1,200 times a segment), each tile +the video its URL names for it (or one video over the layer's rectangle for a +`single-image` layer), seeked to the time's share of its length. A layer +keeps its 48 most recently seen tile videos; a tile waiting on one it lets +go, or on a seek that takes over 10 s (60 s for the seek past its end that +learns the length of a video that does not state it), fails rather than +waiting. A video whose seek did not end is let go, so the next tile loads a +fresh one; one that failed to load (or to say how long it is) fails its tiles +at once for 3 minutes, then loads again. `frameReady` +names the nearest frame's time once every globe tile drawn shows that +frame's own imagery (`src/render/cesium/imageryFrames.js`). The checks +`globe.imagery.frames` and `globe.imagery.video` cover both. + +Every Cesium draw set takes `setColumns` (`columns`): icon sets on the GPU, +any other as the rows the columns make over the items it holds, each row the +item of that id with the columns' fields over it, replacing every item as +`set` does (`columnRows` in `src/render/cesium/draw.js`, as the stub does). +`renderer.shape` holds on Cesium. + +The Cesium port also draws `pattern` line styles (the image repeated +`repeat` times along the line, in the translucent pass; draped too), lines in the +`inertial` frame (turned each frame by the set's motion clock, a depth-fail +style included; never batched; a draped one is draped where the sky is, +turned into the fixed frame, and draped again each second of its clock), +segment colours and shows +on lines of every mode and style (a draped solid line as ground instances, +any other as a primitive a segment with a material of its own, recoloured +and shown in place; an arrow's head on its last segment, a pattern keeping +its image; the check `draw.lines.segmentStyles`), and image fills on clamped ellipses, cut finely so a +round image (the launch pad zone's rim) runs round. A clamped colour fill +whose geometry alone changes (an annotation's target ring, resized as the +camera climbs) is drawn alone where it now is, in the same frame. A hidden +line that cannot settle into a static batch leaves its polyline collection +until it shows again, since the collection draws every line it holds. + +The renderer itself (`renderer.d.ts`) adds capture, pixel reads, settling, +resize, context loss and `destroy`. `common.d.ts` holds the shared shapes +(ECEF positions, colours, listener semantics) and the capability list. + +The rules that hold everywhere: + +- **The application keeps its own records.** It never reads a renderer to learn its own + state, only what the renderer measures: picks, depth, heights and + readiness. +- **Capabilities.** An optional member (`?`) exists only with the capability + its documentation names first. A required member that names a capability + always exists, and without the capability it answers null or empty. + Quality support is listed by `quality.knobs()`, not by capabilities. +- **Picks see the scene before effects.** A style that moves pixels does not + move what is picked, so the application maps a pointer through its own + style first + (`src/input/sensorPick.js`). A bounded `drillPick` (`limit`) also bounds + its work: it looks through at most `max(limit, 16)` things under the + pointer. +- **Heights are physical.** All heights are metres above the ellipsoid, + unexaggerated. Only drawing follows exaggerated terrain. +- **Listeners** run in subscription order. A listener removed during + delivery does not run; one added during delivery runs from the next event. + A listener that throws is reported to the renderer's `error` event, or to + the platform's `reportError` when nothing listens for errors. The other + listeners, and the frame, still run. +- **The frame order is fixed:** camera flight → input → camera `changed` → + follow → `preUpdate` → move detection → `preRender` → render → + `postRender`, the default renderer's own. A camera move made by follow or + in `preUpdate` is reported by `changed` on the next frame. +- **Destroy ends everything.** After `destroy()`, every handle does + nothing: a set's or field's methods neither draw nor throw, and a set or + field asked for afterwards is such a handle. The same holds for one handle + after its own `dispose()`. `frame.renderOnce()` and `capture()` reject + with a "renderer destroyed" error, and a `renderOnce` still waiting at + destroy rejects rather than hang. +- **Results are read-only.** `camera.matrices()` and `followFrame()` may + hand the same arrays again while they hold, and hand new ones once they + change, so one kept from an earlier frame stays as it was. +- **Reading the frame.** `capture()` and `readPixels()` read the last + presented frame; neither draws one of its own when the frame is kept. + Whether to keep the drawing buffer is the renderer's own business, not a + creation option. The creation options a renderer takes are `msaa`, `sky` + and `time`, set before the first frame, and `clock`, which its frame + ticks, the camera's `moveEnd` wait, its input and its flights read, and + its inertia where the renderer times that itself: on Cesium, inertia + keeps Cesium's own timing. +- **Leases:** a tool takes the pointer with `claimPointer`. With `grab`, it + takes only the presses it grabs on `down`; the rest, and wheel and pinch, + stay with the camera and everyone else. The newest claim takes over: it + ends the previous lease, whose `onLost` is called once, after the new lease + holds the pointer, so that tool turns itself off. A lease its holder + releases is never told, and an ended lease's release frees nothing. + The application's own tools (Draw, the imagery box, Directions) claim through + `src/data/inputOwnership.js`, which the input dispatcher bridges onto the + port, so a claim on either takes over from the other. The bridge's lease + grabs no press: the dispatcher decides who hears each event when it + arrives, and the renderer's stock select and double-click follow run + unless a tool holds them off. + +`src/render/contract/index.js` lists every member of every port in `PORTS`, +along with `CAPABILITIES`, `FRAME_STEPS` and `QUALITY_KEYS`. +`checkRendererShape(renderer)` names each required member that is missing, +and each capability member present without its capability. +`contract.test.mjs` type-checks the contract under strict TypeScript, and +fails when `PORTS` and the types disagree on a single member. + +### The vector base painter + +`vectorBase` (`BaseSpec.vector = { styleUrl }`) draws a MapLibre style +document's vector tiles as the globe's base. They are painted in shared, +Cesium-free code, `src/render/vectorBase/`, which the renderer draws as +imagery: + +- `loadVectorStyle(styleUrl, fetch)` fetches the style and the TileJSON its + vector sources name (a source's `url`; inline `tiles` are used as given, + resolved against the style), compiles every layer, and returns the + sources (tile templates, `minzoom`, `maxzoom`, `xyz` or `tms`), the layers + it draws, the background, the sources' attributions, and `skipped`: each + layer it does not draw, with why. +- `paintVectorTile(style, z, x, y, { size, fetch, signal, canvas })` paints + one Web Mercator tile on a canvas at style zoom `z + log2(size / 512)` (at + least 0). A source past its `maxzoom` is drawn from its deepest tile, + overzoomed; below its `minzoom` it draws nothing. Decoded source tiles + (gzipped ones inflated) are kept per style, the last 128. + +What it draws of the style specification: + +- Layers: `background` (`background-color`, `background-opacity`); `fill` + (`fill-color`, `fill-opacity`, `fill-outline-color`); `line` + (`line-color`, `line-width`, `line-opacity`, `line-dasharray`, + `line-cap`, `line-join`, and `line-gap-width` drawn as one line the full + cased width); `circle` (`circle-radius`, `circle-color`, + `circle-opacity`, `circle-stroke-width`, `circle-stroke-color`, + `circle-stroke-opacity`); `symbol` text only (`text-field` as an + expression or with `{name}` tokens, `text-size`, `text-font` as the + system's sans-serif or serif in bold or italic as its name says, + `text-color`, `text-opacity`, `text-halo-color`, `text-halo-width`, + `text-transform`, `text-anchor`, `text-offset`, `text-max-width`). + Layer `minzoom`, `maxzoom`, `filter` and `visibility` hold. +- Labels are painted into the tiles: top layer first (within a layer, its + features in their order in the tile), each clear of those placed before + it and wholly inside its tile (one across a tile edge is + left out). A point labels at itself, a line halfway along it (level, not + along the line), a polygon at its outer ring's bounding-box centre. +- Filters in both syntaxes (legacy, with `$type` and `$id`, and + expressions). Legacy `{stops, base, property, type}` functions + (exponential, interval, categorical, identity; not zoom-and-property); + one without a `type` is exponential on a property that interpolates (a + number or colour) and interval on any other (`line-cap`, `line-join`, + `text-font`, `text-transform`, `text-anchor`, ...), as the specification + says. `has`, `get` and legacy filters see a feature's own properties only. +- Expressions: `literal`, `get`, `has`, `id`, `geometry-type`, `zoom`, + `properties`, `!`, `all`, `any`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, + `case`, `match`, `coalesce`, `step`, `interpolate` (`linear` and + `exponential`; `-hcl` and `-lab` blend in RGB), `to-string`, + `to-number`, `to-boolean`, `to-color`, `number`, `string`, `boolean`, + `rgb`, `rgba`, `concat`, `format` (its text), `upcase`, `downcase`, + `length`, `at`, and arithmetic (`+ - * / % ^`, `min`, `max`, `abs`, + `floor`, `ceil`, `round`, `sqrt`, `ln`, `log10`, `log2`). +- Skipped whole: `fill-extrusion`, `raster`, `hillshade`, `heatmap` and + `sky` layers; layers on raster sources; layers setting a pattern + (`fill-pattern`, `line-pattern`, `background-pattern`), `line-offset`, + `line-gradient` or a translation; layers whose values use an expression + not listed (or are malformed). As MapLibre does, a paint or layout value + that cannot be evaluated for a feature (a type that does not fit, a + `step` or `interpolate` over what is not a number) or is not of the + property's kind (null; not a finite number, a string included, where a + number is needed; not a colour `parseColor` reads, which takes the CSS + colour names; not one of the property's keywords) is the property's + default; a legacy function's miss is its `default`, else the property's. + A feature whose filter cannot be evaluated is left out. Nothing + unsupported throws. +- Ignored: icons (`icon-image`, sprites: a symbol layer draws its text + alone), text along lines (drawn level), `glyphs` (system fonts), and any + other paint or layout property not listed above. + +The Cesium port loads the style before the base changes (a style that fails +leaves the base as it was; a later `setBase`, or disposal, aborts the load and +the overtaken call changes nothing, resolving with `imagery: []` and +`settled: false`; `settled` is whether, when the call resolves, its base is +still the one drawn and has settled, so an earlier call that resolves while a +later call's style is still loading, or after that style fails, is settled, +and one that resolves after a later call changed the base is not), draws it as Web Mercator imagery under the +base's other imagery (`src/render/cesium/vectorBase.js`, 256 px tiles to +level 20, transparent where the style paints no opaque background; a tile +whose request is cancelled, its layer removed, is not painted), and credits each source's attribution as plain text. The stub +loads the style and paints nothing. The check `globe.base.vector` serves a +style and a tile from data URLs and reads the drawn fill. + +### What a renderer does, by role + +A renderer is more than a drawing surface: it is a whole globe engine. The +application keeps the data (providers, records, layers and their +behaviour). The renderer owns everything from a source spec or a draw set +down to the pixels. The ports follow the API's shape; `ROLES` in +`src/render/contract/index.js` names what the engine behind them does, and +puts every member of `PORTS` in exactly one role. It changes no member. + +| Role | What it does | Members | +| --------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `surface` | Streams, decodes and builds the globe from map sources: imagery, terrain, photoreal 3D tiles, draped layers | `globe`, `imageryLayer`, `credits` | +| `scene` | Draws the application's data as keyed, retained sets | `draw`, `drawSet` | +| `view` | Places and moves the camera, hands pointer input to the application | `camera`, `flight`, `input`, `lease` | +| `queries` | Picks, surface positions and heights, rays, projection, occlusion | `query` | +| `look` | Sky and atmosphere, surface shading, per-layer lighting, styles and screen effects | `effects`, `globe.sky`, `globe.weather`, `globe.setSurfaceShading`, `imageryLayer.lit` | +| `host` | Canvas and life cycle, the frame loop and scene time, quality, capture, settling | `renderer`, `frame`, `quality` | + +An entry is a port or a `port.member` prefix; the most specific one wins, so +`roleOf('globe', 'sky.set')` is `'look'` while `roleOf('globe', 'setBase')` +is `'surface'`. `contract.test.mjs` fails when a member has no role, when +two roles claim the same entry, or when an entry names no member. + +## Moving code onto the contract + +Two ratchet tests keep code that has moved onto the contract from drifting +back to Cesium. Both lists only ever shrink. + +- `src/render/cesiumAllowList.json` lists the files outside the Cesium + adapter (`src/render/cesium/`) that may still import or be handed Cesium + (`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list + when it no longer drives Cesium at all; nothing is added. The list is + empty: no file outside the adapter reaches Cesium. Two files name + the adapter by design and are not on it: the application scene + (`src/app/scene.js`), the composition root that picks the default renderer + when it is given none, may import `src/render/cesium/application.js` (only + then, so a page on the stub never loads Cesium) and nothing else of + the adapter; the conformance page (`dev/conformance/main.js`) may import the + adapter's harness and scene renderer. The test names both + (`ADAPTER_ENTRIES`), and that list is never grown. +- `src/render/viewerAccessAllowList.json` counts, per file off that list, + the Cesium-shaped accesses through the viewer it still makes (none: the + list is empty, so no file may make one) + (`src/render/viewerAccess.test.mjs`): the viewer's `entities`, + `dataSources`, `scene`, `camera`, `clock`, `imageryLayers`, + `terrainProvider`, `trackedEntity` and `canvas`, and the scene's + `primitives`, `pick`, `drillPick`, `pickPosition`, `globe`, `preRender`, + `postRender`, `preUpdate`, `postUpdate`, `canvas`, `requestRender` and + `camera`, written plainly, with `?.`, in brackets or destructured. + `viewer.container` is a DOM element and does not count; reach the canvas + through `canvasOf(viewer)`. Comments and tests do not count. + `src/testSupport/viewerAccess.mjs` is the matcher. + A file may not make more accesses than recorded (a file not listed may + make none), and a count higher than the file now needs fails too. So a + file that leaves the Cesium list must port its viewer accesses in the + same change: it cannot be added to the count. After + porting accesses away, run `node scripts/viewer-access-baseline.mjs` (or + `--check` to see what it would change): it lowers counts and drops + entries, and never adds or raises one. + +## The application and its renderer + +The application runs on a renderer with only the contract's required +members (the stub proves it below); nothing outside `src/render//` asks which renderer it runs +on (no `renderer.id`, no engine type, no engine object's presence). + +- **The scene object.** `createApplicationScene` (`src/app/scene.js`) takes a + `RendererPlugin`, or a promise of one (default: Cesium, imported only then; + `loadDefaultRenderer` starts that import as the standalone page starts), + creates the renderer in the page's container, and hands every layer and + tool the application's own scene object (`createSceneHost` in + `src/render/rendererOf.js`): the container and `isDestroyed()`, bound to + the renderer. Code reaches the renderer's + ports through it (`findCamera`, `drawOf`, `canvasOf`...). +- **What only the Cesium renderer needs at startup** is done in its + plugin's `create`: the free-look height limit and keyboard access to its + credits' expand link (`src/render/cesium/appRenderer.js`). +- **What a plugin may hand the application beside the contract** is its + `applicationHooks(renderer)` (`ApplicationHooks`, + `src/render/contract/renderer.d.ts`), asked once as the scene creates the + renderer and recorded for the application (`src/render/applicationHooks.js`): + a map engine of its own, stale command trimming, whether an entity is its + own, whether it shows its credits in a display of its own + (`ownCreditDisplay`; otherwise the application's own line, + `src/ui/creditsView.js`, shows the credits port's list), and what QA + scripts read from `window.__godsEyeView` (Cesium's viewer there, for the + scripts that drive it). Each is optional, none is a contract member, and + a renderer without them runs the application without that behaviour. +- **What the renderer should do is in the ports**, each through the + application's own code: outward zooms stop at a whole-Earth view that + stays framed (`camera.controls.keepEarthFramed`, which the scene turns + on; Cesium's is `src/render/cesium/zoomOutGuard.js`); the detection + overlay leaves out street vehicles something stands in front of through + `query.occlusionTest()` under the `occlusionTest` capability (the GPU + probe is `src/render/occlusion/depthProbe.js`, which Cesium's + `src/render/cesium/sceneOcclusionProbe.js` feeds; without it every such + vehicle's bracket shows); and an inline panel whose host stops animation + frames keeps running through `resize` and `frame.renderNow({ifDue: true})` + (`src/app/panelRendering.js`), so flights, input and the clock go on as + in the renderer's own loop, stopping at a frame that throws. +- **The map stacks** switch through the renderer's own map engine when its + plugin hands one, else through its globe port (`src/maps/globeEngine.js`); + see `docs/CURRENT-STATE.md` § Map source factories and coordination. +- **The proof.** `npm run qa:stub-boot` (`scripts/qa-stub-boot.mjs`) serves + the application's page with `dev/stub-app/main.js` as its entry: the whole + application on the stub with no capability at all. It fails when the page + requests any Cesium module or asset, when the credits line is not shown + with its data credits, on a page or console error, or when a + data layer (flights, military aircraft, transit, traffic, CCTV, vessels, + weather, wind, satellites, FIRMS, wildlife, shipwrecks, news) fails to + turn on or off; `--strict` also fails + a layer that draws nothing on the stub (it needs the live feeds). + `src/app/scene.test.mjs` runs the scene itself on the stub in Node. + +## The stub renderer + +`createStubRenderer({ capabilities, viewport, time, container })` implements +every port in memory and draws nothing. Given a `container` (in a page), its +canvas is a real canvas filling it, which `resize()` follows; otherwise a +stand-in that takes event listeners. `createStubRendererPlugin(options, +onCreate)` is the stub as a `RendererPlugin`. It has: + +- the default camera's exact maths: views, `lookAt`, flights with their + height arc and easing, `changed` thresholds and follows; +- picks against what was drawn, or a scripted table; +- scripted heights; +- a virtual clock that nothing advances on its own; +- models that load at once, but for urls under `stub-fail:` + (`STUB_FAILING_MODEL_SCHEME`), which fire `loadFailed` instead of `ready` + (they are still picked where they are). + +`renderer.testing` drives it with `tick()`, `advance(ms)`, `pointer(type, x, y)`, +`scriptPicks`, `setHeights` and `cacheHeight`, and records its calls. +`testing.drawnPosition({ set, id }, aheadMs)` is where it draws an item now +(or `aheadMs` from now), so a +camera controller over the stub can follow drawn items there. +A listener that throws with nothing subscribed to `error` goes to +`reportError`; Node has none, so the stub rethrows it on a microtask and +`node:test` fails the running test. A test that expects a throw subscribes +to `error`. +The stub passes the whole conformance suite (`src/render/stub/stub.test.mjs`). + +## Conformance suite + +`runConformance(harness)` runs every check against the Cesium renderer or +the stub through the contract alone and reports each one as passed, failed or skipped. It runs in +Node and in a browser page. A harness tells the suite how to drive the +renderer under test: + +- `create({ viewport, capabilities })`; +- `frame(r)`: one frame, 1/60 s on a virtual clock; +- `now(r)` and `toEcef(p)`; +- `tolerance` and `flightPaths`. + +Optional members widen what is checked: `pointer` for synthetic input, +`cameraInput` (the camera answers that input: the drag and wheel traces +run), `scriptHeights`, `resizeContainer` (sizes the element the renderer +fills, for the `resize` check, which skips without it), `assets.model`, and +`assets.missingModel` (a model url that fails to load, for the `loadFailed` +check). `pixels: false` says +the renderer draws nothing but models into its pixels, as the stub: the +checks that read drawn icons, lines and fields then skip. Without it they +run, and the renderer fails them if it draws nothing there. + +There are two layers of checks. + +**Logic checks** run in CI. They cover: + +- the shape check; +- listener semantics and the frame loop; +- draw-set bookkeeping, picks and the `meta` round-trip; +- projection, rays and heights; +- leases and click picks; +- imagery order, sky, styles, credits and quality knobs; +- the camera traces. + +**Camera traces.** `cameraScripts.js` lists camera scripts in the contract's +terms. `scripts/record-camera-goldens.mjs` runs them on Cesium's own +`Camera`, headless, on a virtual clock, and writes +`src/render/conformance/goldens/camera.json`. A renderer under test must +match each recorded pose: + +- within 1 mm in position, 1e-9 in unit vectors and angles, and 1e-3 px on + screen; +- with every flight ending within one frame of the recording. + +Some scripts move the camera by user input: left, middle, Shift and Ctrl +drags, and wheels in pixel and line mode. The recorder runs those on +Cesium's own `ScreenSpaceCameraController`, fed the DOM events the script +describes, with `Date` on the virtual clock too (its coasting reads it). A +renderer under test gets them through its harness's `pointer`, a wheel as +the input port's lines. Only a harness with `cameraInput` runs them: the +stub's camera takes no gestures, so it skips them; a camera controller +over the stub would run them. `cameraPort.test.mjs` runs them on Cesium's +controls under the Cesium camera port, each wheel sent back as lines. + +A wheel's `delta` is lines as Cesium counts them: a pixel-mode wheel at +40 px a line and a page at 3 lines (`src/render/input/wheel.js`). Turning +lines back into pixels at 40 px a line gives Cesium's own wheel in every +mode, so a controller that does that zooms as Cesium does in Chrome (pixel +mode) and Firefox (line mode) alike. + +`src/render/cesium/cameraGoldens.test.mjs` fails when the installed Cesium +no longer records the committed traces. After a Cesium upgrade or a script +change, run `node scripts/record-camera-goldens.mjs` and review the diff. + +**Visual checks** run in the browser. The reference scenes +(`src/render/conformance/scenes.js`) are built from contract calls only: + +- one scene per primitive family; +- a city scene; +- a calibration path from orbit down to the street. + +The scenes load nothing from the network. + +`npm run dev`, then open `/dev/conformance/`. The page can: + +- **Run logic suite (stub)** runs the logic checks in the browser. +- **Record references** draws every scene the chosen renderer supports. + It saves each view to `src/render/conformance/goldens/visual/`, through a + dev-server-only endpoint. +- **Check scenes** draws the scenes again and compares each capture with its + reference. Pixels are compared as pixelmatch compares them: by YIQ + difference (threshold 0.1), with antialiasing in either image excused. A + capture matches when at most 250 pixels are unexcused and at most 2 are + solid (a differing pixel whose four neighbours differ too). Between them + the two catch a dropped 4 px point, a dropped 2 px line and a 1 px shift + of the view, and pass any MSAA setting. A change nowhere 3 px thick (a + thin line gone, an item moved a pixel or two) that covers at most 250 px + passes. `visual.js` has the measurements. + The page shows the capture, the reference and the difference side by side. + +`window.conformance.runScenes()` and `runLogic()` do the same from a script. + +`npm run qa:conformance` runs the logic checks on the Cesium renderer in +headless Chromium (software WebGL, no GPU needed). It starts its own Vite +server unless given `--url`; `--only id,id` runs just those checks and +`--json path` writes the report. It fails on any failed check and on any +skip it does not expect (`query.heights`, which needs scripted heights, is +the one it expects). CI runs it in the `street-level-browser` job. +Browser checks use the chrome-devtools MCP against a page in its own window. + +The Cesium scene renderer (`src/render/cesium/sceneRenderer.js`) draws +every scene (icons, points, lines, shapes, models, quads, meshes, fields +and the city), and the references were recorded with it, on a GPU: a +software rasterizer such as SwiftShader draws the glow line differently. +It has only the members the scenes need. + +Some behaviour is only drawn, so the logic checks cannot see it: course +easing (`courseGlide`), and a hidden row keeping its eased +course. The stub keeps no drawn course. These wait for scenes that capture +an icon mid-turn. Height queries that count a set +(`includeInHeightQueries`) are not checked either: the stub's heights are +scripted, so it does not model them. Nor are video frames (a check needs a +video) or `fetchTile` (the stub fetches nothing). diff --git a/package-lock.json b/package-lock.json index 27ad854e1a..af748fcd3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "h3-js": "^4.4.0", "hls.js": "^1.7.3", "hyparquet": "1.31.2", + "kdbush": "^4.0.2", "mapillary-js": "^4.1.2", "mgrs": "^2.1.0", "pbf": "^5.1.2", @@ -36,6 +37,7 @@ "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", + "typescript": "5.9.3", "vite": "^6.4.4", "vite-plugin-cesium": "^1.2.23", "ws": "^8.21.0" @@ -3579,6 +3581,20 @@ "dev": true, "license": "MIT" }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", diff --git a/package.json b/package.json index ac2738b7e2..1a7f64a6dc 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "gods-eye-view", "private": true, "version": "0.3.0", - "description": "A real-time intelligence console for planet Earth \u2014 photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", + "description": "A real-time intelligence console for planet Earth — photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", "type": "module", "license": "MIT", "author": "Bilawal Sidhu", @@ -53,6 +53,8 @@ "test": "node scripts/run-unit-tests.mjs", "test:perf": "node scripts/run-perf-tests.mjs", "test:track": "node scripts/track-regression.mjs", + "qa:stub-boot": "node scripts/qa-stub-boot.mjs", + "qa:conformance": "node scripts/qa-conformance.mjs", "qa:map-source-tray": "node scripts/qa-map-source-tray.mjs", "qa:street-level": "node scripts/qa-street-level.mjs", "qa:street-level:fixtures": "node scripts/qa-street-level.mjs --fixtures", @@ -72,6 +74,7 @@ "h3-js": "^4.4.0", "hls.js": "^1.7.3", "hyparquet": "1.31.2", + "kdbush": "^4.0.2", "mapillary-js": "^4.1.2", "mgrs": "^2.1.0", "pbf": "^5.1.2", @@ -89,6 +92,7 @@ "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", + "typescript": "5.9.3", "vite": "^6.4.4", "vite-plugin-cesium": "^1.2.23", "ws": "^8.21.0" @@ -98,7 +102,7 @@ "./infrastructure/geojson": "./src/data/localGeojsonCore.js", "./infrastructure/lod": "./src/data/localGeojsonLod.js", "./application": "./src/app/application.js", - "./application/viewer": "./src/app/viewer.js", + "./application/viewer": "./src/render/cesium/applicationViewer.js", "./time": "./src/time/worldClock.js", "./i18n": "./src/i18n/page.js", "./build/vite": { @@ -162,6 +166,7 @@ "./ui/layout": "./src/ui/panelRails.js", "./ui/input": "./src/ui/visualInput.js", "./ui/display": "./src/ui/displayControls.js", + "./ui/display/groups": "./src/ui/displayGroups.js", "./ui/effects": "./src/ui/effects.js", "./ui/effects/bloom": "./src/bloom.js", "./ui/maps": "./src/ui/mapSource.js", @@ -213,9 +218,9 @@ "./geography/neighborhoods": "./src/data/neighborhoodPolygons.js", "./maps/controller": "./src/maps/controller.js", "./maps/catalog": "./src/maps/catalog.js", - "./maps/imagery": "./src/maps/imagery.js", - "./maps/terrain": "./src/maps/terrain.js", - "./maps/3d": "./src/maps/google3d.js", + "./maps/imagery": "./src/render/cesium/mapImagery.js", + "./maps/terrain": "./src/render/cesium/mapTerrain.js", + "./maps/3d": "./src/render/cesium/google3d.js", "./maps/defaults": "./src/maps/defaultSources.js", "./voice/controller": "./src/voice/realtimeController.js", "./voice/control": "./src/voice/control.js", @@ -244,6 +249,9 @@ "./standalone/catalog": "./src/standalone/catalog.js", "./application/layers": "./src/app/constructCatalog.js", "./application/operations": "./src/app/operations.js", + "./data/entity-records": "./src/data/entityRecords.js", + "./input": "./src/input/dispatcher.js", + "./queries/heights": "./src/queries/heights.js", "./data/lifecycle": "./src/data/lifecycle.js", "./ui/navigation": "./src/ui/navigationController.js", "./ui/share-restoration": "./src/ui/shareRestoration.js", @@ -316,6 +324,28 @@ "./tools/services": "./src/tools/services.js", "./view": "./src/view/index.js", "./agent/world-packet": "./src/agent/worldPacket.js", + "./geo": "./src/geo/index.js", + "./sky": "./src/sky/index.js", + "./render/contract": "./src/render/contract/index.js", + "./render/stub": "./src/render/stub/index.js", + "./render/occlusion": "./src/render/occlusion/index.js", + "./render/camera/events": "./src/render/camera/events.js", + "./render/camera/followTransition": "./src/render/camera/followTransition.js", + "./render/cesium/plugin": "./src/render/cesium/plugin.js", + "./render/cesium/unbound": "./src/render/cesium/unbound.js", + "./render/conformance": "./src/render/conformance/index.js", + "./render/input/router": "./src/render/input/router.js", + "./render/stub/camera": "./src/render/stub/camera.js", + "./render/stub/viewRectangle": "./src/render/stub/viewRectangle.js", + "./render/stub/harness": "./src/render/stub/harness.js", + "./render/motion": "./src/render/motion/iconMotion.js", + "./render/vectorBase": "./src/render/vectorBase/index.js", + "./render/iconSegment": "./src/data/iconSegment.js", + "./render/recession": "./src/render/recession.js", + "./render/windStreamlines": "./src/layers/wind/streamlines.js", + "./render/weather": "./src/render/weather.js", + "./weather/effects": "./src/weatherEffectsMath.js", + "./geo/screenCluster": "./src/geo/screenCluster.js", "./layers/wildlife-sightings": "./src/layers/wildlifeSightings/index.js", "./layers/wildlife-sightings/source": "./src/layers/wildlifeSightings/source.js" } diff --git a/scripts/check-import-directions.mjs b/scripts/check-import-directions.mjs index b6d8dba673..3cbbcbbe35 100644 --- a/scripts/check-import-directions.mjs +++ b/scripts/check-import-directions.mjs @@ -15,6 +15,11 @@ const tests = (file) => file.endsWith('.test.mjs') || file.startsWith('src/testSupport/') || file.startsWith('src/tooling/') || + // Test doubles outside src/testSupport, imported by tests only. + file === 'src/input/testDoubles.mjs' || + file === 'src/layers/recentImagery/testDoubles.mjs' || + file === 'src/voice/voiceWorkflowHarness.mjs' || + file === 'src/layers/wildlifeSightings/renderPerformanceFixtures.mjs' || file === 'src/overlays/worldOverlayAllocation.worker.mjs'; const source = (file) => file.startsWith('src/sources/') || diff --git a/scripts/focus-allocation-check.mjs b/scripts/focus-allocation-check.mjs index e15538a2f1..f256f7ef7c 100644 --- a/scripts/focus-allocation-check.mjs +++ b/scripts/focus-allocation-check.mjs @@ -1,11 +1,8 @@ #!/usr/bin/env node import assert from 'node:assert/strict'; -import { - advanceSpriteFocus, -} from '../src/data/focusDeemphasis.js'; -import { - applyAircraftBillboardTreatment, -} from '../src/data/aircraftRecession.js'; +import { advanceSpriteFocus } from '../src/data/focusDeemphasis.js'; +import { aircraftTreatmentAlpha } from '../src/data/aircraftRecession.js'; +import { createIconSet } from '../src/data/iconSet.js'; if (typeof global.gc !== 'function') { throw new Error('focus-allocation-check.mjs requires node --expose-gc'); @@ -66,17 +63,14 @@ const focusInput = { target, }; -const baseColor = { withAlpha: (alpha) => ({ alpha }) }; -const billboard = { scale: 1, color: { alpha: 1 } }; const aircraftInput = { - billboard, - baseScale: 1, baseAlpha: 1, - baseColor, focusFactor: 1, cameraDistanceM: 100, cameraHeightM: 1000, }; +const icons = createIconSet({ capacity: 4 }); +const row = icons.add('sprite', {}); const baseline = bytesPerCall(() => focusInput.nowMs); const focus = netOfLoopBaseline( @@ -84,30 +78,22 @@ const focus = netOfLoopBaseline( baseline, ); const aircraft = netOfLoopBaseline( - bytesPerCall(() => applyAircraftBillboardTreatment(aircraftInput).alpha), + bytesPerCall(() => aircraftTreatmentAlpha(aircraftInput)), baseline, ); const productionSpriteTick = netOfLoopBaseline( bytesPerCall(() => { - // Match the hot civilian/military sprite path: the caller constructs fresh - // option literals, consumes the shared focus result immediately, and then - // constructs the composed aircraft-treatment options for the same sprite. + // Match the hot icon-set focus pass: the caller constructs a fresh option + // literal, consumes the shared focus result immediately and writes it to + // the row's focus column (the shader composes it with limb recession). const focusResult = advanceSpriteFocus(sprite, { screenPosition: focusInput.screenPosition, cameraDistance: focusInput.cameraDistance, nowMs: focusInput.nowMs, target, }); - const treatment = applyAircraftBillboardTreatment({ - billboard, - baseScale: aircraftInput.baseScale, - baseAlpha: aircraftInput.baseAlpha, - baseColor, - focusFactor: focusResult.factor, - cameraDistanceM: aircraftInput.cameraDistanceM, - cameraHeightM: aircraftInput.cameraHeightM, - }); - return focusResult.factor + treatment.alpha; + icons.setFocus(row, focusResult.factor); + return focusResult.factor; }), baseline, ); @@ -118,22 +104,24 @@ assert.ok( ); assert.ok( aircraft.roundedMedian <= PURE_CALL_BUDGET, - `applyAircraftBillboardTreatment allocated ${aircraft.rawMedian.toFixed(3)} B/call median`, + `aircraftTreatmentAlpha allocated ${aircraft.rawMedian.toFixed(3)} B/call median`, ); assert.ok( productionSpriteTick.roundedMedian <= PRODUCTION_SPRITE_TICK_BUDGET, `production sprite tick allocated ${productionSpriteTick.rawMedian.toFixed(3)} B/call median`, ); -console.log(JSON.stringify({ - callsPerTrial: CALLS, - trials: TRIALS, - budgets: { - pureCall: PURE_CALL_BUDGET, - productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET, - }, - loopBaseline: baseline, - advanceSpriteFocus: focus, - applyAircraftBillboardTreatment: aircraft, - productionSpriteTick, -})); +console.log( + JSON.stringify({ + callsPerTrial: CALLS, + trials: TRIALS, + budgets: { + pureCall: PURE_CALL_BUDGET, + productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET, + }, + loopBaseline: baseline, + advanceSpriteFocus: focus, + aircraftTreatmentAlpha: aircraft, + productionSpriteTick, + }), +); diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 99ab5a1c85..e474377e12 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -43,6 +43,34 @@ "scripts/build-admin-packs.mjs", "scripts/qa-admin-outlines.mjs", "src/data/inputOwnership.test.mjs", + "src/input/dispatcher.test.mjs", + "src/input/testDoubles.mjs", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/input.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/nativeClick.test.mjs", + "src/render/cesium/pickMemo.js", + "src/render/cesium/input.test.mjs", + "src/render/cesium/cameraInput.test.mjs", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraControls.test.mjs", + "src/render/input/router.js", + "src/render/input/router.test.mjs", + "src/render/motion/iconMotion.test.mjs", + "src/render/motion/iconBook.test.mjs", + "src/render/camera/poseSignature.test.mjs", + "src/render/cesium/internals.test.mjs", + "src/render/cesium/uploadProbe.js", + "src/render/cesium/uploadProbe.test.mjs", + "src/render/cesium/tileRequests.js", + "src/render/cesium/tileRequests.test.mjs", + "src/queries/heights.test.mjs", + "src/render/cesium/heights.test.mjs", "docs/CODE-BOUNDARIES.md", "src/main.js", "docs/APPLICATION.md", @@ -56,10 +84,8 @@ "src/app/application.test.mjs", "src/app/mapLifecycle.test.mjs", "src/app/startupCamera.test.mjs", - "src/app/viewer.js", - "src/app/zoomOutGuard.test.mjs", - "src/app/controls.test.mjs", - "scripts/qa-zoom-out-guard.mjs", + "src/render/cesium/applicationViewer.js", + "src/sky/icrf.js", "src/app/atmosphereCompat.test.mjs", "src/standalone/application.js", "src/standalone/controls.js", @@ -358,7 +384,6 @@ "src/layers/flights/tracking.js", "src/layers/flights/rendering.js", "src/layers/flights/testing.js", - "src/layers/flights/hiddenContactRotation.test.mjs", "src/layers/flights/evidence.js", "src/layers/flights/ingestion.js", "src/layers/flights/queries.js", @@ -538,6 +563,8 @@ "src/layers/traffic/model.js", "src/layers/traffic/timing.js", "src/layers/traffic/style.js", + "src/layers/traffic/style.test.mjs", + "src/layers/traffic/timing.test.mjs", "src/layers/bikeshare/lifecycle.js", "src/layers/bikeshare/viewport.js", "src/layers/bikeshare/registry.js", @@ -563,13 +590,13 @@ "src/ui/frameRateMonitor.js", "src/ui/frameRateMonitor.test.mjs", "src/ui/frameRateView.test.mjs", - "src/ui/renderFailure.test.mjs", + "src/render/cesium/renderFailure.test.mjs", "src/ui/renderFailureView.test.mjs", - "src/ui/renderFailureLoopErrors.test.mjs", - "src/ui/renderFailureEventRetry.test.mjs", + "src/render/cesium/renderFailureLoopErrors.test.mjs", + "src/render/cesium/renderFailureEventRetry.test.mjs", "src/app/renderFailureInlineRetry.test.mjs", - "src/ui/renderFailureSecondLoop.test.mjs", - "src/ui/renderLoopFixture.mjs", + "src/render/cesium/renderFailureSecondLoop.test.mjs", + "src/render/cesium/renderLoopFixture.mjs", "src/layers/cctv/lifecycle.js", "src/layers/cctv/controls.js", "src/layers/cctv/geometry.js", @@ -650,6 +677,7 @@ "src/layers/radio/volume.js", "src/data/radio.js", "src/layers/radio/source.test.mjs", + "src/layers/radio/lifecycle.test.mjs", "src/layers/submarineCables/bundledSource.js", "src/layers/submarineCables/geometry.js", "src/layers/submarineCables/index.js", @@ -674,10 +702,14 @@ "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", + "src/maps/engine.js", + "src/maps/startupRoute.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js", "src/maps/terrainRetry.js", "src/maps/terrainRetry.test.mjs", "src/mapStackController.js", @@ -685,7 +717,7 @@ "src/mapStackChips.test.mjs", "src/mapStackUnavailableReason.test.mjs", "src/mapStartup.test.mjs", - "src/maps/sourceFactories.test.mjs", + "src/render/cesium/mapSources.test.mjs", "src/search/geospatial.js", "src/search/http.js", "src/search/defaults.js", @@ -702,6 +734,16 @@ "src/services/application.js", "src/services/requests.js", "src/app/scene.js", + "src/render/cesium/appRenderer.test.mjs", + "src/render/noCesiumOutsideRender.test.mjs", + "src/render/cesiumAllowList.json", + "src/render/viewerAccess.test.mjs", + "src/render/viewerAccessAllowList.json", + "src/testSupport/viewerAccess.mjs", + "scripts/viewer-access-baseline.mjs", + "src/geo/geo.test.mjs", + "src/geo/celestial.test.mjs", + "src/geo/quaternion.test.mjs", "src/app/controls.js", "src/app/data.js", "src/app/tools.js", @@ -757,6 +799,7 @@ "src/layers/flights/snapshotRenderer.js", "src/layers/flights/records.test.mjs", "src/layers/flights/ingestion.test.mjs", + "src/layers/flights/controller.test.mjs", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", @@ -840,7 +883,6 @@ "src/tooling/transitProvider.test.mjs", "src/app/layers/transit.js", "src/data/transitIcons.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.test.mjs", @@ -912,6 +954,10 @@ "src/layers/weather/rendering.js", "src/layers/weather/shellRendering.js", "src/layers/weather/shellRendering.test.mjs", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawFields.test.mjs", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawStreamlines.test.mjs", "src/layers/weather/infraredAlpha.js", "src/layers/weather/infraredAlpha.test.mjs", "src/layers/weather/infraredImage.js", @@ -1130,7 +1176,6 @@ "src/layers/traffic/roadModes.test.mjs", "scripts/qa-traffic-motion.mjs", "src/layers/traffic/motion.test.mjs", - "src/layers/traffic/lineRebuild.test.mjs", "scripts/qa-journey-recorder.mjs", "scripts/qa-alpr-journey.mjs", "scripts/qa-context-arrivals.mjs", @@ -1163,6 +1208,9 @@ "src/view/index.test.mjs", "src/tools/views.test.mjs", "src/app/embed.test.mjs", + "src/app/panelRendering.js", + "src/render/cesium/application.js", + "src/app/panelRendering.test.mjs", "src/tools/globePanel.test.mjs", "src/costEndpointThrottle.test.mjs", "src/sources/gbfsStations.test.mjs", @@ -1179,7 +1227,7 @@ "scripts/build-bright-stars.mjs", "scripts/build-milky-way.mjs", "src/sky/stars.test.mjs", - "src/sky/starrySky.test.mjs", + "src/render/cesium/starrySky.test.mjs", "src/tooling/skyAssets.test.mjs", "src/tooling/skyAssets.paintOut.test.mjs", "src/tooling/responseCompression.test.mjs", @@ -1197,6 +1245,31 @@ "src/ui/shellFacade.test.mjs", "src/voice/globeResetConfirmation.test.mjs", "src/hudDms.test.mjs", + "server/providers/common/rateLimitKeys.test.mjs", + "src/render/contract/contract.test.mjs", + "src/render/contract/common.d.ts", + "src/render/contract/renderer.d.ts", + "src/render/contract/frame.d.ts", + "src/render/contract/globe.d.ts", + "src/render/contract/draw.d.ts", + "src/render/contract/camera.d.ts", + "src/render/contract/query.d.ts", + "src/render/contract/input.d.ts", + "src/render/contract/effects.d.ts", + "src/render/contract/credits.d.ts", + "src/render/contract/quality.d.ts", + "src/render/contract/index.d.ts", + "src/render/stub/stub.test.mjs", + "src/render/conformance/scenes.test.mjs", + "src/render/cesium/cameraGoldens.test.mjs", + "scripts/record-camera-goldens.mjs", + "server/standalone/conformance-references.js", + "dev/conformance/index.html", + "dev/conformance/main.js", + "docs/RENDERER-CONTRACT.md", + "src/render/cesium/zoomOutGuard.test.mjs", + "src/app/controls.test.mjs", + "scripts/qa-zoom-out-guard.mjs", "src/hudSummaryGate.test.mjs", "src/hudSummaryLine.test.mjs", "src/testSupport/stubMgrs.mjs", @@ -1302,7 +1375,6 @@ "src/tooling/nominatimGuardLifecycle.test.mjs", "src/tooling/nominatimLockOwnership.test.mjs", "src/tooling/nominatimOutlineRoute.test.mjs", - "server/providers/common/rateLimitKeys.test.mjs", "src/voice/areaCandidateContract.js", "src/voice/layerActionOwnership.js", "src/data/areaGeometry.test.mjs", @@ -1345,6 +1417,7 @@ "src/layers/shipwrecks/index.test.mjs", "src/layers/shipwrecks/source.test.mjs", "src/data/shipwrecksProxy.test.mjs", + "src/data/aircraftIconLayer.test.mjs", "src/app/sourceComposition.js", "src/app/sourceComposition.test.mjs", "src/data/dataCredits.js", @@ -1440,6 +1513,15 @@ "src/data/placePacksLoading.test.mjs", "src/ui/placePacksLoading.js", "src/ui/placePacksLoading.test.mjs", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/globeEngine.test.mjs", + "src/render/cesium/viewers.js", + "src/app/scene.test.mjs", + "dev/stub-app/main.js", + "scripts/qa-stub-boot.mjs", + "src/ui/creditsView.js", + "src/ui/creditsView.test.mjs", "src/cockpitSubjectProviders.js", "src/cockpitSubjectProviders.test.mjs", "src/cockpitProgress.js", diff --git a/scripts/i18n.mjs b/scripts/i18n.mjs index c424666a29..7baf43dc22 100644 --- a/scripts/i18n.mjs +++ b/scripts/i18n.mjs @@ -479,7 +479,8 @@ function readMarkup(file) { // Text that never reaches the page as UI: tool results and descriptions for // AI clients (MCP and the voice model). -const NOT_UI = [/^src\/tools\//]; +// The conformance suite's check titles are developer output, not UI. +const NOT_UI = [/^src\/tools\//, /^src\/render\/conformance\//]; function sourceFiles() { return trackedFiles( diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ec76dd86f5..4147d8f6cd 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -8,12 +8,68 @@ "modules": [ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", + "src/render/cesium/heights.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", "src/data/localGeojsonLod.js", "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", "src/data/infrastructureOverlayEntry.js", - "src/sources/infrastructureData.js" + "src/sources/infrastructureData.js", + "src/queries/heights.js", + "src/render/color.js", + "src/geo/sphere.js", + "src/geo/rhumb.js", + "src/geo/frustum.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "application": { "exports": ["./application"], @@ -214,13 +270,17 @@ "viewer": { "exports": ["./application/viewer"], "modules": [ - "src/app/viewer.js", + "src/render/cesium/applicationViewer.js", "src/app/atmosphereCompat.js", - "src/globeInView.js", - "src/sky/starrySky.js", + "src/render/cesium/starrySky.js", "src/sky/stars.js", "src/data/bundledJson.js", - "src/renderGovernor.js" + "src/renderGovernor.js", + "src/sky/icrf.js", + "src/sky/assets.js", + "src/globeInView.js", + "src/render/cesium/imageryLookAhead.js", + "src/cockpitOrbital.js" ], "external": ["cesium"] }, @@ -745,11 +805,43 @@ "modules": ["src/ui/displayControls.js"], "external": [] }, + "display-groups": { + "exports": ["./ui/display/groups"], + "modules": [ + "src/ui/displayGroups.js", + "src/ui/vueRuntime.js", + "src/ui/stores/display.js", + "src/ui/stores/owners.js", + "src/i18n/locale.js", + "src/i18n/locales/ar.json", + "src/i18n/locales/de.json", + "src/i18n/locales/es.json", + "src/i18n/locales/fr.json", + "src/i18n/locales/it.json", + "src/i18n/locales/he.json", + "src/i18n/locales/ja.json", + "src/i18n/locales/sv.json", + "src/i18n/locales/pt.json", + "src/i18n/locales/ru.json", + "src/i18n/locales/zh-CN.json", + "src/i18n/locales/uk.json", + "src/i18n/locales/zh-Hant.json", + "src/i18n/index.js", + "src/ui/i18n.js" + ], + "external": ["vue", "pinia", "vue-i18n"] + }, + "weather-effects": { + "exports": ["./render/weather", "./weather/effects"], + "modules": ["src/render/weather.js", "src/weatherEffectsMath.js"], + "external": [] + }, "visual-effects": { "exports": ["./ui/effects", "./ui/effects/bloom"], "modules": [ "src/ui/effects.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualPresets.js", "src/bloom.js", "src/styles/retro.js", @@ -942,7 +1034,11 @@ "src/ui/vueRuntime.js", "src/ui/stores/cctv.js", "src/ui/stores/status.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/horizon.js", + "src/render/rendererOf.js" ], "external": ["vue", "pinia", "vue-i18n", "cesium"] }, @@ -993,31 +1089,55 @@ "src/data/distanceFormat.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/ui/cockpitBriefPages.js", "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/layers/installations/classLabel.js", - "src/data/installationNames.js", - "src/i18n/marker.js", - "src/data/placeBelow.js", - "src/layers/satellites/sensors.js", - "src/data/adminBoundaries.js", - "src/data/bundledJson.js", - "src/data/retryableLoad.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", + "src/data/followed.js", "src/ui/cockpitDisplayPortal.js", "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", - "src/data/inputOwnership.js", "src/ui/cockpitInstruments.js", "src/cockpitSubjectProviders.js", "src/cockpitProgress.js", @@ -1028,13 +1148,6 @@ "src/cockpitMath.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/ui/panelRailGeometry.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1051,10 +1164,46 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", "src/ui/layerNames.js", - "src/ui/unitLabels.js" + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/layers/installations/classLabel.js", + "src/data/installationNames.js", + "src/i18n/marker.js", + "src/data/placeBelow.js", + "src/layers/satellites/sensors.js", + "src/data/adminBoundaries.js", + "src/data/bundledJson.js", + "src/data/retryableLoad.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "scene-controls": { "exports": ["./ui/scenes"], @@ -1107,21 +1256,12 @@ "src/cockpitTracking.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/contactsDetectionPolicy.js", "src/contextModePolicy.js", "src/data/detectionPolicy.js", "src/data/installationFeedback.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/militaryAwarenessEngine.js", @@ -1141,6 +1281,57 @@ "src/styles/surveillance.js", "src/styles/thermal.js", "src/ui/applicationShell.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/google3d.js", + "src/maps/startupRoute.js", + "src/sky/stars.js", + "src/renderGovernor.js", + "src/data/bundledJson.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/ui/railEdgeScroll.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", @@ -1155,8 +1346,6 @@ "src/ui/cctvFrames.js", "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", - "src/data/iconOrientation.js", - "src/ui/quebecCctvOverlay.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", @@ -1166,26 +1355,11 @@ "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/layers/installations/classLabel.js", - "src/data/placeBelow.js", - "src/ui/placePacksLoading.js", - "src/ui/ownerFlag.js", - "src/ui/ownerFlagSheet.js", - "src/layers/satellites/sensors.js", - "src/data/adminBoundaries.js", - "src/data/bundledJson.js", - "src/data/retryableLoad.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", - "src/data/inputOwnership.js", "src/ui/cockpitInstruments.js", "src/cockpitSubjectProviders.js", "src/cockpitProgress.js", @@ -1255,10 +1429,18 @@ "src/ui/surfaceKeyboard.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", "src/worldFocus.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/data/feedState.js", "src/data/layerSnapshot.js", "src/ui/aircraftDisplay.js", @@ -1346,7 +1528,19 @@ "src/ui/stores/globeActions.js", "src/ui/stores/recording.js", "src/ui/i18n.js", - "src/time/worldClock.js", + "src/data/entityRecords.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/sky/icrf.js", + "src/data/firmsIntensity.js", "src/ui/kit/UiSegmented.vue", "src/ui/wildlifeSightingCard.js", "src/layers/wildlifeSightings/records.js", @@ -1355,9 +1549,55 @@ "src/ui/wildlifeSightingPlacement.js", "src/overlays/worldOverlayChrome.js", "src/layers/wildlifeSightings/photoText.js", + "src/data/iconOrientation.js", + "src/ui/quebecCctvOverlay.js", + "src/time/worldClock.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/geoDistance.js", + "src/data/satelliteClassMask.js", + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/layers/installations/classLabel.js", + "src/data/placeBelow.js", + "src/ui/placePacksLoading.js", + "src/ui/ownerFlag.js", + "src/ui/ownerFlagSheet.js", + "src/layers/satellites/sensors.js", + "src/data/adminBoundaries.js", + "src/data/retryableLoad.js", + "src/maps/imageryHost.js", + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", "src/time/frameWait.js" ], - "external": ["cesium", "vue", "pinia", "vue-i18n"] + "external": [ + "cesium", + "vue", + "pinia", + "vue-i18n", + "pbf", + "@mapbox/vector-tile", + "kdbush" + ] }, "ui-styles": { "exports": ["./ui/styles"], @@ -1428,6 +1668,41 @@ "src/data/bhoteKoshiFloodPath.js", "src/maps/catalog.js", "src/scenes/director.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/geo/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/scenes/sceneSaveError.js", "src/scenes/playbackAdapter.js", "src/director/playback.js", @@ -1496,9 +1771,24 @@ "src/ui/toast.js", "src/ui/stores/sceneInteractions.js", "src/ui/stores/dataPacks.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "vue", "pinia", "vue-i18n"] + "external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"] }, "live-observations": { "exports": ["./sources/live"], @@ -1536,32 +1826,68 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", + "src/render/color.js", "src/layers/flights/queries.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/followed.js", "src/layers/flights/rendering.js", + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/render/motion/iconBook.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", + "src/geo/index.js", "src/data/trailContinuity.js", "src/layers/flights/records.js", "src/layers/flights/clockFollow.js", @@ -1590,13 +1916,41 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/quaternion.js", + "src/geo/celestial.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/internals.js", + "src/data/firmsIntensity.js", "src/time/worldClock.js", - "src/time/julian.js", + "src/data/satelliteClassMask.js", "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", "src/layers/flights/placed.js", "src/data/courseFromFixes.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "military-flights": { "exports": ["./layers/military"], @@ -1619,16 +1973,16 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/military/controller.js", "src/layers/military/index.js", @@ -1640,12 +1994,47 @@ "src/sources/live/contract.js", "src/layers/military/lifecycle.js", "src/layers/military/motion.js", + "src/data/renderedFrames.js", "src/layers/military/policy.js", + "src/render/color.js", "src/layers/military/queries.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/geo/index.js", + "src/data/followed.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/render/motion/iconBook.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/modelRecord.js", "src/layers/military/state.js", + "src/data/displayDelay.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", + "src/data/trackedAircraftIcon.js", "src/data/trailContinuity.js", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", @@ -1667,14 +2056,42 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/data/firmsIntensity.js", "src/ui/unitLabels.js", "src/time/worldClock.js", - "src/time/julian.js", + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", "src/layers/flights/placed.js", "src/data/courseFromFixes.js", "src/data/approxDistance.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "aircraft-mechanics": { "exports": ["./aircraft"], @@ -1688,23 +2105,30 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/modelRecord.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/data/entityRecords.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", + "src/geo/vector.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/aircraft/classification.js", "src/layers/aircraft/index.js", - "src/data/inputOwnership.js" + "src/data/inputOwnership.js", + "src/data/firmsIntensity.js", + "src/data/satelliteClassMask.js" ], "external": ["cesium"] }, @@ -1720,6 +2144,7 @@ "src/data/fleetTrailAnchors.js", "src/data/headingDegrees.js", "src/layers/vessels/cards.js", + "src/geo/index.js", "src/layers/vessels/evidence.js", "src/layers/vessels/index.js", "src/layers/vessels/ingestion.js", @@ -1729,12 +2154,27 @@ "src/time/worldClock.js", "src/sources/live/contract.js", "src/layers/vessels/cameraArea.js", + "src/geo/ellipsoid.js", "src/layers/vessels/viewArea.js", "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/geo/vector.js", "src/layers/vessels/rendering.js", + "src/render/camera/poseSignature.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", + "src/data/entityRecords.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/vessels/selection.js", + "src/data/followed.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", "src/layers/vessels/tracking.js", @@ -1744,8 +2184,6 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", - "src/geoDistance.js", "src/data/inputOwnership.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1762,15 +2200,283 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/credits.js", + "src/queries/heights.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/layers/vessels/cockpitSubject.js", + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", "src/layers/vessels/photos.js", "src/data/openVesselPhoto.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] + }, + "render-cesium-plugin": { + "exports": ["./render/cesium/plugin"], + "modules": [ + "src/render/cesium/plugin.js", + "src/render/cesium/appRenderer.js", + "src/render/cesium/renderFailure.js", + "src/share/shareLinkPath.js", + "src/app/errors.js", + "src/render/cesium/applicationViewer.js", + "src/render/rendererOf.js", + "src/globeInView.js", + "src/render/cesium/mapEngine.js", + "src/render/contract/index.js", + "src/render/cesium/freeLookLimit.js", + "src/render/cesium/sceneCommandRelease.js", + "src/render/cesium/ports.js", + "src/render/cesium/creditKeyboard.js", + "src/render/cesium/viewers.js", + "src/render/cesium/input.js", + "src/i18n/index.js", + "src/app/atmosphereCompat.js", + "src/render/cesium/imageryLookAhead.js", + "src/render/cesium/starrySky.js", + "src/geo/ellipsoid.js", + "src/data/followed.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/maps/engine.js", + "src/render/cesium/mapImagery.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/google3d.js", + "src/render/cesium/internals.js", + "src/render/cesium/controlledCamera.js", + "src/render/cesium/common.js", + "src/render/cesium/camera.js", + "src/render/cesium/credits.js", + "src/render/cesium/frame.js", + "src/render/cesium/gpuIcons.js", + "src/render/cesium/effects.js", + "src/render/cesium/globe.js", + "src/render/cesium/query.js", + "src/render/cesium/quality.js", + "src/render/input/wheel.js", + "src/render/input/router.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/draw.js", + "src/i18n/locale.js", + "src/i18n/locales/ar.json", + "src/i18n/locales/es.json", + "src/i18n/locales/de.json", + "src/i18n/locales/fr.json", + "src/i18n/locales/he.json", + "src/i18n/locales/ja.json", + "src/i18n/locales/it.json", + "src/i18n/locales/pt.json", + "src/i18n/locales/sv.json", + "src/i18n/locales/ru.json", + "src/i18n/locales/zh-CN.json", + "src/i18n/locales/zh-Hant.json", + "src/i18n/locales/uk.json", + "src/cockpitOrbital.js", + "src/data/bundledJson.js", + "src/renderGovernor.js", + "src/sky/stars.js", + "src/data/entityRecords.js", + "src/sky/icrf.js", + "src/render/applicationHooks.js", + "src/maps/attribution.js", + "src/maps/globeEngine.js", + "src/maps/terrainRetry.js", + "src/maps/startupRoute.js", + "src/maps/keylessTerrain.js", + "src/render/stub/viewRectangle.js", + "src/render/cesium/follow.js", + "src/time/frameWait.js", + "src/render/cesium/cameraControls.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/creditMarkup.js", + "src/render/cesium/nativeClick.js", + "src/data/iconSegment.js", + "src/data/iconSet.js", + "src/data/iconAtlas.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/heights.js", + "src/render/baseTilesets.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/vectorBase.js", + "src/render/cesium/imagery.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/vectorBase/index.js", + "src/render/cesium/drawHit.js", + "src/geo/polyline.js", + "src/geo/screenCluster.js", + "src/geo/celestial.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/render/cesium/drawFields.js", + "src/render/stub/math.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/zoomOutGuard.js", + "src/geo/index.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/geo/horizon.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/aircraftRecession.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/imageryFrames.js", + "src/render/occlusion/depthProbe.js", + "src/render/vectorBase/style.js", + "src/render/cesium/drawStreamlines.js", + "src/render/vectorBase/expressions.js", + "src/geo/quaternion.js", + "src/geo/geodesic.js", + "src/data/detectionOcclusion.js", + "src/render/vectorBase/paint.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/sky/assets.js" + ], + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] + }, + "render-cesium-unbound": { + "exports": ["./render/cesium/unbound"], + "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", + "src/render/cesium/unbound.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/google3d.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/drawHit.js", + "src/queries/heights.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/celestial.js", + "src/geo/ellipsoid.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/nativeClick.js", + "src/render/input/router.js", + "src/render/input/wheel.js", + "src/render/cesium/input.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/render/cesium/mapImagery.js", + "src/maps/terrainRetry.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/mapEngine.js", + "src/data/bundledJson.js", + "src/renderGovernor.js", + "src/sky/icrf.js", + "src/sky/stars.js", + "src/sky/assets.js", + "src/render/cesium/starrySky.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", + "src/time/frameWait.js" + ], + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "earthquakes": { "exports": ["./layers/earthquakes"], "modules": [ "src/layers/earthquakes/index.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", "src/layers/earthquakes/records.js", @@ -1783,6 +2489,9 @@ "modules": [ "src/i18n/marker.js", "src/layers/recentImagery/index.js", + "src/render/rendererOf.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/layers/recentImagery/source.js", "src/layers/recentImagery/model.js", "src/layers/recentImagery/catalog.js", @@ -1805,7 +2514,11 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", - "src/layers/recentImagery/display.js" + "src/layers/recentImagery/display.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", + "src/maps/keylessTerrain.js" ], "external": ["cesium"] }, @@ -1813,20 +2526,53 @@ "exports": ["./layers/firms"], "modules": [ "src/data/firmsAdapt.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/iconOrientation.js", "src/layers/firms/anchors.js", "src/layers/firms/cards.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/render/rendererOf.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", "src/layers/firms/index.js", "src/layers/firms/ingestion.js", "src/layers/firms/lifecycle.js", "src/layers/firms/model.js", + "src/geo/ellipsoid.js", + "src/geo/rectangle.js", + "src/geo/vector.js", "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", + "src/data/entityRecords.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", @@ -1846,34 +2592,85 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/render/color.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "satellites-layer": { "exports": ["./layers/satellites"], "modules": [ "src/data/satelliteClass.js", - "src/data/satelliteClassMask.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/data/satellitePass.js", "src/sources/tle.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", "src/layers/satellites/interaction.js", + "src/data/followed.js", "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/motion.js", "src/layers/satellites/orbits.js", "src/layers/satellites/records.js", "src/layers/satellites/policy.js", + "src/render/color.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", "src/layers/satellites/state.js", "src/layers/satellites/testing.js", "src/layers/satellites/tracking.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", "src/data/inputOwnership.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1891,35 +2688,108 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/ellipsoid.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", "src/data/bundledJson.js", "src/data/retryableLoad.js", - "src/time/worldClock.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "satellite.js"] + "external": ["cesium", "satellite.js", "kdbush"] }, "launches-layer": { "exports": ["./layers/launches"], "modules": [ "src/cyberSonar.js", "src/layers/launches/camera.js", + "src/geo/sphere.js", + "src/geo/geodesic.js", + "src/layers/launches/geometry.js", "src/layers/launches/controls.js", "src/layers/launches/index.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", "src/layers/launches/ingestion.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", "src/layers/launches/model.js", + "src/render/color.js", + "src/geo/index.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/overlays.js", "src/layers/launches/panel.js", "src/layers/launches/paths.js", "src/layers/launches/policy.js", "src/layers/launches/policyHelpers.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/launches/rendering.js", + "src/geo/horizon.js", "src/layers/launches/replay.js", + "src/data/followed.js", "src/layers/launches/selection.js", "src/layers/launches/source.js", "src/layers/launches/state.js", @@ -1940,24 +2810,79 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "installations-layer": { "exports": ["./layers/installations"], "modules": [ - "src/data/cameraSensitivity.js", "src/data/installationFeedback.js", "src/data/militaryInstallationData.js", "src/data/installationNames.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconAtlas.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/geo/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", "src/layers/installations/model.js", + "src/render/color.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", + "src/geo/sphere.js", + "src/data/followed.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -1978,6 +2903,7 @@ "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/layers/installations/namedMarkers.js", + "src/geo/horizon.js", "src/data/infrastructureOverlayEntry.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1994,9 +2920,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/layers/installations/classLabel.js" + "src/layers/installations/classLabel.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "@mapbox/vector-tile", "pbf"] + "external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"] }, "awareness-layer": { "exports": ["./layers/awareness"], @@ -2008,11 +2950,35 @@ "src/awarenessEcho.js", "src/cockpitMath.js", "src/data/iconOrientation.js", + "src/render/camera/poseSignature.js", "src/data/militaryAwarenessEngine.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", + "src/geo/julian.js", "src/data/installationNames.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", "src/layers/awareness/focus.js", + "src/render/cesium/camera.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/awareness/history.js", "src/layers/awareness/index.js", "src/layers/awareness/ingestion.js", @@ -2026,6 +2992,7 @@ "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", "src/layers/awareness/subject.js", + "src/data/followed.js", "src/layers/awareness/testing.js", "src/ui/panelRailGeometry.js", "src/i18n/index.js", @@ -2043,18 +3010,20 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/layers/awareness/rangeRing.js", "src/data/feedState.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", "src/ui/layerNames.js", - "src/ui/unitLabels.js" + "src/render/cesium/zoomOutGuard.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "traffic-layer": { "exports": ["./layers/traffic"], "modules": [ - "src/data/cameraSensitivity.js", "src/data/flowMatch.js", "src/data/tomtomTiles.js", "src/data/tileBudget.js", @@ -2065,6 +3034,9 @@ "src/data/trafficQueue.js", "src/layers/traffic/animation.js", "src/layers/traffic/controls.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/traffic/flow.js", "src/layers/traffic/flowDecode.js", "src/layers/traffic/flowSource.js", @@ -2073,16 +3045,60 @@ "src/layers/traffic/ingestion.js", "src/sources/requestDeadline.js", "src/layers/traffic/lifecycle.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/google3d.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", "src/layers/traffic/model.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/layers/traffic/policy.js", + "src/render/color.js", "src/layers/traffic/rendering.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", "src/layers/traffic/style.js", "src/layers/traffic/surface.js", + "src/render/cesium/heights.js", "src/layers/traffic/timing.js", "src/layers/traffic/viewport.js", + "src/render/rendererOf.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/aircraftRecession.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/render/motion/iconMotion.js", + "src/data/iconAtlas.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/query.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/sources/overpassRoads.js", "src/sources/capability.js", "src/sources/httpBody.js", @@ -2107,9 +3123,28 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/queries/heights.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/render/input/wheel.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/render/input/router.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/input.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["cesium", "pbf", "@mapbox/vector-tile"] + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "bikeshare-layer": { "exports": ["./layers/bikeshare"], @@ -2118,6 +3153,7 @@ "src/layers/bikeshare/index.js", "src/layers/bikeshare/ingestion.js", "src/layers/bikeshare/lifecycle.js", + "src/render/rendererOf.js", "src/layers/bikeshare/model.js", "src/geoDistance.js", "src/sources/gbfsStations.js", @@ -2125,13 +3161,14 @@ "src/layers/bikeshare/queries.js", "src/layers/bikeshare/registry.js", "src/layers/bikeshare/rendering.js", + "src/geo/ellipsoid.js", "src/layers/bikeshare/selection.js", "src/layers/bikeshare/source.js", "src/layers/bikeshare/state.js", "src/layers/bikeshare/testing.js", "src/layers/bikeshare/viewport.js", + "src/geo/vector.js", "src/data/inputOwnership.js", - "src/data/cameraSensitivity.js", "src/i18n/index.js", "src/i18n/locale.js", "src/i18n/locales/ar.json", @@ -2146,19 +3183,44 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, "cctv-layer": { "exports": ["./layers/cctv"], "modules": [ + "src/render/cesium/google3d.js", + "src/render/cesium/globe.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", "src/data/headingDegrees.js", "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", "src/data/cctvViewshed.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/trackingClickGesture.js", "src/layers/cctv/calibration.js", "src/layers/cctv/cards.js", @@ -2166,23 +3228,68 @@ "src/layers/cctv/controls.js", "src/layers/cctv/frames.js", "src/layers/cctv/geometry.js", + "src/data/entityRecords.js", "src/layers/cctv/geometryQueue.js", + "src/data/followed.js", "src/layers/cctv/ground.js", "src/layers/cctv/headingConfidence.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/geo/frames.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", "src/geoDistance.js", "src/layers/cctv/modelSpecs.js", "src/layers/cctv/navigation.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", "src/layers/cctv/policy.js", + "src/render/color.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/render/motion/iconBook.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", @@ -2205,9 +3312,29 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["hls.js", "cesium"] + "external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "street-level-layer": { "exports": [ @@ -2220,10 +3347,44 @@ ], "modules": [ "src/layers/streetLevel/index.js", + "src/render/cesium/credits.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/geo/index.js", + "src/geo/geodesic.js", "src/layers/streetLevel/credits.js", + "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", "src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/cameraFraming.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/streetLevel/marker.js", "src/layers/streetLevel/view.js", "src/layers/streetLevel/uiState.js", @@ -2235,6 +3396,7 @@ "src/layers/streetLevel/policy.js", "src/layers/streetLevel/state.js", "src/layers/streetLevel/lineCoverage.js", + "src/render/color.js", "src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/providers/mapillary/decode.js", @@ -2281,20 +3443,70 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/layers/streetLevel/providers/mapillary/policy.js", - "src/time/worldClock.js" + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"] + "external": [ + "cesium", + "pbf", + "@mapbox/vector-tile", + "mapillary-js", + "kdbush" + ] }, "alpr-cameras": { "exports": ["./layers/alpr"], "modules": [ "src/data/headingDegrees.js", "src/layers/alpr/index.js", + "src/data/followed.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", + "src/geo/horizon.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", "src/data/displayText.js", @@ -2322,22 +3534,41 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "@mapbox/vector-tile", "pbf"] + "external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"] }, "radio-layer": { "exports": ["./layers/radio"], "modules": [ "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/radioCountry.js", "src/layers/radio/catalogModel.js", "src/layers/radio/categories.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/radio/clustering.js", "src/layers/radio/controls.js", "src/layers/radio/index.js", @@ -2347,11 +3578,50 @@ "src/layers/radio/lifecycle.js", "src/layers/radio/model.js", "src/layers/radio/navigation.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/layers/radio/playback.js", "src/layers/radio/policy.js", "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", + "src/render/color.js", + "src/render/cesium/iconOrientation.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -2374,9 +3644,27 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/internals.js", + "src/data/firmsIntensity.js", + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "submarine-cables": { "exports": ["./layers/submarine-cables"], @@ -2384,11 +3672,39 @@ "src/layers/submarineCables/geometry.js", "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", + "src/geo/index.js", "src/layers/submarineCables/interaction.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/layers/submarineCables/pin.js", + "src/data/entityRecords.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/render/color.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/data/inputOwnership.js", @@ -2406,9 +3722,24 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "bundled-cables": { "exports": ["./sources/bundled-cables"], @@ -2445,15 +3776,65 @@ "modules": [ "src/i18n/marker.js", "src/maps/availability.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/credits.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/maps/imageryComparison.js", "src/maps/credits.js", + "src/render/rendererOf.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/creditMarkup.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/keySetupCore.mjs", "src/localRequestGate.mjs", @@ -2472,9 +3853,33 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/render/cesium/input.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/maps/engine.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["cesium"] + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "voice-connection": { "exports": [ @@ -2537,6 +3942,7 @@ "src/voice/narration.js", "src/voice/earcon.js", "src/voice/pointerContext.js", + "src/render/rendererOf.js", "src/voice/pointerReticle.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -2589,6 +3995,22 @@ "./standalone/catalog" ], "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", + "src/render/cesium/controlledCamera.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", "src/data/fleetModels.js", "src/data/fleetTrailAnchors.js", "src/data/fleetModelInstances.js", @@ -2603,10 +4025,15 @@ "src/hudLayouts.js", "src/hudLayoutPolicy.js", "src/ui/radioPanelPlacement.js", - "src/cyberSonarGpu.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", "src/scenes/nepalEvidencePack.js", "src/data/approxDistance.js", "src/data/bhoteKoshiEvent.js", + "src/render/cesium/heights.js", "src/ui/imagerySplit.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", @@ -2647,22 +4074,54 @@ "src/app/layers/traffic.js", "src/app/operations.js", "src/app/scene.js", - "src/app/zoomOutGuard.js", + "src/render/cesium/sceneCommandRelease.js", + "src/render/cesium/appRenderer.js", + "src/render/cesium/renderFailure.js", + "src/render/cesium/frame.js", + "src/render/creditMarkup.js", + "src/render/rendererOf.js", + "src/render/cesium/ports.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/query.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/quality.js", + "src/render/cesium/credits.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/common.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/contract/index.js", "src/sources/sourceSlot.js", "src/app/sources.js", "src/app/startupChrome.js", "src/app/stateChannel.js", "src/app/surfaceServices.js", "src/app/tools.js", - "src/app/viewer.js", - "src/sky/starrySky.js", + "src/data/followed.js", + "src/render/cesium/applicationViewer.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/starrySky.js", "src/sky/stars.js", "src/app/atmosphereCompat.js", "src/bloom.js", "src/camera.js", "src/cameraGroundGuard.js", "src/cameraVerbs.js", - "src/globeInView.js", "src/cctvFocusPolicy.js", "src/cctvFocusRequest.js", "src/celestialRing.js", @@ -2671,14 +4130,9 @@ "src/cockpitTracking.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", "src/contactsDetectionPolicy.js", "src/contextModePolicy.js", - "src/creditKeyboard.js", + "src/render/cesium/creditKeyboard.js", "src/data/aircraftClass.js", "src/data/aircraftEmergency.js", "src/data/aircraftIcons.js", @@ -2715,19 +4169,19 @@ "src/layers/wind/source.js", "src/sources/windBody.js", "src/data/detection.js", + "src/render/cesium/iconOrientation.js", "src/data/detectionCohort.js", "src/data/detectionDraw.js", "src/data/detectionPolicy.js", "src/data/detectionOcclusion.js", "src/data/detectionPresentation.js", "src/data/detectionRenderDemand.js", - "src/data/sceneOcclusionProbe.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", "src/data/earthquakes.js", "src/data/fireAnchors.js", "src/data/firmsAdapt.js", "src/data/firmsHeatmap.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/flights.js", "src/data/flowMatch.js", @@ -2736,17 +4190,19 @@ "src/data/groundFloor.js", "src/data/groundSnap.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", "src/data/installationFeedback.js", "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/lifecycle.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", @@ -2791,7 +4247,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/traffic.js", @@ -2821,6 +4276,7 @@ "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -2866,6 +4322,8 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", @@ -2892,13 +4350,13 @@ "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/clockFollow.js", @@ -2908,13 +4366,18 @@ "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", @@ -2953,6 +4416,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -2972,6 +4436,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -2979,7 +4444,6 @@ "src/layers/radio/tuningNoise.js", "src/layers/radio/volume.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", @@ -3001,10 +4465,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -3038,6 +4505,8 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -3056,10 +4525,12 @@ "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/navigationPolicy.js", "src/orbit.js", @@ -3109,7 +4580,6 @@ "src/ui/applicationShell.js", "src/ui/railEdgeScroll.js", "src/ui/mobileShell.js", - "src/exclusiveSurfaces.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", "src/ui/locationNavigation.js", @@ -3123,7 +4593,6 @@ "src/ui/cctvFrames.js", "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", - "src/ui/quebecCctvOverlay.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", @@ -3133,15 +4602,6 @@ "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/data/placeBelow.js", - "src/ui/placePacksLoading.js", - "src/ui/ownerFlag.js", - "src/ui/ownerFlagSheet.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", @@ -3167,7 +4627,6 @@ "src/ui/displayControls.js", "src/ui/effects.js", "src/ui/frameRateMonitor.js", - "src/ui/renderFailure.js", "src/ui/layerPanel.js", "src/ui/weatherPanel.js", "src/ui/railCards.js", @@ -3216,6 +4675,7 @@ "src/ui/surfaceKeyboard.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", @@ -3265,17 +4725,17 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", "src/data/inputOwnership.js", "src/annotations/drawMarks.js", "src/annotations/drawMode.js", "src/annotations/drawTool.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", + "src/data/geoImportShared.js", "src/ui/flyToDataSource.js", "src/ui/geoFileImport.js", "src/data/routeSteps.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", "src/layers/directions/source.js", "src/data/directions.js", "src/app/layers/directions.js", @@ -3295,12 +4755,14 @@ "src/layers/earthquakes/records.js", "src/app/layers/perimeters.js", "src/layers/perimeters/index.js", + "src/render/color.js", "src/layers/perimeters/source.js", "src/layers/perimeters/records.js", "src/layers/perimeters/cards.js", "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -3360,7 +4822,6 @@ "src/data/railTimeZones.js", "src/data/transit.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/layers/transit/controls.js", @@ -3376,7 +4837,6 @@ "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/transitProxy.js", @@ -3448,6 +4908,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -3752,7 +5213,6 @@ "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", - "src/ui/stores/sceneSharing.js", "src/ui/stores/voice.js", "src/ui/stores/location.js", "src/ui/stores/display.js", @@ -3785,9 +5245,6 @@ "src/ui/stores/globeActions.js", "src/ui/stores/recording.js", "src/ui/i18n.js", - "src/time/viewerClock.js", - "src/time/worldClock.js", - "src/time/julian.js", "src/annotations/outlineRungs.js", "src/sources/openFreeMapOutlines.js", "src/sources/nominatimOutlines.js", @@ -3796,6 +5253,26 @@ "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/pickMemo.js", + "src/maps/startupRoute.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js", + "src/sky/icrf.js", + "src/sky/assets.js", + "src/app/panelRendering.js", + "src/render/cesium/application.js", "src/sources/osmFeatures.js", "src/voice/imageryActions.js", "src/voice/layerActionOwnership.js", @@ -3809,6 +5286,15 @@ "src/layers/osmPlaces/index.js", "src/app/layers/osmPlaces.js", "src/voice/areaActions.js", + "src/render/cesium/zoomOutGuard.js", + "src/layers/awareness/rangeRing.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/data/rioRouteNames.js", + "src/globeInView.js", + "src/app/globeInViewRecovery.js", + "src/render/cesium/freeLookLimit.js", "src/app/layers/wildlifeSightings.js", "src/layers/wildlifeSightings/cards.js", "src/layers/wildlifeSightings/controls.js", @@ -3834,14 +5320,49 @@ "src/overlays/worldOverlayChrome.js", "src/layers/wildlifeSightings/photoText.js", "src/layers/wildlifeSightings/performance.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/layers/wildlifeSightings/view.js", + "src/ui/quebecCctvOverlay.js", + "src/time/viewerClock.js", + "src/time/worldClock.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/data/placeBelow.js", + "src/ui/placePacksLoading.js", + "src/ui/ownerFlag.js", + "src/ui/ownerFlagSheet.js", + "src/layers/vessels/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", + "src/render/cesium/imageryLookAhead.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/ui/creditsView.js", "src/data/planespottersPhoto.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", "src/ui/stores/dataLibrary.js", "src/data/openVesselPhoto.js", "src/layers/vessels/photos.js", + "src/viewSky.js", + "src/render/weather.js", "src/layers/flights/placed.js", "src/data/placementProvider.js", "src/data/courseFromFixes.js", @@ -3862,7 +5383,8 @@ "h3-js", "vue", "pinia", - "vue-i18n" + "vue-i18n", + "kdbush" ] }, "application-catalog": { @@ -3873,6 +5395,17 @@ "application-layer-construction": { "exports": ["./application/layers"], "modules": [ + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/geo/julian.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", "src/data/fleetModels.js", "src/data/fleetTrailAnchors.js", "src/data/fleetModelInstances.js", @@ -3890,6 +5423,25 @@ "src/maps/imageryComparison.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", "src/data/bhoteKoshiIncidentPlaces.js", "src/data/bhoteKoshiFloodPath.js", "src/data/bhoteKoshiShotPaths.js", @@ -3950,13 +5502,13 @@ "src/data/detectionDraw.js", "src/data/detectionPolicy.js", "src/data/firmsAdapt.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/flowMatch.js", "src/data/focusDeemphasis.js", "src/data/geoid.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", "src/data/installationFeedback.js", @@ -3964,9 +5516,9 @@ "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", @@ -3996,7 +5548,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/trafficBounds.js", @@ -4010,11 +5561,13 @@ "src/keylessGeocoder.js", "src/layers/aircraft/classification.js", "src/layers/alpr/index.js", + "src/data/followed.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -4060,6 +5613,8 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", @@ -4070,6 +5625,7 @@ "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/render/cesium/iconOrientation.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", @@ -4086,13 +5642,13 @@ "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/clockFollow.js", @@ -4103,13 +5659,18 @@ "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", @@ -4148,6 +5709,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -4167,6 +5729,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -4174,7 +5737,6 @@ "src/layers/radio/tuningNoise.js", "src/layers/radio/volume.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", @@ -4195,10 +5757,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -4232,11 +5797,17 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", "src/layers/vessels/tracking.js", "src/locations.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/cesium/common.js", "src/cityPois.js", "src/navigationPolicy.js", "src/overlays/worldOverlay.js", @@ -4254,6 +5825,13 @@ "src/ui/panelRailGeometry.js", "src/ui/radioTunerModel.js", "src/worldFocus.js", + "src/geo/index.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", @@ -4264,18 +5842,13 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", "src/data/inputOwnership.js", "src/annotations/worldAnnotationRenderer.js", "src/cameraGroundGuard.js", "src/cameraVerbs.js", - "src/globeInView.js", - "src/scopeMaskPolicy.js", - "src/scopeMask.js", "src/services/groundFloor.js", "src/data/routeSteps.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", "src/layers/directions/source.js", "src/services/terrainHeights.js", "src/data/terrainHeights.js", @@ -4293,12 +5866,14 @@ "src/layers/earthquakes/records.js", "src/app/layers/perimeters.js", "src/layers/perimeters/index.js", + "src/render/color.js", "src/layers/perimeters/source.js", "src/layers/perimeters/records.js", "src/layers/perimeters/cards.js", "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -4358,7 +5933,6 @@ "src/data/railSchedule.js", "src/data/railTimeZones.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/layers/transit/controls.js", @@ -4374,7 +5948,6 @@ "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/transitProxy.js", @@ -4401,6 +5974,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -4422,7 +5996,8 @@ "src/data/detectionRenderDemand.js", "src/data/detectionPresentation.js", "src/data/detectionOcclusion.js", - "src/data/sceneOcclusionProbe.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", "src/data/modelEligibility.js", "src/app/layers/recentImagery.js", "src/layers/recentImagery/index.js", @@ -4430,15 +6005,19 @@ "src/layers/recentImagery/model.js", "src/layers/recentImagery/catalog.js", "src/layers/recentImagery/rendering.js", + "src/render/baseTilesets.js", + "src/render/cesium/globe.js", "src/layers/recentImagery/thumbnails.js", "src/maps/imageryHost.js", "src/layers/streetLevel/index.js", + "src/render/cesium/credits.js", "src/layers/streetLevel/uiState.js", "src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/params.js", "src/layers/streetLevel/registry.js", "scripts/qa-street-level.mjs", "src/layers/streetLevel/credits.js", + "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", "src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/cameraFraming.js", @@ -4519,7 +6098,9 @@ "src/layers/streetLevel/providers/mapillary/policy.js", "src/data/geoImportImages.js", "src/data/geoImportPins.js", + "src/data/geoImportShared.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", "src/ui/stores/imagerySplit.js", "src/ui/vueRuntime.js", "src/ui/stores/windInspection.js", @@ -4527,8 +6108,6 @@ "src/ui/stores/bhoteKoshiPanel.js", "src/hudReadouts.js", "src/ui/i18n.js", - "src/time/worldClock.js", - "src/time/julian.js", "src/annotations/outlineRungs.js", "src/sources/openFreeMapOutlines.js", "src/sources/nominatimOutlines.js", @@ -4537,9 +6116,34 @@ "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", "src/layers/osmPlaces/model.js", "src/layers/osmPlaces/index.js", "src/app/layers/osmPlaces.js", + "src/layers/awareness/rangeRing.js", + "src/data/feedState.js", + "src/loadingFeedback.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/data/rioRouteNames.js", + "src/globeInView.js", + "src/scopeMaskPolicy.js", + "src/scopeMask.js", "src/app/layers/wildlifeSightings.js", "src/layers/wildlifeSightings/cards.js", "src/layers/wildlifeSightings/controls.js", @@ -4563,11 +6167,28 @@ "src/overlays/worldOverlayChrome.js", "src/layers/wildlifeSightings/photoText.js", "src/layers/wildlifeSightings/performance.js", + "src/layers/wildlifeSightings/view.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", + "src/layers/vessels/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", "src/layers/vessels/photos.js", "src/data/openVesselPhoto.js", "src/layers/flights/placed.js", @@ -4588,7 +6209,8 @@ "h3-js", "vue", "pinia", - "vue-i18n" + "vue-i18n", + "kdbush" ] }, "application-operations": { @@ -4618,8 +6240,49 @@ "src/keylessGeocoder.js", "src/layers/firms/anchors.js", "src/locations.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/cityPois.js", "src/cameraGroundGuard.js", + "src/data/followed.js", "src/search/alpsGeocoder.js", "src/search/defaults.js", "src/search/geospatial.js", @@ -4665,7 +6328,21 @@ "src/data/placeBoundaries.js", "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", - "src/data/local_data/wof_neighborhoods/files.js" + "src/data/local_data/wof_neighborhoods/files.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/data/pickRegistry.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/input.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], "external": [ "cesium", @@ -4673,9 +6350,40 @@ "satellite.js", "@mapbox/vector-tile", "pbf", - "mgrs" + "mgrs", + "kdbush" ] }, + "entity-records": { + "exports": ["./data/entity-records"], + "modules": ["src/data/entityRecords.js"], + "external": [] + }, + "input": { + "exports": ["./input"], + "modules": [ + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/render/rendererOf.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" + ], + "external": ["cesium"] + }, "layer-lifecycle": { "exports": ["./data/lifecycle"], "modules": [ @@ -4689,7 +6397,32 @@ "exports": ["./ui/navigation"], "modules": [ "src/navigationPolicy.js", + "src/geo/index.js", "src/ui/navigationController.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/followed.js", "src/app/stateChannel.js", "src/data/cameraArrival.js", "src/i18n/locale.js", @@ -4706,9 +6439,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/i18n/index.js" + "src/i18n/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/data/entityRecords.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "ui-share-restoration": { "exports": ["./ui/share-restoration"], @@ -4716,15 +6465,14 @@ "src/i18n/marker.js", "src/data/installationFeedback.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/loadingFeedback.js", "src/navigationPolicy.js", "src/share/follow.js", "src/ui/shareRestoration.js", + "src/data/followed.js", "src/ui/uiLifetime.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -4741,7 +6489,11 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/data/entityRecords.js", + "src/render/rendererOf.js", + "src/data/firmsIntensity.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js" ], "external": [] }, @@ -4754,14 +6506,6 @@ "src/ui/radioPanelPlacement.js", "src/bloom.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/cockpitOrbitalSatellites.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/contactsDetectionPolicy.js", "src/data/detectionPolicy.js", "src/styles/anime.js", @@ -4775,9 +6519,11 @@ "src/ui/rail/rangeValue.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", + "src/render/rendererOf.js", "src/ui/stores/display.js", "src/ui/stores/owners.js", "src/ui/vueRuntime.js", @@ -4802,7 +6548,15 @@ "src/visualStylePolicy.js", "src/ui/rail/fieldValue.js", "src/ui/kit/UiSlider.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/cockpitOrbitalSatellites.js", + "src/geoDistance.js", + "src/data/motionModel.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -4934,7 +6688,10 @@ "src/data/distanceFormat.js", "src/i18n/marker.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", + "src/render/color.js", "src/layers/directions/source.js", "src/data/routeSteps.js", "src/i18n/index.js", @@ -4952,7 +6709,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -5263,10 +7038,45 @@ "src/data/headingDegrees.js", "src/cyberSonar.js", "src/celestialRing.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/data/approxDistance.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", + "src/render/color.js", "src/data/dataCredits.js", "src/data/detectionCohort.js", "src/data/detectionPolicy.js", @@ -5275,6 +7085,8 @@ "src/data/gtfsRealtime.js", "src/geoDistance.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/labelArbiter.js", "src/data/meshFloorSampler.js", @@ -5283,8 +7095,9 @@ "src/data/spriteOrder.js", "src/data/terrainHeights.js", "src/data/transit.js", + "src/geo/index.js", + "src/geo/geodesic.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/data/transitProxy.js", @@ -5299,11 +7112,14 @@ "src/layers/transit/qaMetrics.js", "src/layers/transit/queries.js", "src/layers/transit/rendering.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/trails.js", "src/layers/transit/viewport.js", + "src/geo/rectangle.js", "src/overlays/worldOverlay.js", "src/overlays/worldOverlayDraw.js", "src/overlays/worldOverlayTokens.js", @@ -5336,10 +7152,29 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/data/rioRouteNames.js", + "src/overlays/worldOverlayChrome.js", "src/time/worldClock.js", - "src/overlays/worldOverlayChrome.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "egm96-universal", "pbf"] + "external": ["cesium", "egm96-universal", "pbf", "kdbush"] }, "transit-layer": { "exports": ["./layers/transit"], @@ -5354,9 +7189,10 @@ "src/data/modelEligibility.js", "src/data/headingDegrees.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/geoDistance.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", @@ -5369,16 +7205,52 @@ "src/layers/transit/policy.js", "src/layers/transit/queries.js", "src/layers/transit/rendering.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", + "src/geo/rectangle.js", + "src/render/rendererOf.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/frame.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", + "src/render/color.js", "src/data/transitProxy.js", "src/data/gtfsRealtime.js", "src/layers/transit/trails.js", + "src/geo/ellipsoid.js", "src/layers/transit/movement.js", "src/layers/transit/qaMetrics.js", "src/layers/transit/qaMetrics.test.mjs", @@ -5402,9 +7274,34 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/geo/vector.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/data/rioRouteNames.js", + "src/time/worldClock.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "pbf"] + "external": ["cesium", "pbf", "kdbush"] }, "transit-source-factory": { "exports": ["./layers/transit/source"], @@ -5503,6 +7400,10 @@ "exports": ["./layers/perimeters"], "modules": [ "src/layers/perimeters/index.js", + "src/render/color.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/layers/perimeters/source.js", @@ -5523,7 +7424,25 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/inputOwnership.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -5531,6 +7450,11 @@ "exports": ["./layers/gnss"], "modules": [ "src/layers/gnss/index.js", + "src/render/color.js", + "src/geo/rectangle.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/layers/gnss/source.js", @@ -5600,12 +7524,17 @@ "exports": ["./layers/ghostmaps"], "modules": [ "src/layers/ghostMaps/index.js", + "src/render/color.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/ghostMaps/catalog.js", "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/source.js", "src/sources/httpBody.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", + "src/data/geoImportShared.js", "src/i18n/marker.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -5624,10 +7553,66 @@ "src/i18n/locales/zh-Hant.json", "src/data/geoImportImages.js", "src/data/geoImportPins.js", + "src/data/geojsonPins.js", + "src/geo/sphere.js", + "src/data/followed.js", "src/layers/streetLevel/tileMath.js", - "src/layers/streetLevel/view.js" + "src/layers/streetLevel/view.js", + "src/geo/ellipsoid.js", + "src/geo/horizon.js", + "src/geo/vector.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/rendererOf.js", + "src/data/entityRecords.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "ghostmaps-source": { "exports": ["./layers/ghostmaps/source"], @@ -5683,7 +7668,17 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/render/color.js", + "src/input/dispatcher.js", + "src/geo/vector.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js" ], "external": ["cesium"] }, @@ -5717,18 +7712,16 @@ "src/tools/queries/brief.js", "src/tools/queries/maritime.js", "src/tools/queries/share.js", - "src/data/firmsIntensity.js", - "src/data/firmsAdapt.js", "src/data/idSwitches.js", "src/data/vesselTypes.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/sources/gbfsStations.js", "src/sources/tle.js", "src/data/satellitePass.js", "src/tools/queries/atmosphere.js", "src/layers/wind/inspection.js", + "src/geo/ellipsoid.js", "src/layers/wind/model.js", "src/layers/wind/fields.js", "src/i18n/marker.js", @@ -5742,7 +7735,6 @@ "src/tools/surfaces.js", "src/layers/transit/policy.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/layers/transit/movement.js", "src/data/contactPlayback.js", "src/data/layerSnapshot.js", @@ -5754,7 +7746,12 @@ "src/tools/globePanel.js", "src/tools/queries/panelRequest.js", "src/geoDistance.js", - "src/visualStylePolicy.js" + "src/visualStylePolicy.js", + "src/geo/vector.js", + "src/data/firmsIntensity.js", + "src/data/firmsAdapt.js", + "src/data/rioRouteNames.js", + "src/data/satelliteClassMask.js" ], "external": ["satellite.js"] }, @@ -5875,6 +7872,10 @@ "exports": ["./layers/air-quality"], "modules": [ "src/layers/airQuality/index.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", + "src/render/color.js", "src/layers/airQuality/model.js", "src/layers/airQuality/source.js", "src/sources/httpBody.js", @@ -5912,15 +7913,130 @@ "agent-world-packet": { "exports": ["./agent/world-packet"], "modules": [ + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/agent/worldPacket.js", "src/data/layerSnapshot.js", "src/data/feedState.js", "src/contextModePolicy.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", - "src/i18n/marker.js" + "src/i18n/marker.js", + "src/render/rendererOf.js" ], - "external": ["cesium"] + "external": [] + }, + "heights": { + "exports": ["./queries/heights"], + "modules": [ + "src/queries/heights.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js" + ], + "external": [] + }, + "geo": { + "exports": ["./geo"], + "modules": [ + "src/geo/index.js", + "src/geo/horizon.js", + "src/geo/geodesic.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js" + ], + "external": [] + }, + "sky": { + "exports": ["./sky"], + "modules": [ + "src/sky/index.js", + "src/sky/assets.js", + "src/sky/stars.js", + "src/sky/icrf.js" + ], + "external": [] + }, + "render": { + "exports": [ + "./render/contract", + "./render/stub", + "./render/occlusion", + "./render/camera/events", + "./render/camera/followTransition", + "./render/conformance", + "./render/input/router", + "./render/stub/camera", + "./render/stub/viewRectangle", + "./render/stub/harness", + "./render/motion", + "./render/vectorBase", + "./render/iconSegment", + "./render/recession", + "./render/windStreamlines", + "./geo/screenCluster" + ], + "modules": [ + "src/render/contract/index.js", + "src/render/stub/index.js", + "src/geo/screenCluster.js", + "src/render/occlusion/index.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/color.js", + "src/geo/polyline.js", + "src/render/motion/iconMotion.js", + "src/geo/horizon.js", + "src/render/conformance/index.js", + "src/render/conformance/scenes.js", + "src/render/conformance/cameraScripts.js", + "src/render/conformance/visual.js", + "src/render/conformance/cameraRunner.js", + "src/render/input/wheel.js", + "src/render/conformance/expect.js", + "src/render/conformance/checks/ports.js", + "src/render/stub/math.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/render/stub/camera.js", + "src/geo/geodesic.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/stub/viewRectangle.js", + "src/render/input/router.js", + "src/render/conformance/goldens/camera.json", + "src/render/conformance/checks/camera.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", + "src/render/vectorBase/encode.js", + "src/render/weather.js", + "src/render/stub/harness.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/recession.js" + ], + "external": ["pbf", "@mapbox/vector-tile", "kdbush"] }, "wildlife-sightings": { "exports": ["./layers/wildlife-sightings"], @@ -5967,7 +8083,22 @@ "src/layers/wildlifeSightings/billboardModel.js", "src/layers/wildlifeSightings/sprites.js", "src/layers/wildlifeSightings/photoText.js", - "src/layers/wildlifeSightings/performance.js" + "src/layers/wildlifeSightings/performance.js", + "src/geo/horizon.js", + "src/render/rendererOf.js", + "src/input/dispatcher.js", + "src/geo/ellipsoid.js", + "src/layers/wildlifeSightings/view.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/render/color.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/geo/vector.js", + "src/data/spriteOrder.js", + "src/styles/styleStages.js", + "src/render/creditMarkup.js" ], "external": ["cesium"] }, diff --git a/scripts/qa-admin-outlines.mjs b/scripts/qa-admin-outlines.mjs index 114daacadf..97fd10c6bb 100644 --- a/scripts/qa-admin-outlines.mjs +++ b/scripts/qa-admin-outlines.mjs @@ -12,10 +12,11 @@ * and finally Brandenburg (Berlin is a hole) and Hawaii (eight islands). * * Asserts for every outline: it resolves from the bundled packs (no geocode, - * boundary or Overpass request), is drawn as a draped outline within the - * budget, and holds still — no rebuilt primitives and no new entities while - * the camera is still. The whole journey must log zero console/page errors and - * send zero requests to any Overpass host or nominatim.openstreetmap.org. + * boundary or Overpass request), shows its first frame within the budget, + * has its draped fill and outline built (their time is reported), and holds + * still — none of its primitives rebuilt while the camera is still. The whole + * journey must log zero console/page errors and send zero requests to any + * Overpass host or nominatim.openstreetmap.org. * * Evidence in qa-shots/ (gitignored): admin-outlines-.png screenshots, * admin-outlines-journey.mp4 (CDP screencast at ~24 fps, frames re-timed from @@ -210,56 +211,84 @@ try { requestAnimationFrame(step); }); }, - annotationSource() { - for (let i = 0; i < viewer.dataSources.length; i++) { - const source = viewer.dataSources.get(i); - if (source.name === 'gev-annotations') return source; - } - return null; - }, - groundPrimitives() { + /** + * The annotations' primitives in the scene, each with the marks its + * instances draw (their pick ids carry `meta.annotation`); only those + * of `mark` when given. + */ + annotationPrimitives(mark) { + const marksOf = (primitive) => { + let inner = primitive; + for (let depth = 0; inner && depth < 4; depth++) { + if (Array.isArray(inner._instanceIds)) + return inner._instanceIds + .map((id) => id?.meta?.annotation) + .filter((id) => id !== undefined); + inner = inner._primitive; + } + return []; + }; const list = []; const walk = (collection) => { for (let i = 0; i < collection.length; i++) { const item = collection.get(i); if (item?.length !== undefined && typeof item.get === 'function') walk(item); - else list.push(item); + else { + const marks = marksOf(item); + if (marks.length && (mark === undefined || marks.includes(mark))) + list.push(item); + } } }; - walk(viewer.scene.groundPrimitives); + walk(viewer.scene.primitives); return list; }, - snapshot() { - const source = this.annotationSource(); - const entities = source ? source.entities.values : []; - const primitives = this.groundPrimitives(); + /** What `mark` draws (every annotation's, without one). */ + snapshot(mark) { + const primitives = this.annotationPrimitives(mark); window.__qaPrimitiveIds ??= new WeakMap(); let next = window.__qaPrimitiveNext ?? 1; - const ids = primitives.map((primitive) => { - if (!window.__qaPrimitiveIds.has(primitive)) - window.__qaPrimitiveIds.set(primitive, next++); - return window.__qaPrimitiveIds.get(primitive); - }); + // By identity only: hosts may trade places without a rebuild. + const ids = primitives + .map((primitive) => { + if (!window.__qaPrimitiveIds.has(primitive)) + window.__qaPrimitiveIds.set(primitive, next++); + return window.__qaPrimitiveIds.get(primitive); + }) + .sort((a, b) => a - b); window.__qaPrimitiveNext = next; return { - entities: entities.length, - polygons: entities.filter((e) => e.polygon).length, - polylines: entities.filter((e) => e.polyline).length, + primitives: primitives.length, + fills: primitives.filter((p) => p instanceof Cesium.GroundPrimitive) + .length, + lines: primitives.filter( + (p) => p instanceof Cesium.GroundPolylinePrimitive, + ).length, + // Draped on terrain and tiles alike. draped: - entities.every( - (e) => - !e.polygon || - e.polygon.classificationType?.getValue() === - Cesium.ClassificationType.BOTH, - ) && - entities.every( - (e) => !e.polyline || e.polyline.clampToGround?.getValue(), + primitives.length > 0 && + primitives.every( + (p) => p.classificationType === Cesium.ClassificationType.BOTH, ), primitiveIds: ids, - ready: viewer.dataSourceDisplay.ready, + ready: primitives.every((p) => p.ready), }; }, + /** The annotations drawn under the middle of the view. */ + marksAtCentre() { + const { canvas } = viewer.scene; + const centre = new Cesium.Cartesian2( + canvas.clientWidth / 2, + canvas.clientHeight / 2, + ); + const marks = new Set(); + for (const hit of viewer.scene.drillPick(centre, 16)) { + const mark = hit?.id?.meta?.annotation; + if (mark !== undefined) marks.add(mark); + } + return [...marks]; + }, }; }); @@ -313,17 +342,31 @@ try { { flyTo }, ); const resolvedMs = performance.now() - started; - // "Drawn" = the first rendered frame after the entity visualizers have - // built the mark's primitives (each tick updates them before render). + // "Drawn" = the first rendered frame after the mark is drawn (as + // before, when it was the entities' first frame); "ready" = the first + // with its primitives all built, which may wait on Cesium's workers. const { viewer } = window.__godsEyeView; + const markId = response.ids?.[0]; + let drawnMs = null; + let readyMs = null; await new Promise((resolve) => { - const off = viewer.scene.postRender.addEventListener(() => { - if (!viewer.dataSourceDisplay.ready) return; + const giveUp = setTimeout(done, 15_000); + function done() { + clearTimeout(giveUp); off(); resolve(); + } + const off = viewer.scene.postRender.addEventListener(() => { + const now = performance.now() - started; + drawnMs ??= now; + const drawn = window.__qaOutlines.annotationPrimitives(markId); + if (drawn.length && drawn.every((p) => p.ready)) { + readyMs = now; + done(); + } }); + viewer.scene.requestRender(); }); - const drawnMs = performance.now() - started; const mark = window.__godsEyeView.annotations .list() .find((m) => m.id === response.ids?.[0]); @@ -331,6 +374,7 @@ try { response: response.results?.[0] ?? null, resolvedMs, drawnMs, + readyMs, parts: mark?.polygons?.length ?? (mark?.ring ? 1 : 0), holes: (mark?.polygons ?? []).reduce( (n, part) => n + part.length - 1, @@ -338,6 +382,7 @@ try { ), ringVertices: mark?.ring?.length ?? 0, pending: Boolean(mark?.pendingOutline), + markId, }; }, target, @@ -347,23 +392,29 @@ try { await settle(); // Hold still: the drawn mark must not rebuild or grow. marker = `still:${name}`; - const before = await page.evaluate(() => window.__qaOutlines.snapshot()); + const before = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const stillStart = frames.length; const times = await page.evaluate( (ms) => window.__qaOutlines.frameTimes(ms), STILL_MS, ); - const after = await page.evaluate(() => window.__qaOutlines.snapshot()); + const after = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const step = { step: `outline:${name}`, target, ...timing, - entities: after.entities, - polygons: after.polygons, - polylines: after.polylines, + primitives: after.primitives, + fills: after.fills, + lines: after.lines, draped: after.draped, stableWhileStill: - before.entities === after.entities && + after.primitives > 0 && JSON.stringify(before.primitiveIds) === JSON.stringify(after.primitiveIds), stillFrameTimes: stats(times), @@ -375,6 +426,7 @@ try { result.steps.push(step); console.log( `${name}: resolved ${timing.resolvedMs.toFixed(0)} ms, drawn ${timing.drawnMs.toFixed(0)} ms, ` + + `ready ${timing.readyMs?.toFixed(0)} ms, ` + `${timing.parts} part(s), ${timing.holes} hole(s), via ${timing.response?.resolvedVia}; ` + `still p50/p95 ${step.stillFrameTimes.p50}/${step.stillFrameTimes.p95} ms; ` + `stable=${step.stableWhileStill}`, @@ -387,6 +439,11 @@ try { timing.drawnMs < OUTLINE_BUDGET_MS, `${name}: drawn in ${timing.drawnMs} ms`, ); + assert.notEqual(timing.readyMs, null, `${name}: its primitives built`); + assert.ok( + step.fills > 0 && step.lines > 0, + `${name}: drawn as a fill and an outline`, + ); assert.equal(step.draped, true, `${name}: draped on terrain/tiles`); assert.equal(step.stableWhileStill, true, `${name}: no redraw when still`); assert.deepEqual(step.lookups, [], `${name}: no network lookups`); @@ -512,8 +569,15 @@ try { await move(name, { lat, lon, height, pitch: -90 }, 1); await outline(name, target); await shot(name); - const rendered = await page.evaluate(() => window.__qaOutlines.snapshot()); - assert.ok(rendered.polygons > 0, `${target} polygon renders`); + const rendered = await page.evaluate(() => ({ + marks: window.__godsEyeView.annotations.list().map((m) => m.id), + atCentre: window.__qaOutlines.marksAtCentre(), + })); + assert.ok( + rendered.marks.length === 1 && + rendered.atCentre.includes(rendered.marks[0]), + `${target} polygon renders`, + ); } if (recordVideo) { @@ -632,6 +696,7 @@ console.table( step: s.step, resolvedMs: s.resolvedMs?.toFixed(0), drawnMs: s.drawnMs?.toFixed(0), + readyMs: s.readyMs?.toFixed(0), parts: s.parts, stable: s.stableWhileStill, p50: (s.stillFrameTimes || s.frameTimes)?.p50, diff --git a/scripts/qa-anime-sky.mjs b/scripts/qa-anime-sky.mjs index a0a0c99350..040ba76f85 100644 --- a/scripts/qa-anime-sky.mjs +++ b/scripts/qa-anime-sky.mjs @@ -127,7 +127,7 @@ try { let animeOn = false; for (let i = 0; i < s.postProcessStages.length; i++) { const stage = s.postProcessStages.get(i); - if (stage.name === 'godsEyeView_anime') + if (stage.name === 'effects_style_anime') animeOn = stage.enabled && stage.uniforms.intensity > 0.99; } return { diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index 88e0a5a2c4..84eb09f6c1 100644 --- a/scripts/qa-cctv-v2.mjs +++ b/scripts/qa-cctv-v2.mjs @@ -263,32 +263,30 @@ function installRenderFramesHelper(page) { // In-page helper (stringified and re-defined inside each evaluate that needs // it, since functions can't cross the puppeteer boundary): serializes the -// 5 frustum polylines + plane position/orientation/dimensions for a camera -// into plain arrays of numbers, using only the camera's own clock time (no -// Cesium namespace needed — Property.getValue just needs *a* JulianDate, -// and the viewer's own clock.currentTime is a valid live instance of one). +// 5 frustum lines + plane position/orientation/dimensions for a camera +// into plain arrays of numbers, from what the layer reports it draws. const SERIALIZE_GEOM_SRC = ` function serializeGeom(camId) { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap']; const poly = {}; for (const role of roles) { - const ent = viewer.entities.getById('cctv-' + camId + '-' + role); - poly[role] = ent && ent.polyline - ? ent.polyline.positions.getValue(time).map((p) => [p.x, p.y, p.z]) + const line = drawn.coverage['cctv-' + camId + '-' + role]; + poly[role] = line?.positions + ? line.positions.map((p) => [p.x, p.y, p.z]) : null; } - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); + const quad = drawn.planes['cctv-' + camId + '-plane']; let plane = null; - if (planeEnt) { - const pos = planeEnt.position.getValue(time); - const orient = planeEnt.orientation.getValue(time); - const dims = planeEnt.plane.dimensions.getValue(time); + if (quad) { + const pos = quad.center; + const orient = quad.orientation; plane = { position: [pos.x, pos.y, pos.z], orientation: [orient.x, orient.y, orient.z, orient.w], - dimensions: [dims.x, dims.y], + dimensions: [quad.size[0], quad.size[1]], }; } return { poly, plane }; @@ -695,10 +693,9 @@ async function main() { const camera = dataManager.layers .get('cctv') .module.getUIState().activeCamera; - const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`); - const mount = ray?.polyline?.positions.getValue( - viewer.clock.currentTime, - )?.[0]; + const ray = dataManager.layers.get('cctv').module._cctvDrawnForTest() + .coverage[`cctv-${camera.id}-ray-tl`]; + const mount = ray?.positions?.[0]; const height = mount && viewer.scene.globe.ellipsoid.cartesianToCartographic(mount) @@ -849,8 +846,10 @@ async function main() { // source. Assert the migrated surface via the host diagnostics. const diag = window.__gevWorldOverlay?.getDiagnostics?.(); g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - g.planeShow = planeEnt ? planeEnt.show : null; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + g.planeShow = quad ? quad.show : null; return g; })(${JSON.stringify(activeId)})`); @@ -1212,26 +1211,22 @@ async function main() { console.log( 'Checking frame-loop health (placeholder -> frame swap, URL family)...', ); - // The plane's material.image is always defined (placeholder canvas from - // the moment the runtime is created, real frame content painted onto the + // The plane's image is always defined (placeholder canvas from the + // moment the runtime is created, real frame content painted onto the // same canvas/video reference once the fetch resolves) — assert it's // never null/undefined once the runtime exists, i.e. there's no gap where // the plane shows nothing. const materialInfo = await page.evaluate((camId) => { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - const mat = planeEnt?.plane?.material; - const image = mat?.image; - const resolved = - image && typeof image.getValue === 'function' - ? image.getValue(time) - : image; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + const source = quad?.source; + const resolved = source?.video || source?.canvas || source?.image; return { - hasMaterial: !!mat, + hasMaterial: !!source, hasImage: !!resolved, tagName: resolved?.tagName || null, - show: planeEnt?.show, + show: quad?.show, }; }, activeId); record( @@ -1665,14 +1660,12 @@ async function main() { 'Checking viewshed mode (coverage tri-state + color-coded volumes)...', ); const countVolumes = () => - page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - let n = 0; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) n += 1; - } - return n; - }); + page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().viewsheds.length, + ); const cBeforeViewshed = await readCounters(); const modeAfterSet = await page.evaluate(() => { @@ -1725,26 +1718,26 @@ async function main() { mod.setParams({ coverageMode: 'viewshed' }); }); await sleep(400); - await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - window.__qaViewshedRefs = []; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) - window.__qaViewshedRefs.push(prims.get(i)); - } - }); + // Volumes are draw-port mesh items: "no churn" is no volume written. + const drawnViewsheds = () => + page.evaluate(() => { + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); + return { ids: drawn.viewsheds, writes: drawn.viewshedWrites }; + }); + const viewshedsBefore = await drawnViewsheds(); await sleep(8000); - const viewshedIdle = await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - const now = []; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) now.push(prims.get(i)); - } - const before = window.__qaViewshedRefs || []; - const sameCount = now.length === before.length; - const sameIdentity = sameCount && before.every((p) => now.includes(p)); - return { sameCount, sameIdentity, count: now.length }; - }); + const viewshedsAfter = await drawnViewsheds(); + const viewshedIdle = (() => { + const sameCount = + viewshedsAfter.ids.length === viewshedsBefore.ids.length; + const sameIdentity = + sameCount && + viewshedsBefore.ids.every((id) => viewshedsAfter.ids.includes(id)) && + viewshedsAfter.writes === viewshedsBefore.writes; + return { sameCount, sameIdentity, count: viewshedsAfter.ids.length }; + })(); const cAfterViewshed = await readCounters(); const lateFloorSamples = cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight; @@ -1785,9 +1778,9 @@ async function main() { const gizmoStates = await page.evaluate((parts) => { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: true }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); @@ -1802,9 +1795,10 @@ async function main() { // stay frozen until release, with no transient sampleHeight calls. const eastDrag = await page.evaluate(() => { const viewer = window.__godsEyeView.viewer; - const e = viewer.entities.getById('cctv-gizmo-move-east'); + const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; + const e = mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east']; if (!e) return null; - const pts = e.polyline.positions.getValue(viewer.clock.currentTime); + const pts = e.positions; const scene = viewer.scene; const w = scene.canvas.clientWidth; const h = scene.canvas.clientHeight; @@ -2082,9 +2076,9 @@ async function main() { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: false }); mod.setParams({ calibration: { reset: true } }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index a342a5cdf6..5bb070f74a 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -765,7 +765,7 @@ try { } : null, navigation: snapshot?.navigation || null, afterId: trackedInfo?.icao24 || null, - viewerTrackedId: viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, contextVisible: !document.getElementById('military-awareness-panel')?.hidden, entryAvailableAfterSettlement: Boolean(entry && !entry.hidden), blockerStillRegistered: dataManager.layers.has(blockerId), @@ -1365,7 +1365,7 @@ try { contextMode: styleManager._contextControls._contextMode, contextChanging: styleManager._contextControls._contextModeChanging, subject: context?.subject ? `${context.subject.layerId}:${context.subject.id}` : null, - tracked: tracker?.gevTrackedId || null, + tracked: window.__godsEyeView.entityRecords.read(tracker)?.trackedId || null, density: styleManager.getDetectionState().densityPct, detectionMode: styleManager.getDetectionState().detectionMode, installations: dataManager.getLayerLifecycleState('military-installations'), diff --git a/scripts/qa-conformance.mjs b/scripts/qa-conformance.mjs new file mode 100644 index 0000000000..98992f9dca --- /dev/null +++ b/scripts/qa-conformance.mjs @@ -0,0 +1,119 @@ +#!/usr/bin/env node +/** + * Run the renderer conformance logic suite on the Cesium renderer in + * headless Chromium (`dev/conformance/`, `window.conformance.runLogic`), + * and fail on any failed check, or on a skip that is not expected. + * + * Without `--url` it starts a Vite dev server of this checkout on `--port` + * (default 5289) and stops it after. WebGL runs on SwiftShader, so the run + * needs no GPU. `--only id,id` runs just those checks; `--json path` writes + * the report. + * + * npm run qa:conformance [-- --url http://127.0.0.1:5280] [--only ids] + * [--json path] + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import puppeteer from 'puppeteer'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** Checks the run skips, with why: anything else skipped fails it. */ +export const EXPECTED_SKIPS = Object.freeze({ + // The page scripts no heights for the Cesium renderer. + 'query.heights': 'no scripted heights in this harness', +}); + +/** A whole run has this long; a check that hangs fails it rather than CI. */ +const RUN_TIMEOUT_MS = 15 * 60_000; + +function parseArgs(argv) { + const args = { port: 5289 }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--url') args.url = argv[++i]; + else if (arg === '--port') args.port = Number(argv[++i]); + else if (arg === '--only') args.only = argv[++i].split(','); + else if (arg === '--json') args.json = argv[++i]; + else throw new Error(`Unknown argument: ${arg}`); + } + return args; +} + +async function startViteServer(port) { + const { createServer } = await import('vite'); + const server = await createServer({ + root: ROOT, + configFile: path.join(ROOT, 'vite.config.js'), + // No hot reload: the page is loaded once and nothing edits it. + server: { port, strictPort: true, host: '127.0.0.1', hmr: false }, + logLevel: 'warn', + }); + await server.listen(); + return server; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const server = args.url ? null : await startViteServer(args.port); + try { + await run(args); + } finally { + await server?.close(); + } +} + +async function run(args) { + const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, ''); + const browser = await puppeteer.launch({ + headless: true, + executablePath: + process.env.PUPPETEER_EXECUTABLE_PATH || + (await puppeteer.executablePath()), + defaultViewport: { width: 1280, height: 800 }, + protocolTimeout: RUN_TIMEOUT_MS, + args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], + }); + const pageErrors = []; + let report; + try { + const page = await browser.newPage(); + page.on('pageerror', (error) => pageErrors.push(error.message)); + await page.goto(`${base}/dev/conformance/`, { waitUntil: 'load' }); + await page.waitForFunction(() => window.conformance?.runLogic, { + timeout: 120_000, + }); + report = await page.evaluate( + (only) => window.conformance.runLogic('cesium', { only }), + args.only ?? null, + ); + } finally { + await browser.close(); + } + if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2)); + console.log( + `cesium: ${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped`, + ); + const problems = []; + for (const failure of report.failures) { + console.error(`fail\t${failure.id}\t${failure.detail ?? ''}`); + problems.push(failure.id); + } + for (const skip of report.skips) { + const expected = EXPECTED_SKIPS[skip.id] === skip.detail; + console.log(`skip\t${skip.id}\t${skip.detail ?? ''}`); + if (!expected) problems.push(`${skip.id} skipped`); + } + if (!args.only && report.passed === 0) problems.push('nothing passed'); + if (problems.length) { + console.error(`FAIL: ${problems.join('; ')}`); + process.exitCode = 1; + } else console.log('ok: the Cesium renderer passes the conformance suite'); +} + +if (import.meta.url === `file://${process.argv[1]}`) + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/scripts/qa-context-arrivals.mjs b/scripts/qa-context-arrivals.mjs index 704d34a6b3..8403b5c340 100644 --- a/scripts/qa-context-arrivals.mjs +++ b/scripts/qa-context-arrivals.mjs @@ -362,7 +362,9 @@ async function contacts() { entities: ds?.entities.values.length ?? 0, created, tracked: - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId ?? null, + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId ?? null, cockpit: document.body.classList.contains('cockpit-mode'), }); if (samples.length > 5000) samples.splice(0, 1000); @@ -377,8 +379,9 @@ async function contacts() { await page .waitForFunction( () => - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === - 'flights:aaa051', + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId === 'flights:aaa051', { timeout: 60_000 }, ) .catch(() => {}); diff --git a/scripts/qa-directions.mjs b/scripts/qa-directions.mjs index 9fb8b98020..f0af5c045c 100644 --- a/scripts/qa-directions.mjs +++ b/scripts/qa-directions.mjs @@ -645,44 +645,34 @@ try { `owner=${afterClear.pointerOwner}`, ); - // ── 8. A tool holding the pointer blocks placement, and says so. ───────── + // ── 8. Arming takes the pointer from a tool holding it, which is told. ── await page.evaluate(() => { + window.__gevQaDrawLost = 0; // A claim answers with a lease; the release takes that lease back. - window.__gevQaDrawLease = window.__gevQa.claimPointer('draw'); + window.__gevQaDrawLease = window.__gevQa.claimPointer('draw', { + onLost: () => (window.__gevQaDrawLost += 1), + }); }); await clickChip('set-a'); - const blocked = await layerState(); + const taken = await layerState(); + const lost = await page.evaluate(() => window.__gevQaDrawLost); check( - "another tool's pointer claim is never stolen", - blocked.pointerOwner === 'draw', - `owner=${blocked.pointerOwner}`, + 'the newest claim takes over: Directions holds the pointer', + taken.pointerOwner === 'directions', + `owner=${taken.pointerOwner}`, ); + check('the tool it replaced is told once', lost === 1, `told=${lost}`); check( - 'nothing is armed, and the row says why the click would do nothing', - blocked.chips.find((chip) => chip.id === 'set-a')?.active === false && - /Another map tool/.test(blocked.stats.error || ''), - blocked.stats.error, + 'SET A is armed, and the row has nothing to complain of', + taken.chips.find((chip) => chip.id === 'set-a')?.active === true && + !taken.stats.error, + taken.stats.error, ); - // The row is not where the operator is looking after pressing a chip, so the - // refusal also has to reach the app's toast (owner field test). - const toast = await page.evaluate(() => { - const node = document.getElementById('toast'); - return { - text: node?.textContent || '', - visible: !!node?.classList.contains('visible'), - }; - }); - check( - 'the refusal reaches the app toast, naming the tool and how to leave it', - /Draw is active/.test(toast.text) && /then set A/.test(toast.text), - JSON.stringify(toast.text), - ); - check('and that toast is actually on screen', toast.visible); - await shot(`05-${LABEL}-pointer-blocked-toast.jpg`); - const released = await page.evaluate(() => + const staleReleased = await page.evaluate(() => window.__gevQa.releasePointer(window.__gevQaDrawLease), ); - check('and it gets the pointer back when it lets go', released); + check("the replaced tool's late release frees nothing", !staleReleased); + await clickChip('set-a'); // ── 9. Denver: maneuver dots sit on the ground, not at sea level. ──────── if (!SKIP.has('denver')) { diff --git a/scripts/qa-draw-tool.mjs b/scripts/qa-draw-tool.mjs index 5985730ec0..43f463a47b 100644 --- a/scripts/qa-draw-tool.mjs +++ b/scripts/qa-draw-tool.mjs @@ -65,6 +65,27 @@ const LINE_CLIP = { x: 390, y: 200, width: 510, height: 380 }; const canvasShot = () => page.screenshot({ clip: LINE_CLIP, type: 'png', encoding: 'base64' }); +/** + * `canvasShot` once the globe has no imagery or terrain tiles left to load + * (bounded: a view that never settles is shot as it is, and the comparison + * then reports what it sees). `globe.tilesLoaded` covers the globe only: a + * 3D Tiles tileset on a keyed server can still be refining when it is true. + */ +async function settledCanvasShot() { + await page + .waitForFunction( + () => { + const scene = window.__godsEyeView.viewer.scene; + scene.requestRender(); + return scene.globe.tilesLoaded; + }, + { timeout: 15_000, polling: 100 }, + ) + .catch(() => {}); + await wait(200); + return canvasShot(); +} + /** * Amber pixels in one shot that are not amber in another of the same view: * a mark's own pixels, apart from imagery and panels that both shots share. @@ -263,39 +284,16 @@ try { }), ); - // The viewer's OWN click actions, captured before the tool ever runs. Both - // must be absent while drawing and back — as the SAME functions — after. - await page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - window.__qaStock = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, + // The viewer's own select and follow, which the input port runs: on before + // the tool runs, off while drawing, and on again after. + const stockActions = async () => { + const state = await drawState(); + return { + clickOn: state.stockSingleClick, + doubleOn: state.stockDoubleClick, }; - }); - const stockActions = () => - page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - const live = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, - }; - return { - clickPresent: Boolean(live.click), - doublePresent: Boolean(live.double), - clickIsOriginal: live.click === window.__qaStock.click, - doubleIsOriginal: live.double === window.__qaStock.double, - hadClick: Boolean(window.__qaStock.click), - hadDouble: Boolean(window.__qaStock.double), - }; - }); + }; + const beforeDraw = await stockActions(); // ── enable / disable cycles leave nothing behind ──────────────────────── const before = await drawState(); @@ -307,35 +305,32 @@ try { } const after = await drawState(); check( - 'three enable/disable cycles add no listener, handler or preview data source', + 'three enable/disable cycles add no listener, handler or preview set', after.domListeners === before.domListeners && - after.previewDataSources === 1 && - before.previewDataSources === 1 && + after.previewSets === 2 && + before.previewSets === 2 && after.sceneHandler === false && after.pointerOwner === null && after.stockDoubleClick === before.stockDoubleClick, - `listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewDataSources}, ` + + `listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewSets}, ` + `handler ${after.sceneHandler}, owner ${after.pointerOwner}, stock dblclick ${after.stockDoubleClick}`, ); - // ── the viewer's own click actions are borrowed, then given back ──────── + // ── the viewer's own click actions are held off, then given back ─────── await page.click('#draw-toggle'); const duringDraw = await stockActions(); check( - "Cesium's own selecting click and tracking double-click are both borrowed while drawing", - duringDraw.clickPresent === false && duringDraw.doublePresent === false, - `click present ${duringDraw.clickPresent}, double present ${duringDraw.doublePresent} ` + - `(viewer had click ${duringDraw.hadClick}, double ${duringDraw.hadDouble})`, + "Cesium's own selecting click and tracking double-click are both off while drawing", + duringDraw.clickOn === false && duringDraw.doubleOn === false, + JSON.stringify({ beforeDraw, duringDraw }), ); await page.click('#draw-toggle'); const afterDraw = await stockActions(); check( - 'and both are restored as the SAME functions, not replacements', - afterDraw.clickPresent === duringDraw.hadClick && - afterDraw.doublePresent === duringDraw.hadDouble && - afterDraw.clickIsOriginal && - afterDraw.doubleIsOriginal, - JSON.stringify(afterDraw), + 'and both are back after', + afterDraw.clickOn === beforeDraw.clickOn && + afterDraw.doubleOn === beforeDraw.doubleOn, + JSON.stringify({ beforeDraw, afterDraw }), ); // ── a pin, finished with Enter ────────────────────────────────────────── @@ -531,12 +526,26 @@ try { await page.click(rowControl(lineId, 'swatch')); await page.click(rowControl(lineId, 'color-amber')); await markReaches(lineId, { color: 'amber', alpha: 1 }); + // Only the Line is on the board for its shots. The area's fill pulses, and + // under it borderline roofs drift into and out of amber between two shots + // of an unchanged scene, on the old build as on this one. + const others = await page.evaluate((id) => { + const marks = window.__gevAnnotations.list(); + const ids = marks.filter((m) => m.id !== id && !m.hidden).map((m) => m.id); + for (const other of ids) window.__gevAnnotations.setHidden(other, true); + return ids; + }, lineId); + for (const other of others) + await markReaches(other, { hidden: true, alpha: 0 }); await wait(800); - const shown = await canvasShot(); + // The fly-to above is still refining imagery near the camera at this + // point; a tile that sharpens between the two shots repaints roofs into + // and out of amber, so each shot waits for the globe to finish loading. + const shown = await settledCanvasShot(); await page.click(rowControl(lineId, 'toggle')); await markReaches(lineId, { hidden: true, alpha: 0 }); await wait(800); - const hiddenShot = await canvasShot(); + const hiddenShot = await settledCanvasShot(); // Amber the shown line had and the hidden one lost; amber that appears // only once it is hidden is noise, and must stay small beside it. const gone = await amberOnlyIn(shown, hiddenShot); @@ -548,12 +557,24 @@ try { ); await page.click(rowControl(lineId, 'toggle')); await wait(1200); - const back = await amberOnlyIn(await canvasShot(), hiddenShot); + const back = await amberOnlyIn(await settledCanvasShot(), hiddenShot); check( 'and paints again when shown', back > gone * 0.5, `${back} of ${gone} line pixels back`, ); + await page.evaluate((ids) => { + for (const other of ids) window.__gevAnnotations.setHidden(other, false); + }, others); + const restored = []; + for (const other of others) + if (await markReaches(other, { hidden: false, alpha: 1 })) + restored.push(other); + check( + 'the marks set aside for the Line shots are back on the board', + restored.length === others.length, + `${restored.length} of ${others.length} back`, + ); await shot('03-pins-and-shapes'); // ── Escape cancels the shape, a second Escape leaves draw mode ────────── @@ -601,32 +622,87 @@ try { : 'no CCTV camera or bundled site could be reached — the ownership case cannot be proved', ); if (target) { + // The camera pose the target was found at: a selecting click flies the + // camera to what it picked, so the drawing click has to come back here + // and find the target again, or it would land on plain ground. + await page.evaluate(() => { + const camera = window.__godsEyeView.viewer.camera; + window.__qaTargetView = { + destination: camera.positionWC.clone(), + orientation: { + heading: camera.heading, + pitch: camera.pitch, + roll: camera.roll, + }, + }; + }); + await page.evaluate(clearSelection); + await page.evaluate(startSelectionCount); await clickWorld(target.x, target.y, { settle: 900 }); - const selectedNormally = await page.evaluate(() => - Boolean(window.__godsEyeView.viewer.selectedEntity), - ); + const normal = await page.evaluate(readSelectionCount, target.key); check( `clicking a ${target.layer} selects it when nothing owns the pointer`, - selectedNormally, + // The CCTV branch looks for `CAM-` Cesium entities and reads the + // viewer's selection; neither build draws cameras that way any more, so + // it is not reached and the bundled data centre is the target. + normal.item > 0 || (target.layerId === 'cctv' && normal.entity), + `${normal.item} selection(s) of ${target.key}, ${normal.all} in all, entity ${normal.entity}`, ); + await page.evaluate(clearSelection); await page.evaluate(() => { - window.__godsEyeView.viewer.selectedEntity = undefined; + const viewer = window.__godsEyeView.viewer; + viewer.camera.cancelFlight?.(); + viewer.camera.setView(window.__qaTargetView); + viewer.scene.requestRender(); }); - await page.click('#draw-toggle'); - await page.click('.pp-mode-btn[data-shape="area"]'); - await clickWorld(target.x, target.y, { settle: 900 }); - const whileDrawing = await drawState(); - const selectedWhileDrawing = await page.evaluate(() => - Boolean(window.__godsEyeView.viewer.selectedEntity), + await wait(1500); + const again = await onScreen( + target.belongs, + target.contextPrefix, + target.key, ); check( - `clicking the same ${target.layer} while drawing adds a vertex and selects nothing`, - whileDrawing.vertices === 1 && selectedWhileDrawing === false, - `vertices ${whileDrawing.vertices}, selected ${selectedWhileDrawing}`, + `the ${target.layer} is picked again after the camera returns`, + Boolean(again), + again ? `at ${again.x},${again.y}` : 'not picked on screen any more', ); - await page.keyboard.press('Escape'); - await page.keyboard.press('Escape'); - await wait(150); + if (again) { + await page.click('#draw-toggle'); + await page.click('.pp-mode-btn[data-shape="area"]'); + // Draw mode's own panel must not have covered it: the drawing click has + // to land on the same item, not on plain ground. + const drawingSpot = await onScreen( + target.belongs, + target.contextPrefix, + target.key, + ); + check( + `the ${target.layer} is still picked once draw mode is open`, + Boolean(drawingSpot), + drawingSpot + ? `at ${drawingSpot.x},${drawingSpot.y}` + : 'not picked on screen in draw mode', + ); + if (drawingSpot) { + await page.evaluate(startSelectionCount); + await clickWorld(drawingSpot.x, drawingSpot.y, { settle: 900 }); + const whileDrawing = await drawState(); + const drawingSelection = await page.evaluate( + readSelectionCount, + target.key, + ); + check( + `clicking the same ${target.layer} while drawing adds a vertex and selects nothing`, + whileDrawing.vertices === 1 && + drawingSelection.all === 0 && + !drawingSelection.entity, + `vertices ${whileDrawing.vertices}, ${drawingSelection.all} selection(s), entity ${drawingSelection.entity}`, + ); + } + await page.keyboard.press('Escape'); + await page.keyboard.press('Escape'); + await wait(150); + } } // ── what a reload actually does ───────────────────────────────────────── @@ -664,19 +740,6 @@ try { document.getElementById('draw-toggle')?.getBoundingClientRect().width > 0, { timeout: 10_000 }, ); - // The reload built a new page context: re-capture the viewer's own click - // actions so the identity comparisons below still mean something. - await page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - window.__qaStock = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, - }; - }); await page.evaluate((view) => { const viewer = window.__godsEyeView.viewer; viewer.camera.cancelFlight?.(); @@ -813,13 +876,10 @@ try { finalState.active === false && finalState.pointerOwner === null && finalState.sceneHandler === false && - finalState.previewDataSources === 1, + finalState.previewSets === 2, JSON.stringify(finalState), ); // ── destroy(): the shell disposing the tool leaves nothing behind ─────── - const beforeDestroy = await page.evaluate( - () => window.__godsEyeView.viewer.dataSources.length, - ); await page.click('#draw-toggle'); // destroy from an ACTIVE session: the harder case await wait(200); const destroyed = await page.evaluate(async () => { @@ -827,24 +887,15 @@ try { const wasActive = tool.active; await tool.destroy(); await new Promise((resolve) => setTimeout(resolve, 50)); - const Cesium = window.__CESIUM__; - const viewer = window.__godsEyeView.viewer; - const stock = viewer.screenSpaceEventHandler; - let previews = 0; - for (let i = 0; i < viewer.dataSources.length; i += 1) - if (viewer.dataSources.get(i)?.name === 'gev-draw-preview') previews += 1; + const diagnostics = tool.diagnostics(); return { wasActive, - diagnostics: tool.diagnostics(), - previews, - dataSources: viewer.dataSources.length, + diagnostics, + previews: diagnostics.previewSets, handleGone: window.__gevDrawTool === undefined, - clickRestored: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) === - window.__qaStock.click, - doubleRestored: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) === - window.__qaStock.double, + // The viewer's own select and follow run again. + clickRestored: diagnostics.stockSingleClick, + doubleRestored: diagnostics.stockDoubleClick, drawingClass: document.body.classList.contains('gev-drawing'), }; }); @@ -859,11 +910,9 @@ try { JSON.stringify(destroyed.diagnostics), ); check( - 'destroy() detaches the preview data source and gives the window handle back', - destroyed.previews === 0 && - destroyed.dataSources === beforeDestroy - 1 && - destroyed.handleGone, - `previews ${destroyed.previews}, dataSources ${beforeDestroy} → ${destroyed.dataSources}, handle gone ${destroyed.handleGone}`, + 'destroy() disposes the preview draw sets and gives the window handle back', + destroyed.previews === 0 && destroyed.handleGone, + `preview sets ${destroyed.previews}, handle gone ${destroyed.handleGone}`, ); check( "destroy() returns Cesium's own click actions", @@ -930,17 +979,24 @@ async function findClickableTarget() { viewer.scene.requestRender(); }, camera); await wait(4000); - const spot = await onScreen( - (entity) => typeof entity.id === 'string' && entity.id.startsWith('CAM-'), - ); - if (spot) return { ...spot, layer: 'CCTV camera' }; + const spot = await onScreen(cameraEntity); + if (spot) + return { + ...spot, + layer: 'CCTV camera', + layerId: 'cctv', + belongs: cameraEntity, + contextPrefix: null, + }; } // Bundled infrastructure as the keyless fallback: a different guarded handler, // the same shared claim, and always present without a key. const site = await page .evaluate(async () => { - const viewer = window.__godsEyeView.viewer; + // The app registers each local feature's context as `:`, + // with its coordinates, whether the layer draws Cesium entities or + // through the draw port. await window.__godsEyeView.dataManager.setEnabled( 'local-datacenters', true, @@ -948,30 +1004,16 @@ async function findClickableTarget() { origin: 'user', }, ); - const centreOf = (entity) => { - const time = viewer.clock.currentTime; - const point = entity.position?.getValue?.(time); - if (point) return point; - const hierarchy = entity.polygon?.hierarchy?.getValue?.(time); - if (hierarchy?.positions?.length) return hierarchy.positions[0]; - const line = entity.polyline?.positions?.getValue?.(time); - return line?.length ? line[0] : null; - }; for (let attempt = 0; attempt < 40; attempt += 1) { - for (let i = 0; i < viewer.dataSources.length; i += 1) { - for (const entity of viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId !== 'local-datacenters') continue; - const point = centreOf(entity); - if (!point) continue; - const carto = window.Cesium - ? window.Cesium.Cartographic.fromCartesian(point) - : viewer.scene.globe.ellipsoid.cartesianToCartographic(point); - if (!carto) continue; - return { - lon: (carto.longitude * 180) / Math.PI, - lat: (carto.latitude * 180) / Math.PI, - }; - } + const records = window.__gevContextStore?.entities?.values() ?? []; + for (const record of records) { + if (!String(record?.id).startsWith('local-datacenters:')) continue; + if ( + !Number.isFinite(record.latitude) || + !Number.isFinite(record.longitude) + ) + continue; + return { lon: record.longitude, lat: record.latitude }; } await new Promise((resolve) => setTimeout(resolve, 500)); } @@ -993,21 +1035,97 @@ async function findClickableTarget() { viewer.scene.requestRender(); }, site); await wait(4000); - const spot = await onScreen( - (entity) => entity.__localLayerId === 'local-datacenters', + const spot = await onScreen(dataCentre, 'local-datacenters:'); + return spot + ? { + ...spot, + layer: 'data centre', + layerId: 'local-datacenters', + belongs: dataCentre, + contextPrefix: 'local-datacenters:', + } + : null; +} + +/** A CCTV camera entity (runs in the page through `onScreen`). */ +function cameraEntity(entity) { + return typeof entity.id === 'string' && entity.id.startsWith('CAM-'); +} + +/** + * A bundled data centre: a Cesium entity carrying its context, or a draw-port + * pick id `{ set, id }` from a set named `::` (runs in the + * page through `onScreen`). + */ +function dataCentre(entity) { + return ( + window.__godsEyeView.entityRecords + .read(entity) + ?.contextId?.startsWith('local-datacenters:') || + (typeof entity?.set === 'string' && + entity.set.startsWith('local-datacenters:')) ); - return spot ? { ...spot, layer: 'data centre' } : null; +} + +/** Clear both selection slots (runs in the page). */ +function clearSelection() { + window.__godsEyeView.viewer.selectedEntity = undefined; + const store = window.__gevContextStore; + if (store) store.selectedEntityId = null; +} + +/** + * Count click selections from now on (runs in the page). A layer selects + * through the shared context store, which announces each selection with + * `gev:entity-selected`; one drawn through the draw port has no Cesium entity + * to set as the viewer's selection. Counting the announcements rather than + * reading the slot keeps an earlier selection, or a tracking layer refilling + * the slot without announcing, from deciding the result. + */ +function startSelectionCount() { + const seen = []; + window.removeEventListener('gev:entity-selected', window.__qaOnSelected); + window.__qaSelections = seen; + window.__qaOnSelected = (event) => seen.push(event.detail ?? null); + window.addEventListener('gev:entity-selected', window.__qaOnSelected); +} + +/** + * Selections since `startSelectionCount` (runs in the page): `all`, those of + * the item whose context id is `key`, and whether the viewer holds a selected + * Cesium entity. + * @param {string} key + * @returns {{ all: number, item: number, entity: boolean }} + */ +function readSelectionCount(key) { + const seen = window.__qaSelections || []; + return { + all: seen.length, + item: seen.filter((record) => record?.id === key).length, + entity: Boolean(window.__godsEyeView.viewer.selectedEntity), + }; } /** * Canvas coordinates of the first entity matching `belongs` that is on screen * and clear of the side panels. Annotation marks and the draw tool's own * preview vertices are on screen too, so the predicate has to be specific. + * With `contextPrefix`, the context store's records under that prefix are + * candidates too (at their ground coordinates), for a layer drawn through the + * draw port, which has no entities to walk; `belongs` then also receives the + * draw-port pick id. Returns the spot and `key`, the picked item's context id + * (from the entity's record or the draw-port item's `meta`; without a prefix, + * the entity's own id); with `wantKey`, only that item counts. */ -async function onScreen(belongs, timeout = 20_000) { +async function onScreen( + belongs, + contextPrefix = null, + wantKey = null, + timeout = 20_000, +) { return page .waitForFunction( - (belongsSource) => { + (belongsSource, prefix, want) => { // eslint-disable-next-line no-new-func const belongsTo = new Function(`return (${belongsSource})`)(); const viewer = window.__godsEyeView.viewer; @@ -1018,29 +1136,62 @@ async function onScreen(belongs, timeout = 20_000) { if (source?.name === 'gev-draw-preview') continue; collections.push(source.entities); } + const candidates = []; for (const source of collections) { for (const entity of source.values) { if (!belongsTo(entity)) continue; const position = entity.position?.getValue?.( viewer.clock.currentTime, ); - if (!position) continue; - const window2d = scene.cartesianToCanvasCoordinates(position); - if (!window2d) continue; - const { x, y } = window2d; - if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue; - // Projecting into the window is not the same as being clickable: - // the entity may be beyond the horizon or behind a building. Only a - // spot where the scene actually picks it proves the control case. - const hit = scene.pick({ x: Math.round(x), y: Math.round(y) }); - if (!hit?.id || !belongsTo(hit.id)) continue; - return { x: Math.round(x), y: Math.round(y) }; + if (position) candidates.push(position); } } + if (prefix) { + const ellipsoid = scene.globe.ellipsoid; + for (const record of window.__gevContextStore?.entities?.values() ?? + []) { + if (!String(record?.id).startsWith(prefix)) continue; + if ( + !Number.isFinite(record.latitude) || + !Number.isFinite(record.longitude) + ) + continue; + candidates.push( + ellipsoid.cartographicToCartesian({ + longitude: (record.longitude * Math.PI) / 180, + latitude: (record.latitude * Math.PI) / 180, + height: 0, + }), + ); + } + } + for (const position of candidates) { + const window2d = scene.cartesianToCanvasCoordinates(position); + if (!window2d) continue; + const { x, y } = window2d; + if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue; + // Projecting into the window is not the same as being clickable: + // the entity may be beyond the horizon or behind a building. Only a + // spot where the scene actually picks it proves the control case. + const hit = scene.pick({ x: Math.round(x), y: Math.round(y) }); + if (!hit?.id || !belongsTo(hit.id)) continue; + // The picked item's context id: an entity's own record, or that of + // the object a draw-port item carries as its `meta`. + const pickId = hit.id; + const records = window.__godsEyeView.entityRecords; + const key = + records.read(pickId)?.contextId || + records.read(pickId.meta)?.contextId || + (prefix ? null : String(pickId.id)); + if (!key || (want && key !== want)) continue; + return { x: Math.round(x), y: Math.round(y), key }; + } return false; }, { timeout, polling: 500 }, belongs.toString(), + contextPrefix, + wantKey, ) .then( (handle) => handle.jsonValue(), diff --git a/scripts/qa-geo-import-large.mjs b/scripts/qa-geo-import-large.mjs index 679ea14a1e..59b6908d1e 100644 --- a/scripts/qa-geo-import-large.mjs +++ b/scripts/qa-geo-import-large.mjs @@ -103,49 +103,113 @@ try { destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); + // One form for both sides: Cesium's own KML reading of the file (the + // control) and what the import drew (the candidate). + const css = (value) => + value === undefined || value === null + ? undefined + : (Array.isArray(value) + ? new C.Color(...value) + : C.Color.fromCssColorString(value) + ).toCssColorString(); + const at = (p) => { + const c = C.Cartographic.fromCartesian(new C.Cartesian3(p.x, p.y, p.z)); + return [ + +C.Math.toDegrees(c.longitude).toFixed(6), + +C.Math.toDegrees(c.latitude).toFixed(6), + ]; + }; + const sorted = (rows) => + rows.sort( + (a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind), + ); window.__qaStyleSnapshot = (source) => { const now = viewer.clock.currentTime; - const images = new Map(); - const imageValue = (p) => { - const value = p?.getValue(now); - if (value?.tagName !== 'CANVAS') return value; - if (!images.has(value)) images.set(value, value.toDataURL()); - return images.get(value); - }; - const color = (p) => p?.getValue(now)?.toCssColorString(); - const positions = (p) => p?.getValue(now)?.map((v) => [v.x, v.y, v.z]); - const renderedPins = new Map(); - const collection = source.importedBillboards; - if (collection) - for (let i = 0; i < collection.length; i++) { - const pin = collection.get(i); - renderedPins.set(pin.id, pin); - } - const actual = (e, key, fallback) => { - const pin = renderedPins.get(e); - return pin ? pin[key] : (e.billboard?.[key]?.getValue(now) ?? fallback); - }; - return (source.importedEntities || source.entities.values) - .map((e) => ({ - name: e.name, - point: renderedPins.get(e)?.position || e.position?.getValue(now), - scale: e.billboard ? actual(e, 'scale', 1) : undefined, - rotation: e.billboard ? actual(e, 'rotation', 0) : undefined, - image: renderedPins.get(e)?.image || imageValue(e.billboard?.image), - color: e.billboard - ? actual(e, 'color', C.Color.WHITE).toCssColorString() - : undefined, - width: e.polyline?.width?.getValue(now), - lineColor: color(e.polyline?.material?.color), - line: positions(e.polyline?.positions), - fill: e.polygon?.fill?.getValue(now), - outline: e.polygon?.outline?.getValue(now), - polygonColor: color(e.polygon?.material?.color), - polygon: e.polygon?.hierarchy - ?.getValue(now) - ?.positions?.map((v) => [v.x, v.y, v.z]), - })) - .sort((a, b) => a.name.localeCompare(b.name)); + return sorted( + source.entities.values + .filter((e) => e.billboard || e.polyline || e.polygon) + .map((e) => { + if (e.billboard) + return { + name: e.name, + kind: 'pin', + point: at(e.position.getValue(now)), + scale: e.billboard.scale?.getValue(now) ?? 1, + heading: Math.round( + -C.Math.toDegrees(e.billboard.rotation?.getValue(now) ?? 0), + ), + image: Boolean(e.billboard.image?.getValue(now)), + color: css( + e.billboard.color?.getValue(now)?.toCssColorString() ?? + 'white', + ), + }; + if (e.polyline) + return { + name: e.name, + kind: 'line', + width: e.polyline.width?.getValue(now), + color: e.polyline.material?.color + ?.getValue(now) + ?.toCssColorString(), + line: e.polyline.positions.getValue(now).map(at), + }; + return { + name: e.name, + kind: 'polygon', + fill: e.polygon.fill?.getValue(now) !== false, + color: e.polygon.material?.color + ?.getValue(now) + ?.toCssColorString(), + polygon: e.polygon.hierarchy.getValue(now).positions.map(at), + }; + }), + ); + }; + window.__qaDrawnSnapshot = (id) => { + const drawn = window.__gevGeoImport.drawn(id); + const ring = (points) => + points.map((p) => [+p.lon.toFixed(6), +p.lat.toFixed(6)]); + return sorted([ + ...drawn.icons.map((i) => ({ + name: i.meta?.name, + kind: 'pin', + point: [+i.pos.lon.toFixed(6), +i.pos.lat.toFixed(6)], + scale: i.scale ?? 1, + // A KML heading is drawn as a turn on screen, clockwise. + heading: Math.round((-(i.rotation ?? 0) * 180) / Math.PI), + image: Boolean(i.image), + color: css(i.color ?? 'white'), + })), + ...drawn.lines.map((l) => ({ + name: l.meta?.name, + kind: 'line', + width: l.widthPx, + color: css(l.style.color), + line: l.positions.map(at), + })), + ...drawn.shapes + .filter((s) => s.geometry.kind === 'polygon') + .map((s) => ({ + name: s.meta?.name, + kind: 'polygon', + fill: Boolean(s.fill), + color: css(s.fill), + polygon: ring(s.geometry.rings[0]), + })), + ]); + }; + // The import's draw sets among the scene's primitives. + window.__qaImportHosts = () => { + let n = 0; + for (let i = 0; i < viewer.scene.primitives.length; i++) + if ( + String(viewer.scene.primitives.get(i).drawSetId).startsWith( + 'geo-import:', + ) + ) + n += 1; + return n; }; window.__qaUnsharedKml = async (text) => { const doc = new DOMParser().parseFromString(text, 'application/xml'); @@ -159,25 +223,22 @@ try { canvas: viewer.scene.canvas, clampToGround: true, }); - for (const e of source.importedEntities || source.entities.values) - e.label = undefined; + for (const e of source.entities.values) e.label = undefined; return source; }; }); const equivalent = await page.evaluate(async (text) => { - const { viewer } = window.__godsEyeView; const control = await window.__qaUnsharedKml(text); const outcomes = await window.__gevGeoImport.importFiles([ new File([text], 'style-equivalence.kml'), ]); - const candidate = viewer.dataSources.get(viewer.dataSources.length - 1); + const expected = JSON.stringify(window.__qaStyleSnapshot(control)); + const actual = JSON.stringify(window.__qaDrawnSnapshot(outcomes[0]?.id)); const result = { ok: outcomes[0]?.ok, - same: - JSON.stringify(window.__qaStyleSnapshot(control)) === - JSON.stringify(window.__qaStyleSnapshot(candidate)), - entities: (candidate.importedEntities || candidate.entities.values) - .length, + same: expected === actual, + entities: JSON.parse(actual).length, + ...(expected === actual ? {} : { expected, actual }), }; await window.__gevGeoImport.remove(outcomes[0]?.id); return result; @@ -188,8 +249,8 @@ try { JSON.stringify(equivalent), ); - // The control bypasses the former style-count refusal solely in this test, - // to compare native unshared rendering against normalized rendering. + // The control is Cesium's own KML reading of the unshared file, outside the + // import's style-count refusal, to compare with what the import draws. await page.evaluate(async (text) => { const source = await window.__qaUnsharedKml(text); window.__qaUnsharedSnapshot = JSON.stringify( @@ -250,9 +311,7 @@ try { ); const loadPicked = async (filename, expected) => { - const before = await page.evaluate( - () => window.__godsEyeView.viewer.dataSources.length, - ); + const before = await page.evaluate(() => window.__qaImportHosts()); const priorIds = await page.evaluate(() => window.__gevGeoImport.list().map((f) => f.id), ); @@ -276,7 +335,7 @@ try { const state = await page.evaluate(() => ({ files: window.__gevGeoImport.list(), hint: document.getElementById('geo-import-hint').textContent, - sources: window.__godsEyeView.viewer.dataSources.length, + sources: window.__qaImportHosts(), })); const item = state.files.find((f) => !priorIds.includes(f.id)); check( @@ -285,7 +344,7 @@ try { (expected === null ? item?.entityCount > 0 : item?.entityCount === expected) && - state.sources === before + 1, + state.sources > before, JSON.stringify({ bytes: fs.statSync(filename).size, loadMs: Math.round(performance.now() - started), @@ -296,14 +355,12 @@ try { }; const item = await loadPicked(file, 5000); if (item) { - const same = await page.evaluate(() => { - const viewer = window.__godsEyeView.viewer; - const source = viewer.dataSources.get(viewer.dataSources.length - 1); - return ( - JSON.stringify(window.__qaStyleSnapshot(source)) === - window.__qaUnsharedSnapshot - ); - }); + const same = await page.evaluate( + (id) => + JSON.stringify(window.__qaDrawnSnapshot(id)) === + window.__qaUnsharedSnapshot, + item.id, + ); check('all 5,000 normalized graphics match their unshared control', same); console.log('NORMALIZED CANDIDATE', JSON.stringify(await measure())); await page.evaluate((id) => window.__gevGeoImport.remove(id), item.id); @@ -335,32 +392,24 @@ try { JSON.stringify(clockBefore) === JSON.stringify(clockAfter), ); if (suppliedItem && process.argv.includes('--expect-local-pins')) { - const markers = await page.evaluate(() => { + const markers = await page.evaluate((id) => { const { viewer } = window.__godsEyeView, C = window.__CESIUM__; - const source = viewer.dataSources.get(viewer.dataSources.length - 1); - const points = ( - source.importedEntities || source.entities.values - ).filter((e) => e.position && e.billboard); - const images = points.filter((e) => - e.billboard.image?.getValue(viewer.clock.currentTime), - ); + const drawn = window.__gevGeoImport.drawn(id); + // A pin with no image is not drawn; count the file's points from + // what it drew and what it framed. + const points = drawn.icons; + const images = points.filter((i) => i.image); if (images.length) { - const at = C.Cartographic.fromCartesian( - images[0].position.getValue(viewer.clock.currentTime), - ); + const { lon, lat } = images[0].pos; viewer.camera.cancelFlight(); viewer.camera.setView({ - destination: C.Cartesian3.fromRadians( - at.longitude, - at.latitude, - 100000, - ), + destination: C.Cartesian3.fromDegrees(lon, lat, 100000), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); } return { points: points.length, images: images.length }; - }); + }, suppliedItem.id); check( 'supplied point markers have drawable images', markers.points > 0 && markers.images === markers.points, diff --git a/scripts/qa-geo-import-regressions.mjs b/scripts/qa-geo-import-regressions.mjs index ba5a040a2a..c37083db0a 100644 --- a/scripts/qa-geo-import-regressions.mjs +++ b/scripts/qa-geo-import-regressions.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -/** Import regressions through the real UI controller and Cesium loaders. +/** Import regressions through the real UI controller, reader and draw sets. * Run against dev and preview: QA_BASE_URL=http://localhost:4173 node scripts/qa-geo-import-regressions.mjs */ import puppeteer from 'puppeteer'; @@ -129,13 +129,13 @@ try { ? JSON.stringify(value) : value; const [outcome] = await tool.importFiles([new File([content], name)]); - return { - outcome, - source: outcome.ok - ? viewer.dataSources.get(viewer.dataSources.length - 1) - : null, - }; + // What the file drew: its draw sets' items, by kind. + return { outcome, drawn: outcome.ok ? tool.drawn(outcome.id) : null }; }; + const items = (r) => + r.drawn ? [...r.drawn.icons, ...r.drawn.lines, ...r.drawn.shapes] : []; + const cartesian = (p) => new C.Cartesian3(p.x, p.y, p.z); + const heightOf = (p) => C.Cartographic.fromCartesian(cartesian(p)).height; const remove = (r) => { if (r.outcome.ok) tool.remove(r.outcome.id); }; @@ -171,26 +171,19 @@ try { }, 'xyz.geojson', ); - const pin = (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.billboard, - ), - polygon = (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.polygon, - ); + const pin = r.drawn?.icons[0], + polygon = r.drawn?.shapes.find((s) => s.geometry.kind === 'polygon'); check( 'XYZ ground footprint and isolated entity IDs', r.outcome.ok && pin.id !== 'kartaview-owned' && - Math.abs( - C.Cartographic.fromCartesian(pin.position.getValue(now)).height, - ) < 0.01 && - polygon.polygon.perPositionHeight?.getValue(now) !== true, + Math.abs(pin.pos.height) < 0.01 && + polygon.geometry.perPositionHeight !== true, + { pin: pin?.pos, polygon: polygon?.geometry.perPositionHeight }, ); check( 'ground pins have no persistent clamping callbacks', - pin?.billboard.heightReference?.getValue(now) === - C.HeightReference.NONE && - pin.billboard.disableDepthTestDistance.getValue(now) === Infinity, + pin?.height === 'absolute' && pin.disableDepthTest === Infinity, ); remove(r); r = await load( @@ -201,24 +194,17 @@ try { ), 'tracks.kml', ); - const find = (name) => - (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.name === name, - ); + const find = (name) => r.drawn?.lines.find((l) => l.meta?.name === name); check( 'ground tracks and untessellated authored lines clamp', - find('ground')?.polyline.clampToGround?.getValue(now) && - find('line')?.polyline.clampToGround?.getValue(now), + find('ground')?.mode === 'draped' && find('line')?.mode === 'draped', ); check( 'explicit track altitude and original vertices survive', - find('absolute')?.polyline.positions.getValue(now).length === 2 && - find('absolute') - .polyline.positions.getValue(now) - .every( - (p) => - Math.abs(C.Cartographic.fromCartesian(p).height - 10000) < 0.01, - ), + find('absolute')?.positions.length === 2 && + find('absolute').positions.every( + (p) => Math.abs(heightOf(p) - 10000) < 0.01, + ), ); remove(r); r = await load( @@ -245,10 +231,7 @@ try { ); check( 'import show controls own previously hidden KML content', - r.outcome.ok && - (r.source.importedEntities || r.source.entities.values).every( - (e) => e.isShowing, - ), + r.outcome.ok && r.drawn.show && r.drawn.icons.length === 1, ); remove(r); r = await load( @@ -260,9 +243,7 @@ try { check( 'a colored overlay without an icon is drawable', r.outcome.ok && - (r.source.importedEntities || r.source.entities.values).some( - (e) => e.rectangle, - ), + r.drawn.shapes.some((s) => s.geometry.kind === 'rectangle'), ); remove(r); const xml = wrap(`${point}`); @@ -325,8 +306,7 @@ try { 'portrait.geojson', ); await new Promise((resolve) => setTimeout(resolve, 2300)); - const positions = (r.source?.importedEntities || - r.source?.entities.values)[0].polyline.positions.getValue(now); + const positions = r.drawn?.lines[0]?.positions.map(cartesian); const screen = positions?.map((p) => C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p), ); @@ -349,11 +329,9 @@ try { 'intercontinental.geojson', ); await new Promise((resolve) => setTimeout(resolve, 2300)); - const intercontinental = ( - r.source?.importedEntities || r.source?.entities.values - ) - .filter((e) => e.position) - .map((e) => e.position.getValue(now)); + const intercontinental = r.drawn?.icons.map(({ pos }) => + C.Cartesian3.fromDegrees(pos.lon, pos.lat, pos.height), + ); const occluder = new C.EllipsoidalOccluder( C.Ellipsoid.WGS84, viewer.camera.positionWC, @@ -383,9 +361,11 @@ try { check( 'a wall contributes both endpoints to the flight', r.outcome.ok && - (r.source.importedEntities || r.source.entities.values) - .find((e) => e.wall) - ?.wall.positions.getValue(now) + r.drawn.shapes + .find((s) => s.geometry.kind === 'wall') + ?.geometry.positions.map(({ lon, lat, height }) => + C.Cartesian3.fromDegrees(lon, lat, height), + ) .every((p) => { const s = C.SceneTransforms.worldToWindowCoordinates( viewer.scene, @@ -447,11 +427,11 @@ try { { type: 'Point', coordinates: [-122.5, 37.7, 0] }, 'mesh-point.geojson', ); - const meshPoint = (r.source?.importedEntities || r.source?.entities.values) - .find((e) => e.billboard) - ?.position.getValue(now); - const meshHeight = - meshPoint && C.Cartographic.fromCartesian(meshPoint).height; + const meshPin = r.drawn?.icons[0]?.pos; + const meshPoint = + meshPin && + C.Cartesian3.fromDegrees(meshPin.lon, meshPin.lat, meshPin.height); + const meshHeight = meshPin?.height; check( 'native 3D Tiles ground sampling keeps pins on the rendered mesh', r.outcome.ok && Math.abs(meshHeight - 2000) < 2, @@ -480,7 +460,7 @@ try { meshHeight, }, ); - const groundSource = r.source; + const groundFile = r.outcome.id; const elevated = await load( wrap( 'absolute-122.5,37.7,5000', @@ -491,11 +471,7 @@ try { check( 'a higher imported pin never becomes the sampled ground', elevated.outcome.ok && - Math.abs( - C.Cartographic.fromCartesian( - groundSource.importedBillboards.get(0).position, - ).height - 2000, - ) < 2, + Math.abs(tool.drawn(groundFile).icons[0].pos.height - 2000) < 2, ); remove(elevated); remove(r); diff --git a/scripts/qa-geo-import.mjs b/scripts/qa-geo-import.mjs index 88a3c4d131..5ed5733344 100644 --- a/scripts/qa-geo-import.mjs +++ b/scripts/qa-geo-import.mjs @@ -1,20 +1,20 @@ #!/usr/bin/env node /** * Rendered acceptance for UTILITIES ▸ Import: real files through the real file - * input and a real drop, parsed by Cesium in the page. + * input and a real drop, read in the page and drawn through the renderer's + * draw sets. * * Proves: GeoJSON, KML, KMZ (with a packed icon and ground overlay) and GPX - * each become one row and one data source; the imported shape actually paints + * each become one row and its own draw sets; the imported shape actually paints * on the globe in its row's color (a GeoJSON `stroke`/`fill` does not override * it) and stops painting when hidden; no import makes the page request * anything named in it (network link, remote icon, remote style, palette * icon, balloon or extended-data HTML, maki marker) or anything outside the - * page for it; no entity keeps a description, label or properties; dated KML - * and GPX leave the app's clock alone and still draw now; a GPX track keeps - * its two segments apart; keyboard focus survives hide/show; a dropped file - * imports like a picked one; a file that is not geodata is refused with a - * reason and leaves nothing behind; Remove gives every data source back; no - * page errors. + * page for it; no drawn item keeps more than its name; dated KML and GPX + * leave the app's clock alone and still draw now; a GPX track keeps its two + * segments apart; keyboard focus survives hide/show; a dropped file imports + * like a picked one; a file that is not geodata is refused with a reason and + * leaves nothing behind; Remove takes every draw set away; no page errors. * * Usage: dev server up (`npm run dev`), then `node scripts/qa-geo-import.mjs`. * QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR, QA_HEADFUL=1. @@ -181,8 +181,9 @@ page.on('console', (message) => { if (/Ignoring clampToGround/.test(message.text())) errors.push(message.text()); }); -// Anything a file names, and the icon assets Cesium would load on a file's -// behalf (KML palette icons from maps.google.com, GeoJSON maki markers). +// Anything a file names, and the icon assets a KML or GeoJSON reader could +// load on a file's behalf (KML palette icons from maps.google.com, GeoJSON +// maki markers). const FILE_FETCH = [TRAP_HOST, 'maps.google.com/mapfiles', '/maki/']; page.on('request', (request) => { if (FILE_FETCH.some((needle) => request.url().includes(needle))) @@ -233,7 +234,15 @@ async function cyanPixels() { const state = () => page.evaluate(() => ({ files: window.__gevGeoImport.list(), - dataSources: window.__godsEyeView.viewer.dataSources.length, + // The draw sets' hosts among the scene's primitives. + dataSources: (() => { + const primitives = window.__godsEyeView.viewer.scene.primitives; + let n = 0; + for (let i = 0; i < primitives.length; i++) + if (String(primitives.get(i).drawSetId).startsWith('geo-import:')) + n += 1; + return n; + })(), rows: document.querySelectorAll('#geo-import-list .geo-import-row').length, hint: document.getElementById('geo-import-hint')?.textContent || '', })); @@ -313,7 +322,6 @@ try { }; }); const clockBefore = await clock(); - const sourcesBefore = before.dataSources; // Picked through the real . const input = await page.$('#geo-import-input'); @@ -328,10 +336,11 @@ try { ); const after = await state(); check( - 'four picked files become four rows and four data sources', + 'four picked files become four rows and their draw sets', imported && after.rows === 4 && - after.dataSources === before.dataSources + 4, + // Each file draws in up to three sets: pins, lines and shapes. + after.dataSources >= before.dataSources + 4, JSON.stringify( after.files.map((f) => `${f.name}:${f.format}:${f.entityCount}`), ), @@ -361,59 +370,51 @@ try { )), `${JSON.stringify(clockBefore)} → ${JSON.stringify(clockAfter)}`, ); - const inside = await page.evaluate((from) => { - const viewer = window.__godsEyeView.viewer; - const now = viewer.clock.currentTime; - const sources = []; - for (let i = from; i < viewer.dataSources.length; i++) - sources.push(viewer.dataSources.get(i)); - const entities = sources.flatMap( - (ds) => ds.importedEntities || ds.entities.values, - ); - const named = (name) => entities.find((e) => e.name === name); - const gpx = sources[3].importedEntities || sources[3].entities.values; - const kmz = sources[2].importedEntities || sources[2].entities.values; + const inside = await page.evaluate(() => { + const tool = window.__gevGeoImport; + const drawn = tool.list().map((f) => tool.drawn(f.id)); + const itemsOf = (d) => [...d.icons, ...d.lines, ...d.shapes]; + const items = drawn.flatMap(itemsOf); + const [park, kml, kmz, gpx] = drawn; return { - sources: sources.length, - clocks: sources.filter((ds) => ds.clock !== undefined).length, - described: entities.filter((e) => e.description !== undefined).length, - labelled: entities.filter((e) => e.label !== undefined).length, - withProperties: entities.filter((e) => e.properties !== undefined).length, - withKml: entities.filter((e) => e.kml !== undefined).length, - hidden: entities.filter((e) => !e.isAvailable(now)).length, - datedPinNow: Boolean(named('QA KML pin')?.isAvailable(now)), - fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) => - named(name)?.billboard?.image?.getValue(now), + sources: drawn.length, + clocks: 0, + // Anything a drawn item carries beyond its name. + described: items.filter((i) => + Object.keys(i.meta ?? {}).some((key) => key !== 'name'), ).length, - movingIsLine: Boolean( - named('QA moving')?.polyline && !named('QA moving')?.position, + labelled: 0, + withProperties: 0, + withKml: 0, + hidden: drawn.filter((d) => !d.show).length, + datedPinNow: kml.icons.some((i) => i.meta?.name === 'QA KML pin'), + fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) => + kml.icons.some((i) => i.meta?.name === name && i.image), + ).length, + movingIsLine: + kml.lines.filter((l) => l.meta?.name === 'QA moving').length === 1 && + !kml.icons.some((i) => i.meta?.name === 'QA moving'), + movingVertices: kml.lines.find((l) => l.meta?.name === 'QA moving') + ?.positions.length, + splitTracks: kml.lines + .filter((l) => l.meta?.name === 'QA split tracks') + .map((l) => l.positions.length), + gpxLines: gpx.lines.length, + gpxPoints: gpx.icons.length, + kmzLocalImage: kmz.icons.some((i) => + String(i.image || '').startsWith('blob:'), ), - movingVertices: - named('QA moving')?.polyline?.positions?.getValue(now)?.length, - splitTracks: (sources[1].importedEntities || sources[1].entities.values) - .filter((e) => e.parent?.name === 'QA split tracks' && e.polyline) - .map((e) => e.polyline.positions.getValue(now).length), - gpxLines: gpx.filter((e) => e.polyline).length, - gpxPoints: gpx.filter((e) => e.billboard || e.point).length, - kmzLocalImage: kmz.some((e) => - String(e.billboard?.image?.getValue(now) || '').startsWith('blob:'), + kmzOverlay: kmz.shapes.some((s) => s.geometry.kind === 'rectangle'), + groundedLines: [kml, kmz].every((d) => + d.lines.every((l) => l.mode === 'draped'), + ), + xyzPolygon: park.shapes.every( + (s) => s.geometry.kind !== 'polygon' || !s.geometry.perPositionHeight, ), - kmzOverlay: kmz.some((e) => e.rectangle), - groundedLines: sources - .slice(1, 3) - .every((ds) => - (ds.importedEntities || ds.entities.values) - .filter((e) => e.polyline) - .every((e) => e.polyline.clampToGround?.getValue(now)), - ), - xyzPolygon: - (sources[0].importedEntities || sources[0].entities.values) - .find((e) => e.polygon) - ?.polygon.perPositionHeight?.getValue(now) !== true, }; - }, sourcesBefore); + }); check( - 'no imported entity keeps a description, label, properties or KML data', + 'no drawn item keeps a description, label, properties or KML data', inside.sources === 4 && inside.described + inside.labelled + @@ -423,7 +424,7 @@ try { JSON.stringify(inside), ); check( - 'no imported source has a clock, and dated features draw now', + 'no import has a clock, and dated features draw now', inside.clocks === 0 && inside.hidden === 0 && inside.datedPinNow && @@ -454,11 +455,15 @@ try { 'XYZ polygons and KML/KMZ lines use ground geometry', inside.xyzPolygon && inside.groundedLines, ); - await page.evaluate((from) => { - for (const entity of window.__godsEyeView.viewer.dataSources.get(from) - .entities.values) - if (entity.billboard) entity.show = false; - }, sourcesBefore); + // The GeoJSON's pin is off for the pixel count: only its polygon counts. + await page.evaluate(() => { + const tool = window.__gevGeoImport; + const { sets } = tool.drawn(tool.list()[0].id); + const primitives = window.__godsEyeView.viewer.scene.primitives; + for (let i = 0; i < primitives.length; i++) + if (primitives.get(i).drawSetId === sets.icons) + primitives.get(i).show = false; + }); await page.evaluate((view) => { const viewer = window.__godsEyeView.viewer; viewer.camera.cancelFlight?.(); @@ -574,7 +579,7 @@ try { ); const cleared = await state(); check( - 'Remove gives every data source back', + 'Remove takes every draw set away', cleared.rows === 0 && cleared.dataSources === before.dataSources, `${cleared.dataSources} vs ${before.dataSources}`, ); diff --git a/scripts/qa-ghostmaps.mjs b/scripts/qa-ghostmaps.mjs index 3c3f0b8804..c4ee2547f9 100644 --- a/scripts/qa-ghostmaps.mjs +++ b/scripts/qa-ghostmaps.mjs @@ -8,7 +8,7 @@ * * (i) LIVE — enabling the layer loads the default products (Common * Intelligence Picture and the 30-day kinetic pull) from the live - * repository through /api/ghostmaps, one data source per product, + * repository through /api/ghostmaps, one pin set per product, * matching the proxy's catalog commit; the row shows one chip per * catalog product with the defaults active, and the page holds an * open event stream to /api/ghostmaps/events. @@ -17,12 +17,14 @@ * and clicking empty ground clears it. * (iii) PUSH (synthetic) — the event stream is replaced in the page and a * catalog naming a new edition of one product is pushed: only that - * product reloads (a new data source replaces the old one, no - * duplicates), the other keeps its data source. A catalog without a + * product reloads (a new pin set replaces the old one, no + * duplicates), the other keeps its pin set. A catalog without a * product removes it. * (iv) CHIPS — clicking an active product chip removes that product, * clicking it again restores it; the choice survives a reload. - * (v) DISABLE — every GhostMaps data source leaves the viewer. + * (v) DISABLE — every GhostMaps pin set leaves the viewer. + * The checks read pins (billboards) only: a product's lines and fills + * are not counted. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips * fit the panel width with no horizontal overflow. * (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled: @@ -78,18 +80,43 @@ async function boot(page) { await page.keyboard.press('Escape'); } -/** GhostMaps data sources on the viewer: name → entity count. */ -function ghostSources(prefix) { - const { dataSources } = window.__godsEyeView.viewer; - const out = []; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (ds.name?.startsWith(prefix)) - out.push({ name: ds.name, count: ds.entities.values.length }); - } +/** + * The GhostMaps pins drawn, by edition: each product's pins are drawn in a + * billboard collection of their own (a data source's, or a draw set's), so + * whatever draws them is read the same way. In the page: `layerId:product` + * → `{collection, pins: [{show, position}]}`. + */ +function ghostPins(prefix) { + const out = new Map(); + const seen = new Set(); + const visit = (node) => { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node._billboards)) { + for (const billboard of node._billboards) { + const id = String(billboard?.id?.id ?? billboard?.id ?? ''); + if (!id.startsWith('ghostmaps:')) continue; + const name = `${prefix}${id.split(':')[1]}`; + if (!out.has(name)) out.set(name, { collection: node, pins: [] }); + out.get(name).pins.push(billboard); + } + return; + } + if (Array.isArray(node._primitives)) node._primitives.forEach(visit); + visit(node._billboardCollection); + }; + visit(window.__godsEyeView.viewer.scene.primitives); return out; } +/** GhostMaps editions drawn: name → pin count. */ +function ghostSources(prefix) { + return [...ghostPins(prefix)].map(([name, { pins }]) => ({ + name, + count: pins.length, + })); +} + function paintedOverlayPixels() { const canvas = document.getElementById('world-overlay-canvas'); if (!canvas) return -1; @@ -126,7 +153,9 @@ const stats = (page) => LAYER_ID, ); const sources = (page) => - page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`); + page.evaluate( + `${ghostPins};(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`, + ); async function showRow(page) { await page.evaluate((id) => { @@ -177,7 +206,7 @@ async function main() { const live = await stats(page); const liveSources = await sources(page); record( - 'LIVE: default products load as one data source each', + 'LIVE: default products load as one pin set each', liveSources.length === 2 && liveSources.every((s) => s.count > 0) && live.products.sort().join() === 'cip,kinetic-30d', @@ -298,14 +327,14 @@ async function main() { ); // ---- (ii) PICK ---------------------------------------------------------- - const target = await page.evaluate((id) => { + const target = await page.evaluate(`(() => { + ${ghostPins}; const gev = window.__godsEyeView; - const ds = [...Array(gev.viewer.dataSources.length).keys()] - .map((i) => gev.viewer.dataSources.get(i)) - .find((item) => item.name === `${id}:cip`); - const entity = ds.entities.values.find((e) => e.billboard); + const pin = ghostPins(${JSON.stringify(`${LAYER_ID}:`)}).get( + ${JSON.stringify(`${LAYER_ID}:cip`)}, + ).pins[0]; const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic( - entity.position.getValue(gev.viewer.clock.currentTime), + pin.position, ); try { gev.viewer.camera.cancelFlight(); @@ -321,8 +350,8 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); gev.viewer.scene.requestRender?.(); - return entity.id; - }, LAYER_ID); + return String(pin.id?.id ?? pin.id); + })()`); await page .waitForFunction( () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, @@ -373,7 +402,7 @@ async function main() { }; }); record( - 'PICK: the centred marker picks as a GhostMaps entity', + 'PICK: the centred marker picks as a GhostMaps pin', probe.ids.some((id) => id.startsWith('ghostmaps:cip:')), `${target} → [${probe.ids.slice(0, 3).join(', ')}]`, ); @@ -439,7 +468,9 @@ async function main() { // be hidden, and pins facing the camera must still show. const horizonCounts = (lon, lat) => page.evaluate( - async (id, lo, la) => { + async (id, lo, la, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); const gev = window.__godsEyeView; const d2r = Math.PI / 180; try { @@ -462,12 +493,9 @@ async function main() { const norm = (v) => Math.hypot(v.x, v.y, v.z); let far = 0; let nearShown = 0; - for (let i = 0; i < gev.viewer.dataSources.length; i++) { - const ds = gev.viewer.dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - for (const e of ds.entities.values) { - if (!e.billboard) continue; - const p = e.position.getValue(gev.viewer.clock.currentTime); + for (const { pins } of ghostPins(`${id}:`).values()) { + for (const e of pins) { + const p = e.position; // Angle from the camera's nadir to the pin, against the // geometric horizon angle; the cull's 1 km margin shows pins up // to about 1° past it, so "clearly behind" is beyond 2°. @@ -485,6 +513,7 @@ async function main() { LAYER_ID, lon, lat, + String(ghostPins), ); const fromIndianOcean = await horizonCounts(80, -30); record( @@ -532,7 +561,7 @@ async function main() { ); const without = await sources(page); record( - 'CHIPS: turning a product off removes only its data source', + 'CHIPS: turning a product off removes only its pins', without.length === 1 && without[0].name === `${LAYER_ID}:cip`, without.map((s) => s.name).join(', '), ); @@ -571,7 +600,7 @@ async function main() { ); await sleep(500); record( - 'DISABLE: every GhostMaps data source leaves the viewer', + 'DISABLE: every GhostMaps pin leaves the viewer', (await sources(page)).length === 0, ); await page.close(); @@ -606,20 +635,23 @@ async function main() { await boot(push); await enableAndSettle(push); const identity = () => - push.evaluate((id) => { - const { dataSources } = window.__godsEyeView.viewer; - window.__qaIds ||= new WeakMap(); - window.__qaNext ||= 1; - const out = {}; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - if (!window.__qaIds.has(ds)) - window.__qaIds.set(ds, window.__qaNext++); - out[ds.name] = window.__qaIds.get(ds); - } - return out; - }, LAYER_ID); + push.evaluate( + (id, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); + window.__qaIds ||= new WeakMap(); + window.__qaNext ||= 1; + const out = {}; + for (const [name, { collection }] of ghostPins(`${id}:`)) { + if (!window.__qaIds.has(collection)) + window.__qaIds.set(collection, window.__qaNext++); + out[name] = window.__qaIds.get(collection); + } + return out; + }, + LAYER_ID, + String(ghostPins), + ); const first = await identity(); const pushed = Date.now(); await push.evaluate(async (id) => { diff --git a/scripts/qa-gnss.mjs b/scripts/qa-gnss.mjs index c56f9a8aab..d407853465 100644 --- a/scripts/qa-gnss.mjs +++ b/scripts/qa-gnss.mjs @@ -9,7 +9,7 @@ * stub that route in the page so they are deterministic. * * (i) LIVE — over Poland and the southern Baltic the layer settles with no error, - * one geometry per cell and legend band counts that sum to the cell + * its cells drawn and legend band counts that sum to the cell * count; cells are required only when the returned rows, binned * into H3 cells with the layer's own rules, give at least one cell * (live traffic varies by hour). Requires a non-stale response no older than 60 s. @@ -26,7 +26,7 @@ * CAMERA/GLOBE verify automatic sampling and the screen-centre anchor. * (iii) FAILURE — the route stubbed to 502: stats.error is set and the * cells already on the globe are kept. - * (iv) DISABLE — owned ground primitives are hidden. + * (iv) DISABLE — the cells' ground primitives are hidden. * (v) KEYBOARD — the row's toggle button, focused, turns the layer on * with Enter and off with Space, keeps focus and names its state. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its legend @@ -116,10 +116,34 @@ async function boot(page, { lon, lat, height }) { ); } +/** + * In the page: the GNSS cells' ground primitives, each with the collection + * drawing it. The layer draws them through the renderer's draw port as + * ground fills that never take part in picks, the only such fills the app + * draws, so they are found by that. + */ +function gnssGround() { + const out = []; + const walk = (collection) => { + for (let i = 0; i < collection.length; i++) { + const item = collection.get(i); + if (typeof item?.length === 'number' && typeof item.get === 'function') + walk(item); + else if ( + item?.allowPicking === false && + item.classificationType !== undefined + ) + out.push({ primitive: item, host: collection }); + } + }; + walk(window.__godsEyeView.viewer.scene.primitives); + return out; +} + /** Enable (or refresh) the layer and poll until it settles. */ async function enableAndSettle(page, { refresh = false } = {}) { return page.evaluate( - async (id, again) => { + async (id, again, findGround) => { const dm = window.__godsEyeView.dataManager; const layer = dm.layers.get(id).module; if (again) await dm.refreshLayer(id); @@ -131,22 +155,21 @@ async function enableAndSettle(page, { refresh = false } = {}) { const rowName = document.querySelector(`[data-layer-id="${id}"] .data-name`) ?.textContent ?? ''; - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); + // eslint-disable-next-line no-new-func + const ground = new Function(`return (${findGround})()`)(); return { stats, legend, blurb, rowName, name: layer.name, - entities: ds?.get(0)?.geometryInstances.length ?? 0, - shown: ds?.show ?? null, + drawn: ground.length > 0, + shown: ground[0]?.host.show ?? null, }; }, LAYER_ID, refresh, + String(gnssGround), ); } @@ -186,31 +209,21 @@ async function shoot(page, name) { await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) }); } -/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */ -function cellStates(id) { - const { viewer } = window.__godsEyeView; - const all = viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); - if (!ds?.length) return []; - return [ds.get(0).ready ? 0 : 1]; -} +/** Build state of every GNSS ground primitive: DONE = 0, PENDING = 1. */ +const cellStates = `() => (${gnssGround})().map(({ primitive }) => (primitive.ready ? 0 : 1))`; /** Wait until every GNSS cell's ground polygon has finished building. */ async function waitForBuiltCells(page, timeoutMs = 60000) { const built = await page - .waitForFunction( - `(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`, - { timeout: timeoutMs, polling: 250 }, - ) + .waitForFunction(`(${cellStates})().every((state) => state === 0)`, { + timeout: timeoutMs, + polling: 250, + }) .then( () => true, () => false, ); - const states = await page.evaluate( - `(${cellStates})(${JSON.stringify(LAYER_ID)})`, - ); + const states = await page.evaluate(`(${cellStates})()`); return { built, detail: `states=${JSON.stringify(states)}` }; } @@ -420,9 +433,9 @@ async function main() { } const expectedCells = binGnssCells(expectedStore).length; record( - 'LIVE: no error, one geometry per cell', - !l.stats.error && l.entities === l.stats.count, - `cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`, + 'LIVE: no error, cells drawn when there are any', + !l.stats.error && l.drawn === l.stats.count > 0, + `cells=${l.stats.count} drawn=${l.drawn} error=${JSON.stringify(l.stats.error)}`, ); if (expectedCells > 0) { record( @@ -466,8 +479,8 @@ async function main() { f.legend.find(({ label }) => label.startsWith(prefix))?.count; record( 'BANDS: 5 cells shown, the 2-aircraft cell included', - f.stats.count === 5 && f.entities === 5, - `cells=${f.stats.count} entities=${f.entities}`, + f.stats.count === 5 && f.drawn, + `cells=${f.stats.count} drawn=${f.drawn}`, ); record( 'BANDS: 5/10 and 2/2 are high, 2/30 is medium, 1/3 and 0/4 are low', @@ -774,20 +787,22 @@ async function main() { const e = await enableAndSettle(page, { refresh: true }); record( 'FAILURE: error surfaced, cells kept', - Boolean(e.stats.error) && e.stats.count === 5 && e.entities === 5, + Boolean(e.stats.error) && e.stats.count === 5 && e.drawn, `error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`, ); await shoot(page, 'failure'); // ── (iv) DISABLE ────────────────────────────────────────────────────── console.log('\n(iv) DISABLE...'); - const shown = await page.evaluate(async (id) => { - await window.__godsEyeView.dataManager.setEnabled(id, false); - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - return Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - )?.show; - }, LAYER_ID); + const shown = await page.evaluate( + async (id, findGround) => { + await window.__godsEyeView.dataManager.setEnabled(id, false); + // eslint-disable-next-line no-new-func + return new Function(`return (${findGround})()`)()[0]?.host.show; + }, + LAYER_ID, + String(gnssGround), + ); record('DISABLE: data source hidden', shown === false, `show=${shown}`); await shoot(page, 'disabled'); @@ -953,8 +968,8 @@ async function main() { const old = await enableAndSettle(aged, {}); record( 'AGE: a snapshot observed 31 min ago adds no cells and is not an error', - old.stats.count === 0 && old.entities === 0 && !old.stats.error, - `cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`, + old.stats.count === 0 && !old.drawn && !old.stats.error, + `cells=${old.stats.count} drawn=${old.drawn} error=${JSON.stringify(old.stats.error)}`, ); await aged.evaluate(() => { window.__gnssQaAgeMs = 29 * 60_000; @@ -962,8 +977,8 @@ async function main() { const recent = await enableAndSettle(aged, { refresh: true }); record( 'AGE: the same snapshot observed 29 min ago is still inside the window', - recent.stats.count === 5 && recent.entities === 5, - `cells=${recent.stats.count} entities=${recent.entities}`, + recent.stats.count === 5 && recent.drawn, + `cells=${recent.stats.count} drawn=${recent.drawn}`, ); await aged.close(); record( diff --git a/scripts/qa-heading-b3.mjs b/scripts/qa-heading-b3.mjs index b9151bbbdd..645c71d844 100644 --- a/scripts/qa-heading-b3.mjs +++ b/scripts/qa-heading-b3.mjs @@ -170,8 +170,8 @@ async function observeTrackedHostPaint(page, timeoutMs = 5000) { const tracked = viewer?.trackedEntity; const current = { elapsedMs: Math.round(performance.now() - startedAt), - entryId: tracked?.gevTrackedId || null, - hasPresentationModel: Boolean(tracked?.gevLabelModel?.title), + entryId: window.__godsEyeView?.entityRecords?.read(tracked)?.trackedId || null, + hasPresentationModel: Boolean(window.__godsEyeView?.entityRecords?.read(tracked)?.labelModel?.title), candidateCount: diagnostics.candidateCount || 0, projectedCount: diagnostics.projectedCount || 0, selectedCount: diagnostics.selectedCount || 0, @@ -612,7 +612,7 @@ async function main() { if (!pool.length) return null; const ent = v.trackedEntity; let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function') tracked = window.__godsEyeView.entityRecords.read(ent)?.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { diff --git a/scripts/qa-infra-lod.mjs b/scripts/qa-infra-lod.mjs index 5be19fe640..3c4c75c3a3 100644 --- a/scripts/qa-infra-lod.mjs +++ b/scripts/qa-infra-lod.mjs @@ -218,9 +218,11 @@ try { const gev = window.__godsEyeView; const snap = () => infraIds.map((id) => { const visibleIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < gev.viewer.dataSources.length; i++) { for (const entity of gev.viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId === id && entity.show) visibleIds.push(String(entity.id)); + const contextId = gev.entityRecords.read(entity)?.contextId; + if (contextId?.startsWith(`${id}:`) && entity.show) visibleIds.push(String(entity.id)); } } return visibleIds.sort(); diff --git a/scripts/qa-installation-navigation.mjs b/scripts/qa-installation-navigation.mjs index 5ecf03e1a8..8eff6e99bb 100644 --- a/scripts/qa-installation-navigation.mjs +++ b/scripts/qa-installation-navigation.mjs @@ -40,9 +40,29 @@ try { page.on('console', (m) => { if (m.type() === 'error') result.errors.push(m.text()); }); - await page.evaluateOnNewDocument(() => - sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'), - ); + await page.evaluateOnNewDocument(() => { + sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'); + // The site dots the layer draws, read from its draw-port point set: each + // row is a drawn dot whose pick id is the draw port's `{set, id, meta}`; + // `meta` is the site's carrier, kept while the site's geometry is. + window.__qaInstallationDots = () => { + const out = []; + const visit = (node) => { + if (!node || typeof node.get !== 'function') return; + if (typeof node.length !== 'number') return; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && typeof id.set === 'string') { + if (/^military-installations:\d+:dots$/.test(id.set)) + out.push({ id: id.id, meta: id.meta, primitive: child }); + } else visit(child); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives); + return out; + }; + }); await page.goto( args.find((a) => /^https?:/.test(a)), { waitUntil: 'domcontentloaded' }, @@ -156,14 +176,15 @@ try { .catch(() => {}); const snapshot = await page.evaluate(() => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const points = ds.entities.values.filter((e) => e.point); + const points = window.__qaInstallationDots(); const stable = points.every( (e) => !window.installationEntityRefs.has(e.id) || - window.installationEntityRefs.get(e.id) === e, + window.installationEntityRefs.get(e.id) === e.meta, + ); + window.installationEntityRefs = new Map( + points.map((e) => [e.id, e.meta]), ); - window.installationEntityRefs = new Map(points.map((e) => [e.id, e])); return { ...g.dataManager.layers .get('military-installations') @@ -186,7 +207,7 @@ try { new Set(row.ids).size !== row.ids.length ) result.failures.push( - `${name}/${height}: unstable or duplicate site entities`, + `${name}/${height}: unstable or duplicate site markers`, ); if (name.endsWith('return')) { const first = result.views.find( @@ -244,10 +265,7 @@ try { 0.6, ); await page.waitForFunction( - () => - window.__godsEyeView.viewer.dataSources - .getByName('military-installations')[0] - .entities.values.some((e) => e.point), + () => window.__qaInstallationDots().length > 0, { timeout: 5000 }, ); await page.evaluate(() => { @@ -268,8 +286,7 @@ try { await sleep(1000); await page.evaluate(async () => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const id = ds.entities.values.find((e) => e.point).id; + const id = window.__qaInstallationDots()[0].id; window.installationSubjectId = id; await g.dataManager.layers .get('military-awareness') diff --git a/scripts/qa-installation-polish.mjs b/scripts/qa-installation-polish.mjs index 6971d85ba5..8a9703e2c3 100644 --- a/scripts/qa-installation-polish.mjs +++ b/scripts/qa-installation-polish.mjs @@ -17,9 +17,11 @@ export async function checkInstallationPan(page, dir) { 'military-installations', ).module; const centerIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < g.viewer.dataSources.length; i++) for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.__localLayerId === 'local-datacenters') centerIds.push(e.id); + if (g.entityRecords.read(e)?.contextId?.startsWith('local-datacenters:')) + centerIds.push(e.id); window.__polishPanFrames = []; window.__stopPolishPan = g.viewer.scene.postRender.addEventListener(() => { const sites = [], @@ -175,18 +177,13 @@ export async function checkInstallationSelection( await import('/src/data/contextStore.js'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); - const knownFills = new Set(); - const fillEntities = () => { - const list = []; - for (let i = 0; i < g.viewer.dataSources.length; i++) - for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.id.startsWith(`${record.id}:selected-fill:`)) list.push(e); - for (const e of list) knownFills.add(e); - return list; - }; - // Geometry-instance ids prove the ground primitive actually built, not just an entity declaration. - const primitives = () => { - let count = 0; + // The selected site's fill parts, as the ground primitives built for + // the layer's fill set hold them: each instance's id is the + // draw port's pick id `{set, id}`. Only built, shown instances count, + // so this proves the ground primitive actually built, not just an + // item declaration. + const fillParts = () => { + const parts = []; const walk = (collection) => { if (collection?._collectionsArray) { for (const child of collection._collectionsArray) walk(child); @@ -194,31 +191,44 @@ export async function checkInstallationSelection( } for (let i = 0; i < (collection?.length || 0); i++) { const p = collection.get(i); - if ( - p.ready && - typeof p.getGeometryInstanceAttributes === 'function' - ) { - for (const e of knownFills) { + const ids = p?._primitive?._primitive?._instanceIds; + if (p?.ready && Array.isArray(ids)) + for (const id of ids) { + if ( + !/^military-installations:\d+:fills$/.test(id?.set) || + !String(id.id).startsWith(`${record.id}:selected-fill:`) + ) + continue; try { - const a = p.getGeometryInstanceAttributes(e); - if (a && (!a.show || a.show[0])) count++; + const a = p.getGeometryInstanceAttributes(id); + if (a && (!a.show || a.show[0])) + parts.push({ + id: id.id, + classification: p.classificationType, + }); } catch {} } - } - if (typeof p.get === 'function' || p._collectionsArray) walk(p); + if (typeof p?.get === 'function' || p?._collectionsArray) + walk(p); } }; + // The draw port adds its ground primitives under the scene's + // primitives, in its set's collection. walk(g.viewer.scene.groundPrimitives); - return count; + walk(g.viewer.scene.primitives); + return parts; + }; + window.__polishFillProbe = () => { + const parts = fillParts(); + return { + // Distinct fill parts drawn, and the built instances drawing them + // (a ground swap can draw a part twice while it lasts). + entities: new Set(parts.map((part) => part.id)).size, + primitives: parts.length, + classification: parts.map((part) => part.classification), + selected: getSelectedEntityContext()?.id || null, + }; }; - window.__polishFillProbe = () => ({ - entities: fillEntities().length, - primitives: primitives(), - classification: fillEntities().map((e) => - e.polygon.classificationType.getValue(), - ), - selected: getSelectedEntityContext()?.id || null, - }); window.__stopPolishSelection = g.viewer.scene.postRender.addEventListener(() => { window.__polishSelectionFrames.push({ @@ -333,7 +343,8 @@ export async function checkInstallationSelection( for (let y = 250; y < 650; y += 75) for (let x = 400; x < 850; x += 75) { const pick = g.viewer.scene.pick({ x, y }); - if (!pick?.id?.installationId && !pick?.id?.gevTrackedId) + // Nothing picked: no installation marker, outline or tracked contact. + if (!pick?.id) return { x, y }; } throw new Error('No empty map point'); diff --git a/scripts/qa-label-readability.mjs b/scripts/qa-label-readability.mjs index b7d17752c2..3b5e80ee49 100644 --- a/scripts/qa-label-readability.mjs +++ b/scripts/qa-label-readability.mjs @@ -257,10 +257,6 @@ async function main() { () => window.__godsEyeView?.viewer && window.__godsEyeView?.styleManager, { timeout: 60_000, polling: 100 }, ); - // flyToAustin arrives ~500 ms after init; let it start and land before any - // scene sets its own pose, or the arrival overwrites the first camera. - await new Promise((resolve) => setTimeout(resolve, 2500)); - const selected = SCENE_FILTER.length ? SCENES.filter((scene) => SCENE_FILTER.some((prefix) => scene.id.startsWith(prefix))) : SCENES; diff --git a/scripts/qa-labels.mjs b/scripts/qa-labels.mjs index fb04d00252..911b986c36 100644 --- a/scripts/qa-labels.mjs +++ b/scripts/qa-labels.mjs @@ -267,12 +267,6 @@ async function main() { { timeout: 60000, polling: 100 }, ); - // flyToAustin schedules its 600 m arrival 500 ms after initialization. - // Let that callback start, then cancel it before establishing the global - // measurement camera so startup motion cannot invalidate the sample. - await new Promise((resolve) => setTimeout(resolve, 600)); - await page.evaluate(() => window.__godsEyeView.viewer.camera.cancelFlight()); - const stateChecks = await page.evaluate((storageKey) => { const manager = window.__godsEyeView.styleManager; const restored = manager.getDetectionState(); diff --git a/scripts/qa-map-source-tray.mjs b/scripts/qa-map-source-tray.mjs index 2317259976..b07eb06136 100644 --- a/scripts/qa-map-source-tray.mjs +++ b/scripts/qa-map-source-tray.mjs @@ -342,7 +342,7 @@ try { const before = { activeId: controller.getActiveId(), creditVisible: document.body.innerText.includes('Powered by Esri'), - globeShown: styleManager.viewer.scene.globe.show, + globeShown: window.__godsEyeView.viewer.scene.globe.show, hasLayer: Boolean(controller._imageryLayer), }; provider?.errorEvent?.raiseEvent?.({ timesRetried: 0 }); @@ -369,7 +369,7 @@ try { activeId: controller.getActiveId(), lastError: controller.getState().lastError, creditVisible: document.body.innerText.includes('Powered by Esri'), - globeShown: styleManager.viewer.scene.globe.show, + globeShown: window.__godsEyeView.viewer.scene.globe.show, hasLayer: Boolean(controller._imageryLayer), active: [...document.querySelectorAll('.map-stack-chip')] .filter((chip) => chip.getAttribute('aria-pressed') === 'true') diff --git a/scripts/qa-overpass-offload.mjs b/scripts/qa-overpass-offload.mjs index 8f6594011f..4d5c7c3f0e 100644 --- a/scripts/qa-overpass-offload.mjs +++ b/scripts/qa-overpass-offload.mjs @@ -1277,8 +1277,9 @@ try { outlines = 0; for (let i = 0; i < viewer.dataSources.length; i++) for (const entity of viewer.dataSources.get(i).entities.values) { - if (!ids.has(entity.installationId || entity.id) || !entity.show) - continue; + // Outline entities are `:outline:`. + const recordId = String(entity.id).replace(/:outline:\d+$/, ''); + if (!ids.has(recordId) || !entity.show) continue; if (entity.billboard || entity.point) markers++; if (entity.polyline) outlines++; } diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index 83b3596053..bec07d25c5 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -184,6 +184,50 @@ async function main() { queueMicrotask(() => this.dispatchEvent(new Event('playing'))); return Promise.resolve(); }; + // What Radio draws, read from the renderer's draw-port sets: the + // station dots (`stations`), cluster dots (`clusters`), and the + // selected station's dot (`selected`) and bracket + // (`selected-bracket`). Each row is a drawn point or billboard whose + // pick id is the draw port's `{set, id, meta}`; `show` is whether it + // draws, its set's host included. + window.__qaRadioRows = (kind) => { + const pattern = new RegExp(`^radio:\\d+:${kind}$`); + const out = []; + const visit = (node, shown) => { + if (!node || typeof node.get !== 'function' || typeof node.length !== 'number') return; + const here = shown && node.show !== false; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && !Array.isArray(id) && typeof id.set === 'string') { + if (pattern.test(id.set)) { + out.push({ + primitive: child, + id: id.id, + meta: id.meta, + show: here && child.show !== false, + setShown: here, + }); + } + } else visit(child, here); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives, true); + return out; + }; + // The selected station's drawn dot and bracket, with its pick id. + window.__qaRadioSelected = () => { + const dot = window.__qaRadioRows('selected')[0] || null; + if (!dot) return null; + const bracket = window.__qaRadioRows('selected-bracket')[0] || null; + return { + id: dot.id, + show: dot.show, + position: dot.primitive.position, + dot, + bracket, + }; + }; }); await page.setRequestInterception(true); let catalogDegraded = false; @@ -420,7 +464,7 @@ async function main() { await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const result = { presentationActive: module.getUIState().presentationActive, - markerSourceVisible: gev.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), tunerHidden: document.getElementById('radio-tuner').hidden, filterDisabled: document.getElementById('radio-filter').disabled, prevDisabled: document.getElementById('radio-prev-btn').disabled, @@ -514,7 +558,7 @@ async function main() { const disablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -583,7 +627,7 @@ async function main() { const enablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -687,8 +731,6 @@ async function main() { const sample = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const dataSource = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const { radioStationIdFromPick } = await import('/src/data/radio.js'); return new Promise((resolve) => { @@ -710,7 +752,9 @@ async function main() { host: getWorldOverlayDiagnostics(), paintedSingletonIds, pickableSingletonIds, - nativeLabelCount: dataSource.entities.values.filter((entity) => Boolean(entity.label)).length, + // The station dots are a draw-port point set, which draws no + // labels of its own; a label primitive would be a row here. + nativeLabelCount: window.__qaRadioRows('stations').filter((row) => row.primitive.text !== undefined).length, }); }; const timeout = setTimeout(finish, 500); @@ -1255,12 +1299,10 @@ async function main() { }); await page.select('#radio-filter', 'all'); const allPalette = await page.evaluate(() => { - const source = Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => ( - window.__godsEyeView.viewer.dataSources.get(index) - )).find((item) => item.name === 'Radio stations'); + const rows = new Map(window.__qaRadioRows('stations').map((row) => [row.id, row])); const colorFor = (index) => { const id = `radio:00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`; - const color = source?.entities.getById(id)?.point?.color?.getValue?.(); + const color = rows.get(id)?.primitive.color; return color ? [color.red, color.green, color.blue].map((value) => Math.round(value * 255)) : null; }; return { news: colorFor(0), talk: colorFor(1), music: colorFor(7) }; @@ -1277,8 +1319,6 @@ async function main() { const viewer = window.__godsEyeView.viewer; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const baselineSolveRevision = getWorldOverlayDiagnostics().solveRevision; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const ellipsoid = viewer.scene.globe.ellipsoid; viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -1289,26 +1329,25 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - source.clustering.enabled = false; viewer.scene.requestRender(); - await new Promise((resolve) => setTimeout(resolve, 100)); + // The camera's move clusters the stations again: wait for a cluster dot. return new Promise((resolve) => { - const originalPixelRange = source.clustering.pixelRange; - const timeout = setTimeout(() => { - remove(); - resolve(null); - }, 2_000); - const remove = source.clustering.clusterEvent.addEventListener(async (entities, cluster) => { - clearTimeout(timeout); - remove(); + const started = performance.now(); + const poll = async () => { + const cluster = window.__qaRadioRows('clusters').find((row) => row.show); + if (!cluster) { + if (performance.now() - started > 2_000) resolve(null); + else setTimeout(poll, 50); + return; + } + // The cluster's dot is a draw-port point, which draws no label. const native = { - count: entities.length, - labelShow: cluster.label.show, - labelText: cluster.label.text, - pointSize: cluster.point.pixelSize, - pointMaxDistance: cluster.point.distanceDisplayCondition?.far ?? null, + count: cluster.meta.stationIds.length, + labelShow: cluster.primitive.text !== undefined, + labelText: cluster.primitive.text ?? '', + pointSize: cluster.primitive.pixelSize, + pointMaxDistance: cluster.primitive.distanceDisplayCondition?.far ?? null, }; - source.clustering.pixelRange = originalPixelRange; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; await new Promise((done) => setTimeout(done, 0)); let painted = null; @@ -1345,9 +1384,8 @@ async function main() { source: radio.getOverlayDiagnostics(), host: painted?.host || getWorldOverlayDiagnostics(), }); - }); - source.clustering.enabled = true; - viewer.scene.requestRender(); + }; + poll(); }); }); check( @@ -1393,15 +1431,13 @@ async function main() { 0, cameraRadius * cameraRadius - ellipsoid.maximumRadius * ellipsoid.maximumRadius, )); - const points = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.clustering?._clusterPointCollection; let clusterPoint = null; - // Pool order is not visibility order after a camera change. Choose an - // on-screen point independently of the native pick result being tested. + // Choose an on-screen cluster dot independently of the native pick + // result being tested. const visiblePoints = []; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point?.show || !Array.isArray(point.id) || !point.id.length) continue; + for (const row of window.__qaRadioRows('clusters')) { + const point = row.primitive; + if (!row.show || !row.meta?.stationIds?.length) continue; const anchor = viewer.scene.cartesianToCanvasCoordinates(point.position); if (!anchor) continue; if (anchor.x < 0 || anchor.y < 0 || anchor.x > viewer.canvas.clientWidth || anchor.y > viewer.canvas.clientHeight) continue; @@ -2432,26 +2468,23 @@ async function main() { await sleep(700); const newsClusterTarget = await page.evaluate(() => { const gev = window.__godsEyeView; - const source = Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const points = source.clustering._clusterPointCollection; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point.show || !Array.isArray(point.id) || !point.id.length) continue; - const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(point.position); + const rows = window.__qaRadioRows('clusters'); + for (const row of rows) { + if (!row.show || !row.meta?.stationIds?.length) continue; + const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(row.primitive.position); if (!canvasPoint) continue; return { x: canvasPoint.x, y: canvasPoint.y, - firstId: String(point.id[0]?.id || '').replace(/^radio:/, ''), - pointIds: point.id.map((entity) => entity.id), + firstId: row.meta.stationIds[0], + pointIds: row.meta.stationIds.map((id) => `radio:${id}`), }; } return { missing: true, - points: Array.from({ length: points?.length || 0 }, (_, index) => ({ - show: points.get(index).show, - pointIds: Array.isArray(points.get(index)?.id) ? points.get(index).id.length : 0, + points: rows.map((row) => ({ + show: row.show, + pointIds: row.meta?.stationIds?.length || 0, })), }; }); @@ -2654,9 +2687,13 @@ async function main() { const horizon = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const ellipsoid = viewer.scene.globe.ellipsoid; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const visibleIds = () => source.entities.values.filter((entity) => entity.show).map((entity) => entity.id); + // A station dot standing in a cluster is hidden too; the cluster's + // dot draws its stations' ids. + const visibleIds = () => [ + ...window.__qaRadioRows('stations').filter((row) => row.show).map((row) => row.id), + ...window.__qaRadioRows('clusters').filter((row) => row.show) + .flatMap((row) => row.meta.stationIds.map((id) => `radio:${id}`)), + ]; const setView = (lon, lat = 0) => { viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -2702,8 +2739,7 @@ async function main() { buttons: type === 'pointerup' || type === 'pointercancel' ? 0 : 1, })); const snapshot = () => { - const markerId = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = window.__qaRadioSelected()?.id || null; return { slot: Number(slider.value), markerId, @@ -2823,8 +2859,7 @@ async function main() { // The tuner renders from the Radio store; let Vue patch before reading. await Promise.resolve(); const shiftedSlot = Number(slider.value); - const previewBeforeCancel = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const previewBeforeCancel = window.__qaRadioSelected()?.id || null; const flyToCallsBeforeCancel = flyToCalls.length; pointer('pointercancel', targetIndex); await Promise.resolve(); @@ -2840,8 +2875,7 @@ async function main() { tuningActive: afterState.tuningActive, }; const flyToCallsAfterCancel = flyToCalls.length; - const selectedEntity = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')) || null; + const selectedEntity = () => window.__qaRadioSelected(); const restoredEntity = selectedEntity(); const previewId = restoredEntity?.id || null; after.previewId = previewId; @@ -2858,7 +2892,7 @@ async function main() { filter: changedFilterState.filter, restoredStationId: changedFilterState.tuningRestoredStationId, selectedId: changedFilterState.selected?.id || null, - entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity !== restoredEntity), + entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity.dot.primitive !== restoredEntity?.dot.primitive), entityId: changedFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === changedFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - changedFilterPlays, @@ -2882,7 +2916,7 @@ async function main() { restoredAfter: sameFilterState.tuningRestoredStationId, filter: sameFilterState.filter, selectedId: sameFilterState.selected?.id || null, - entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity !== sameFilterRestoredEntity), + entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity.dot.primitive !== sameFilterRestoredEntity?.dot.primitive), entityId: sameFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === sameFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - sameFilterPlays, @@ -3327,8 +3361,7 @@ async function main() { cancelable: true, key: value, })); - const markerId = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = () => window.__qaRadioSelected()?.id || null; const startIndex = Number(slider.value); const expectedIndex = Math.min(style._radioControls._radioTunerStations.length - 1, startIndex + 1); const expectedId = style._radioControls._radioTunerStations[expectedIndex]?.id || null; @@ -3428,8 +3461,7 @@ async function main() { centerIndex, slot: Number(slider.value), ratio: Number(document.getElementById('radio-tuner').style.getPropertyValue('--radio-tuner-ratio')), - markerId: gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null, + markerId: window.__qaRadioSelected()?.id || null, expectedId: style._radioControls._radioTunerStations[centerIndex]?.id || null, }; slider.dispatchEvent(new PointerEvent('pointercancel', { @@ -3554,9 +3586,6 @@ async function main() { const markerTarget = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - source.clustering.enabled = false; const selectedId = radio.getUIState().selected?.id || null; if (selectedId) { radio.selectStation(selectedId, { @@ -3583,9 +3612,6 @@ async function main() { }); viewer.scene.requestRender(); }); - // Cesium clears its private cluster collections during the rendered - // disabled-state update. Publish the same-filter singleton overlay only - // after that frame so this harness mutation cannot leak stale clusters. radio.setFilter('news'); viewer.scene.requestRender(); await new Promise((resolve) => setTimeout(resolve, 500)); @@ -3614,14 +3640,14 @@ async function main() { let visibleEntityCount = 0; let singletonEntityCount = 0; let paintedSingletonCount = 0; - for (const entity of source.entities.values) { - if (!entity.show) continue; + for (const row of window.__qaRadioRows('stations')) { + if (!row.show) continue; visibleEntityCount += 1; - const id = String(entity.id).slice('radio:'.length); + const id = String(row.id).slice('radio:'.length); const overlayId = `station:${id}`; if (!singletonIds.has(overlayId)) continue; singletonEntityCount += 1; - const position = entity.position?.getValue(viewer.clock.currentTime); + const position = row.primitive.position; const canvas = position && viewer.scene.cartesianToCanvasCoordinates(position); const paintRect = getOverlayPaintRect('radio', overlayId); if (paintRect) paintedSingletonCount += 1; @@ -3631,7 +3657,7 @@ async function main() { id, x: canvas.x, y: canvas.y, - ownsNativeLabel: Boolean(entity.label), + ownsNativeLabel: row.primitive.text !== undefined, labelPainted: true, singletonTexts: diagnostics.singletonTexts, }); @@ -3700,8 +3726,6 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); radio.stopPlayback(); - Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations').clustering.enabled = true; // Next plays only while a stream is active, so start from a playing station. radio.selectStation('00000000-0000-4000-8000-000000000001', { autoplay: true, focus: false }); }); @@ -3757,8 +3781,7 @@ async function main() { const playing = await page.evaluate(async () => { const radio = window.__godsEyeView.dataManager.layers.get('radio').module; const viewer = window.__godsEyeView.viewer; - const selectedEntity = window.__godsEyeView.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')); + const selectedEntity = window.__qaRadioSelected(); const { getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const flightTargets = window.__qaRadioFlyToCalls.map(({ destination }) => { const position = viewer.scene.globe.ellipsoid.cartesianToCartographic(destination); @@ -3775,11 +3798,10 @@ async function main() { flightTargets, cameraHeight: window.__qaRadioCameraHeight, playLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'), - regularMarkerSize: Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => window.__godsEyeView.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.entities.values[0]?.point?.pixelSize?.getValue(), - selectedMarkerSize: selectedEntity?.point?.pixelSize?.getValue(), - selectedBracketWidth: selectedEntity?.billboard?.width?.getValue(), - selectedOwnsNativeLabel: Boolean(selectedEntity?.label), + regularMarkerSize: window.__qaRadioRows('stations')[0]?.primitive.pixelSize, + selectedMarkerSize: selectedEntity?.dot.primitive.pixelSize, + selectedBracketWidth: selectedEntity?.bracket?.primitive.width, + selectedOwnsNativeLabel: Boolean(window.__qaRadioRows('selected-label').length), overlay: radio.getOverlayDiagnostics(), host: getWorldOverlayDiagnostics(), expectedPrimary: window.__qaRadioExpectedPrimary, @@ -3817,7 +3839,7 @@ async function main() { id: `qa:${ownerPrefix}:radio-camera-owner`, position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = `${ownerPrefix}:qa-radio-camera-owner`; + window.__godsEyeView.entityRecords.write(owner).trackedId = `${ownerPrefix}:qa-radio-camera-owner`; viewer.trackedEntity = owner; await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const beforeStationId = radio.getUIState().selected?.id || null; @@ -3831,7 +3853,7 @@ async function main() { afterStationId: radio.getUIState().selected?.id || null, flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, }; viewer.trackedEntity = undefined; viewer.entities.remove(owner); @@ -3867,11 +3889,11 @@ async function main() { id: 'qa:flights:delayed-radio-fallback-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-delayed-radio-fallback-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-delayed-radio-fallback-owner'; viewer.trackedEntity = owner; window.__qaDelayedRadioTrackingOwner = owner; window.__qaRejectRadioPlay(); - return owner.gevTrackedId; + return window.__godsEyeView.entityRecords.read(owner)?.trackedId; }); await page.waitForFunction(() => window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().audioState === 'playing'); const delayedFallbackOwnership = await page.evaluate((beforeFlyToCalls) => { @@ -3880,7 +3902,7 @@ async function main() { const result = { flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, selectedId: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().selected?.id || null, }; viewer.trackedEntity = undefined; @@ -3940,8 +3962,12 @@ async function main() { destination, orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let painted = null; @@ -3949,7 +3975,7 @@ async function main() { // after the camera jump, so a stationary view waits for both to settle. for ( let attempt = 0; - attempt < 20 && !(painted?.rect && selectedEntity?.show === true); + attempt < 20 && !(painted?.rect && selectedEntity()?.show === true); attempt += 1 ) { painted = await new Promise((resolve) => { @@ -3974,7 +4000,7 @@ async function main() { expectedEntryId, rect: painted?.rect || null, host: painted?.host || getWorldOverlayDiagnostics(), - selectedEntityShow: selectedEntity?.show, + selectedEntityShow: selectedEntity()?.show, cameraHeight: viewer.camera.positionCartographic.height, }; }); @@ -3999,8 +4025,12 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let rect = null; @@ -4025,7 +4055,8 @@ async function main() { viewer.scene.requestRender(); }); } - const entityPosition = selectedEntity?.position?.getValue?.(); + const selectedDrawn = selectedEntity(); + const entityPosition = selectedDrawn?.position; const entityAnchor = entityPosition && viewer.scene.cartesianToCanvasCoordinates(entityPosition); let selectedNativePick = null; @@ -4035,13 +4066,16 @@ async function main() { // billboard satisfy the loop while the point anchor was still missing. for (let attempt = 0; entityAnchor && attempt < 8 && !selectedPointPick; attempt += 1) { const picks = viewer.scene.drillPick(entityAnchor, 16) || []; - selectedNativePick = picks.find((picked) => picked?.id === selectedEntity); + selectedNativePick = picks.find((picked) => ( + picked?.primitive === selectedDrawn.dot.primitive + || picked?.primitive === selectedDrawn.bracket?.primitive + )); selectedPointPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.dot.primitive && String(picked?.primitive?.constructor?.name || '').includes('PointPrimitive') )); selectedBillboardPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.bracket?.primitive && String(picked?.primitive?.constructor?.name || '').includes('Billboard') )); if (!selectedPointPick) { @@ -4054,18 +4088,15 @@ async function main() { }); } } - const selectedPointDistance = selectedEntity?.point?.distanceDisplayCondition?.getValue?.(); + const selectedPointDistance = selectedDrawn?.dot.primitive.distanceDisplayCondition; return { rect, selectedNativePickable: Boolean(selectedNativePick), selectedPointPickable: Boolean(selectedPointPick), selectedBillboardPickable: Boolean(selectedBillboardPick), selectedPointMaxDistance: selectedPointDistance?.far ?? null, - selectedEntityShow: selectedEntity?.show, - selectedBracketVisible: Boolean( - selectedEntity?.billboard - && selectedEntity.billboard.show?.getValue?.() !== false - ), + selectedEntityShow: selectedDrawn?.show, + selectedBracketVisible: Boolean(selectedDrawn?.bracket?.show), entityAnchor: entityAnchor ? { x: entityAnchor.x, y: entityAnchor.y } : null, entityDistance: entityPosition ? Math.hypot( @@ -4222,7 +4253,7 @@ async function main() { id: 'qa:flights:radio-recenter-stage-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-radio-recenter-stage-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-radio-recenter-stage-owner'; viewer.trackedEntity = owner; completeFlight(0); const trackingBetweenStagesCalls = calls.length; diff --git a/scripts/qa-sky-model-lighting.mjs b/scripts/qa-sky-model-lighting.mjs index 206d19d785..6352a3be96 100644 --- a/scripts/qa-sky-model-lighting.mjs +++ b/scripts/qa-sky-model-lighting.mjs @@ -32,13 +32,15 @@ try { const results = await page.evaluate(async () => { window.CESIUM_BASE_URL = '/cesium/'; // Use StarrySky's exact Vite dependency URL, including its version query. - const source = await fetch('/src/sky/starrySky.js').then((r) => r.text()); + const source = await fetch('/src/render/cesium/starrySky.js').then((r) => + r.text(), + ); const cesiumUrl = source.match( /from ["']([^"']*\/cesium\.js[^"']*)["']/, )?.[1]; if (!cesiumUrl) throw new Error('run against the Vite dev server'); const C = await import(cesiumUrl); - const { StarrySky } = await import('/src/sky/starrySky.js'); + const { StarrySky } = await import('/src/render/cesium/starrySky.js'); const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z'); const results = {}; for (const kind of ['black', 'starry', 'white']) { diff --git a/scripts/qa-street-level.mjs b/scripts/qa-street-level.mjs index 18616b4ceb..3dd0a3aa5f 100644 --- a/scripts/qa-street-level.mjs +++ b/scripts/qa-street-level.mjs @@ -378,7 +378,9 @@ const findPick = (page, prefix, { box = null, step = 3 } = {}) => }; for (let py = y; py < y + h; py += stride) for (let px = x; px < x + w; px += stride) { - const id = scene.pick({ x: px, y: py })?.id; + // A drawn item's pick id names its draw set and its own id. + const picked = scene.pick({ x: px, y: py })?.id; + const id = typeof picked === 'string' ? picked : picked?.id; if (typeof id === 'string' && id.startsWith(want)) return { x: rect.left + px, diff --git a/scripts/qa-stub-boot.mjs b/scripts/qa-stub-boot.mjs new file mode 100644 index 0000000000..a3a3292ac7 --- /dev/null +++ b/scripts/qa-stub-boot.mjs @@ -0,0 +1,427 @@ +#!/usr/bin/env node +/** + * Boot the whole application on the stub renderer with only the contract's + * required members (`dev/stub-app/main.js`), headless, and check that: + * + * - it starts, with no Cesium module requested at all (no script, no + * worker, no asset it would fetch; the one Cesium stylesheet the build's + * `vite-plugin-cesium` links into every page is reported, not failed); + * - the credits show in the application's own line, and its list opens + * with the data credits; + * - each data layer named below turns on, and off, without a page error or + * a console error (a feed's failed response is reported as the feed's, + * not failed: without network access or keys a feed answers with an + * error, and the layer must take that without one of its own; the dev + * server's client's own errors are reported as the tooling's); + * - with `--strict`, each of them draws on the stub: items in its draw sets, + * imagery added through the globe port, or a field (`draw.field`). + * + * The page is the application's own (`index.html`), served with the stub + * entry in place of `src/main.js`. Without `--url` it starts a Vite dev + * server of this checkout on `--port` (default 5290) and stops it after. + * Live feeds answer through the dev server's providers, so without network + * access or keys a layer turns on with nothing to draw: the run says so, + * and only `--strict` fails it. + * + * `--all-capabilities` gives the stub every capability instead, to see what + * the layers draw where a renderer has them all. + * + * npm run qa:stub-boot [-- --url http://127.0.0.1:5280] [--strict] + * [--settle-ms 20000] [--json path] [--all-capabilities] + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import puppeteer from 'puppeteer'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** The data layers the stub must run, by catalog id. */ +export const STUB_BOOT_LAYERS = Object.freeze([ + 'flights', + 'military', + 'transit', + 'traffic', + 'cctv', + 'ais-live-vessels', + 'weather-radar', + 'weather-satellite', + 'wind', + 'satellites', + 'local-firms', + 'wildlife-sightings', + 'shipwrecks', + 'news', +]); + +/** A request that is Cesium: the package, its pre-bundle, or its assets. */ +export const isCesiumRequest = (url) => + /(?:^|[/._-])cesium(?:[/._-]|$)/i.test(new URL(url).pathname); + +/** The stylesheet `vite-plugin-cesium` links into every page it serves. */ +const isPluginStylesheet = (url, type) => + type === 'stylesheet' && + new URL(url).pathname === '/cesium/Widgets/widgets.css'; + +/** + * A browser's line for a feed's response that failed: one of the dev + * server's providers (`/api/`) or another origin's. The application's own + * modules and assets failing are the page's. + */ +const isFailedResponse = (text, at, base) => { + if (!/^Failed to load resource:/.test(text)) return false; + try { + const url = new URL(at); + return ( + url.origin !== new URL(base).origin || url.pathname.startsWith('/api/') + ); + } catch { + return false; + } +}; + +/** + * An error the dev server's own client logs (its socket to the server, which + * a headless browser can refuse): the tooling's, not the application's. + */ +const isDevClient = (at) => { + try { + return new URL(at).pathname === '/@vite/client'; + } catch { + return false; + } +}; + +function parseArgs(argv) { + const args = { strict: false, port: 5290, settleMs: 20_000 }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--strict') args.strict = true; + else if (arg === '--url') args.url = argv[++i]; + else if (arg === '--port') args.port = Number(argv[++i]); + else if (arg === '--settle-ms') args.settleMs = Number(argv[++i]); + else if (arg === '--json') args.json = argv[++i]; + else if (arg === '--all-capabilities') args.allCapabilities = true; + else throw new Error(`Unknown argument: ${arg}`); + } + return args; +} + +async function startViteServer(port) { + const { createServer } = await import('vite'); + const server = await createServer({ + root: ROOT, + configFile: path.join(ROOT, 'vite.config.js'), + // No hot reload: the page is loaded once and nothing edits it. + server: { port, strictPort: true, host: '127.0.0.1', hmr: false }, + logLevel: 'warn', + }); + await server.listen(); + return server; +} + +/** + * In the page: what the stub renderer draws now, its draw sets with how many + * items each holds and the globe port's imagery layers, and how many calls + * it has had on each port member. + */ +function readDrawn() { + const renderer = window.__stubBoot?.renderers?.[0]; + if (!renderer) return null; + const testing = renderer.testing; + const calls = {}; + for (const call of testing.calls) { + const key = `${call.port}.${call.member}`; + calls[key] = (calls[key] ?? 0) + 1; + } + return { + sets: Object.fromEntries( + testing.sets().map((id) => [id, testing.setRecord(id)?.items?.size ?? 0]), + ), + imagery: renderer.globe.imagery.list().length, + calls, + }; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const server = args.url ? null : await startViteServer(args.port); + try { + await run(args); + } finally { + await server?.close(); + } +} + +async function run(args) { + const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, ''); + const browser = await puppeteer.launch({ + headless: true, + executablePath: + process.env.PUPPETEER_EXECUTABLE_PATH || + (await puppeteer.executablePath()), + defaultViewport: { width: 1280, height: 800 }, + protocolTimeout: 300_000, + args: ['--no-sandbox'], + }); + /** Every error the page reports, in order: `page`, `console` or `response`. */ + const errors = []; + const cesiumRequests = []; + const cesiumStylesheets = []; + const report = { url: base, layers: {}, ok: false }; + try { + const page = await browser.newPage(); + page.on('console', (message) => { + if (message.type() !== 'error') return; + const text = message.text(); + const at = message.location()?.url ?? null; + errors.push({ + kind: isFailedResponse(text, at, base) + ? 'response' + : isDevClient(at) + ? 'tooling' + : 'console', + text, + at, + }); + }); + page.on('pageerror', (error) => + errors.push({ kind: 'page', text: String(error?.stack || error) }), + ); + await page.setRequestInterception(true); + page.on('request', async (request) => { + const url = request.url(); + if (url.startsWith(base) && isCesiumRequest(url)) + (isPluginStylesheet(url, request.resourceType()) + ? cesiumStylesheets + : cesiumRequests + ).push(url); + // The application's page, with the stub entry in place of its own. + if (request.isNavigationRequest() && url.startsWith(base)) { + const response = await fetch(url); + const html = (await response.text()).replace( + 'src="/src/main.js"', + 'src="/dev/stub-app/main.js"', + ); + if (!html.includes('/dev/stub-app/main.js')) + throw new Error('The page has no /src/main.js entry to replace'); + await request.respond({ + status: response.status, + contentType: 'text/html', + body: html, + }); + return; + } + await request.continue(); + }); + await page.goto( + `${base}/${args.allCapabilities ? '?capabilities=all' : ''}`, + { waitUntil: 'load', timeout: 180_000 }, + ); + await page.waitForFunction(() => window.__stubBoot, { timeout: 180_000 }); + const started = await page.evaluate(() => window.__stubBoot.started); + report.started = started; + if (!started.ok) throw new Error(`Startup failed: ${started.error}`); + await page.waitForFunction(() => window.__godsEyeView?.dataManager, { + timeout: 60_000, + }); + report.renderer = await page.evaluate(() => { + const renderer = window.__stubBoot.renderers[0]; + return { + id: renderer.id, + capabilities: [...renderer.capabilities], + canvasInPage: document.contains(renderer.canvas), + }; + }); + report.startupErrors = errors.slice(); + // The credits show in the application's own line, with no Cesium: the + // line is on screen and its list opens with the data credits in it. + report.credits = await page.evaluate(async () => { + const line = document.getElementById('gev-credits'); + const expand = line?.querySelector('.gev-credits-expand'); + const panel = document.getElementById('gev-credits-panel'); + const box = line?.getBoundingClientRect(); + const visible = + Boolean(box && box.width > 0 && box.height > 0) && + getComputedStyle(line).visibility !== 'hidden'; + expand?.click(); + await new Promise((resolve) => requestAnimationFrame(resolve)); + const listed = + panel?.hidden === false ? panel.querySelectorAll('li').length : 0; + expand?.click(); + return { visible, line: line?.textContent ?? null, listed }; + }); + console.log( + `credits: ${report.credits.visible ? 'shown' : 'NOT shown'}; line "${report.credits.line}"; ${report.credits.listed} listed`, + ); + const known = await page.evaluate(() => + window.__godsEyeView.dataManager.getAll().map((layer) => layer.id), + ); + report.missingLayers = STUB_BOOT_LAYERS.filter((id) => !known.includes(id)); + for (const id of STUB_BOOT_LAYERS) { + if (!known.includes(id)) continue; + const errorsBefore = errors.length; + const before = await page.evaluate(readDrawn); + const enabled = await page.evaluate( + (layerId) => + window.__godsEyeView.dataManager + .setEnabled(layerId, true, { origin: 'user' }) + .then( + // It can answer false rather than throw: on is what it says. + (value) => ({ + ok: + value !== false && + window.__godsEyeView.dataManager.isEnabled(layerId), + value: value ?? null, + }), + (error) => ({ ok: false, error: String(error?.stack || error) }), + ), + id, + ); + // Feeds load on their own schedule; keep ticking until they draw. + const deadline = Date.now() + args.settleMs; + let drawn = { sets: {}, imagery: 0, calls: {}, fields: 0 }; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 1_000)); + const now = await page.evaluate(readDrawn); + drawn = { + sets: Object.fromEntries( + Object.entries(now.sets).filter( + ([setId, items]) => items > 0 && before.sets[setId] !== items, + ), + ), + imagery: Math.max(0, now.imagery - before.imagery), + calls: Object.fromEntries( + Object.entries(now.calls) + .map(([key, n]) => [key, n - (before.calls[key] ?? 0)]) + .filter(([, n]) => n > 0), + ), + }; + drawn.fields = drawn.calls['draw.field'] ?? 0; + if (Object.keys(drawn.sets).length || drawn.imagery || drawn.fields) + break; + } + const stats = await page.evaluate((layerId) => { + const row = window.__godsEyeView.dataManager + .getAll() + .find((layer) => layer.id === layerId); + return { + enabled: row?.enabled ?? null, + count: row?.stats?.count ?? null, + error: row?.stats?.error ?? null, + source: row?.stats?.source ?? null, + }; + }, id); + const disabled = await page.evaluate( + (layerId) => + window.__godsEyeView.dataManager + .setEnabled(layerId, false, { origin: 'user' }) + .then( + (value) => ({ + ok: + value !== false && + !window.__godsEyeView.dataManager.isEnabled(layerId), + }), + (error) => ({ ok: false, error: String(error?.stack || error) }), + ), + id, + ); + const layerErrors = errors.slice(errorsBefore); + report.layers[id] = { + enabled, + disabled, + stats, + drawn, + errors: layerErrors.filter( + (error) => error.kind === 'page' || error.kind === 'console', + ), + failedResponses: layerErrors + .filter((error) => error.kind === 'response') + .map((error) => error.at), + }; + const what = [ + ...Object.entries(drawn.sets).map(([setId, n]) => `${setId}=${n}`), + ...(drawn.imagery ? [`${drawn.imagery} imagery layer(s)`] : []), + ...(drawn.fields ? [`${drawn.fields} field(s)`] : []), + ]; + console.log( + `${id}: ${enabled.ok && disabled.ok ? 'ran' : 'FAILED'}; drew ${ + what.length ? what.join(', ') : 'nothing' + }${stats.error ? `; feed: ${stats.error}` : ''}${ + report.layers[id].failedResponses.length + ? `; ${report.layers[id].failedResponses.length} failed response(s)` + : '' + }`, + ); + } + report.ok = true; + } catch (error) { + // Reported with the rest below, so the report and errors are kept. + report.failure = String(error?.stack || error); + } finally { + report.cesiumRequests = cesiumRequests; + report.cesiumStylesheets = cesiumStylesheets; + report.errors = errors; + await browser.close(); + } + const pageErrors = errors.filter((error) => error.kind === 'page'); + const consoleErrors = errors.filter((error) => error.kind === 'console'); + const failedResponses = errors.filter((error) => error.kind === 'response'); + const toolingErrors = errors.filter((error) => error.kind === 'tooling'); + const problems = []; + if (report.failure) problems.push(`the run stopped: ${report.failure}`); + if (!report.started?.ok) problems.push('the application did not start'); + if (!report.renderer?.canvasInPage) + problems.push("the stub's canvas is not in the page"); + if ( + report.started?.ok && + (!report.credits?.visible || !report.credits.listed) + ) + problems.push('the credits line is not shown, or its list is empty'); + if (cesiumRequests.length) + problems.push(`Cesium was requested: ${cesiumRequests.join(', ')}`); + if (pageErrors.length) problems.push(`${pageErrors.length} page error(s)`); + if (consoleErrors.length) + problems.push(`${consoleErrors.length} console error(s)`); + if (report.missingLayers?.length) + problems.push(`layers not in the catalog: ${report.missingLayers}`); + for (const [id, layer] of Object.entries(report.layers)) { + if (!layer.enabled.ok || !layer.disabled.ok) + problems.push(`${id} failed to turn on or off`); + if ( + args.strict && + !Object.keys(layer.drawn.sets).length && + !layer.drawn.imagery && + !layer.drawn.fields + ) + problems.push(`${id} drew nothing`); + } + report.problems = problems; + if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2)); + for (const error of [...pageErrors, ...consoleErrors]) + console.error(`${error.kind} error: ${error.text} (${error.at ?? '?'})`); + if (cesiumStylesheets.length) + console.log( + `note: the build's Cesium plugin linked ${cesiumStylesheets.join(', ')}`, + ); + if (toolingErrors.length) + console.log( + `note: the dev server's client logged ${toolingErrors.length} error(s): ${[ + ...new Set(toolingErrors.map((error) => error.text)), + ].join(' | ')}`, + ); + if (failedResponses.length) + console.log( + `note: ${failedResponses.length} feed response(s) failed (keys or network)`, + ); + if (problems.length) { + console.error(`FAIL: ${problems.join('; ')}`); + process.exitCode = 1; + } else console.log('ok: the application runs on the stub renderer'); +} + +if (import.meta.url === `file://${process.argv[1]}`) + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/scripts/qa-terrain-429.mjs b/scripts/qa-terrain-429.mjs index 8164e34b5b..8db513d2c2 100644 --- a/scripts/qa-terrain-429.mjs +++ b/scripts/qa-terrain-429.mjs @@ -8,7 +8,7 @@ * answers HTTP 429 for most of them. This harness drives that burst, counts the * throttled responses, keeps the first 429's headers as evidence, and then * checks whether every throttled tile eventually loaded — the contract the - * client-side retry in `src/maps/terrain.js` provides. + * client-side retry in `src/render/cesium/mapTerrain.js` provides. * * Run against a keyless dev server (no Google or ion credentials): * env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180 diff --git a/scripts/qa-traffic-baseline.mjs b/scripts/qa-traffic-baseline.mjs index 7059bf4381..57b1bea875 100644 --- a/scripts/qa-traffic-baseline.mjs +++ b/scripts/qa-traffic-baseline.mjs @@ -8,13 +8,16 @@ * 1. exact-viewport revisit (traffic module's full-road cache), * 2. adjacent 0.4–2 km pan (new exact bbox with heavy spatial overlap), * 3. cold city (no traffic-module entry for that city), - * 4. degraded upstream (synthetic delay on `/api/overpass` only). + * 4. degraded upstream (synthetic delay on the road requests: OpenFreeMap's + * host, which only traffic reads in this capture, or the Overpass proxy). * - * The proxy's actual `X-Overpass-Cache` result is printed for every network - * pass, so HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference. - * The degraded leg delays request release in Puppeteer; it exercises the same - * fetch-start→response boundary without adding a failure switch to the - * application or proxy. Pass `--degraded-delay-ms 0` to skip that leg. + * Keyless roads come from OpenFreeMap vector tiles (`tiles.openfreemap.org`); + * a build that still reads them through the Overpass proxy has its + * `X-Overpass-Cache` result printed for every network pass, so + * HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference ("—" for + * tiles). The degraded leg delays the road requests' release in Puppeteer; + * it exercises the same fetch-start→response boundary without adding a + * failure switch to the application or proxy. Pass `--degraded-delay-ms 0` to skip that leg. * TomTom status is intercepted as keyless so no live-flow key is required and * the capture isolates the OSM road-to-visible-dot chain. * @@ -93,9 +96,42 @@ function debugUrl(rawUrl) { return url.toString(); } -/** Position the camera and explicitly raise the boundaries the layer observes. */ +/** + * Let the camera report a move the way a user's does: traffic hears the + * camera port's `changed` at its own 5% threshold (layers/traffic/policy.js + * CAMERA_CHANGED_THRESHOLD), which the port measures on every scene tick + * (the first measurement after a listener subscribes only records its + * baseline pose). Waiting for two drawn frames after the move is the sync + * point that the port has measured it. Cesium's own moveEnd (500 ms after + * stillness) is left to Cesium, as in the app; traffic re-checks the view + * on it. Installed in the page as `window.__qaRenderAfterMove`; throws when + * the frames do not draw within 5 s. + */ +function installRenderAfterMove() { + window.__qaRenderAfterMove = (gev) => new Promise((resolve, reject) => { + const scene = gev.viewer.scene; + let frames = 0; + let remove = null; + const timer = setTimeout(() => { + remove(); + reject(new Error(`the camera move rendered ${frames} frame(s) in 5 s`)); + }, 5000); + remove = scene.postRender.addEventListener(() => { + if (++frames >= 2) { + clearTimeout(timer); + remove(); + resolve(frames); + return; + } + scene.requestRender(); + }); + scene.requestRender(); + }); +} + +/** Position the camera and render, so the layer hears the move as it would a user's. */ async function moveCamera(page, view) { - return page.evaluate((v) => { + return page.evaluate(async (v) => { const gev = window.__godsEyeView; const module = gev.dataManager.layers.get('traffic').module; const beforeLastUpdate = module.getStats().lastUpdate; @@ -115,12 +151,7 @@ async function moveCamera(page, view) { roll: 0, }, }); - // setView normally propagates through Cesium's render loop. Raising these - // explicitly makes the capture boundary deterministic across GPU speeds. - // Pairing still flows through camera.changed's schedule-time anchor; the - // synthetic moveEnd is emitted only as the same diagnostic used naturally. - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + await window.__qaRenderAfterMove(gev); return { beforeLastUpdate, boundaryTime }; }, view); } @@ -159,14 +190,29 @@ function readTrafficMeasures(page, boundaryTime) { })), boundaryTime); } +/** + * Road requests the page sent, counted by the request interceptor: `sent` is + * every road request that reached the network, `delayed` those it held for + * the degraded leg. `requestRoads()` can be answered from decoded tiles + * already in memory, so a `fetch-to-response` measure alone does not prove + * the network was used. + */ +const roadRequests = { sent: 0, delayed: 0 }; + /** Drive one measured state and return its raw User Timing measures. */ async function captureState(page, name, view, setDelay) { setDelay(name === 'degraded-upstream' ? DEGRADED_DELAY_MS : 0); + const before = { ...roadRequests }; const { beforeLastUpdate, boundaryTime } = await moveCamera(page, view); await waitForTrafficCapture(page, beforeLastUpdate, boundaryTime); const measures = await readTrafficMeasures(page, boundaryTime); setDelay(0); - return { name, measures }; + return { + name, + measures, + sent: roadRequests.sent - before.sent, + delayed: roadRequests.delayed - before.delayed, + }; } /** Format a duration without hiding zero-duration measurements. */ @@ -318,13 +364,14 @@ async function main() { const page = await browser.newPage(); await page.setViewport({ width: 1440, height: 900 }); await page.evaluateOnNewDocument(() => localStorage.clear()); + await page.evaluateOnNewDocument(installRenderAfterMove); page.on('console', (message) => { if (message.type() === 'error') consoleErrors.push(message.text()); }); page.on('pageerror', (error) => consoleErrors.push(error.message)); - // Force keyless traffic and optionally hold Overpass requests to model a - // degraded proxy/upstream. No server key or proxy debug endpoint is needed. + // Force keyless traffic and optionally hold the road requests to model a + // degraded upstream. No server key or proxy debug endpoint is needed. await page.setRequestInterception(true); page.on('request', async (request) => { if (request.url().includes('/api/tomtom/status')) { @@ -335,7 +382,11 @@ async function main() { }); return; } - if (activeProxyDelayMs > 0 && request.url().includes('/api/overpass')) { + const roadRequest = request.url().includes('/api/overpass') + || new URL(request.url()).hostname === 'tiles.openfreemap.org'; + if (roadRequest) roadRequests.sent += 1; + if (activeProxyDelayMs > 0 && roadRequest) { + roadRequests.delayed += 1; await sleep(activeProxyDelayMs); } try { await request.continue(); } catch { /* page closed or already handled */ } @@ -363,8 +414,9 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); await gev.dataManager.setEnabled('traffic', true); - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + // Also records the baseline pose traffic's new `changed` listener + // measures the first measured move against. + await window.__qaRenderAfterMove(gev); }, VIEWS.austin); await sleep(500); @@ -386,7 +438,7 @@ async function main() { // Clear the last-bounds gate without clearing the module's road cache, then // revisit the byte-identical camera pose for a true client-cache hit. - await page.evaluate((view) => { + await page.evaluate(async (view) => { const gev = window.__godsEyeView; const ellipsoid = gev.viewer.scene.globe.ellipsoid; const radians = Math.PI / 180; @@ -398,8 +450,7 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + await window.__qaRenderAfterMove(gev); }, VIEWS.austin); await sleep(500); @@ -428,7 +479,7 @@ async function main() { } for (const capture of captures.slice(1)) { if (!capture.measures.some((entry) => entry.detail?.segment === 'fetch-to-response')) { - throw new Error(`${capture.name} did not issue an Overpass request`); + throw new Error(`${capture.name} did not issue a road request`); } } if (DEGRADED_DELAY_MS > 0) { @@ -438,20 +489,35 @@ async function main() { && entry.duration >= DEGRADED_DELAY_MS * 0.9 )); if (!delayed) throw new Error('degraded-upstream leg did not observe the synthetic delay'); + // The delay has to come from held road requests, not from processing + // that happened to run long. + if (!degraded.delayed) throw new Error('degraded-upstream leg sent no road request to hold'); } + // A city the client has never seen has no tiles in memory: it must reach + // the network. The other legs may legitimately be answered from tiles + // already decoded, so their counts are reported, not asserted. + const cold = captures.find((capture) => capture.name === 'cold city (client)'); + if (!cold?.sent) throw new Error('cold city leg sent no road request to the network'); const rows = captures.flatMap(rowsForCapture); if (!rows.length) throw new Error('no measured traffic renders were captured'); console.log('\nCausal segments (one row per visible major/full pass)'); console.table(rows); + console.log('\nRoad requests sent to the network per leg (held by the degraded leg)'); + console.table(captures.map((capture) => ({ + State: capture.name, + Sent: capture.sent, + Held: capture.delayed, + }))); console.log('\nNotes:'); console.log(' - Render→postRender is the first visible-frame boundary used by Phase 0.'); - console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch.'); - console.log(' - response.json includes both body transfer and JSON decoding; the production path does not split them.'); - console.log(' - Last change→fetch is approximately the 320 ms FETCH_DEBOUNCE for the first fetch by construction.'); + console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch, or the roads came from OpenFreeMap tiles.'); + console.log(' - Through the Overpass proxy, Fetch→response is the HTTP response and response.json is body transfer plus JSON decoding.'); + console.log(' - From OpenFreeMap tiles, Fetch→response spans the tile requests, body reads, decoding and composition, and response.json only hands back the built object; a held leg can stack the delay over tiles fetched in turn.'); + console.log(' - Last change→fetch is the 320 ms FETCH_DEBOUNCE for the first fetch by construction, plus timer and main-thread latency (larger under SwiftShader).'); console.log(' - Full-pass Last change→fetch also includes the intentionally sequential major pass.'); - console.log(' - Cesium moveEnd is a diagnostic raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it.'); - console.log(' - Synthetic events bypass camera percentageChanged/inertia but use the same camera.changed schedule-time anchor as natural captures.'); + console.log(' - Cesium moveEnd is raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it, and traffic only re-checks the view on it.'); + console.log(' - Moves are setView plus rendered frames: the camera port measures traffic\'s own 5% changed threshold as for a user move (inertia is bypassed).'); console.log(' - The keyless capture zeroes Flow race and Heat lines work; live-keyed numbers will differ.'); console.log(' - Measurement caveat: timings include instrumentation overhead (observer effect) and browser clock-floor quantization.'); console.log(' - Per-road clock observations inside road-parse-total/waypoint-materialization slightly overstate production work.'); diff --git a/scripts/qa-traffic-motion.mjs b/scripts/qa-traffic-motion.mjs index af73c8d1c2..b9c0f52d5a 100644 --- a/scripts/qa-traffic-motion.mjs +++ b/scripts/qa-traffic-motion.mjs @@ -158,9 +158,13 @@ try { (window.__motion.holdStart === null ? '' : ` | camera stopped +${((now - window.__motion.holdStart) / 1000).toFixed(1)}s`); + // A layer dot is its draw item (`pos`, hidden only when `show` is + // false); a collection's point is Cesium's. const visit = (id, roadId, point) => { - if (!point.show) return; - const s = scene.cartesianToCanvasCoordinates(point.position); + if (point.show === false) return; + const s = scene.cartesianToCanvasCoordinates( + point.pos ?? point.position, + ); if (s && s.x >= 0 && s.y >= 0 && s.x <= 1280 && s.y <= 800) points.set(id, { x: s.x, y: s.y, roadId }); }; @@ -168,7 +172,7 @@ try { offRoad = 0; if (!baseline && layer.visitMotionDots) { layer.visitMotionDots((id, roadId, point, road) => { - if (point.show) { + if (point.show !== false) { const p = road?.roadProperties; const allowed = road?.directFlow ? [ @@ -195,7 +199,7 @@ try { p?.brunnel !== 'tunnel'; if (!allowed) offRoad++; } - if (point.show) n++; + if (point.show !== false) n++; visit(id, roadId, point); }); } else { diff --git a/scripts/qa-traffic-oblique.mjs b/scripts/qa-traffic-oblique.mjs index 6ea1c953d5..a365bcd446 100644 --- a/scripts/qa-traffic-oblique.mjs +++ b/scripts/qa-traffic-oblique.mjs @@ -83,9 +83,10 @@ try { lower = 0; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; - const s = viewer.scene.cartesianToCanvasCoordinates(p.position); + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const s = viewer.scene.cartesianToCanvasCoordinates(dot.pos); if (s && s.x >= 240 && s.x <= 1040 && s.y >= 0 && s.y <= 800) { if (s.y < 400) upper++; else lower++; @@ -197,8 +198,10 @@ try { const camera = viewer.camera.positionWC; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const p = { position: dot.pos }; const q = viewer.scene.cartesianToCanvasCoordinates(p.position); if (q && q.x >= 240 && q.x <= 1040 && q.y >= 0 && q.y <= 800) { if (q.y < 400) upper++; diff --git a/scripts/qa-transit-browser.mjs b/scripts/qa-transit-browser.mjs index 23925c7439..7b9f1ee449 100644 --- a/scripts/qa-transit-browser.mjs +++ b/scripts/qa-transit-browser.mjs @@ -177,6 +177,19 @@ export async function sampleTransitPixels(page, palette) { ]; const width = canvas.clientWidth; const height = canvas.clientHeight; + // The billboards the draw port drew for the layer's two sets, by + // vehicle key, with the collection drawing each. + const drawn = new Map(); + const setIds = layer._transitSetIdsForTest(); + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) { + const billboard = host.get(j); + if (typeof billboard?.id?.id === 'string') + drawn.set(billboard.id.id, { billboard, host }); + } + } const sprites = []; const footprints = []; const intersects = (a, b) => @@ -256,20 +269,26 @@ export async function sampleTransitPixels(page, palette) { }; for (const entry of state._vehicles.values()) { if (!entry.marker || entry.marker.show === false) continue; - const p = entry.marker.position; + const row = drawn.get(entry.key); + if (!row || row.billboard.show === false) { + skipped.push({ key: entry.key, reason: 'billboard not drawn' }); + continue; + } + const billboard = row.billboard; + const p = billboard.position; const clip = mul(proj, mul(view, [p.x, p.y, p.z, 1])); if (!(clip[3] > 0)) continue; - const screen = entry.marker.computeScreenSpacePosition?.(scene) || { + const screen = billboard.computeScreenSpacePosition?.(scene) || { x: ((clip[0] / clip[3]) * 0.5 + 0.5) * width, y: (1 - ((clip[1] / clip[3]) * 0.5 + 0.5)) * height, }; - const rect = entry.marker.constructor.getScreenSpaceBoundingBox?.( - entry.marker, + const rect = billboard.constructor.getScreenSpaceBoundingBox?.( + billboard, screen, ) || { x: screen.x - 16, y: screen.y - 16, width: 32, height: 32 }; const { x, y } = screenPoint(screen.x, screen.y); - const c = Math.abs(Math.cos(entry.marker.rotation || 0)), - sn = Math.abs(Math.sin(entry.marker.rotation || 0)); + const c = Math.abs(Math.cos(billboard.rotation || 0)), + sn = Math.abs(Math.sin(billboard.rotation || 0)); const w = rect.width * c + rect.height * sn, h = rect.height * c + rect.width * sn; const footprint = { x: x - w / 2, y: y - h / 2, w, h }; @@ -282,10 +301,7 @@ export async function sampleTransitPixels(page, palette) { rect.y + rect.height > height ) reason = 'billboard rectangle outside frame'; - if ( - entry.marker.color?.alpha < 0.95 || - entry.markerCollection?.show === false - ) + if (billboard.color?.alpha < 0.95 || row.host.show === false) reason = 'billboard not opaque/collection hidden'; const raster = rasters.get(entry.marker.image); if (!raster) reason = 'billboard alpha unavailable'; @@ -351,12 +367,12 @@ export async function sampleTransitPixels(page, palette) { bracketX: entry.detectContact?._candidateScreenX ?? screen.x, bracketY: entry.detectContact?._candidateScreenY ?? screen.y, raster, - rotation: entry.marker.rotation || 0, - halfW: Number.isFinite(entry.marker.width) - ? Math.ceil(entry.marker.width / 2) + 2 + rotation: billboard.rotation || 0, + halfW: Number.isFinite(billboard.width) + ? Math.ceil(billboard.width / 2) + 2 : 11, - halfH: Number.isFinite(entry.marker.height) - ? Math.ceil(entry.marker.height / 2) + 2 + halfH: Number.isFinite(billboard.height) + ? Math.ceil(billboard.height / 2) + 2 : 7, }); } @@ -658,12 +674,23 @@ export function readTransitFleetStyle({ key, resetSelection = false } = {}) { const entry = key ? state._vehicles.get(key) : [...state._vehicles.values()].find((e) => e.marker?.show); - return entry + // The billboard the draw port drew for it, in either of the layer's sets. + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + let billboard = null; + for (let i = 0; entry && !billboard && i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === entry.key) billboard = host.get(j); + } + // An undrawn marker has no style to compare: no answer. + return entry && billboard ? { key: entry.key, selected: state._selectedKey === entry.key, - color: entry.marker.color.toCssColorString(), - width: entry.marker.width, + color: billboard.color.toCssColorString(), + width: billboard.width, image: entry.marker.image, } : null; diff --git a/scripts/qa-transit-recovery.mjs b/scripts/qa-transit-recovery.mjs index a54e812399..6d45e684b7 100644 --- a/scripts/qa-transit-recovery.mjs +++ b/scripts/qa-transit-recovery.mjs @@ -182,7 +182,8 @@ try { }); parts.rendering.sampleIdle(entry); parts.rendering.schedulePlayback(entry); - const V = entry.marker.position.constructor; + // Marker positions are plain records; the camera's eye is a Cartesian3. + const V = scene.camera.positionWC.constructor; const points = entry.trailSegments .filter((s) => s.toT <= entry.sample.displayT) .flatMap((s) => s.positions); diff --git a/scripts/qa-transit-scenes.mjs b/scripts/qa-transit-scenes.mjs index f325cb9f73..d75d235fdc 100644 --- a/scripts/qa-transit-scenes.mjs +++ b/scripts/qa-transit-scenes.mjs @@ -146,11 +146,7 @@ export async function runFleetBudgets({ // The retained delta is conservative: it includes concurrent page growth. const retained = await cdp.send('Runtime.getHeapUsage'); // Timing/upload acceptance runs without the allocation profiler attached. - const trace = await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('transit') - .module._measureTransitFramesForTest(8000), - ); + const trace = await page.evaluate(measureTransitFrames, 8000); await page.evaluate(() => window.__godsEyeView.dataManager.layers .get('transit') @@ -166,11 +162,7 @@ export async function runFleetBudgets({ page, `${count} budget visibility before allocation trace`, ); - const allocationTrace = await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('transit') - .module._measureTransitFramesForTest(6000), - ); + const allocationTrace = await page.evaluate(measureTransitFrames, 6000); const { profile } = await cdp.send('HeapProfiler.stopSampling'); const allocations = allocationTotals(profile); const retainedBytes = retained.usedSize - before.usedSize; @@ -361,13 +353,23 @@ export async function runBostonMatrix({ const modes = await page.evaluate(() => { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; + // The billboards the draw port drew for the markers, by key. + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + const drawn = new Map(); + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + drawn.set(host.get(j)?.id?.id, host.get(j)); + } return [...layer._transitStateForTest()._vehicles.values()].map( (e) => ({ key: e.key, route: e.record.routeId, image: e.marker.image, - width: e.marker.width, - color: e.marker.color.toCssHexString(), + width: drawn.get(e.key)?.width ?? null, + color: drawn.get(e.key)?.color.toCssHexString() ?? null, }), ); }); @@ -418,15 +420,29 @@ export async function runBostonMatrix({ window.__godsEyeView.dataManager.layers.get('transit').module; layer._transitPartsForTest().selection.clearSelection(); const e = layer._transitStateForTest()._vehicles.get(key); + // The billboard the draw port drew for it: the last under its key, + // as the fleet sample above reads it (the fleet-models set draws + // one under the same key first). + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + let drawn = null; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === key) drawn = host.get(j); + } return { + drawn: Boolean(drawn), image: e.marker.image, - width: e.marker.width, - color: e.marker.color.toCssHexString(), + width: drawn?.width ?? null, + color: drawn?.color.toCssHexString() ?? null, }; }, target.key); check( `Boston ${background.name}/${look.name}/${target.route}: deselect restores fleet styling`, - restored.image === target.image && + restored.drawn && + restored.image === target.image && restored.width === target.width && restored.color === target.color, ); @@ -727,6 +743,15 @@ export async function runTrailVisibility({ bodyUploadMax = 0, frames = 0; const headCpu = []; + // The Cesium primitives drawing one of the trail's draw-port sets: one, + // or while a rebuild builds, the retiring one and its replacement. + const hostsOf = (set) => { + const hosts = []; + for (let i = 0; set && i < scene.primitives.length; i++) + if (scene.primitives.get(i).drawSetId === set.id) + hosts.push(scene.primitives.get(i)); + return hosts; + }; const wrap = (primitive, kind) => { if (!primitive || wrapped.has(primitive)) return; const update = primitive.update; @@ -767,8 +792,8 @@ export async function runTrailVisibility({ const pre = scene.preRender.addEventListener(() => { headBytes = bodyBytes = 0; const trail = parts.trails.diagnostics(); - wrap(trail?.body, 'body'); - wrap(trail?.headPrimitive || trail?.head?._polylineCollection, 'head'); + for (const host of hostsOf(trail?.body)) wrap(host, 'body'); + for (const host of hostsOf(trail?.headLines)) wrap(host, 'head'); }); const post = scene.postRender.addEventListener(() => { frames++; @@ -807,6 +832,26 @@ export async function runTrailVisibility({ const trail = parts.trails.diagnostics(); if (!entry || !trail) return { ...setup, present: 0, reason: 'selection disappeared' }; + // The Cesium primitives drawing one of the trail's draw-port sets: one, + // or while a rebuild builds, the retiring one and its replacement. + const hostsOf = (set) => { + const hosts = []; + for (let i = 0; set && i < scene.primitives.length; i++) + if (scene.primitives.get(i).drawSetId === set.id) + hosts.push(scene.primitives.get(i)); + return hosts; + }; + // Each part of a set's primitive, for readiness and height exclusion. + const partsOf = (set) => { + const out = []; + for (const host of hostsOf(set)) + for (let i = 0; i < host.length; i++) out.push(host.get(i)); + return out; + }; + // One host (no rebuild under way) whose parts have all built. + const drawnReady = (set) => + hostsOf(set).length === 1 && + partsOf(set).every((part) => part.ready !== false); const { setRate } = await import('/src/data/contactPlayback.js'); setRate(entry.track, 0, { wallNowMs: Date.now(), @@ -819,8 +864,8 @@ export async function runTrailVisibility({ app.tileset?.show !== false && app.tileset?.tilesLoaded === true && (scene.globe?.show === false || scene.globe?.tilesLoaded === true) && - trail.body?.ready === true && - (!trail.headPrimitive || trail.headPrimitive.ready === true); + drawnReady(trail.body) && + (!trail.headLines?.show || drawnReady(trail.headLines)); // Require sustained readiness after freezing playback, before projecting // onto the refined surface. Repeated captures still check pixel stability. const tilesReady = await new Promise((resolve) => { @@ -855,7 +900,18 @@ export async function runTrailVisibility({ if (points.length < 2) return { ...setup, present: 0, reason: 'no completed path' }; const C = scene.camera.positionCartographic.constructor; - const V = entry.marker.position.constructor; + // Marker positions are plain records; the camera's eye is a Cartesian3. + const V = scene.camera.positionWC.constructor; + // The billboard the draw port drew for the marker, seen through. + const setIds = layer._transitSetIdsForTest(); + const markerBillboards = []; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === entry.key) + markerBillboards.push(host.get(j)); + } const lengths = [0]; for (let i = 1; i < points.length; i++) lengths.push(lengths.at(-1) + V.distance(points[i - 1], points[i])); @@ -875,10 +931,11 @@ export async function runTrailVisibility({ new V(), ); const cart = C.fromCartesian(p); - const height = scene.sampleHeight( - cart, - [entry.marker, trail.body, trail.headPrimitive].filter(Boolean), - ); + const height = scene.sampleHeight(cart, [ + ...markerBillboards, + ...partsOf(trail.body), + ...partsOf(trail.headLines), + ]); if (Number.isFinite(height)) cart.height = height; const surface = C.toCartesian(cart); const q = mul( @@ -943,13 +1000,12 @@ export async function runTrailVisibility({ }); const bodyShow = trail.body?.show, headShow = trail.head?.show, - headPrimitiveShow = trail.headPrimitive?.show, + headLinesShow = trail.headLines?.show, backingShow = trail.backing?.show; let showTrail = false; const applyVisibility = () => { if (trail.body) trail.body.show = showTrail && bodyShow; - if (trail.headPrimitive) - trail.headPrimitive.show = showTrail && headPrimitiveShow; + if (trail.headLines) trail.headLines.show = showTrail && headLinesShow; if (trail.head) trail.head.show = showTrail && headShow; if (trail.backing) trail.backing.show = showTrail && backingShow; }; @@ -966,13 +1022,13 @@ export async function runTrailVisibility({ const current = parts.trails.diagnostics(); captureReady &&= ready() && - current?.body === trail.body && - current?.headPrimitive === trail.headPrimitive; + current?.rebuilds === trail.rebuilds && + current?.headRebuilds === trail.headRebuilds; } } finally { removeVisibility(); if (trail.body) trail.body.show = bodyShow; - if (trail.headPrimitive) trail.headPrimitive.show = headPrimitiveShow; + if (trail.headLines) trail.headLines.show = headLinesShow; if (trail.head) trail.head.show = headShow; if (trail.backing) trail.backing.show = backingShow; await frame(); @@ -994,7 +1050,7 @@ export async function runTrailVisibility({ tilesReady: captureReady, elapsedDisplayMs: entry.sample.displayT - setup.startDisplayT, movedMetres: Math.abs(entry.sample.lat - setup.startLat) * 111320, - body: trail.body?.constructor.name, + body: hostsOf(trail.body)[0]?.constructor.name, headStrategy: trail.headStrategy || 'PolylineCollection', headRebuilds: trail.headRebuilds ?? null, }; @@ -1048,3 +1104,24 @@ export async function runTrailVisibility({ .selection.clearSelection(), ); } + +/** + * The transit frame probe over the bytes the renderer uploads for the + * layer's marker sets (the Cesium renderer's upload probe), in the page. + * @param {number} durationMs + */ +async function measureTransitFrames(durationMs) { + const { countDrawSetUploads } = + await import('/src/render/cesium/uploadProbe.js'); + const app = window.__godsEyeView; + const layer = app.dataManager.layers.get('transit').module; + const uploads = countDrawSetUploads( + app.viewer, + layer._transitSetIdsForTest(), + ); + try { + return await layer._measureTransitFramesForTest(durationMs, uploads); + } finally { + uploads.stop(); + } +} diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index 32bfb596a6..c73a0cafc6 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -98,7 +98,7 @@ const renderingSource = await readFile( ); const frameSource = renderingSource .split('function onPreRender()')[1] - .split('const occluder')[0]; + .split('const candidatePosition')[0]; check( 'frame pass does not scan the fleet or copy the moving set', !/_vehicles\.values|\[\.\.\.state\._moving\]/.test(frameSource), @@ -815,25 +815,38 @@ try { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; const state = layer._transitStateForTest(); - const entry = state._vehicles.get(key); + const scene = window.__godsEyeView.viewer.scene; + // The billboard the draw port drew for it, and the set drawing it. + const setIds = layer._transitSetIdsForTest(); + let billboard = null, + setId = null; + for (let i = 0; !billboard && i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === key) { + billboard = host.get(j); + setId = host.drawSetId; + } + } + const set = layer._transitPartsForTest().rendering.setNameOf(setId); return { selected: state._selectedKey === key, - color: entry?.marker.color.toCssColorString(), - width: entry?.marker.width, + color: billboard?.color.toCssColorString(), + width: billboard?.width, pickOwner: (() => { - const p = window.__godsEyeView.viewer.scene.pick( - entry.marker.computeScreenSpacePosition( - window.__godsEyeView.viewer.scene, - ), - ); + const p = billboard + ? scene.pick(billboard.computeScreenSpacePosition(scene)) + : null; return { - id: typeof p?.id === 'string' ? p.id : null, - primitiveId: - typeof p?.primitive?.id === 'string' ? p.primitive.id : null, + id: typeof p?.id?.id === 'string' ? p.id.id : null, + set: typeof p?.id?.set === 'string' ? p.id.set : null, collection: - entry.markerCollection === state._animatedMarkers + set === 'moving' ? 'animated' - : 'stationary', + : set === 'still' + ? 'stationary' + : null, }; })(), }; @@ -1596,7 +1609,8 @@ try { key: entry.key, x, y, - pickKey: picked?.id ?? picked?.primitive?.id ?? null, + // A draw-port pick carries {set, id, meta}; the vehicle is its id. + pickKey: picked?.id?.id ?? picked?.id ?? picked?.primitive?.id ?? null, }; }); let anchor = null; @@ -1849,19 +1863,33 @@ try { await page.$eval(row, (element) => element.scrollIntoView({ block: 'center' }), ); + // The marker sets drawn while on, to look for after disable. + const markerSets = await page.evaluate(() => + window.__godsEyeView.dataManager.layers + .get('transit') + .module._transitSetIdsForTest(), + ); await page.click(`${row} .data-toggle-btn`); await page.waitForFunction( () => !window.__godsEyeView.dataManager.isEnabled('transit'), { timeout: 20_000 }, ); const afterDisable = transitRequests.length; - const teardown = await page.evaluate(() => { + const teardown = await page.evaluate((setIds) => { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; const state = layer._transitStateForTest(); return { vehicles: state._vehicles.size, - primitives: - (state._markers?.length || 0) + (state._animatedMarkers?.length || 0), + // Billboards still drawn in the sets drawn while on. + primitives: (() => { + const scene = window.__godsEyeView.viewer.scene; + let count = 0; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (setIds.includes(host?.drawSetId)) count += host.length || 0; + } + return count; + })(), visible: state._visible.size, moving: state._moving.size, detect: state._detectCache, @@ -1873,12 +1901,12 @@ try { ], trailPending: layer._transitPartsForTest().trails.requestDiagnostics() .pending, - shown: state._markers ? state._markers.show : null, + shown: state._markersShown ?? null, inFlight: state._inFlight.size, activeFeeds: state._activeFeeds.size, holds: window.__godsEyeView.getRenderGovernorDiagnostics().holds, }; - }); + }, markerSets); check( 'disable leaves no vehicles and no point primitives', teardown.vehicles === 0 && diff --git a/scripts/qa-visual-effects.mjs b/scripts/qa-visual-effects.mjs index f3b9ab8bd3..3c96e66547 100644 --- a/scripts/qa-visual-effects.mjs +++ b/scripts/qa-visual-effects.mjs @@ -169,7 +169,7 @@ try { result.bloom.intensityPct === 98 && snapshot.bloom.intensity === 98 && manager._visualEffects.bloomIntensity === 98 && - manager._bloomStage.enabled + window.__godsEyeView.viewer.scene.postProcessStages.bloom.enabled ); }), ); @@ -183,7 +183,11 @@ try { result.sharpen.intensityPct === 61 && manager.getVisualState().sharpen.intensity === 61 && manager._visualEffects.sharpenIntensity === 0.61 && - Math.abs(manager._sharpenStage.uniforms.amount - 1.32) < 1e-9 + Math.abs( + window.__godsEyeView.viewer.scene.postProcessStages.getStageByName( + 'effects_sharpen', + ).uniforms.amount - 1.32, + ) < 1e-9 ); }), ); @@ -199,9 +203,10 @@ try { const manager = window.__godsEyeView.styleManager; const effects = manager._visualEffects; manager.setStyle('retro'); - const owned = [...Object.values(effects.stages), effects.sharpenStage]; - const collection = manager.viewer.scene.postProcessStages; - const previousBloom = effects.previousBloom; + const collection = window.__godsEyeView.viewer.scene.postProcessStages; + const owned = Object.keys(effects.stages).map((name) => + collection.getStageByName(`effects_style_${name}`), + ); const pending = manager.dispose(); const stoppedBeforeAwait = effects.stopped && @@ -210,12 +215,15 @@ try { await pending; return { stoppedBeforeAwait, - removed: owned.every((stage) => !collection.contains(stage)), - restored: - effects.bloomStage.enabled === previousBloom.enabled && - Object.entries(previousBloom.uniforms).every( - ([name, value]) => effects.bloomStage.uniforms[name] === value, + removed: + owned.every(Boolean) && + Object.keys(effects.stages).every( + (name) => !collection.getStageByName(`effects_style_${name}`), ), + // The renderer gives the scene's bloom back when it goes. + restored: + !collection.bloom.enabled && + !collection.getStageByName('effects_sharpen')?.enabled, }; }); check( @@ -223,7 +231,7 @@ try { teardown.stoppedBeforeAwait, ); check( - 'UI teardown removes owned stages and restores borrowed bloom', + 'UI teardown removes its styles and turns bloom and sharpen off', teardown.removed && teardown.restored, ); check( diff --git a/scripts/qa-visual-input.mjs b/scripts/qa-visual-input.mjs index 3c096acdc1..914476aeb3 100644 --- a/scripts/qa-visual-input.mjs +++ b/scripts/qa-visual-input.mjs @@ -150,7 +150,9 @@ try { manager._bloomSlider.focus(); return { value: Number(manager._bloomSlider.value), - contrast: manager._bloomStage.uniforms.contrast, + contrast: + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast, }; }); await page.keyboard.press('ArrowRight'); @@ -160,7 +162,8 @@ try { const manager = window.__godsEyeView.styleManager; return ( Number(manager._bloomSlider.value) > before.value && - manager._bloomStage.uniforms.contrast < before.contrast + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast < before.contrast ); }, displayBefore), ); @@ -267,13 +270,16 @@ try { const manager = window.__godsEyeView.styleManager; manager._displayBindings._detachDisplayControls(); const before = manager.bloomEnabled; - const contrast = manager._bloomStage.uniforms.contrast; + const contrast = + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast; manager._bloomBtn.click(); manager._bloomSlider.value = '15'; manager._bloomSlider.dispatchEvent(new Event('input', { bubbles: true })); return ( manager.bloomEnabled === before && - manager._bloomStage.uniforms.contrast === contrast + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast === contrast ); }), ); diff --git a/scripts/qa-zoom-out-guard.mjs b/scripts/qa-zoom-out-guard.mjs index 770a4148d8..5faf70b9f0 100644 --- a/scripts/qa-zoom-out-guard.mjs +++ b/scripts/qa-zoom-out-guard.mjs @@ -36,7 +36,8 @@ try { ); const renderer = await page.evaluate(async () => { const C = await import('/node_modules/cesium/Build/Cesium/index.js'); - const { maxPitchForHeight } = await import('/src/app/zoomOutGuard.js'); + const { maxPitchForHeight } = + await import('/src/render/cesium/zoomOutGuard.js'); const { readCameraTargetFrame } = await import('/src/ui/cameraOrientationControls.js'); const viewer = window.__godsEyeView.viewer; @@ -86,7 +87,7 @@ try { }; viewer.camera.setView = (options) => { // Cesium itself also calls setView while processing touch movement. - if (new Error().stack.includes('/src/app/zoomOutGuard.js')) + if (new Error().stack.includes('/src/render/cesium/zoomOutGuard.js')) qa.guardWrites++; return original(options); }; diff --git a/scripts/record-camera-goldens.mjs b/scripts/record-camera-goldens.mjs new file mode 100644 index 0000000000..17f4131bc7 --- /dev/null +++ b/scripts/record-camera-goldens.mjs @@ -0,0 +1,28 @@ +#!/usr/bin/env node +// Writes the reference camera traces the conformance suite compares a +// renderer against: src/render/conformance/goldens/camera.json. Run it after +// a Cesium upgrade or a change to the camera scripts, and review the diff. +// +// node scripts/record-camera-goldens.mjs [--check] +// +// With --check it writes nothing and exits 1 when the file is out of date. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { recordCameraGoldens } from '../src/render/cesium/cameraGoldens.js'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const OUT = path.join(ROOT, 'src/render/conformance/goldens/camera.json'); + +const text = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`; +if (process.argv.includes('--check')) { + const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8') : ''; + if (current !== text) { + console.error(`${path.relative(ROOT, OUT)} is out of date`); + process.exit(1); + } +} else { + fs.mkdirSync(path.dirname(OUT), { recursive: true }); + fs.writeFileSync(OUT, text); + console.log(`wrote ${path.relative(ROOT, OUT)}`); +} diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index 10d3e39791..4e163cd398 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -33,7 +33,8 @@ * moves the camera — it stays in the follow band). * 3. NO CROSS-LAYER — tracking military then commercial (and vice versa) * ORPHAN clears the FIRST layer (its getTrackedInfo()===null), - * via the per-layer viewer.trackedEntityChanged listener. + * via each layer's follow-changed listener (the follow + * service, data/followed.js: onFollowChanged). * 4. INIT CLEAN — app loads, all 12 layers present, no console errors, * [Detection] Initialized + [TrackedReadout] Initialized. * @@ -44,8 +45,8 @@ * M3. AGE-OUT RELEASE — when the tracked plane's fixes stop arriving * it stays tracked (STALE, then SIGNAL LOST) until * 10 min after its newest fix; then tracking clears - * and the camera is RELEASED IN PLACE: viewer.trackedEntity - * undefined, NO jump (owner decision 2026-07-02 — + * and the camera is RELEASED IN PLACE: the camera + * follows nothing (data/followed.js), NO jump (owner decision 2026-07-02 — * the old ~80 km overview flyTo is gone). * * And the landing-ghost polish (2026-07-02): a LOW+SLOW (landed) plane that @@ -74,11 +75,16 @@ * the TRACKED grounded plane gets the standalone tracked model too (the * owner's "tracked SWA143 at 0 kts showed a 2D billboard" case). * - * And arrival-rotation freshness (2026-07-03 ground-polish): camera.moveEnd - * forces a full rotation pass on the next frame (fly-to settles the - * pose-signature gate can eat), and a billboard flipping INTO view while the - * camera idles re-aims the same tick instead of wearing a stale nose for up - * to ROTATION_REFRESH_MS. Both layers. + * And arrival-rotation freshness (2026-07-03 ground-polish): the nose is right + * on the first settled frame after a camera move and on the first frame a + * hidden contact is shown again. Both layers. (The CPU rotation passes that + * once guaranteed it are gone: the icon sets turn every icon along its drawn + * course on the GPU each frame, so the group reads the drawn rows.) + * + * The probes read what the app draws through its own seams: what the camera + * follows through the follow service (data/followed.js), icons from the draw + * port's icon sets as the renderer holds them, models by their `{set, id}` + * pick ids. * * Run: npm run test:track (assumes dev server already up on :4173) * node scripts/track-regression.mjs @@ -272,6 +278,98 @@ async function main() { try { const page = await browser.newPage(); await page.evaluateOnNewDocument((base) => { window.__gevQaSourceBase = base; }, SOURCE_BASE); + // What the camera follows, read through the app's follow service + // (data/followed.js) rather than Cesium's `trackedEntity`: the follow + // camera runs through the renderer's camera port, whose Cesium adapter + // tracks a hidden helper entity, and the tracked aircraft is no longer an + // entity at all. `__qaFollowed()` is null until the app is up (and the + // module loaded), so every wait that reads it simply keeps polling. + await page.evaluateOnNewDocument(() => { + window.__qaFollowed = () => { + // A probe that cannot read the follow service must not read as + // "follows nothing". + if (window.__qaFollowedError) throw new Error(`followed.js: ${window.__qaFollowedError}`); + return window.__qaFollowedOf?.(window.__godsEyeView?.viewer) ?? null; + }; + const timer = setInterval(() => { + if (!window.__godsEyeView?.viewer) return; + clearInterval(timer); + import(`${window.__gevQaSourceBase || '/src'}/data/followed.js`) + .then((module) => { window.__qaFollowedOf = module.followedOf; }) + .catch((error) => { window.__qaFollowedError = String(error?.message || error); }); + }, 100); + // A contact's id from a drawn model's pick id: the draw port's models + // carry `{set, id}`; older builds stamped the bare id. + window.__qaModelIcao = (model) => { + const id = model?.id; + if (id && typeof id === 'object') return id.id == null ? null : String(id.id); + return id == null ? null : String(id); + }; + // A contact's FLEET icon as the renderer draws it, shaped like the + // billboard the probes below were written against: `show`, `scale`, + // `color` (the row's colour with its alpha column applied; focus and + // limb recession, which the shader also folds in, are not), + // `disableDepthTestDistance` and `position` (where the last frame drew + // it). The draw port's icon sets draw on the GPU (one IconSetPrimitive + // per set, rows keyed by item id; before the draw port, one a layer + // drew itself); a set off the GPU draws Cesium + // billboards whose pick id is `{set, id}`. The tracked icon's own set + // (`-tracked-icon:`) is left out: the fleet icon is what these + // probes always read. + window.__qaFindIcon = (wanted) => { + const scene = window.__godsEyeView?.viewer?.scene; + if (!scene) return null; + const trackedSet = (setId) => typeof setId === 'string' && setId.includes('-tracked-icon:'); + let found = null; + const walk = (coll) => { + const n = coll.length; + for (let i = 0; i < n; i++) { + let p; + try { p = coll.get(i); } catch { continue; } + if (!p) continue; + if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } + if (p.set && typeof p.set.row === 'function' && typeof p.set.has === 'function') { + if (!p.set.has(wanted)) continue; + // A primitive a layer drew itself (before the draw port) names + // no set. + const setId = typeof p._pickObject === 'function' + ? p._pickObject(wanted, p.set, p)?.id?.set ?? null + : null; + if (trackedSet(setId)) continue; + const set = p.set; + const row = set.row(wanted); + const color = set.color(row); + color.alpha *= set.alpha(row); + // (A set without the column draws over depth by default.) + const depth = typeof set.depthTestDistance === 'function' + ? set.depthTestDistance(row) + : Number.POSITIVE_INFINITY; + found = { + id: wanted, + setId, + show: set.shown(row), + scale: set.scale(row), + color, + disableDepthTestDistance: depth >= 1e30 ? Number.POSITIVE_INFINITY : depth, + position: set.position(row, p._tau), + // Degrees clockwise from north: the course the last frame + // turned the icon along (its rotation is derived from it on + // the GPU each frame). + course: set.course(row, p._tau), + // Whether the row turns along that course at all (ICON_ROTATES + // in data/iconSet.js); one that does not is drawn upright. + rotates: (set.flags(row) & 2) !== 0, + }; + } else if (p.image !== undefined && p.alignedAxis !== undefined) { + const id = p.id && typeof p.id === 'object' ? p.id : { id: p.id }; + if (id.id === wanted && !trackedSet(id.set)) found = p; + } + } + }; + walk(scene.primitives); + return found; + }; + }); await page.setViewport({ width: 1280, height: 800 }); await page.setRequestInterception(true); page.on('request', (request) => { @@ -725,7 +823,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__qaFollowed()?.key === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -736,7 +834,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, }; }); record( @@ -766,7 +864,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__qaFollowed()?.key === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -777,7 +875,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, }; }); record( @@ -839,7 +937,7 @@ async function main() { const latchedShare = await evalPage(() => ({ tracked: window.__godsEyeView.dataManager.layers .get('flights').module.getTrackedInfo()?.icao24 || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, })); record( 'share-v2: the pending subject latches on when it arrives on a later poll', @@ -1353,8 +1451,8 @@ async function main() { ); } - // NOTE: we do NOT manually reposition the camera. Tracking sets - // viewer.trackedEntity + a calibrated viewFrom, so the follow camera lands + // NOTE: we do NOT manually reposition the camera. Tracking follows the + // plane with a calibrated viewFrom, so the follow camera lands // in the few-km band (altitude*1.1+2500, clamped 3–30 km) — far below the // MODEL_ALT_CEIL_M = 800 km ceiling, so _modelRegimeActive() is true and the // standalone tracked model renders. That's the exact path the invariants @@ -1399,12 +1497,12 @@ async function main() { // report the neighbor's id even though the correct tracked model is up. const trackedInfo = fl.getTrackedInfo(); const exactPickModel = trackedInfo - ? pool.find((model) => String(model.id) === trackedInfo.icao24) + ? pool.find((model) => window.__qaModelIcao(model) === trackedInfo.icao24) : null; if (exactPickModel) return exactPickModel; - const ent = window.__godsEyeView.viewer.trackedEntity; + const followed = window.__qaFollowed(); let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (typeof followed?.displayPosition === 'function') tracked = followed.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { @@ -1422,7 +1520,7 @@ async function main() { }; }); - // Track a synthetic commercial plane. Tracking sets viewer.trackedEntity + + // Track a synthetic commercial plane. Tracking follows it with a // viewFrom, so the follow camera lands in the few-km band and the standalone // 3D model renders (model regime active below the 800 km ceiling). const trackedIcao = SYNTH.flights[0].icao; @@ -1437,7 +1535,7 @@ async function main() { const ti = fl.getTrackedInfo(); if (!ti || ti.icao24 !== icao) return false; const found = window.__findTrackedModel ? window.__findTrackedModel() : null; - return !!(found && found.ready && found.show && String(found.id) === icao); + return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao); }, { timeout: 60000, polling: 250 }, trackedIcao).then(() => true).catch(() => false); record('3D: tracked commercial model becomes ready through the DISPLAY toggle', modelUp, modelUp ? `ready+shown id=${trackedIcao}` : 'tracked product model never became ready+shown'); @@ -1450,8 +1548,8 @@ async function main() { jitterResult = await sampleFrames(page, 30, (icao) => { const dm = window.__godsEyeView.dataManager; const fl = dm.layers.get('flights').module; - const ent = window.__godsEyeView.viewer.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const followed = window.__qaFollowed(); + const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null; const dets = fl.getDetectableObjects({ maxCount: 1000 }); const me = dets.find((d) => d.id === icao || d.id === (fl.getTrackedInfo() && fl.getTrackedInfo().callsign)); if (!disp || !me || !me.position) return null; @@ -1700,7 +1798,7 @@ async function main() { mil.trackById(hex); await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const milTrackedBefore = !!mil.getTrackedInfo(); - fl.trackById(icao); // tracking commercial flips viewer.trackedEntity → military listener fires + fl.trackById(icao); // tracking commercial changes what the camera follows → military listener fires await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); return { milTrackedBefore, @@ -1755,16 +1853,22 @@ async function main() { const ti = fl.getTrackedInfo(); if (!ti || ti.icao24 !== icao) return false; const found = window.__findTrackedModel ? window.__findTrackedModel() : null; - return !!(found && found.ready && found.show && String(found.id) === icao); + return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao); }, { timeout: 60000, polling: 250 }, h1Icao).then(() => true).catch(() => false); if (h1ModelUp) { const modelPickId = await evalPage(() => { const m = window.__findTrackedModel(); - return m && m.id !== undefined && m.id !== null ? String(m.id) : null; + if (!m || m.id === undefined || m.id === null) return null; + // The draw port's pick id is `{set, id}`: the click resolver keys on + // both, so the set must be this layer's tracked model set. + if (typeof m.id === 'object') return { set: String(m.id.set), id: String(m.id.id) }; + return { set: null, id: String(m.id) }; }); - record('H1: tracked standalone model exposes its pick id', modelPickId === h1Icao, - `model.id=${JSON.stringify(modelPickId)} (want "${h1Icao}")`); + record('H1: tracked standalone model exposes its pick id', + modelPickId?.id === h1Icao + && (modelPickId.set === null || modelPickId.set.startsWith('flights-tracked-model:')), + `model.id=${JSON.stringify(modelPickId)} (want id "${h1Icao}" in the flights tracked-model set)`); } else if (!glbBackendCapable) { skip('H1: tracked standalone model exposes its pick id', `independent GLB control unavailable (${glbControlDetail})`); @@ -1783,15 +1887,21 @@ async function main() { const fl = window.__godsEyeView.dataManager.layers.get('flights').module; const ti = fl.getTrackedInfo(); if (!ti) return null; - const ent = v.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const followed = window.__qaFollowed(); + const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null; const pos = disp || ti.position; if (!pos) return null; const center = v.scene.cartesianToCanvasCoordinates(pos); if (!center) return null; + // The tracked plane is drawn by the layer's own tracked icon and + // tracked model sets; a pick on either names `{set, id}`. const isTrackedPick = (picked) => { if (!picked) return null; - if (picked.id === ent) return 'entity'; + const hit = picked.id && typeof picked.id === 'object' ? picked.id : null; + if (hit && String(hit.id) === ti.icao24 && typeof hit.set === 'string') { + if (hit.set.startsWith('flights-tracked-icon:')) return 'tracked-icon'; + if (hit.set.startsWith('flights-tracked-model:')) return 'tracked-model'; + } const raw = typeof picked.id === 'string' ? picked.id : (picked.primitive && picked.primitive.id); return raw === ti.icao24 ? 'icao-pick' : null; }; @@ -1849,7 +1959,7 @@ async function main() { }, 45); const h1StillTracking = await evalPage((icao) => { const ti = window.__godsEyeView.dataManager.layers.get('flights').module.getTrackedInfo(); - return !!(ti && ti.icao24 === icao) && !!window.__godsEyeView.viewer.trackedEntity; + return !!(ti && ti.icao24 === icao) && !!window.__qaFollowed(); }, h1Icao); record('H1: click on tracked plane keeps tracking (no deselect)', h1StillTracking, `picked via ${h1ClickPoint.via}; still tracking=${h1StillTracking}`); @@ -1862,8 +1972,8 @@ async function main() { // REGRESSION M3 (rewritten 2026-07-02 — deliberate behavior change): // when the TRACKED plane ages out (10 min after its newest fix, past the // 3 missed polls that remove an untracked plane), tracking must clear - // and the camera must be RELEASED IN PLACE — viewer.trackedEntity - // undefined and NO jump (the old contract flew an ~80 km overview; the + // and the camera must be RELEASED IN PLACE — following nothing + // and NO jump (the old contract flew an ~80 km overview; the // owner field-ruled that wrong: "it randomly zooms way up and loses my // context"). The M3 ordering fix stays: tracking is cleared BEFORE the // removal loop deletes the plane's state, so we never sit mid-follow @@ -1914,7 +2024,7 @@ async function main() { trackedThroughMisses, atAgeOut, stillTrackedAfter: !!fl.getTrackedInfo(), - viewerStillTracking: !!v.trackedEntity, + viewerStillTracking: !!window.__qaFollowed(), }; } finally { Date.now = realNow; @@ -1927,7 +2037,7 @@ async function main() { record('M3: tracking cleared after the tracked plane ages out (getTrackedInfo null)', m3.beforeTracking && !m3.stillTrackedAfter, `before=${m3.beforeTracking} trackedAfter=${m3.stillTrackedAfter}`); - record('M3: camera released after age-out (viewer.trackedEntity undefined)', + record('M3: camera released after age-out (the camera follows nothing)', !m3.viewerStillTracking, `viewerTracked=${m3.viewerStillTracking}`); @@ -2052,16 +2162,17 @@ async function main() { const v = window.__godsEyeView.viewer; const fl = window.__godsEyeView.dataManager.layers.get('flights').module; const labelText = () => { - const ent = v.trackedEntity; + const ent = window.__qaFollowed(); if (!ent) return null; // Post overlay-unification the tracked text lives in the host // presentation model (entities are asserted native-label-free); // the native read stays as a fallback so this probe still fails // loudly if BOTH surfaces are ever absent. - const model = ent.gevLabelModel; + const model = ent.labelModel; if (model) return [model.title, ...(model.details || [])].filter(Boolean).join('\n'); - if (!ent.label || !ent.label.text) return null; - const t = ent.label.text; + const label = ent.entity?.label; + if (!label || !label.text) return null; + const t = label.text; return typeof t === 'string' ? t : (t.getValue ? String(t.getValue(v.clock.currentTime)) : null); }; // Track a cruise plane that IS in the feed (aaa003: 8700 m, 250 m/s — @@ -2106,19 +2217,7 @@ async function main() { const fl = dm.layers.get('flights').module; const mil = dm.layers.get('military').module; const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const snap = (id) => { const bb = findBB(id); @@ -2393,19 +2492,7 @@ async function main() { await fl.update(v); await mil.update(v); const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const flBB = findBB('aaa077'); const milBB = findBB('bbb177'); @@ -2440,7 +2527,7 @@ async function main() { try { p = coll.get(i); } catch { continue; } if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.modelMatrix && typeof p.ready !== 'undefined' && p.id === id) found = p; + if (p.modelMatrix && typeof p.ready !== 'undefined' && window.__qaModelIcao(p) === id) found = p; } }; walk(v.scene.primitives); @@ -2469,19 +2556,7 @@ async function main() { const g3dState = await evalPage(() => { const v = window.__godsEyeView.viewer; const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const modelRadius = (id) => { const m = window.__g3dFindModel(id); @@ -2697,7 +2772,7 @@ async function main() { } // WELD (tracked): the tracked CARD anchors to the model you can see. - // `gevVisualPosition` is a SEPARATE accessor from `gevDisplayPosition` on + // the record's `visualPosition` is a SEPARATE accessor from its `displayPosition` on // purpose — the latter carries the follow-camera anti-jitter contract and // must keep returning the cached dead-reckoned value the camera settled // on. So this asserts both halves: the visual accessor is welded to the @@ -2705,7 +2780,7 @@ async function main() { // dead-reckoned position rather than having been quietly repurposed. if (g3dTrackedUp) { const trackedWeld = await evalPage(() => { - const ent = window.__godsEyeView.viewer.trackedEntity; + const ent = window.__qaFollowed(); const m = window.__g3dFindModel('aaa077'); if (!m) return { error: 'no tracked model' }; const matrix = m.modelMatrix; @@ -2724,10 +2799,10 @@ async function main() { const at = (p) => (p ? Math.hypot( p.x - anchor.x, p.y - anchor.y, p.z - anchor.z, ) : null); - const visual = typeof ent?.gevVisualPosition === 'function' ? ent.gevVisualPosition() : null; - const display = typeof ent?.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const visual = typeof ent?.visualPosition === 'function' ? ent?.visualPosition() : null; + const display = typeof ent?.displayPosition === 'function' ? ent?.displayPosition() : null; return { - hasVisualAccessor: typeof ent?.gevVisualPosition === 'function', + hasVisualAccessor: typeof ent?.visualPosition === 'function', visualDelta: at(visual), displayDelta: at(display), }; @@ -2743,7 +2818,7 @@ async function main() { // anti-jitter accessor has been repurposed and the follow camera is at // risk. Skipped (not failed) when the DR cache is momentarily invalid. const displayDelta = trackedWeld.displayDelta; - record('weld: gevDisplayPosition still reports the dead-reckoned position (anti-jitter intact)', + record('weld: the record displayPosition still reports the dead-reckoned position (anti-jitter intact)', !Number.isFinite(displayDelta) || displayDelta > ACCESSOR_SEPARATION_EPSILON_M, Number.isFinite(displayDelta) ? `displayΔ=${displayDelta.toFixed(3)} m (must stay > ${ACCESSOR_SEPARATION_EPSILON_M} m — the ground-snap split)` @@ -2832,6 +2907,21 @@ async function main() { // CHANGE 4 (2026-07-03): arrival rotation freshness. Field test: "planes // look weird when you first come to them — rotations are weird". Two // repaired holes, both layers: + // + // SINCE THE GPU ICON SETS (2c4c66c71) there is no CPU rotation pass to + // tamper with or repair: each frame the shader turns every icon along the + // course its row's motion segment carries at that frame's time. The + // invariant — the nose is right on the first settled frame after a + // camera move and on the first frame a hidden contact is shown again — + // is now observed on the drawn rows: the on-screen nose the drawn course + // projects to, against the one the plane's feed course projects to, at + // the same position, on exactly those two frames (same 10° bound, same + // per-frame budgets). That the shader turns an icon to the screen angle + // its course projects to is the renderer's own contract, which the + // renderer conformance reference scenes draw (course-rotated arrows, + // top and tilted views); a CPU readback cannot see the GPU's rotation. The reveal hides and re-shows the row through the + // layer's own icon book, the only thing that hides a fleet icon. + // The two holes the passes repaired, for the record: // (a) SETTLE PASS — camera.moveEnd forces a full rotation pass on the // next frame (the pose-signature gate can eat a fly-to's settle: // the final easing frames land inside one 10 m/0.06° quantization @@ -2840,39 +2930,25 @@ async function main() { // idles gets its rotation refreshed the same tick (it used to // reappear wearing its stale/creation-north nose for up to 1 s). // Staged deterministically: park the camera nadir over the synthetic - // cluster, let rotations settle, TAMPER a billboard's rotation, then - // trigger each path with the camera idle. The fleet runs every 80 ms, - // independently of rendered FPS. Observe the first completed settle frame - // within 500 ms of forcing moveEnd and the first reveal frame within - // 500 ms of that settle frame: each budget sits inside the 1 s idle - // rotation refresh that could otherwise repair an incorrect first reveal, - // and a ~300 ms headless SwiftShader frame fits inside each of them. + // cluster, let it settle, then trigger each path with the camera idle. + // Observe the first completed settle frame within 500 ms of forcing + // moveEnd and the first reveal frame within 500 ms of that settle frame + // (the budgets once sat inside the 1 s idle rotation refresh; they are + // kept as they were). // ============================================================ - console.log('\nChange 4 — arrival rotation: moveEnd settle pass + horizon-reveal pass'); + console.log('\nChange 4 — arrival rotation: the drawn nose on the settle frame and the first reveal'); const arrival = await evalPage(async () => { const v = window.__godsEyeView.viewer; const dm = window.__godsEyeView.dataManager; - const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/data/iconOrientation.js`); + const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/render/cesium/iconOrientation.js`); const { observeArrivalRotationWithRetry } = await import(`${window.__gevQaSourceBase || '/src'}/tooling/trackArrivalObservation.mjs`); - // 3D models OFF for this phase: a model-handed-off billboard is hidden - // and skips rotation updates entirely — the probes need live billboards - // (this is also the app's default state the field report came from). + // 3D models OFF for this phase: a model-handed-off icon is hidden, and + // the probes need shown icons (this is also the app's default state the + // field report came from). dm.layers.get('flights').module.setParams({ models3d: false }); dm.layers.get('military').module.setParams({ models3d: false }); const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const nextFrames = (n) => new Promise((res) => { let count = 0; @@ -2896,8 +2972,8 @@ async function main() { }); // Park the camera straight above the flights cluster (lift a live // billboard's position radially — no Cesium global needed in-page) so - // every probe plane projects on-screen, then let rotations settle at - // the new pose (the setView pose change forces a pass on the next tick). + // every probe plane projects on-screen, then let a few frames draw at + // the new pose. // aaa002 — aaa001 was evicted for good by the M3 age-out phase. const anchor = findBB('aaa002'); if (!anchor) return { error: 'anchor aaa002 missing' }; @@ -2911,62 +2987,99 @@ async function main() { }); await nextFrames(3); const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b))); - const probe = async (id, course) => { + const probe = async (layer, id, course) => { const bb = findBB(id); if (!bb || !bb.show) return { error: `${id} missing/hidden` }; - const r0 = bb.rotation; // settled tamper origin; correctness uses a fresh projection below + if (!Number.isFinite(bb.course) && !Number.isFinite(bb.rotation)) { + return { error: `${id} has no drawn course or rotation` }; + } + const setIconShown = layer.testing?._setIconForTest; + if (typeof setIconShown !== 'function') return { error: `${id}: the layer has no icon test seam` }; + // The on-screen nose the drawn row shows now, against the feed's. + const drawnError = () => { + const now = findBB(id); + if (!now) return { shown: false, rotationError: NaN }; + // A GPU row is turned along its drawn course, or drawn upright; a + // billboard carries its screen rotation itself. + const drawn = Number.isFinite(now.course) + ? (now.rotates ? screenProjectedRotation(v.scene, now.position, now.course, null) : 0) + : now.rotation; + return { + shown: !!now.show, + rotationError: angDiff(drawn, screenProjectedRotation(v.scene, now.position, course, null)), + }; + }; const hasModel = !!(window.__g3dFindModel && window.__g3dFindModel(id)); - // A wall-clock timeout is inconclusive, not a wrong angle: the frame - // landed where the 1 s idle refresh could already have repaired it - // (seen once on headless SwiftShader: a 926 ms first frame). Such an - // observation gets one more attempt; one that measured a wrong angle — - // a wrong first reveal, or a wrong settle frame before a reveal - // timeout — never does. + // The settle/reveal budgets and the retry were written for the removed + // CPU passes (a frame late enough for the 1 s idle refresh to repair + // it was inconclusive); they are kept unchanged as a guard. A + // wall-clock timeout gets one more attempt; one that measured a wrong + // angle — a wrong first reveal, or a wrong settle frame before a + // reveal timeout — never does. + // + // The reveal: the row is hidden right after the settle frame, frames + // must actually draw it hidden, and only then is it shown again, so + // the frame measured is the first one that draws it after a hidden + // frame. It stays hidden for two drawn frames, past the frame that + // follows the settle frame, so the reveal is timed on an ordinary + // frame rather than on whether that one was pipelined; each hidden + // frame restarts the reveal's clock, and the setup is `hiddenMs`. + const REVEAL_HIDDEN_FRAMES = 2; + let revealArmed = false; + let hiddenFrames = 0; const observed = await observeArrivalRotationWithRetry({ async prepare() { - // Freshen both layers' rotation passes right before the probe, so - // the settle frame is measured against a pass that just ran rather - // than one left over from the previous probe — with the camera - // idle, a layer otherwise runs a pass only every - // ROTATION_REFRESH_MS. + // One settled camera move and a frame before each attempt, as the + // passes once needed (the layers' moveEnd now runs their fleet + // pass on the next frame). + revealArmed = false; + hiddenFrames = 0; v.camera.moveEnd.raiseEvent(); await nextFrames(1); }, scene: v.scene, startMoveEnd() { - // Only moveEnd can repair the tampered angle at the idle pose. - bb.rotation = r0 + 1.5; v.camera.moveEnd.raiseEvent(); }, startReveal() { - // Hide immediately after the confirmed settle frame. The next - // eligible fleet tick must reveal AND re-aim in that same tick. - bb.rotation = r0 + 1.5; - bb.show = false; + // Hide immediately after the confirmed settle frame, through the + // layer's icon book (written to the draw set as this task ends). + setIconShown(id, { shown: false }); + revealArmed = true; }, read() { - return { - shown: bb.show, - rotationError: angDiff(bb.rotation, - screenProjectedRotation(v.scene, bb.position, course, null)), - }; + const sample = drawnError(); + // A frame drew it hidden: after the last one, show it again for + // the next frame; the reveal is measured from here. + if (revealArmed && sample.shown === false) { + hiddenFrames += 1; + if (hiddenFrames >= REVEAL_HIDDEN_FRAMES) { + revealArmed = false; + setIconShown(id, { shown: true }); + } + return { ...sample, revealStartsNow: true }; + } + return sample; }, }); - return { r0, ...observed, hasModel }; + // A reveal is only one after a frame drew the row hidden. + if (!observed.error && hiddenFrames === 0) { + return { ...observed, error: 'no frame drew the row hidden before its reveal', hasModel }; + } + return { ...observed, hiddenFrames, hasModel }; }; const flightCourse = window.__SYNTH.flights.find((f) => f.icao === 'aaa002')?.track ?? 0; const militaryCourse = window.__SYNTH.military.find((m) => m.hex === 'bbb101')?.track ?? 0; return { - flights: await probe('aaa002', flightCourse), - military: await probe('bbb101', militaryCourse), + flights: await probe(dm.layers.get('flights').module, 'aaa002', flightCourse), + military: await probe(dm.layers.get('military').module, 'bbb101', militaryCourse), }; }); const fmtArr = (a) => (!a ? `no result (${arrival?.error || 'phase error'})` : a.error ? `${a.error}; ${arrivalAngleViolated(a) ? 'angle violation (not retried); ' : ''}${Number.isFinite(a.dMoveEnd) ? `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° ` : ''}${Number.isFinite(a.dReveal) ? `reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° ` : ''}elapsed=${Number(a.elapsedMs).toFixed(1)} ms attempts=${a.attempts}` - : `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`); - const TAMPER_DEG = 1.5 * 180 / Math.PI; // ≈ 86° — an uncorrected nose stays this far off - record(`arrival: moveEnd + first reveal both re-aim before idle refresh, flights (tamper was ${TAMPER_DEG.toFixed(0)}°)`, + : `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms hidden=${a.hiddenMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`); + record('arrival: the drawn nose is right on the settle frame and the first reveal, flights', arrivalRotationPassed(arrival.flights), fmtArr(arrival.flights)); - record(`arrival: moveEnd + first reveal both re-aim before idle refresh, military (tamper was ${TAMPER_DEG.toFixed(0)}°)`, + record('arrival: the drawn nose is right on the settle frame and the first reveal, military', arrivalRotationPassed(arrival.military), fmtArr(arrival.military)); // ============================================================ @@ -3027,18 +3140,7 @@ async function main() { }; fl.setParams({ models3d: false }); // billboards own the visual (T7 gate open) window.__dfFindBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; window.__dfCarto = (pos) => { const c = Cesium.Cartographic.fromCartesian(pos, Cesium.Ellipsoid.WGS84); @@ -3124,7 +3226,7 @@ async function main() { if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined) { - if (icao !== undefined && p.id !== icao) continue; + if (icao !== undefined && window.__qaModelIcao(p) !== icao) continue; if (p.show) { shown += 1; if (p.ready === true) rendering += 1; @@ -3149,7 +3251,7 @@ async function main() { if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined - && p.id === icao && p.modelMatrix) { + && window.__qaModelIcao(p) === icao && p.modelMatrix) { const m = p.modelMatrix; // Cesium's default is the IDENTITY matrix — translation (0,0,0), // the Earth's centre, which `Cartographic.fromCartesian` refuses. @@ -3167,23 +3269,18 @@ async function main() { walk(v.scene.primitives); return h; }; - // Tracked-contact model regime (2026-08-20). The tracked contact's model - // is NOT governed by the DISPLAY-rail 3D toggle — that toggle owns the - // FLEET's draw-call budget. The tracked model is default-on and driven by - // camera distance, entering below TRACKED_MODEL_ENTER_ALT_M and handing - // back to the billboard only above TRACKED_MODEL_EXIT_ALT_M (the - // anti-flap band). The CAMERA is therefore what decides whether a model - // or a billboard is the visual for a tracked contact, which is exactly - // what the display floor stands aside for — so these pins drive the - // camera explicitly instead of the toggle. + // Tracked-contact model regime. The tracked contact draws as a model + // exactly when the fleet's rule would draw it so: 3D on, the camera + // below the fleet ceiling, and the contact inside the nearest-first + // add/keep band from the eye. These pins drive the camera across that + // band: a model inside the ADD radius, the billboard past the KEEP one. // - // Read the thresholds from the app's own policy module so a later retune - // of the swap distance moves these pins with it rather than stranding - // them on stale numbers. - const reg = await import(`${window.__gevQaSourceBase || '/src'}/data/trackedModelRegime.js`); + // Read the radii from the app's own policy module so a retune moves + // these pins with it rather than stranding them on stale numbers. + const reg = await import(`${window.__gevQaSourceBase || '/src'}/layers/flights/policy.js`); window.__dfRegime = { - enter: reg.TRACKED_MODEL_ENTER_ALT_M, - exit: reg.TRACKED_MODEL_EXIT_ALT_M, + enter: reg.MODEL_PROX_ADD_M, + exit: reg.MODEL_PROX_KEEP_M, }; // Zooming while following is safe: the tracked-camera framer positions // the camera ONCE per selection and is deliberately read-only on normal @@ -3529,9 +3626,29 @@ async function main() { // after d0 was read; a lower seed makes the negative model-ownership // assertion impossible even when the clamp correctly stands aside. const seeded = Math.max(d0.h, 400) + 40; - for (let dy = -1; dy <= 1; dy++) { - for (let dx = -1; dx <= 1; dx++) { - gf.reportMeshFloorCell(cell(d0.lat) + dy * 0.001, cell(d0.lon) + dx * 0.001, seeded); + // The contact keeps taxiing while the regimes below are driven (the + // model wait alone can run to 20 s), so the planted floor reaches + // along its heading as well: the 3×3 cells around it, and the same + // three cells across the track every ~100 m for 600 m ahead. A + // contact that left a 3×3 patch was read over an unplanted cell, + // where a DEM floor that had already landed under its raw height + // decided the assertion instead of the regime. + const headingDeg = window.__SYNTH.flights.find((f) => f.icao === 'aaa097')?.track ?? 0; + const headingRad = headingDeg * Math.PI / 180; + const metresPerDegLat = 111320; + const metresPerDegLon = metresPerDegLat * Math.cos(d0.lat * Math.PI / 180); + const plantedCells = new Set(); + for (let aheadM = 0; aheadM <= 600; aheadM += 100) { + const lat = d0.lat + (aheadM * Math.cos(headingRad)) / metresPerDegLat; + const lon = d0.lon + (aheadM * Math.sin(headingRad)) / metresPerDegLon; + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + const c = [cell(lat) + dy * 0.001, cell(lon) + dx * 0.001]; + const key = `${c[0].toFixed(3)},${c[1].toFixed(3)}`; + if (plantedCells.has(key)) continue; + plantedCells.add(key); + gf.reportMeshFloorCell(c[0], c[1], seeded); + } } } const fleetClampDeadline = Date.now() + 5000; @@ -3549,7 +3666,7 @@ async function main() { // the sensor value the data APIs report, at whatever regime the camera // is currently in. const readTracked = () => { - const pos = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const pos = window.__qaFollowed()?.position?.(); if (!pos) return null; const c = window.__dfCarto(pos); const info = fl.getTrackedInfo(); @@ -3624,19 +3741,19 @@ async function main() { for (let i = 0; i < collection.length; i++) { const item = collection.get(i); if (typeof item?.get === 'function' && typeof item.length === 'number') walk(item); - else if (item?.id === 'aaa097' && item.activeAnimations !== undefined + else if (window.__qaModelIcao(item) === 'aaa097' && item.activeAnimations !== undefined && item.minimumPixelSize !== undefined) found = item; } }; walk(v.scene.primitives); return found; }; - const trackedEntity = v.trackedEntity; + const trackedEntity = window.__qaFollowed(); const trackedModel = findOwnModel(); const achievedOut = await window.__dfZoomAbove(window.__dfRegime.exit + 5000); const zoomedOut = await window.__dfObserveTrackedExit({ scene: v.scene, trackedEntity, trackedModel, getTrackedModel: findOwnModel, - getTrackedEntity: () => v.trackedEntity, + getTrackedEntity: () => window.__qaFollowed(), getTrackedId: () => fl.getTrackedInfo()?.icao24, getCameraHeight: window.__dfCamH, exitHeight: window.__dfRegime.exit, read: readTracked, @@ -3804,7 +3921,7 @@ async function main() { return { skipped: 'no tracked model rendered in this browser' }; } // While the model IS the visual the clamp must stand aside (T7). - const entWith = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entWith = window.__qaFollowed()?.position?.(); const withModelH = entWith ? window.__dfCarto(entWith).h : null; // Close the deterministic skin again for the rest of the group. The // model is up on a snap that is already cached, so it stays up until the @@ -3819,7 +3936,7 @@ async function main() { // contact's primitive, and an unrelated model in the scene must not be // able to answer it either way. const afterOut = window.__dfCountModels('aaa097'); - const ent = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const ent = window.__qaFollowed()?.position?.(); const c = ent ? window.__dfCarto(ent) : null; // Plant a floor above wherever it now renders so "floored" is decisive. // Mesh cells latch ONE-SHOT, so the earlier scenario's seed would win @@ -3840,7 +3957,7 @@ async function main() { // from mistaking a cached same-frame position for a failed clamp. v.scene.requestRender(); await window.__dfSettle(900); - const ent2 = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const ent2 = window.__qaFollowed()?.position?.(); const c2 = ent2 ? window.__dfCarto(ent2) : null; const out = { toggleOff, @@ -3932,7 +4049,7 @@ async function main() { let p; try { p = coll.get(i); } catch { continue; } if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && p.id === id) found = p; + if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && window.__qaModelIcao(p) === id) found = p; } }; walk(v.scene.primitives); @@ -3948,19 +4065,30 @@ async function main() { fl.setParams({ models3d: false }); return { skipped: 'no fleet model for aaa097 in this browser' }; } + // The layer decides who owns the visual from its OWN record of the + // model (data/modelRecord.js: `ready` from the draw set's ready event, + // `show` as it last sent it), not from the renderer's model object, so + // the shown-but-not-ready state is planted on that record. The record + // is the registered layer's own, reached through its test seam. + const fleetRecord = await fl.testing?._ensureFleetModelForTest?.('aaa097'); + if (!fleetRecord || typeof fleetRecord !== 'object') { + fl.setParams({ models3d: false }); + return { error: 'the flights layer has no model record for aaa097' }; + } // Accessors with SWALLOWING setters, not data properties: the fleet tick - // assigns `model.show = false` for a not-ready model, and assigning to a + // assigns `show = false` for a not-ready model, and assigning to a // non-writable own property throws in strict mode — which lands inside - // Cesium's render loop and stops rendering for the rest of the run. - const priorReady = Object.getOwnPropertyDescriptor(fleetModel, 'ready'); - const priorShow = Object.getOwnPropertyDescriptor(fleetModel, 'show'); + // the render loop and stops rendering for the rest of the run. + const priorReady = Object.getOwnPropertyDescriptor(fleetRecord, 'ready'); + const priorShow = Object.getOwnPropertyDescriptor(fleetRecord, 'show'); let armed = false; let processedFrame = null; let sample = null; + let sampledRecord = null; let removePostRender = null; try { - Object.defineProperty(fleetModel, 'ready', { get: () => false, set: () => {}, configurable: true }); - Object.defineProperty(fleetModel, 'show', { + Object.defineProperty(fleetRecord, 'ready', { get: () => false, set: () => {}, configurable: true }); + Object.defineProperty(fleetRecord, 'show', { get: () => true, set: (value) => { // Both the not-ready handoff and horizon cull clear show AFTER @@ -3974,7 +4102,10 @@ async function main() { }); const bb = window.__dfFindBB('aaa097'); if (!bb) return { error: 'aaa097 billboard missing' }; - bb.show = true; // the handoff would not have hidden it: the model is not ready + // (The icon is not forced shown here, as the old billboard fixture did: + // the renderer draws what the layer sends, so the handoff the record + // drives is the only thing that decides it.) + const sameIcon = (a, b) => !!a && !!b && (a === b || (a.setId === b.setId && a.id === b.id)); const d0 = window.__dfCarto(bb.position); gf._clearMeshFloorCellsForTest(); // Earlier display-floor scenarios deliberately leave this contact's @@ -3997,13 +4128,18 @@ async function main() { sample = { fleetTickCompleted: true, fleetFrame: v.scene.frameState.frameNumber, - fleetModelReady: fleetModel.ready, - fleetModelShow: fleetModel.show, + fleetModelReady: fleetRecord.ready, + fleetModelShow: fleetRecord.show, fleetBillboardVisible: !!currentBb?.show, fleetSeeded: seededFleet, fleetH: currentBb ? window.__dfCarto(currentBb.position).h : null, }; - if (currentBb !== bb || currentModel !== fleetModel || fleetModel.isDestroyed() + // (An older build's seam answers asynchronously: its answer is + // checked once the frame is done, below.) + const currentRecord = fl.testing._ensureFleetModelForTest('aaa097'); + if (typeof currentRecord?.then === 'function') sampledRecord = currentRecord; + else if (currentRecord !== fleetRecord) sample.error = 'fleet loading fixture changed before its completed frame'; + if (!sameIcon(currentBb, bb) || currentModel !== fleetModel || fleetModel.isDestroyed() || fl.getTrackedInfo()) sample.error = 'fleet loading fixture changed before its completed frame'; }); armed = true; @@ -4014,14 +4150,17 @@ async function main() { await window.__dfSettle(50); } while (!sample && Date.now() < tickDeadline); if (!sample) return { error: 'fleet loading fixture did not complete an aircraft update within 5000 ms' }; + if (sampledRecord && (await sampledRecord) !== fleetRecord) { + sample.error = 'fleet loading fixture changed before its completed frame'; + } Object.assign(out, sample); } finally { armed = false; removePostRender?.(); - if (priorReady) Object.defineProperty(fleetModel, 'ready', priorReady); - else delete fleetModel.ready; - if (priorShow) Object.defineProperty(fleetModel, 'show', priorShow); - else delete fleetModel.show; + if (priorReady) Object.defineProperty(fleetRecord, 'ready', priorReady); + else delete fleetRecord.ready; + if (priorShow) Object.defineProperty(fleetRecord, 'show', priorShow); + else delete fleetRecord.show; fl.setParams({ models3d: false }); } await window.__dfSettle(400); @@ -4032,7 +4171,7 @@ async function main() { // it finishes. Sample within that window. if (!fl.trackById('aaa097')) return { ...out, error: 'trackById(aaa097) failed' }; await window.__dfSettle(500); - const entBefore = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entBefore = window.__qaFollowed()?.position?.(); const cBefore = entBefore ? window.__dfCarto(entBefore) : null; gf._clearMeshFloorCellsForTest(); fl._clearDisplayFloorStateForTest(); @@ -4054,7 +4193,7 @@ async function main() { // billboard-owned. The shared helper keys models by their pick id and // uses the production ownership pair (`show && ready`). out.renderingModelsDuringLoad = window.__dfCountModels('aaa097').rendering; - const entLoad = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entLoad = window.__qaFollowed()?.position?.(); out.trackedSeeded = seededTracked; out.trackedLoadH = entLoad ? window.__dfCarto(entLoad).h : null; fl.setParams({ models3d: false }); @@ -4174,7 +4313,12 @@ async function main() { const taxiCarto = window.__dfCarto(taxiPos); const baseMeshM = gfns?.cachedMeshFloor?.(baseCarto.lat, baseCarto.lon) ?? null; const taxiMeshM = gfns?.cachedMeshFloor?.(taxiCarto.lat, taxiCarto.lon) ?? null; + // The layer writes its icon changes to the draw set together once the + // current task's microtasks run (data/aircraftIconLayer.js), so the + // drawn row is read after that write, with no frame in between. + const iconWrites = () => Promise.resolve(); const heldOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: taxiPos, course: 90 }); + await iconWrites(); const heldH = window.__dfModelHeight(holdIcao); const heldBb = !!window.__dfFindBB(holdIcao)?.show; @@ -4182,6 +4326,7 @@ async function main() { // been. It is released rather than stretched, and the gate takes over. const farPos = Cesium.Cartesian3.fromDegrees(base.lon + 0.004, base.lat, base.h); const releasedOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: farPos, course: 90 }); + await iconWrites(); const releasedBb = !!window.__dfFindBB(holdIcao)?.show; fl.setParams({ models3d: false }); diff --git a/scripts/viewer-access-baseline.mjs b/scripts/viewer-access-baseline.mjs new file mode 100644 index 0000000000..4a2614a9bd --- /dev/null +++ b/scripts/viewer-access-baseline.mjs @@ -0,0 +1,63 @@ +/** + * Lower `src/render/viewerAccessAllowList.json` to the Cesium-shaped viewer + * accesses the files off the Cesium list still hold + * (`src/render/viewerAccess.test.mjs`). It only lowers counts and drops + * entries (files with none left, gone, or back on the Cesium list); it never + * adds a file or raises a count. A file over its count is reported and the + * script exits 1: port that access instead. + * + * `--check` reports what it would change without writing, and exits 1 when + * there is anything to lower. + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { + BASELINE, + countedFiles, + currentHits, + readBaseline, + ROOT, +} from '../src/testSupport/viewerAccess.mjs'; + +const check = process.argv.includes('--check'); +const baseline = readBaseline(); +const hits = currentHits(); +const counted = new Set(countedFiles()); + +const next = {}; +const changes = []; +for (const [file, allowed] of Object.entries(baseline)) { + const found = counted.has(file) ? (hits.get(file)?.length ?? 0) : 0; + const count = Math.min(allowed, found); + if (count > 0) next[file] = count; + if (count !== allowed) changes.push(`${file}: ${allowed} → ${count}`); +} +const over = [...hits] + .filter(([file, found]) => found.length > (baseline[file] ?? 0)) + .map( + ([file, found]) => + `${file}: ${found.length} found, ${baseline[file] ?? 0} recorded`, + ); + +if (changes.length) { + console.log( + `${check ? 'Would lower' : 'Lowered'}:\n ${changes.join('\n ')}`, + ); + if (!check) { + const sorted = Object.fromEntries( + Object.keys(next) + .sort() + .map((file) => [file, next[file]]), + ); + writeFileSync( + path.join(ROOT, BASELINE), + `${JSON.stringify(sorted, null, 2)}\n`, + ); + } else process.exitCode = 1; +} else console.log(`${BASELINE} is as low as it goes.`); +if (over.length) { + console.error( + `Over their counts (never raised; port these):\n ${over.join('\n ')}`, + ); + process.exitCode = 1; +} diff --git a/server/standalone/conformance-references.js b/server/standalone/conformance-references.js new file mode 100644 index 0000000000..669fef616a --- /dev/null +++ b/server/standalone/conformance-references.js @@ -0,0 +1,59 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +const DIR = fileURLToPath( + new URL('../../src/render/conformance/goldens/visual/', import.meta.url), +); +const NAME = /^[a-z0-9-]+\.(png|json)$/; +const MAX_BYTES = 8 * 1024 * 1024; + +/** + * Dev server only: lets `/dev/conformance/` save the visual references it + * records into `src/render/conformance/goldens/visual/`. Takes a PUT of one + * PNG or the manifest, named in the path; nothing else is written. + */ +export function conformanceReferencesPlugin() { + return { + name: 'conformance-references', + apply: 'serve', + configureServer(server) { + server.middlewares.use('/__conformance/references/', (req, res) => { + const name = decodeURIComponent((req.url ?? '').replace(/^\//, '')); + // Only the page on this machine: a loopback peer, sent from the + // dev server's own origin. + const peer = req.socket.remoteAddress ?? ''; + const loopback = /^(127\.|::1$|::ffff:127\.)/.test(peer); + let sameOrigin = false; + try { + sameOrigin = new URL(req.headers.origin).host === req.headers.host; + } catch { + // No Origin, or not a URL. + } + if (!loopback || !sameOrigin) { + res.writeHead(403).end(); + return; + } + if (req.method !== 'PUT' || !NAME.test(name)) { + res.writeHead(400).end(); + return; + } + const chunks = []; + let size = 0; + req.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_BYTES) req.destroy(); + else chunks.push(chunk); + }); + req.on('end', async () => { + try { + await mkdir(DIR, { recursive: true }); + await writeFile(DIR + name, Buffer.concat(chunks)); + res.writeHead(204).end(); + } catch (error) { + res.writeHead(500).end(String(error?.message ?? error)); + } + }); + }); + }, + }; +} diff --git a/server/standalone/vite.config.js b/server/standalone/vite.config.js index 76d26ba5d2..f660bfbd33 100644 --- a/server/standalone/vite.config.js +++ b/server/standalone/vite.config.js @@ -5,6 +5,7 @@ import { createBrowserViteConfig } from '../../build/vite.js'; import { localProviderPlugins } from '../providers/local.js'; import { localMcpPlugin } from '../mcp/plugin.js'; import { apiNotFoundPlugin } from './api-not-found.js'; +import { conformanceReferencesPlugin } from './conformance-references.js'; import { googleTokenUnavailablePlugin } from './google-token-unavailable.js'; import { standaloneVoiceTools } from './voiceTools.js'; import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js'; @@ -30,6 +31,7 @@ export function standaloneConfig( }), localMcpPlugin(), googleTokenUnavailablePlugin(), + conformanceReferencesPlugin(), apiNotFoundPlugin(), unwatchedRuntimeDirsPlugin(), ], diff --git a/src/agent/worldPacket.js b/src/agent/worldPacket.js index 4f8dad144c..9217bd9b39 100644 --- a/src/agent/worldPacket.js +++ b/src/agent/worldPacket.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { findCamera } from '../render/rendererOf.js'; import { feedProvenanceEnvelope, layerSnapshot, @@ -104,14 +104,12 @@ export function getWorldPacket(options = {}) { // A default parameter only covers undefined; null or NaN would age every // feed against the epoch and report stale data as "just now". const now = Number.isFinite(requestedNow) ? requestedNow : Date.now(); - if (!viewer?.camera?.positionWC) - throw new TypeError('World Packet requires a viewer camera'); + const pose = findCamera(viewer)?.pose(); + if (!pose) throw new TypeError('World Packet requires a viewer camera'); if (!dataManager || typeof dataManager.getAll !== 'function') throw new TypeError('World Packet requires a data manager'); - const cartographic = Cesium.Cartographic.fromCartesian( - viewer.camera.positionWC, - ); + const eye = { lon: pose.lon, lat: pose.lat, height: pose.height }; // Read the roster once. Voice must not rewalk disabled layers: preserving the // current enabled-only view keeps the model's context budget bounded. const rows = dataManager.getAll(); @@ -126,9 +124,9 @@ export function getWorldPacket(options = {}) { ok: true, action: 'get_current_view_state', camera: { - latitude: Cesium.Math.toDegrees(cartographic.latitude), - longitude: Cesium.Math.toDegrees(cartographic.longitude), - heightM: cartographic.height, + latitude: eye.lat, + longitude: eye.lon, + heightM: eye.height, }, style: styleManager?.activeStyle || 'normal', context: contextState diff --git a/src/agent/worldPacket.test.mjs b/src/agent/worldPacket.test.mjs index 063e3652c2..a10b407da6 100644 --- a/src/agent/worldPacket.test.mjs +++ b/src/agent/worldPacket.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { getWorldPacket } from './worldPacket.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { createStubRenderer } from '../render/stub/index.js'; import { createGevActionRunner } from '../voice/gevActions.js'; function withoutVoicePresentation(result) { @@ -18,6 +20,9 @@ function harness() { const viewer = { trackedEntity: undefined, clock: { onTick: { addEventListener: () => () => {} } }, + get canvas() { + return this.scene.canvas; + }, scene: { canvas: { clientWidth: 1200, @@ -60,6 +65,14 @@ function harness() { getCockpitState: () => null, getControlState: () => ({ hud: { visible: 'auto' } }), }; + // The packet reads the eye from the camera port of the renderer bound to + // the scene object. + const renderer = createStubRenderer(); + renderer.camera.setView({ + destination: { lon: -97.74, lat: 30.26, height: 500 }, + orientation: { heading: 0, pitch: Cesium.Math.toRadians(-45), roll: 0 }, + }); + bindRenderer(viewer, renderer); return { viewer, dataManager, styleManager }; } diff --git a/src/annotations/adminOutline.test.mjs b/src/annotations/adminOutline.test.mjs index 2028fe711f..4bb5cba35e 100644 --- a/src/annotations/adminOutline.test.mjs +++ b/src/annotations/adminOutline.test.mjs @@ -4,11 +4,13 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { createAnnotationEngine } from './annotationEngine.js'; import { _resetRenderGovernorForTest } from '../renderGovernor.js'; function viewerAt(lat, lon, height = 20_000) { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: (lat * Math.PI) / 180, @@ -16,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) { height, }, }, - }; + }); } /** A resolver whose boundary lookups and geocoder record every call. */ diff --git a/src/annotations/annotationEngine.js b/src/annotations/annotationEngine.js index c8cda0bf0d..352d65f4fd 100644 --- a/src/annotations/annotationEngine.js +++ b/src/annotations/annotationEngine.js @@ -1,6 +1,9 @@ import { isUnavailableCapability } from '../sources/capability.js'; import { defaultGeospatial } from '../search/defaults.js'; -import * as Cesium from 'cesium'; +import { cameraOf, findCamera, findQuery } from '../render/rendererOf.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { sphereFromPoints } from '../geo/sphere.js'; +import { distance, toRadians } from '../geo/vector.js'; import { greatCircleMeters } from '../geoDistance.js'; import { holdContinuousRender, @@ -20,11 +23,6 @@ import { } from '../sources/phaseTiming.js'; import { formatDistanceText } from '../data/distanceFormat.js'; -// Dev convenience: expose the app's Cesium instance for console/preview probing -// (single shared module instance — avoids dual-Cesium state bugs when testing). -if (typeof window !== 'undefined' && !window.__CESIUM__) - window.__CESIUM__ = Cesium; - /** * Annotation engine — the voice agent's "whiteboard" over the 3D world. * @@ -1717,18 +1715,20 @@ export function createAnnotationEngine({ frameAnnotation(marks[0]); return; } - const cart = points.map((p) => - Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0), + const cart = points.map((p) => fromDegrees(p.lon, p.lat, p.height || 0)); + const sphere = sphereFromPoints(cart); + const camera = cameraOf(viewer); + camera.flyToBounds( + { center: sphere.center, radius: sphere.radius }, + { + offset: { + heading: camera.pose().heading, + pitch: toRadians(-35), + range: Math.max(900, sphere.radius * 2.6), + }, + durationS: 1.6, + }, ); - const sphere = Cesium.BoundingSphere.fromPoints(cart); - viewer.camera.flyToBoundingSphere(sphere, { - offset: new Cesium.HeadingPitchRange( - viewer.camera.heading, - Cesium.Math.toRadians(-35), - Math.max(900, sphere.radius * 2.6), - ), - duration: 1.6, - }); } catch { /* camera assist is best-effort */ } @@ -1738,23 +1738,35 @@ export function createAnnotationEngine({ * globe. On any API hiccup, report visible — bad data must never move the camera. */ function isPointOnScreen(p) { try { - const camera = viewer.camera; - const pos = Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0); - const cv = camera.frustum.computeCullingVolume( - camera.position, - camera.direction, - camera.up, - ); - if ( - cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) === - Cesium.Intersect.OUTSIDE - ) - return false; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - camera.position, - ); - return occluder.isPointVisible(pos); + const camera = findCamera(viewer); + const query = findQuery(viewer); + if (!camera || !query) return true; + const pos = fromDegrees(p.lon, p.lat, p.height || 0); + // Inside the view frustum: a 1 m sphere at the point is not wholly + // outside any of its six planes, read off the view-projection (depth + // runs -1..1). An invalid matrix measures no distance and reads as + // visible. + const { view, projection } = camera.matrices(); + const m = new Float64Array(16); + for (let col = 0; col < 4; col++) + for (let row = 0; row < 4; row++) { + let sum = 0; + for (let k = 0; k < 4; k++) + sum += projection[k * 4 + row] * view[col * 4 + k]; + m[col * 4 + row] = sum; + } + const at = (row, col) => m[col * 4 + row]; + for (const [axis, sign] of FRUSTUM_PLANES) { + const a = at(3, 0) + sign * at(axis, 0); + const b = at(3, 1) + sign * at(axis, 1); + const c = at(3, 2) + sign * at(axis, 2); + const d = at(3, 3) + sign * at(axis, 3); + const distanceM = + (a * pos.x + b * pos.y + c * pos.z + d) / Math.hypot(a, b, c); + if (distanceM < -1) return false; + } + // On the near side of the globe. + return !query.isOccluded(pos); } catch { return true; } @@ -1778,22 +1790,23 @@ export function createAnnotationEngine({ : anno.ring, ) : viewportRange(anno.viewport) || 600; - viewer.camera.flyToBoundingSphere( - new Cesium.BoundingSphere( - Cesium.Cartesian3.fromDegrees( - target.lon, - target.lat, - anno.anchor.height || 0, - ), - range, - ), + const camera = cameraOf(viewer); + camera.flyToBounds( { - offset: new Cesium.HeadingPitchRange( - viewer.camera.heading, - Cesium.Math.toRadians(-35), - range * 2.4, - ), - duration: 1.8, + center: { + lon: target.lon, + lat: target.lat, + height: anno.anchor.height || 0, + }, + radius: range, + }, + { + offset: { + heading: camera.pose().heading, + pitch: toRadians(-35), + range: range * 2.4, + }, + durationS: 1.8, }, ); } catch { @@ -2005,15 +2018,17 @@ export function createAnnotationEngine({ }) { if (destroyed) return; try { - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees(lon, lat, height), - orientation: { - heading: Cesium.Math.toRadians(heading), - pitch: Cesium.Math.toRadians(pitch), - roll: 0, + cameraOf(viewer).flyTo( + { lon, lat, height }, + { + orientation: { + heading: toRadians(heading), + pitch: toRadians(pitch), + roll: 0, + }, + durationS: duration, }, - duration, - }); + ); } catch { /* camera flight best-effort */ } @@ -2175,13 +2190,23 @@ function pendingAnimation(anno, now) { // fly_to_location natural-region heuristic uses (owner field test 2026-07-23). const VIEWPORT_ASSIST_RANGE_CAP_M = 120000; +/** The view frustum's planes as `row 3 ± row axis` of the view-projection. */ +const FRUSTUM_PLANES = [ + [0, 1], + [0, -1], + [1, 1], + [1, -1], + [2, 1], + [2, -1], +]; + /** flyTo range from a Places viewport box (low/high lat-lng corners), or null. */ function viewportRange(vp) { if (!vp?.low || !vp?.high) return null; try { - const span = Cesium.Cartesian3.distance( - Cesium.Cartesian3.fromDegrees(vp.low.longitude, vp.low.latitude), - Cesium.Cartesian3.fromDegrees(vp.high.longitude, vp.high.latitude), + const span = distance( + fromDegrees(vp.low.longitude, vp.low.latitude), + fromDegrees(vp.high.longitude, vp.high.latitude), ); return Number.isFinite(span) && span > 0 ? Math.max(300, Math.min(span * 0.7, VIEWPORT_ASSIST_RANGE_CAP_M)) @@ -2206,9 +2231,9 @@ function ringRange(ring) { if (lon < minLon) minLon = lon; if (lon > maxLon) maxLon = lon; } - const span = Cesium.Cartesian3.distance( - Cesium.Cartesian3.fromDegrees(minLon, minLat), - Cesium.Cartesian3.fromDegrees(maxLon, maxLat), + const span = distance( + fromDegrees(minLon, minLat), + fromDegrees(maxLon, maxLat), ); return Math.max(300, span * 0.7); } diff --git a/src/annotations/annotationEngine.test.mjs b/src/annotations/annotationEngine.test.mjs index da7e4ae06d..c545ac988c 100644 --- a/src/annotations/annotationEngine.test.mjs +++ b/src/annotations/annotationEngine.test.mjs @@ -1,3 +1,4 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { createStandalonePlaceSearch } from '../standalone/placeSearch.js'; // Voice-annotation resilience contract tests — pure logic, no network, no browser. // @@ -25,6 +26,7 @@ import { installRenderGovernor, _resetRenderGovernorForTest, } from '../renderGovernor.js'; +import { framePortFor } from '../testSupport/fakeFramePort.mjs'; // A resolver that replays a scripted sequence of outcomes (undefined = transient, // null = definitive miss, object = footprint) and counts its invocations. @@ -1471,7 +1473,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and const { renderer, calls } = fakeRenderer(); const flights = []; const engine = createAnnotationEngine({ - viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }, + viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }), renderer, }); let changes = 0; @@ -1540,12 +1542,12 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec const { renderer, calls } = fakeRenderer(); const flights = []; const engine = createAnnotationEngine({ - viewer: { + viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere), }, - }, + }), renderer, }); let changes = 0; @@ -1757,7 +1759,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one _resetRenderGovernorForTest(); t.after(() => _resetRenderGovernorForTest()); let renders = 0; - installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } }); + installRenderGovernor(framePortFor({ requestRenderMode: true, requestRender: () => (renders += 1) })); const { renderer } = fakeRenderer(); const engine = createAnnotationEngine({ viewer: {}, renderer }); await engine.annotate([ @@ -1898,3 +1900,67 @@ test('plain recaption keeps the old mark addressable when its removal throws', a ); assert.equal(engine.count(), 0); }); + +// The camera assist frames a fresh mark only when none of it is in view: +// off the frustum or behind the globe, as the renderer's camera and query +// ports see it. A camera that cannot answer leaves the view alone. +test('camera assist frames marks out of view and leaves visible ones alone', async (t) => { + installAnimationFrameStubs(t); + const { bindRenderer } = await import('../render/rendererOf.js'); + const { horizonFrom } = await import('../geo/horizon.js'); + const viewerOver = (lon, lat, height, { broken = false } = {}) => { + const position = Cesium.Cartesian3.fromDegrees(lon, lat, height); + const direction = Cesium.Cartesian3.negate( + Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + const view = Cesium.Matrix4.computeView(position, direction, up, right, new Cesium.Matrix4()); + const frustum = new Cesium.PerspectiveFrustum({ + fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, far: 5e7, + }); + const flights = []; + const viewer = {}; + const horizon = horizonFrom(position); + bindRenderer(viewer, { + camera: { + pose: () => ({ heading: 0 }), + matrices() { + if (broken) throw new Error('no camera'); + return { + view: Float64Array.from(Cesium.Matrix4.toArray(view)), + projection: Float64Array.from(Cesium.Matrix4.toArray(frustum.projectionMatrix)), + }; + }, + flyTo: (...args) => flights.push(['flyTo', ...args]), + flyToBounds: (...args) => flights.push(['flyToBounds', ...args]), + }, + query: { isOccluded: (p) => !horizon.isPointVisible(p) }, + }); + return { viewer, flights }; + }; + const pinAt = async (viewer, lon, lat) => { + const engine = createAnnotationEngine({ viewer, renderer: fakeRenderer().renderer }); + await engine.annotate([{ type: 'pin', manual: true, latitude: lat, longitude: lon }], { persist: true, flyTo: false }); + }; + + const inView = viewerOver(-97.74, 30.27, 9000); + await pinAt(inView.viewer, -97.742, 30.268); + assert.equal(inView.flights.length, 0, 'a mark in view is left alone'); + + const aside = viewerOver(-97.74, 30.27, 9000); + await pinAt(aside.viewer, -97.5, 30.6); + assert.equal(aside.flights.length, 1, 'a mark off the frustum is framed'); + + const behind = viewerOver(60, 30, 9_000_000); + await pinAt(behind.viewer, -120, -30); + assert.equal(behind.flights.length, 1, 'a mark behind the globe is framed'); + + const broken = viewerOver(-97.74, 30.27, 9000, { broken: true }); + await pinAt(broken.viewer, -97.5, 30.6); + assert.equal(broken.flights.length, 0, 'a camera that cannot answer moves nothing'); +}); diff --git a/src/annotations/annotationResolver.test.mjs b/src/annotations/annotationResolver.test.mjs index 2c51213c19..acd84e878e 100644 --- a/src/annotations/annotationResolver.test.mjs +++ b/src/annotations/annotationResolver.test.mjs @@ -13,6 +13,7 @@ import { createPlaceSearch } from '../search/placeSearch.js'; // Run with: npm test (node --test) import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { resolveAnnotationTarget as resolveTarget, selectFootprint, @@ -157,7 +158,8 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => { }); function closeViewportViewer() { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: 30.2672 * Math.PI / 180, @@ -165,7 +167,7 @@ function closeViewportViewer() { height: 1000, }, }, - }; + }); } function geocodePayload({ lat, lon, types, label }) { @@ -369,11 +371,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township // Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs. const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 }; function capitolViewer() { - return { camera: { positionCartographic: { + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: CAPITOL_ANCHOR.lat * Math.PI / 180, longitude: CAPITOL_ANCHOR.lon * Math.PI / 180, height: 1000, - } } }; + } } }); } function installCapitolMocks(t, elements, components = [ { long_name: 'Washington', types: ['locality', 'political'] }, diff --git a/src/annotations/drawTool.js b/src/annotations/drawTool.js index f44d30753d..b1f8d1d05a 100644 --- a/src/annotations/drawTool.js +++ b/src/annotations/drawTool.js @@ -1,5 +1,5 @@ /** - * Manual whiteboard drawing: the Cesium + DOM half. + * Manual whiteboard drawing: the scene + DOM half. * * UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a * shape (area, line or pin) and a colour, click the vertices on the real world, @@ -15,12 +15,13 @@ * (`src/data/inputOwnership.js`), and every ambient selection handler yields, * so a vertex clicked on top of an aircraft or a camera is a vertex and * nothing else. It is one claim consulted by all of them, not a list of - * exceptions inside each. + * exceptions inside each. Turning Draw on takes the pointer from any tool + * holding it; a newer tool taking it turns Draw off. * - Cesium's Viewer binds its OWN left click (select the entity under the * pointer) and double click (track it) on the viewer's handler, outside every - * layer and therefore outside the shared claim. Both are borrowed for the + * layer and therefore outside the shared claim. Both are suppressed for the * session and given back on the way out, and `destroy()` gives back every - * listener, the Cesium handler, the preview data source and the window + * listener, the pointer subscriptions, the preview draw sets and the window * handle, so the tool can be turned off or the shell disposed without leaving * anything behind. * @@ -30,14 +31,13 @@ * drapes finished areas and routes onto the surface, so the height is dropped * at finish, deliberately and in one place — see `finishSpec` in drawMode.js. */ -import * as Cesium from 'cesium'; import { pickWorldFromScreen } from './annotationResolver.js'; import { claimPointer, pointerOwner, releasePointer, } from '../data/inputOwnership.js'; -import { pointerOwnerName } from '../data/pointerOwnerNames.js'; +import { inputFor } from '../input/dispatcher.js'; import { DRAW_SHAPES, MAX_VERTICES, @@ -59,7 +59,14 @@ import { presentDrawMarks, } from './drawMarks.js'; -import { onLocaleChange, t, translateKnown } from '../i18n/index.js'; +import { onLocaleChange, t } from '../i18n/index.js'; +import { fromDegrees } from '../geo/index.js'; +import { cssColor } from '../render/color.js'; +import { + canvasOf as sceneCanvasOf, + drawOf, + findFrame, +} from '../render/rendererOf.js'; /** The longest note a row action leaves under its row, in characters. */ const NOTE_MAX = 200; /** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */ @@ -74,7 +81,15 @@ function noteText(text) { /** The id this tool claims the pointer under. */ const DRAW_POINTER_OWNER = 'draw'; -const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview'; +/** Each tool's preview sets get their own ids. */ +let previewSerial = 0; +/** + * Preview sets drawn on each viewer by its live tools, so a tool left + * undestroyed beside its replacement shows up in `diagnostics()`. + */ +const livePreviewSets = new WeakMap(); +const countPreviewSets = (viewer, delta) => + livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta); const PREVIEW = DRAW_COLOR_CSS; @@ -89,7 +104,7 @@ const PREVIEW = DRAW_COLOR_CSS; * `markActions` are the application's own buttons on an area's or a line's * row (drawMarks.js `drawMarkActions`); a press runs the action with the * shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`). - * @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps + * @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps * @returns {{destroy: Function}|null} */ export function initDrawTool({ @@ -115,16 +130,13 @@ export function initDrawTool({ let shape = 'area'; let color = 'primary'; let hint = ''; - let handler = null; + let unbindScene = null; let lease = null; - let savedDoubleClick = null; - let savedSingleClick = null; let cursor = null; // last mouse position on the canvas, for the rubber band // Bumped by anything that supersedes an in-flight finish: cancelling, clearing // the board, leaving draw mode, teardown. An `annotate()` that resolves after // one of those must not write its outcome over the newer state. let generation = 0; - const previewEntities = []; // Every DOM listener this tool adds (the session's keydown), so teardown is // one loop rather than a list that can fall out of step with the bindings. const domListeners = []; @@ -133,14 +145,26 @@ export function initDrawTool({ domListeners.push([target, type, listener, options]); }; - const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME); - // `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would - // remove a source that had not been attached yet and leave the attachment to - // land afterwards — a preview data source nobody owns. Chain the removal onto - // the attachment instead of racing it. - let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch( - () => null, - ); + // The preview: one dashed rubber band and a dot per vertex, drawn through + // the renderer's draw port. Both sets live as long as the tool. + const draw = drawOf(viewer); + const previewId = `draw-preview:${++previewSerial}`; + const previewLines = draw.lines({ id: `${previewId}:line` }); + const previewPoints = draw.points({ id: `${previewId}:vertices` }); + countPreviewSets(viewer, 2); + let previewReleased = false; + const releasePreview = () => { + if (previewReleased) return; + previewReleased = true; + countPreviewSets(viewer, -2); + previewLines.dispose(); + previewPoints.dispose(); + }; + /** The canvas the renderer draws in (the viewer's own when none is bound). */ + const canvasOf = () => sceneCanvasOf(viewer); + const requestRender = () => findFrame(viewer)?.requestRender('draw-preview'); + // Teardown finishes synchronously; `whenSettled()` keeps its promise. + const attaching = Promise.resolve(); const present = () => { const marks = annotations.list?.() || []; @@ -169,70 +193,71 @@ export function initDrawTool({ // ---- preview --------------------------------------------------------- const vertexPositions = () => - session.vertices.map((v) => - Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0), - ); - const previewLine = dataSource.entities.add({ - show: false, - polyline: { - positions: new Cesium.CallbackProperty(() => { - if (!session) return []; - const pts = vertexPositions(); - if (cursor && session.shape !== 'pin') pts.push(cursor); - if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]); - return pts; - }, false), - width: 3, - material: new Cesium.PolylineDashMaterialProperty({ - color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9), - dashLength: 16, - }), - depthFailMaterial: new Cesium.PolylineDashMaterialProperty({ - color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35), - dashLength: 16, - }), - clampToGround: false, - }, - }); - const syncPreview = () => { + session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0)); + /** The rubber band, from the vertices to the pointer (and closed for an area). */ + const syncPreviewLine = () => { if (destroyed) return; - previewEntities.forEach((e) => dataSource.entities.remove(e)); - previewEntities.length = 0; - if (!session) { - previewLine.show = false; - setHint(() => drawHint(null)); - viewer.scene.requestRender(); + if (!session || session.shape === 'pin') { + previewLines.clear(); return; } - const stroke = Cesium.Color.fromCssColorString( - PREVIEW[color] || PREVIEW.primary, - ); - previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({ - color: stroke.withAlpha(0.9), - dashLength: 16, - }); - previewLine.show = session.shape !== 'pin'; - for (const v of session.vertices) { - previewEntities.push( - dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0), - point: { - pixelSize: 8, - color: stroke, - outlineColor: Cesium.Color.BLACK.withAlpha(0.6), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }), - ); + const pts = vertexPositions(); + if (cursor) pts.push(cursor); + if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]); + if (pts.length < 2) { + previewLines.clear(); + return; } + previewLines.upsert([ + { + id: 'band', + positions: pts, + widthPx: 3, + // Along the ellipsoid between vertices, as the entity polyline was. + mode: 'geodesic', + style: { + kind: 'dash', + color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9), + length: 16, + }, + // Dashed behind the surface too, as the band in front of it is. + depthFail: { + kind: 'dash', + color: withAlpha(cssColor(PREVIEW.primary), 0.35), + length: 16, + }, + }, + ]); + }; + const syncPreview = () => { + if (destroyed) return; + if (!session) { + previewPoints.clear(); + previewLines.clear(); + setHint(() => drawHint(null)); + requestRender(); + return; + } + const stroke = cssColor(PREVIEW[color] || PREVIEW.primary); + previewPoints.set( + session.vertices.map((v, index) => ({ + id: String(index), + pos: { lon: v.lon, lat: v.lat, height: v.height || 0 }, + pixelSize: 8, + color: stroke, + outlineColor: [0, 0, 0, 0.6], + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + })), + ); + syncPreviewLine(); setHint(() => drawHint(session)); - viewer.scene.requestRender(); + requestRender(); }; // ---- vertices from clicks -------------------------------------------- const worldAt = (position) => { - const canvas = viewer.scene.canvas; + const canvas = canvasOf(); const w = canvas.clientWidth || canvas.width || 1; const h = canvas.clientHeight || canvas.height || 1; return pickWorldFromScreen(viewer, position.x / w, position.y / h); @@ -260,11 +285,12 @@ export function initDrawTool({ }; const onMove = (event) => { if (!session || session.shape === 'pin' || destroyed) return; - const p = worldAt(event.endPosition); - cursor = p - ? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0) - : null; - viewer.scene.requestRender(); + // The click's own position is sensor-corrected; the rubber band must + // follow the same point the click would place. + const p = worldAt(event.pickPosition ?? event.endPosition); + cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null; + syncPreviewLine(); + requestRender(); }; // ---- finish / cancel ------------------------------------------------- @@ -344,9 +370,7 @@ export function initDrawTool({ t.closest('button, a, select, [role="button"], [role="radio"]') ) return false; - return ( - t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS' - ); + return t === document.body || t === canvasOf() || t.tagName === 'CANVAS'; }; const onKey = (event) => { if (!active || destroyed || typingElsewhere(event)) return; @@ -383,18 +407,15 @@ export function initDrawTool({ function setActive(next) { if (destroyed || next === active) return active; if (next) { - lease = claimPointer(DRAW_POINTER_OWNER); - if (!lease) { - // Somebody else is using the pointer — possibly an older instance of - // this same tool that has not finished tearing down. Say so instead of - // half-starting. - setHint(() => - t('{owner} is using the pointer — close it first.', { - owner: translateKnown(pointerOwnerName(pointerOwner())), - }), - ); - return active; - } + // The newest claim takes over: a tool holding the pointer is told and + // turns itself off, and a newer one turns Draw off as if the person had. + const claimed = claimPointer(DRAW_POINTER_OWNER, { + onLost: () => { + if (lease === claimed) setActive(false); + }, + }); + if (!claimed) return active; + lease = claimed; } active = next; present(); @@ -416,50 +437,29 @@ export function initDrawTool({ } function bindSceneHandler() { - if (handler) return; - handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); - handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK); - handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE); - handler.setInputAction(() => { - void finish(); - }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); - // Cesium's Viewer binds BOTH stock click actions on its own handler: the - // single click picks an entity into `viewer.selectedEntity`, the double - // click tracks it. Neither goes through a layer, so neither can be fixed by - // the shared pointer claim — they have to be borrowed outright for the - // session and given back on the way out. Borrowing the single click is what - // stops a vertex placed on a contact from also selecting it. - const stock = viewer.screenSpaceEventHandler; - savedSingleClick = - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null; - savedDoubleClick = - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null; - stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK); - stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); + if (unbindScene) return; + const input = inputFor(viewer); + const held = { lease: () => lease }; + const offs = [ + input.onPointer('click', onClick, held), + input.onPointer('move', onMove, held), + input.onPointer('dblclick', () => void finish(), held), + // Cesium's Viewer binds BOTH stock click actions on its own handler: the + // single click picks an entity into `viewer.selectedEntity`, the double + // click tracks it. Neither goes through a layer, so neither yields to the + // shared pointer claim — they are suppressed for the session and given + // back on the way out. Suppressing the single click is what stops a + // vertex placed on a contact from also selecting it. + input.suppressStockClicks(), + ]; + unbindScene = () => offs.forEach((off) => off()); listen(document, 'keydown', onKey, true); } function releaseSceneHandler() { - if (handler) { - handler.destroy(); - handler = null; - } - if (savedSingleClick) { - viewer.screenSpaceEventHandler.setInputAction( - savedSingleClick, - Cesium.ScreenSpaceEventType.LEFT_CLICK, - ); - savedSingleClick = null; - } - if (savedDoubleClick) { - viewer.screenSpaceEventHandler.setInputAction( - savedDoubleClick, - Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, - ); - savedDoubleClick = null; - } - // Drop the keydown listener bound alongside this handler. + unbindScene?.(); + unbindScene = null; + // Drop the keydown listener bound alongside the pointer subscriptions. for (let i = domListeners.length - 1; i >= 0; i -= 1) { const [target, type, listener, options] = domListeners[i]; if (listener !== onKey) continue; @@ -608,26 +608,18 @@ export function initDrawTool({ return { active, destroyed, - sceneHandler: Boolean(handler), + sceneHandler: Boolean(unbindScene), domListeners: domListeners.length, - previewDataSources: countPreviewDataSources(viewer), - previewEntities: destroyed ? 0 : dataSource.entities.values.length, + // Every live tool's on this viewer: 2 while one tool lives. + previewSets: livePreviewSets.get(viewer) ?? 0, + previewItems: previewReleased + ? 0 + : previewLines.size() + previewPoints.size(), pointerOwner: pointerOwner(), - // The viewer's OWN click actions. While a session is open both are - // borrowed (absent here); after it closes both are back. A harness can - // compare the restored functions by identity with what it captured - // before, which is the only way to prove they were given back rather - // than replaced. - stockSingleClick: Boolean( - viewer.screenSpaceEventHandler?.getInputAction?.( - Cesium.ScreenSpaceEventType.LEFT_CLICK, - ), - ), - stockDoubleClick: Boolean( - viewer.screenSpaceEventHandler?.getInputAction?.( - Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, - ), - ), + // The viewer's own select and follow, which the input port runs: off + // while a session is open, back on after it closes. + stockSingleClick: inputFor(viewer).stockEnabled('select'), + stockDoubleClick: inputFor(viewer).stockEnabled('dblclickFollow'), }; }, /** Resolves once every deferred teardown step has run. */ @@ -649,18 +641,7 @@ export function initDrawTool({ for (const [target, type, listener, options] of domListeners.splice(0)) { target.removeEventListener(type, listener, options); } - previewEntities.length = 0; - dataSource.entities.removeAll(); - // Wait for the pending add() before removing: a destroy() in the same - // tick as init would otherwise remove nothing and let the attachment land - // behind it. - attaching = attaching.then(() => { - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* viewer already disposed — nothing to detach from */ - } - }); + releasePreview(); document.body.classList.remove('gev-drawing'); hint = ''; present(); @@ -672,13 +653,7 @@ export function initDrawTool({ return api; } -/** How many draw previews are attached — more than one means a leaked tool. */ -function countPreviewDataSources(viewer) { - const sources = viewer?.dataSources; - if (!sources) return 0; - let found = 0; - for (let index = 0; index < sources.length; index += 1) { - if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1; - } - return found; +/** `color` at `alpha`. */ +function withAlpha(color, alpha) { + return [color[0], color[1], color[2], alpha]; } diff --git a/src/annotations/drawTool.test.mjs b/src/annotations/drawTool.test.mjs index 67ff94cfa3..2d7b2a6013 100644 --- a/src/annotations/drawTool.test.mjs +++ b/src/annotations/drawTool.test.mjs @@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => { // rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels // against a keyless server; this stops the constant being narrowed again. const renderer = read('src/annotations/worldAnnotationRenderer.js'); - assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/); - assert.doesNotMatch( - renderer, - /classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/, - ); + assert.match(renderer, /const CLAMP_TO = 'both';/); + assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/); }); test('the draw modules are registered for formatting and boundary checks', () => { diff --git a/src/annotations/drawToolBehaviour.test.mjs b/src/annotations/drawToolBehaviour.test.mjs index b435fdf247..862cae6574 100644 --- a/src/annotations/drawToolBehaviour.test.mjs +++ b/src/annotations/drawToolBehaviour.test.mjs @@ -13,6 +13,8 @@ import { releasePointer, resetPointerOwnership, } from '../data/inputOwnership.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; /* ── DOM doubles ───────────────────────────────────────────────────────── */ @@ -68,9 +70,17 @@ class FakeElement { } closest(selector) { // Only what the tool asks: "am I inside an activatable control?" - const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]']; + const activatable = [ + 'button', + 'a', + 'select', + '[role="button"]', + '[role="radio"]', + ]; if (!activatable.some((part) => selector.includes(part))) return null; - return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT' + return this.tagName === 'BUTTON' || + this.tagName === 'A' || + this.tagName === 'SELECT' ? this : null; } @@ -143,39 +153,22 @@ function fakeViewer() { setInputAction: (action, type) => actions.set(type, action), removeInputAction: (type) => actions.delete(type), }; - const attached = []; - const pendingAdds = []; - const dataSources = { - get length() { - return attached.length; - }, - get: (index) => attached[index], - add(source) { - // Cesium resolves this on a later tick — the whole point of finding 7. - const promise = Promise.resolve().then(() => { - attached.push(source); - return source; - }); - pendingAdds.push(promise); - return promise; - }, - remove(source) { - const at = attached.indexOf(source); - if (at >= 0) attached.splice(at, 1); - return at >= 0; - }, - }; return { scene: { canvas, requestRender() {} }, screenSpaceEventHandler: stockHandler, - dataSources, - _attached: attached, _actions: actions, }; } function fakeAnnotations() { - const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] }; + const calls = { + annotate: [], + clear: 0, + restyle: [], + setHidden: [], + frame: [], + remove: [], + }; const marks = []; const listeners = new Set(); const changed = () => listeners.forEach((listener) => listener()); @@ -223,10 +216,21 @@ function fakeAnnotations() { } /** Stand up a tool against fresh doubles, with globals restored afterwards. */ -function harness({ navigation = null, markActions = [] } = {}) { +function harness({ + navigation = null, + beforeInput = () => {}, + markActions = [], +} = {}) { resetPointerOwnership(); const { byId, documentDouble } = fakeDom(); const viewer = fakeViewer(); + // The viewer's own actions are bound before its input port takes them. + beforeInput(viewer); + const input = fakeInput(viewer); + // The renderer the tool draws its preview with, drawing in the viewer's canvas. + const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, { + canvas: viewer.scene.canvas, + }); const annotations = fakeAnnotations(); const previousDocument = globalThis.document; const previousWindow = globalThis.window; @@ -250,6 +254,7 @@ function harness({ navigation = null, markActions = [] } = {}) { tool, shown, viewer, + draw, annotations, byId, documentDouble, @@ -257,7 +262,10 @@ function harness({ navigation = null, markActions = [] } = {}) { controls, /** A control's change, as the view sends it. */ act: (name, ...args) => controls.actions?.[name]?.(...args), + input, restore() { + input.destroy(); + unbindDraw(); resetPointerOwnership(); if (previousDocument === undefined) delete globalThis.document; else globalThis.document = previousDocument; @@ -288,23 +296,42 @@ test('turning Draw on takes a lease and turning it off gives it back', async () } }); -test('Draw refuses to start when something else holds the pointer', async () => { +test('Draw takes the pointer from another tool, which is told', async () => { const h = harness(); try { - const other = claimPointer('directions'); + let lost = 0; + claimPointer('directions', { onLost: () => (lost += 1) }); h.act('toggleDraw'); - assert.equal(h.tool.active, false, 'it must not half-start'); - assert.equal(pointerOwner(), 'directions', 'and must not steal the claim'); - // Named by its tool, not by the internal owner id. - assert.equal( - h.shown.view.hint, - 'Directions is using the pointer — close it first.', - ); - assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound'); + assert.equal(h.tool.active, true, 'the newest claim takes over'); + assert.equal(pointerOwner(), 'draw'); + assert.equal(lost, 1, 'the other tool is told once'); + } finally { + h.restore(); + } +}); +test('Draw turns off, as if toggled off, when a newer tool takes the pointer', async () => { + const h = harness({ + beforeInput(viewer) { + viewer.screenSpaceEventHandler.setInputAction(() => {}, LEFT_CLICK); + }, + }); + try { + h.act('toggleDraw'); + assert.equal(h.tool.diagnostics().stockSingleClick, false); + assert.ok(h.tool.addVertex(10, 20), 'a shape is under way'); + const other = claimPointer('directions'); + assert.equal(h.tool.active, false); + assert.equal(h.tool.session, null, 'the half-drawn shape is dropped'); + assert.equal(h.shown.view.active, false, 'the Draw control reads off'); + const after = h.tool.diagnostics(); + assert.equal(after.sceneHandler, false, 'its subscriptions are gone'); + assert.equal(after.stockSingleClick, true, 'the stock clicks are back'); + assert.equal(after.previewItems, 0, 'the preview is cleared'); + assert.equal(pointerOwner(), 'directions', 'the newer tool keeps it'); releasePointer(other); h.act('toggleDraw'); - assert.equal(h.tool.active, true, 'and it starts once the pointer is free'); + assert.equal(h.tool.active, true, 'and it turns on again when asked'); } finally { h.restore(); } @@ -336,30 +363,36 @@ test('a destroyed instance cannot free the pointer its replacement holds', async } }); -test('both stock viewer click actions are borrowed for the session and given back', async () => { - const h = harness(); +test('both stock viewer click actions are held off for the session and given back', async () => { + const stockClick = () => 'viewer picks and selects'; + const stockDouble = () => 'viewer tracks'; + const h = harness({ + beforeInput(viewer) { + viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK); + viewer.screenSpaceEventHandler.setInputAction( + stockDouble, + LEFT_DOUBLE_CLICK, + ); + }, + }); try { - const stockClick = () => 'viewer picks and selects'; - const stockDouble = () => 'viewer tracks'; - h.viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK); - h.viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK); - + assert.equal(h.input.stockEnabled('select'), true); h.act('toggleDraw'); assert.equal( - h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK), - undefined, + h.input.stockEnabled('select'), + false, "the viewer's own selecting click must not run while drawing", ); - assert.equal( - h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK), - undefined, - ); + assert.equal(h.input.stockEnabled('dblclickFollow'), false); h.act('toggleDraw'); + assert.equal(h.input.stockEnabled('select'), true); + assert.equal(h.input.stockEnabled('dblclickFollow'), true); + h.input.destroy(); assert.equal( h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK), stockClick, - 'the exact function is restored, not a replacement', + 'the exact function goes back to the viewer, not a replacement', ); assert.equal( h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK), @@ -380,20 +413,34 @@ test('Enter finishes from the canvas and the label field, never from a focused b h.tool.addVertex(-97.74, 30.27); // Enter while the Clear button has keyboard focus means "press Clear". - h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.element('draw-clear'), + }); await Promise.resolve(); assert.equal( h.annotations.calls.annotate.length, 0, 'a focused button keeps its own Enter', ); - assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched'); + assert.equal( + h.tool.session.vertices.length, + 3, + 'and the shape is untouched', + ); // Enter from the page body (the canvas has focus in practice) finishes it. - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); - assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes'); + assert.equal( + h.annotations.calls.annotate.length, + 1, + 'Enter on the map finishes', + ); assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area'); } finally { h.restore(); @@ -429,21 +476,29 @@ test('the live preview hangs at the height the click landed on', async () => { h.tool.addVertex(-97.75, 30.26, 187.5); h.tool.addVertex(-97.74, 30.26, 212.25); - await h.tool.whenSettled(); - const source = h.viewer._attached[0] ?? null; - assert.ok(source, 'the preview data source is attached'); - const points = source.entities.values.filter((entity) => entity.point); - assert.equal(points.length, 2, 'one preview dot per vertex'); - const heights = points.map((entity) => { - const position = entity.position.getValue(Cesium.JulianDate.now()); - return Cesium.Cartographic.fromCartesian(position).height; - }); + const dots = [...h.draw.sets.values()].find( + (set) => !set.disposed && set.kind === 'points', + ); + assert.equal(dots.items.size, 2, 'one preview dot per vertex'); + const heights = [...dots.items.values()].map((item) => item.pos.height); + const band = [...h.draw.sets.values()] + .find((set) => !set.disposed && set.kind === 'lines') + .items.get('band'); + assert.equal( + band.positions.length, + 2, + 'the rubber band joins the vertices', + ); + assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped'); assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`); assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`); // …and the finished shape is still flattened, deliberately: the renderer // drapes, so a height carried further would be discarded out of sight. - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); const spec = h.annotations.calls.annotate[0].specs[0]; @@ -456,17 +511,60 @@ test('the live preview hangs at the height the click landed on', async () => { } }); -test('destroy in the same tick as init still removes the preview data source', async () => { +test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => { const h = harness(); try { - // Nothing has been attached yet — dataSources.add() resolves later. - assert.equal(h.viewer._attached.length, 0, 'the add is still pending'); - await h.tool.destroy(); - await Promise.resolve(); + const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed); + const band = () => + sets() + .find((set) => set.kind === 'lines') + .items.get('band'); + h.act('toggleDraw'); + h.tool.setShape('area'); + h.tool.addVertex(-97.75, 30.26); + assert.equal(band(), undefined, 'one vertex and no pointer draw no band'); + h.tool.addVertex(-97.74, 30.26); + h.tool.addVertex(-97.74, 30.27); assert.equal( - h.viewer._attached.length, + band().positions.length, + 4, + 'an area of three closes back to its first vertex', + ); + assert.deepEqual(band().positions[3], band().positions[0]); + + h.tool.setColor('red'); + assert.deepEqual( + band().style.color, + [1, 107 / 255, 107 / 255, 0.9], + 'the band takes the colour', + ); + assert.deepEqual( + band().depthFail, + { kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 }, + 'behind the surface it stays the primary colour, dashed, as before', + ); + assert.equal(band().style.kind, 'dash'); + assert.equal(band().style.length, 16); + assert.equal(band().widthPx, 3); + + h.tool.setShape('pin'); + assert.equal(band(), undefined, 'a pin has no rubber band'); + } finally { + h.restore(); + } +}); + +test('destroy in the same tick as init disposes the preview sets', async () => { + const h = harness(); + try { + const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed); + assert.equal(live().length, 2, 'the rubber band and the vertex dots'); + await h.tool.destroy(); + assert.equal(live().length, 0, 'nothing is left drawn behind the teardown'); + assert.equal( + h.tool.diagnostics().previewSets, 0, - 'the preview must not be left attached behind the teardown', + 'no live tool draws a preview', ); } finally { h.restore(); @@ -490,7 +588,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act assert.equal(isPointerFree(), true, 'the pointer is free'); const after = h.tool.diagnostics(); assert.equal(after.destroyed, true); - assert.equal(after.sceneHandler, false, 'the Cesium handler is gone'); + assert.equal( + after.sceneHandler, + false, + 'the pointer subscriptions are gone', + ); assert.equal(after.domListeners, 0, 'every DOM listener came off'); assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown'); assert.equal(h.controls.actions, null, 'and the controls are disconnected'); @@ -499,8 +601,12 @@ test('destroy releases the pointer, the handler, the listeners and the stock act stockClick, 'the viewer got its selecting click back', ); - assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached'); - assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board'); + assert.equal(after.previewSets, 0, 'the preview sets are disposed'); + assert.equal( + h.annotations.listeners.size, + 0, + 'and it no longer follows the board', + ); // Idempotent: a second destroy is harmless. await h.tool.destroy(); @@ -519,7 +625,11 @@ test('Clear wipes the board and the shape in progress', async () => { h.act('clearDraw'); assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed'); - assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress'); + assert.equal( + h.tool.session.vertices.length, + 0, + 'and so is the shape in progress', + ); } finally { h.restore(); } @@ -533,7 +643,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it h.act('setDrawColor', 'amber'); assert.deepEqual( { ...h.shown.view, hint: undefined }, - { active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] }, + { + active: true, + shape: 'line', + color: 'amber', + hint: undefined, + marks: [], + }, 'the view shows what the controls chose', ); h.act('setDrawColor', 'purple'); @@ -545,7 +661,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it assert.equal(h.tool.session.vertices.length, 0); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); const spec = h.annotations.calls.annotate[0].specs[0]; @@ -570,12 +689,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n try { const board = h.annotations; board.marks.push( - { id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false }, - { id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false }, + { + id: 'a1', + type: 'route', + manual: true, + name: null, + label: '950 m', + color: 'amber', + hidden: false, + }, + { + id: 'a2', + type: 'pin', + manual: false, + label: 'Voice pin', + color: 'primary', + hidden: false, + }, ); board.changed(); assert.deepEqual( - h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })), + h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ + id, + placeholder, + hidden, + })), [{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }], 'only hand-drawn marks are listed, an unnamed line by its length', ); @@ -590,7 +728,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n ]); assert.deepEqual(board.calls.setHidden, [['a1', true]]); assert.deepEqual(board.calls.frame, ['a1']); - assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy'); + assert.deepEqual( + navigations, + ['drawing'], + 'fly-to goes through the navigation policy', + ); assert.deepEqual(board.calls.remove, ['a1']); assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark'); } finally { @@ -598,7 +740,7 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n } }); -test('an application\'s row actions show on the shapes they are for and run with the shape', async () => { +test("row actions given to the tool show on the shapes they are for and run with the shape", async () => { const ran = []; const h = harness({ markActions: [ @@ -622,30 +764,102 @@ test('an application\'s row actions show on the shapes they are for and run with try { const board = h.annotations; board.marks.push( - { id: 'r1', type: 'area', manual: true, name: 'Strait', color: 'primary', hidden: false, ring: [[29, 41], [29.1, 41], [29.1, 41.1]] }, - { id: 'l1', type: 'route', manual: true, name: null, label: '9 km', color: 'amber', hidden: false, path: [{ lon: 29, lat: 41.05, height: 0 }, { lon: 29.1, lat: 41.05, height: 0 }] }, - { id: 'p1', type: 'pin', manual: true, name: 'Camp', color: 'red', hidden: false }, + { + id: 'r1', + type: 'area', + manual: true, + name: 'Strait', + color: 'primary', + hidden: false, + ring: [ + [29, 41], + [29.1, 41], + [29.1, 41.1], + ], + }, + { + id: 'l1', + type: 'route', + manual: true, + name: null, + label: '9 km', + color: 'amber', + hidden: false, + path: [ + { lon: 29, lat: 41.05, height: 0 }, + { lon: 29.1, lat: 41.05, height: 0 }, + ], + }, + { + id: 'p1', + type: 'pin', + manual: true, + name: 'Camp', + color: 'red', + hidden: false, + }, ); board.changed(); assert.deepEqual( h.shown.view.marks.map(({ id, actions }) => [id, actions]), [ - ['r1', [ - { id: 'tag', icon: 'sell', label: 'Tag Strait' }, - { id: 'measure', icon: 'straighten', label: 'Measure Strait' }, - ]], + [ + 'r1', + [ + { id: 'tag', icon: 'sell', label: 'Tag Strait' }, + { id: 'measure', icon: 'straighten', label: 'Measure Strait' }, + ], + ], ['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]], ['p1', []], ], ); assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true); - assert.equal(h.act('runDrawMarkAction', 'l1', 'measure'), false, 'a line is not offered an area action'); + assert.equal( + h.act('runDrawMarkAction', 'l1', 'measure'), + false, + 'a line is not offered an area action', + ); assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false); assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false); assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true); assert.deepEqual(ran, [ - ['tag', { id: 'l1', shape: 'line', name: '', title: 'Line · 9 km', geometry: { type: 'LineString', coordinates: [[29, 41.05], [29.1, 41.05]] } }], - ['measure', { id: 'r1', shape: 'area', name: 'Strait', title: 'Strait', geometry: { type: 'Polygon', coordinates: [[[29, 41], [29.1, 41], [29.1, 41.1], [29, 41]]] } }], + [ + 'tag', + { + id: 'l1', + shape: 'line', + name: '', + title: 'Line · 9 km', + geometry: { + type: 'LineString', + coordinates: [ + [29, 41.05], + [29.1, 41.05], + ], + }, + }, + ], + [ + 'measure', + { + id: 'r1', + shape: 'area', + name: 'Strait', + title: 'Strait', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [29, 41], + [29.1, 41], + [29.1, 41.1], + [29, 41], + ], + ], + }, + }, + ], ]); } finally { h.restore(); @@ -655,16 +869,40 @@ test('an application\'s row actions show on the shapes they are for and run with test('an action that throws is reported and leaves the row alone', async () => { const h = harness({ markActions: [ - { id: 'boom', icon: 'bolt', label: () => { throw new Error('label'); }, shapes: ['area'], run: () => { throw new Error('run'); } }, + { + id: 'boom', + icon: 'bolt', + label: () => { + throw new Error('label'); + }, + shapes: ['area'], + run: () => { + throw new Error('run'); + }, + }, ], }); const warn = console.warn; const warned = []; console.warn = (...args) => warned.push(args[0]); try { - h.annotations.marks.push({ id: 'r1', type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] }); + h.annotations.marks.push({ + id: 'r1', + type: 'area', + manual: true, + name: null, + color: 'primary', + hidden: false, + ring: [ + [0, 0], + [1, 0], + [1, 1], + ], + }); h.annotations.changed(); - assert.deepEqual(h.shown.view.marks[0].actions, [{ id: 'boom', icon: 'bolt', label: 'boom' }]); + assert.deepEqual(h.shown.view.marks[0].actions, [ + { id: 'boom', icon: 'bolt', label: 'boom' }, + ]); assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false); assert.deepEqual(warned, ['[draw] boom failed']); } finally { @@ -673,7 +911,7 @@ test('an action that throws is reported and leaves the row alone', async () => { } }); -test('what a row action answers is its row\'s note; the row is busy until then, and a removed shape drops it', async () => { +test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => { const pending = []; const h = harness({ markActions: [ @@ -682,34 +920,73 @@ test('what a row action answers is its row\'s note; the row is busy until then, icon: 'straighten', label: (name) => `Measure ${name}`, shapes: ['area'], - run: () => new Promise((resolve, reject) => pending.push({ resolve, reject })), + run: () => + new Promise((resolve, reject) => pending.push({ resolve, reject })), + }, + { + id: 'now', + icon: 'bolt', + label: () => 'Now', + shapes: ['area'], + run: () => ' 12 km² ', + }, + { + id: 'long', + icon: 'notes', + label: () => 'Long', + shapes: ['area'], + run: () => `${'word '.repeat(60)}end`, }, - { id: 'now', icon: 'bolt', label: () => 'Now', shapes: ['area'], run: () => ' 12 km² ' }, - { id: 'long', icon: 'notes', label: () => 'Long', shapes: ['area'], run: () => `${'word '.repeat(60)}end` }, ], }); const warn = console.warn; console.warn = () => {}; try { const board = h.annotations; - const area = (id) => ({ id, type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] }); + const area = (id) => ({ + id, + type: 'area', + manual: true, + name: null, + color: 'primary', + hidden: false, + ring: [ + [0, 0], + [1, 0], + [1, 1], + ], + }); board.marks.push(area('r1'), area('r2')); board.changed(); const row = (id) => h.shown.view.marks.find((entry) => entry.id === id); assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true); assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']); h.act('runDrawMarkAction', 'r1', 'long'); - assert.ok(row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), 'a long note is cut at a word'); + assert.ok( + row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), + 'a long note is cut at a word', + ); assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true); assert.deepEqual([row('r1').busy, row('r1').note], [true, '']); - assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), false, 'a busy row takes no second press'); + assert.equal( + h.act('runDrawMarkAction', 'r1', 'now'), + false, + 'a busy row takes no second press', + ); pending[0].resolve('412 km², 38 km of edge'); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.deepEqual([row('r1').busy, row('r1').note], [false, '412 km², 38 km of edge']); + assert.deepEqual( + [row('r1').busy, row('r1').note], + [false, '412 km², 38 km of edge'], + ); h.act('runDrawMarkAction', 'r1', 'measure'); pending[1].reject(new Error('refused')); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.deepEqual([row('r1').busy, row('r1').note], [false, ''], 'a failure clears the note'); + assert.deepEqual( + [row('r1').busy, row('r1').note], + [false, ''], + 'a failure clears the note', + ); h.act('runDrawMarkAction', 'r2', 'measure'); board.marks.splice(1, 1); board.changed(); @@ -718,7 +995,11 @@ test('what a row action answers is its row\'s note; the row is busy until then, assert.equal(row('r2'), undefined); board.marks.push(area('r2')); board.changed(); - assert.deepEqual([row('r2').busy, row('r2').note], [false, ''], 'a late answer never reaches a shape that went'); + assert.deepEqual( + [row('r2').busy, row('r2').note], + [false, ''], + 'a late answer never reaches a shape that went', + ); } finally { console.warn = warn; h.restore(); @@ -731,30 +1012,49 @@ test('Backspace on the page removes the last vertex', () => { h.act('toggleDraw'); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); - h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Backspace', + target: h.documentDouble.body, + }); assert.equal(h.tool.session.vertices.length, 1); } finally { h.restore(); } }); -test('keys on the shape list are the list\'s, not the drawing\'s', async () => { +test("keys on the shape list are the list's, not the drawing's", async () => { const h = harness(); try { const listButton = new FakeElement('BUTTON'); - listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null); + listButton.closest = (selector) => + selector === '#draw-mark-list' ? {} : null; const elsewhere = new FakeElement('INPUT', 'location-search'); h.act('toggleDraw'); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); h.documentDouble.emit('keydown', { key: 'Escape', target: listButton }); - assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape'); + assert.equal( + h.tool.session.vertices.length, + 2, + 'Escape in the list keeps the shape', + ); assert.equal(h.tool.active, true, 'and keeps Draw on'); h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere }); await Promise.resolve(); - assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter'); - h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body }); - assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape'); + assert.equal( + h.annotations.calls.annotate.length, + 0, + 'another field keeps its Enter', + ); + h.documentDouble.emit('keydown', { + key: 'Escape', + target: h.documentDouble.body, + }); + assert.equal( + h.tool.session.vertices.length, + 0, + 'Escape on the page drops the open shape', + ); } finally { h.restore(); } diff --git a/src/annotations/hybridAnnotationRenderer.test.mjs b/src/annotations/hybridAnnotationRenderer.test.mjs index cf61502c47..ef56dea496 100644 --- a/src/annotations/hybridAnnotationRenderer.test.mjs +++ b/src/annotations/hybridAnnotationRenderer.test.mjs @@ -5,6 +5,9 @@ import { createPinia } from 'pinia'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; +import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; /** A hybrid renderer whose screen board is presented to its own store. */ function hybridWithBoard(viewer) { @@ -89,11 +92,41 @@ function installBrowserGlobals(t) { }); } +/** + * `viewer` with the fake scene's camera, query, frame and draw ports and the + * fake credits bound over it as one renderer. + */ +function withScenePorts(viewer) { + const { unbind, ...ports } = bindFakeCesiumScene(viewer); + unbind(); + bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) }); + return ports.draw; +} + +/** What the world renderer draws, each item of its live sets (of `kind`). */ +function worldItems(draw, kind) { + const items = []; + for (const record of draw.sets.values()) + if ( + !record.disposed && + record.spec.id.startsWith('annotations:') && + (!kind || record.kind === kind) + ) + items.push(...record.items.values()); + return items; +} + +/** Surface heights the scene samples: `height(lon, lat)` in degrees. */ +function sampleHeights(scene, height) { + scene.sampleHeightSupported = true; + scene.sampleHeight = (carto) => + height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude)); +} + /** A viewer whose scene/camera is just enough for both sub-renderers. */ function fakeViewer(lon, lat) { const credits = new Set(); const camera = cameraLookingAt(lon, lat); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -107,31 +140,19 @@ function fakeViewer(lon, lat) { scene.renderRequests += 1; }, }; - return { - dataSources, - frames, - viewer: { - credits, - creditDisplay: { - addStaticCredit: (credit) => credits.add(credit), - removeStaticCredit: (credit) => credits.delete(credit), - }, - scene, - camera, - trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, + const viewer = { + credits, + creditDisplay: { + addStaticCredit: (credit) => credits.add(credit), + removeStaticCredit: (credit) => credits.delete(credit), }, + scene, + camera, + canvas: scene.canvas, + trackedEntity: null, }; + const draw = withScenePorts(viewer); + return { draw, frames, viewer }; } function controlledFrames() { @@ -192,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' }); const camera = cameraLookingAt(-99, 31); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -206,19 +226,12 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' const viewer = { scene, camera, + canvas: scene.canvas, trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, }; + // The screen board projects through the renderer's camera and query; the + // world renderer draws through its draw port. + const { draw } = bindFakeCesiumScene(viewer); const { store, renderer } = hybridWithBoard(viewer); const anno = { id: 'anno-hybrid-fb3', @@ -235,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' renderer.add(anno); const [before] = annotationGroups(store); assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2); - assert.equal(dataSources.length, 1); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const ring = [ [-106, 25], @@ -268,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1)); assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1)); assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned'); - assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline'); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1); - assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy'); + assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline'); + assert.equal(worldItems(draw, 'shapes').length, 1); + assert.equal(worldItems(draw, 'lines').length, 1); + assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy'); const outer = [ [-99, 31], [-98.999, 31], @@ -298,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' buildingHeight: 20, }; const completion = renderer.add(building); - assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes'); + assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes'); for (let frame = 0; frame < 8; frame += 1) frames.emit(); assert.equal((await completion).status, 'installed'); - const added = dataSources[0].entities.values.slice(2); - const fills = added.filter( - (entity) => entity.polygon && entity.polygon.fill?.getValue() !== false, - ); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal( fills.length, 2, - 'every building part gets a classification volume', + 'every building part gets a volume', ); - assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1); - assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0); + assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole'); + assert.equal(fills[1].geometry.rings.length, 1); + assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour'); assert.equal( - fills[0].polygon.material, - fills[1].polygon.material, - 'parts share the fill material', - ); - assert.equal( - added.filter((entity) => entity.polyline).length, + worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length, 3, 'all outer and hole outlines are retained', ); renderer.remove(building); assert.equal( - dataSources[0].entities.values.length, + worldItems(draw).length, 2, 'multipart removal leaves only the earlier area', ); @@ -341,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -369,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove', }; assert.throws(() => renderer.add(anno), /screen insert failed/); - assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live'); + assert.equal(worldItems(draw).length, 2, 'the world drape is already live'); assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself'); // The engine's rollback path — it must reach the partial state by id. renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released'); + assert.equal(worldItems(draw).length, 0, 'partial world state must be released'); // …and the id is free again: a retry draws ONE mark, not a second one over // an orphan nothing owns. renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape'); + assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape'); assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption'); renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('a release that throws keeps the mark addressable for a retry cleanup', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -404,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) }; renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2); + assert.equal(worldItems(draw).length, 2); assert.equal(annotationGroups(store).length, 1); // The world route releases fine, then the screen release fails part-way @@ -412,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) const workingSetTimeout = globalThis.window.setTimeout; globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); }; assert.throws(() => renderer.remove(anno), /teardown scheduling failed/); - assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release'); + assert.equal(worldItems(draw).length, 0, 'the world route did release'); assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan'); // Dropping the routing entry here would make that orphan permanently @@ -420,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) globalThis.window.setTimeout = workingSetTimeout; renderer.remove(anno); assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan'); - assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route'); + assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route'); // Fully released now — a third call is inert. renderer.remove(anno); @@ -430,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) test('a world add that fails mid-way leaves its landed entities removable', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -446,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t) }; // The draped fill lands; the outline throws (bad geometry / lost context). - const entities = dataSources[0].entities; - const realAdd = entities.add.bind(entities); - let addsLeft = 1; - entities.add = (options) => { - if (addsLeft <= 0) throw new Error('entity add failed'); - addsLeft -= 1; - return realAdd(options); + const realLines = draw.lines; + draw.lines = (spec) => { + const set = realLines(spec); + set.set = () => { throw new Error('draw failed'); }; + return set; }; - assert.throws(() => renderer.add(anno), /entity add failed/); - assert.equal(entities.values.length, 1, 'one entity landed before the failure'); + assert.throws(() => renderer.add(anno), /draw failed/); + assert.equal(worldItems(draw).length, 1, 'one item landed before the failure'); - entities.add = realAdd; + draw.lines = realLines; renderer.remove(anno); - assert.equal(entities.values.length, 0, - 'the rollback must see the entities that landed before the throw'); + assert.equal(worldItems(draw).length, 0, + 'the rollback must see the items that landed before the throw'); renderer.add(anno); - assert.equal(entities.values.length, 2, 'the retry draws a complete mark'); + assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark'); assert.equal(annotationGroups(store).length, 1); renderer.destroy(); }); @@ -475,7 +478,7 @@ function workTrace() { test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); t.after(() => renderer.destroy()); const first = buildingAnnotation('sampled-building'); @@ -485,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering showOsmCredit(viewer, otherOwner); const probes = []; const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90]; - viewer.scene.clampToHeight = (position) => { - const cartographic = Cesium.Cartographic.fromCartesian(position); - const lon = Cesium.Math.toDegrees(cartographic.longitude); - const lat = Cesium.Math.toDegrees(cartographic.latitude); + sampleHeights(viewer.scene, (lon, lat) => { probes.push([lon, lat]); const outcome = outcomes[probes.length - 1]; if (outcome instanceof Error) throw outcome; - return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome); - }; + return outcome == null ? undefined : outcome; + }); // Suppress screen points: these counts concern the eight outside-building // probes, not the screen renderer's separate anchor-height sampling. const firstTrace = workTrace(); @@ -510,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace }); const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace }); assert.equal(probes.length, 0, 'enqueue must not probe synchronously'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1, 'pending outlines add no tile credit to the other owner'); for (let frame = 0; frame < 16; frame += 1) { const before = probes.length; frames.emit(); assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget'); - if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts'); + if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts'); } const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]); assert.equal(installed.status, 'installed'); @@ -540,8 +540,9 @@ test('buildings share one probe per frame and preserve probe geometry, filtering const detail = parent.detail; assert.equal(detail.index, index); assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing'); + // The fourth probe finds nothing and the fifth throws: both are misses. assert.equal(detail.clampResult, - trace === firstTrace && index === 4 ? 'threw' : 'returned'); + trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed'); assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd)); assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end); if (index === 7) { @@ -571,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10); } assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8); - const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal(fills.length, 2); - assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); - assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); + assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); + assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); const afterCompletion = probes.length; frames.emit(); assert.equal(probes.length, afterCompletion, 'completion releases the sampler'); @@ -597,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as t.mock.method(globalThis.performance, 'now', () => now); const { viewer, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); - viewer.scene.clampToHeight = (position) => position; + sampleHeights(viewer.scene, () => 0); const traces = [workTrace(), workTrace(), workTrace()]; const completions = [0, 0.01, 0.02].map((offset, index) => renderer.add(buildingAnnotation(`queued-${index}`, offset), { @@ -626,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); let probeCount = 0; - viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; }; + sampleHeights(viewer.scene, () => { probeCount += 1; return 0; }); const cancelled = buildingAnnotation('cancelled-building'); const cancelledTrace = workTrace(); const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace }); @@ -671,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks assert.equal(viewer.credits.size, 0); for (const listener of savedTimeout) listener(); assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const pending = buildingAnnotation('destroyed-building'); const destruction = renderer.add(pending, { pendingVisible: false }); @@ -681,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks for (const listener of savedDestroy) listener(); t.mock.timers.tick(2000); assert.equal(probeCount, 1); - assert.equal(dataSources.length, 0, 'destroy removes the owned data source'); + assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go'); assert.equal(frames.size, 0, 'destroy removes frame listeners'); assert.equal(viewer.credits.size, 0); }); @@ -690,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' }; renderer.add(anno); @@ -703,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy assert.equal(after.key, before.key); assert.equal(others.length, 0); assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); frames.emit(); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' }; renderer.add(anno); @@ -724,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet // Frame projection is still ordinary pending-point work. Arm the failure // only after sampling completes, before its promise converts the caption. for (let frame = 0; frame < 8; frame += 1) frames.emit(); - assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion'); + assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion'); assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy'); // The caption conversion fails when it presents the converted mark. const publish = store.publish; @@ -747,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1); - assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back'); + assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back'); assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy'); assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable'); globalThis.window.setTimeout = workingSetTimeout; @@ -781,6 +782,7 @@ test('a deadline passed during caption conversion leaves a drawn pending point', const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out')); assert.equal(live.length, 1); assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws'); + assert.notEqual(live[0].display, 'none', 'and is on screen'); renderer.remove(anno); renderer.destroy(); }); diff --git a/src/annotations/outlineRungs.test.mjs b/src/annotations/outlineRungs.test.mjs index 6554e6f61a..016012bbfb 100644 --- a/src/annotations/outlineRungs.test.mjs +++ b/src/annotations/outlineRungs.test.mjs @@ -18,6 +18,7 @@ import { outlineQueryText, } from './outlineRungs.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { decodeOpenFreeMapOutlineTile } from '../sources/openFreeMapOutlines.js'; import { createNominatimOutlineClient } from '../sources/nominatimOutlines.js'; import { createApplicationRequestServices } from '../services/requests.js'; @@ -924,15 +925,17 @@ const PLACES = { }, }; -const viewerAt = (lat, lon, height = 4000) => ({ - camera: { - positionCartographic: { - latitude: (lat * Math.PI) / 180, - longitude: (lon * Math.PI) / 180, - height, +// The resolver reads the camera through the renderer's camera port. +const viewerAt = (lat, lon, height = 4000) => + bindFakeCesiumCamera({ + camera: { + positionCartographic: { + latitude: (lat * Math.PI) / 180, + longitude: (lon * Math.PI) / 180, + height, + }, }, - }, -}); + }); test('default settings: outline, street and building asks send nothing to Overpass', async (t) => { const prior = process.env.OVERPASS_UPSTREAMS; diff --git a/src/annotations/placeOutline.test.mjs b/src/annotations/placeOutline.test.mjs index 7f2acdde36..07e65449a5 100644 --- a/src/annotations/placeOutline.test.mjs +++ b/src/annotations/placeOutline.test.mjs @@ -5,11 +5,14 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { polygonsContain } from '../data/adminBoundaries.js'; import { streetFootprint } from './outlineRungs.js'; +import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; function viewerAt(lat, lon, height = 20_000) { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: (lat * Math.PI) / 180, @@ -17,7 +20,7 @@ function viewerAt(lat, lon, height = 20_000) { height, }, }, - }; + }); } /** A resolver whose boundary lookups and geocoder record every call. */ @@ -180,10 +183,10 @@ test('a geocoded city or neighborhood upgrades to the bundled outline', async () const credits = []; const cancelled = await city.resolve( 'Austin', - { + bindFakeCesiumCredits({ ...viewerAt(39, -100, 5_000_000), creditDisplay: { addStaticCredit: (credit) => credits.push(credit) }, - }, + }), { signal: controller.signal }, ); const pending = cancelled.resolveOutline(); diff --git a/src/annotations/resolver.js b/src/annotations/resolver.js index 527f451131..5e5506ed44 100644 --- a/src/annotations/resolver.js +++ b/src/annotations/resolver.js @@ -14,7 +14,6 @@ import { nearestPointOnLines, } from '../sources/featureGeometry.js'; import { defaultGeospatial } from '../search/defaults.js'; -import * as Cesium from 'cesium'; import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js'; import { lookupNaturalRegionOutline, @@ -45,6 +44,9 @@ import { import { createOutlineRungs } from './outlineRungs.js'; import { unavailablePlaceSearch } from '../search/placeSearch.js'; import { isPickedWorldPosition } from '../data/scenePick.js'; +import { heightsOf } from '../queries/heights.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js'; /** Prepare only local dateline outlines for planar admission and centering. */ function localOutlineFrame(fp) { @@ -178,7 +180,7 @@ export function createAnnotationResolver({ * Resolve a single annotation target to a normalized world anchor. * * @param {object} opts - * @param {Cesium.Viewer} opts.viewer + * @param {object} opts.viewer The viewer the renderer is bound to. * @param {string} [opts.target] Place name to geocode. * @param {number} [opts.latitude] Explicit latitude (wins over target). * @param {number} [opts.longitude] Explicit longitude. @@ -2216,11 +2218,10 @@ export function createAnnotationResolver({ */ function viewportProximity(viewer) { try { - const carto = viewer?.camera?.positionCartographic; - if (!carto) return null; - const lat = Cesium.Math.toDegrees(carto.latitude); - const lon = Cesium.Math.toDegrees(carto.longitude); - const radiusKm = Math.max((carto.height / 1000) * 3, 5); + const pose = viewer ? findCamera(viewer)?.pose() : null; + if (!pose) return null; + const { lat, lon } = pose; + const radiusKm = Math.max((pose.height / 1000) * 3, 5); if (![lat, lon, radiusKm].every(Number.isFinite)) return null; return { lat, lon, radiusKm }; } catch { @@ -2231,12 +2232,12 @@ export function createAnnotationResolver({ /** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */ function viewportBias(viewer) { try { - const rect = viewer?.camera?.computeViewRectangle?.(); + const rect = viewer ? findCamera(viewer)?.viewRectangle() : null; if (!rect) return null; - const swLat = Cesium.Math.toDegrees(rect.south).toFixed(4); - const swLng = Cesium.Math.toDegrees(rect.west).toFixed(4); - const neLat = Cesium.Math.toDegrees(rect.north).toFixed(4); - const neLng = Cesium.Math.toDegrees(rect.east).toFixed(4); + const swLat = rect.south.toFixed(4); + const swLng = rect.west.toFixed(4); + const neLat = rect.north.toFixed(4); + const neLng = rect.east.toFixed(4); if ([swLat, swLng, neLat, neLng].some((v) => v === 'NaN')) return null; return `${swLat},${swLng}|${neLat},${neLng}`; } catch { @@ -2289,58 +2290,39 @@ export function createAnnotationResolver({ * name the place, and we anchor the mark to the actual world point under it. */ function pickWorldFromScreen(viewer, nx, ny) { - const scene = viewer?.scene; - if (!scene) return null; - const canvas = scene.canvas; + const query = viewer ? findQuery(viewer) : null; + // The renderer's canvas; a viewer with no renderer bound, its own. + const canvas = canvasOf(viewer); + if (!query || !canvas) return null; const w = canvas.clientWidth || canvas.width || 0; const h = canvas.clientHeight || canvas.height || 0; if (!w || !h) return null; const px = Math.max(0, Math.min(1, nx)) * w; const py = Math.max(0, Math.min(1, ny)) * h; - const pos = new Cesium.Cartesian2(px, py); // Each stage is validated before it is accepted: a depth pick over empty sky - // can return a NaN or centre-of-the-earth Cartesian, and converting one of - // those throws inside Cesium. A degenerate pick IS a missed pick, so it falls - // through to the next stage and ultimately to the caller's null. - let cart = null; - if ( - scene.pickPositionSupported && - typeof scene.pickPosition === 'function' - ) { + // can return a NaN or centre-of-the-earth position, and converting one of + // those throws inside the renderer. A degenerate pick IS a missed pick, so it + // falls through to the next stage and ultimately to the caller's null. + const attempt = (pick) => { try { - cart = scene.pickPosition(pos); + return pick(); } catch { - cart = null; + return null; } - } - if ( - !isPickedWorldPosition(cart) && - typeof viewer.camera.pickEllipsoid === 'function' - ) { - try { - cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84); - } catch { - cart = null; - } - } - if ( - !isPickedWorldPosition(cart) && - typeof viewer.camera.getPickRay === 'function' - ) { - try { - const ray = viewer.camera.getPickRay(pos); - cart = ray ? scene.globe?.pick(ray, scene) || null : null; - } catch { - cart = null; - } - } + }; + // The depth pick answers null where the renderer has no depth support. + let cart = attempt(() => query.pickPosition(px, py)); + if (!isPickedWorldPosition(cart)) + cart = attempt(() => query.pickEllipsoid(px, py)); + if (!isPickedWorldPosition(cart)) + cart = attempt(() => query.pickGlobe(query.pickRay(px, py))); if (!isPickedWorldPosition(cart)) return null; - const carto = Cesium.Cartographic.fromCartesian(cart); + const carto = toLonLatH(cart); if (!carto) return null; return { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), + lat: carto.lat, + lon: carto.lon, // The height the pick actually landed on — a roof, a hillside, or 0 on // the ellipsoid. Callers that only want a coordinate ignore it; the draw // tool's live preview needs it, or the rubber band sinks to sea level @@ -2355,28 +2337,18 @@ export function createAnnotationResolver({ * the tiles for that spot aren't loaded we fall back to the ellipsoid (0). */ function sampleGroundHeight(viewer, lon, lat) { - const scene = viewer?.scene; - if (!scene) return 0; - try { - if ( - scene.clampToHeightSupported && - typeof scene.clampToHeight === 'function' - ) { - const carto = Cesium.Cartographic.fromDegrees(lon, lat); - const surface = Cesium.Cartographic.toCartesian(carto); - const clamped = scene.clampToHeight(surface); - if (clamped) { - const h = Cesium.Cartographic.fromCartesian(clamped).height; - if (Number.isFinite(h)) return h; - } + if (!viewer) return 0; + const heights = heightsOf(viewer); + // A miss is tiles not ready: fall through to the terrain, then 0. + if (heights.supported().clamp) { + const clamped = heights.clampNow(fromDegrees(lon, lat, 0)); + if (clamped) { + const h = toLonLatH(clamped)?.height; + if (Number.isFinite(h)) return h; } - } catch { - /* tiles not ready — fall through */ } - const globeHeight = scene.globe?.getHeight?.( - Cesium.Cartographic.fromDegrees(lon, lat), - ); - return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0; + const globeHeight = heights.now({ lon, lat }, { against: 'terrain' }); + return globeHeight !== null && globeHeight > 0 ? globeHeight : 0; } function shortLabel(formattedAddress) { diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index ef0448f8a6..660a4066a9 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { followedOf } from '../data/followed.js'; import { getOverlayPaintRect } from '../overlays/worldOverlay.js'; import { getActiveTrackedReadoutId, @@ -8,6 +8,15 @@ import { t } from '../i18n/index.js'; import { nextTick } from 'vue'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { applicationPinia } from '../ui/vueRuntime.js'; +import { heightsOf } from '../queries/heights.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { distance } from '../geo/vector.js'; +import { + canvasOf as sceneCanvasOf, + findCamera, + findFrame, + findQuery, +} from '../render/rendererOf.js'; /** A label whose detailed outline could not be resolved. */ function outlineUnavailableLabel(label) { @@ -78,11 +87,13 @@ export function createScreenAnnotationRenderer( const arrowMarkers = new Map(); let viewBox = null; - const scene = viewer.scene; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - scene.camera.positionWC, - ); + // The eye this frame is projected from (the camera port's pose), and the + // query port and canvas it is projected through, read once per pass. + let pose = null; + let passQuery = null; + let passCanvas = null; + // The renderer's canvas; a viewer with no renderer bound, its own. + const canvasOf = () => sceneCanvasOf(viewer); const records = new Map(); // anno.id -> { key, anno, group, parts } const leaving = new Map(); // key -> a removed mark's record while it fades out const byKey = new Map(); // key -> record, live or fading @@ -91,8 +102,6 @@ export function createScreenAnnotationRenderer( let published = ''; // Only the renderer whose board the store shows may change or remove it. const shown = () => store.board?.owner === owner; - const scratch = new Cesium.Cartesian2(); - const scratchDir = new Cesium.Cartesian3(); // Per-point ground height cache. Marks must sit on the real surface, not at // sea level — otherwise in elevated cities (Austin ~150 m) they project // underground and parallax sinks them at oblique angles. Sampled once the @@ -121,7 +130,7 @@ export function createScreenAnnotationRenderer( // Re-project every annotation each rendered frame so marks stay glued to the // world. postRender runs after the camera/tiles update, so positions are exact. const onPostRender = () => projectAll(); - scene.postRender.addEventListener(onPostRender); + const removePostRender = findFrame(viewer)?.on('postRender', onPostRender); function color(anno) { return PALETTE[anno.color] || PALETTE.primary; @@ -141,15 +150,12 @@ export function createScreenAnnotationRenderer( return cached.h; } try { - if ( - scene.clampToHeightSupported && - typeof scene.clampToHeight === 'function' - ) { - const c = scene.clampToHeight( - Cesium.Cartesian3.fromDegrees(lon, lat, 0), - ); + const heights = heightsOf(viewer); + if (heights.supported().clamp) { + // A miss is tiles not ready. + const c = heights.clampNow(fromDegrees(lon, lat, 0)); if (c) { - const h = Cesium.Cartographic.fromCartesian(c).height; + const h = toLonLatH(c)?.height; if (Number.isFinite(h) && h > -430 && h < 9000) { heightCache.set(key, { h, settled: true, gen: projGen }); trimHeightCache(); @@ -278,7 +284,7 @@ export function createScreenAnnotationRenderer( } // Record the mark BEFORE it reaches the board, then unwind on any throw - // from here down (projectAll reaches into Cesium and can fail on a lost + // from here down (projectAll reaches into the renderer and can fail on a lost // context). Previously a throw past the insert left an ORPHANED mark: the // engine's rollback only deletes its own map entry, so the next annotate // of the same geometry stacked a fresh mark on top of the corpse. @@ -363,26 +369,27 @@ export function createScreenAnnotationRenderer( // Anchor at the real surface height (cached + validated), so marks sit on // the ground/building instead of at sea level. The settle-once cache keeps // it stable (no per-frame jitter that earlier broke nearby projections). - const world = Cesium.Cartesian3.fromDegrees( - lon, - lat, - groundHeight(lon, lat), - ); + const world = fromDegrees(lon, lat, groundHeight(lon, lat)); + if (!pose) return null; // Reject points behind the camera (they produce wrapped/extreme coords). - Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir); - if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0) + const eye = pose.position; + const look = pose.direction; + if ( + (world.x - eye.x) * look.x + + (world.y - eye.y) * look.y + + (world.z - eye.z) * look.z <= + 0 + ) return null; // Reject points beyond the globe horizon. - if (!occluder.isPointVisible(world)) return null; - const win = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - world, - scratch, - ); + const query = passQuery; + if (!query || query.isOccluded(world)) return null; + const win = query.project(world); if (!win || !Number.isFinite(win.x) || !Number.isFinite(win.y)) return null; // Reject absurd off-screen projections (anchor not in view). - const w = scene.canvas.clientWidth || scene.canvas.width; - const h = scene.canvas.clientHeight || scene.canvas.height; + const canvas = passCanvas; + const w = canvas.clientWidth || canvas.width; + const h = canvas.clientHeight || canvas.height; if ( !allowOffscreen && (win.x < -w || win.x > 2 * w || win.y < -h || win.y > 2 * h) @@ -406,7 +413,6 @@ export function createScreenAnnotationRenderer( const TRACKED_FADE_FRAME_MS = 1000 / 60; let trackedFadeAtMs = -Infinity; const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop - const _scratchTrackedWin = new Cesium.Cartesian2(); // Evaluate a NearFarScalar (billboard scaleByDistance) at a camera distance. function nearFarValue(nfs, dist) { @@ -427,32 +433,23 @@ export function createScreenAnnotationRenderer( let top = painted?.y; let bottom = painted ? painted.y + painted.h : undefined; - const ent = viewer.trackedEntity; - const now = Cesium.JulianDate.now(); + const followed = followedOf(viewer); + const displayPosition = followed?.displayPosition; const world = - typeof ent?.gevDisplayPosition === 'function' - ? ent.gevDisplayPosition() - : null; - const win = world - ? Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - world, - _scratchTrackedWin, - ) - : null; + typeof displayPosition === 'function' ? displayPosition() : null; + const win = world ? (passQuery?.project(world) ?? null) : null; - // Billboard box — centered on the anchor, magnified by scaleByDistance. - const bb = ent?.billboard; - if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { - const baseW = bb.width?.getValue?.(now) ?? 28; - const baseH = bb.height?.getValue?.(now) ?? 28; + // Billboard box — centered on the anchor, magnified by scaleByDistance, from + // the size the tracking layer recorded for its sprite. + const sprite = followed?.sprite; + if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { + const baseW = sprite.width ?? 28; + const baseH = sprite.height ?? 28; let scale = 1; - const sbd = bb.scaleByDistance?.getValue?.(now); - if (sbd) - scale = nearFarValue( - sbd, - Cesium.Cartesian3.distance(scene.camera.positionWC, world), - ); + const sbd = sprite.scaleByDistance; + // No eye to measure from: the sprite's own size. + if (sbd && pose) + scale = nearFarValue(sbd, distance(pose.position, world)); const hw = (baseW * scale) / 2; const hh = (baseH * scale) / 2; const bbLeft = win.x - hw; @@ -481,14 +478,17 @@ export function createScreenAnnotationRenderer( return; } projGen += 1; // new frame: entries touched below are "hot" and survive trimming + pose = findCamera(viewer)?.pose() ?? null; + passQuery = findQuery(viewer); + passCanvas = canvasOf(); const trackedRect = trackedEntityRect(); - occluder.cameraPosition = scene.camera.positionWC; - const h = scene.canvas.clientHeight || scene.canvas.height; - const w = scene.canvas.clientWidth || scene.canvas.width; + const canvas = passCanvas; + const h = canvas.clientHeight || canvas.height; + const w = canvas.clientWidth || canvas.width; viewBox = `0 0 ${w} ${h}`; // Shrink point-marker geometry as the camera pulls back (declutter the blob). const mScale = markScale( - viewer.camera.positionCartographic?.height ?? 1000, + Number.isFinite(pose?.height) ? pose.height : 1000, ); for (const rec of records.values()) { @@ -834,7 +834,7 @@ export function createScreenAnnotationRenderer( function destroy() { try { - scene.postRender.removeEventListener(onPostRender); + removePostRender?.(); } catch { /* torn down */ } diff --git a/src/annotations/screenAnnotationRenderer.test.mjs b/src/annotations/screenAnnotationRenderer.test.mjs index 00188c5276..406938cf31 100644 --- a/src/annotations/screenAnnotationRenderer.test.mjs +++ b/src/annotations/screenAnnotationRenderer.test.mjs @@ -6,7 +6,19 @@ import { createApp, nextTick } from 'vue'; import { createPinia } from 'pinia'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import ScreenAnnotations from '../ui/views/panels/ScreenAnnotations.vue'; -import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js'; +import { createScreenAnnotationRenderer as createRenderer } from './screenAnnotationRenderer.js'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; +import { rendererOf } from '../render/rendererOf.js'; + +/** + * The renderer over a viewer double with the camera, query and frame ports + * bound over it (once per double), and the scene's canvas as the viewer's. + */ +function createScreenAnnotationRenderer(viewer, options) { + if (!rendererOf(viewer)) bindFakeCesiumScene(viewer); + viewer.canvas ??= viewer.scene?.canvas; + return createRenderer(viewer, options); +} // happy-dom does not lay out SVG; every element measures as a 40 x 16 box. for (const type of [globalThis.SVGElement, globalThis.SVGGraphicsElement]) { @@ -53,7 +65,7 @@ function sceneFor(camera, extra = {}) { return { camera, canvas: { clientWidth: 800, clientHeight: 600, width: 800, height: 600 }, - clampToHeightSupported: false, + sampleHeightSupported: false, postRender: { addEventListener() {}, removeEventListener() {} }, ...extra, }; @@ -173,14 +185,13 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => { const sampledAnchors = []; const scene = sceneFor(camera, { canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 }, - clampToHeightSupported: true, - clampToHeight(world) { - const cartographic = Cesium.Cartographic.fromCartesian(world); + sampleHeightSupported: true, + sampleHeight(cartographic) { sampledAnchors.push([ Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)), Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)), ]); - return world; + return 0; }, }); const renderer = createScreenAnnotationRenderer( diff --git a/src/annotations/worldAnnotationRenderer.js b/src/annotations/worldAnnotationRenderer.js index 189d46830c..dd4d802ae0 100644 --- a/src/annotations/worldAnnotationRenderer.js +++ b/src/annotations/worldAnnotationRenderer.js @@ -1,64 +1,156 @@ import { recordWorkSlice } from '../sources/phaseTiming.js'; import { ringCentroid } from '../sources/featureGeometry.js'; -import * as Cesium from 'cesium'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { + drawOf, + findCamera, + findFrame, + frameOf, +} from '../render/rendererOf.js'; +import { heightsOf } from '../queries/heights.js'; /** * World-space annotation renderer (Direction A). * - * Draws annotations as native Cesium entities anchored to lon/lat. Because they - * live in the 3D scene they track the camera, sit at the right depth, and are - * occluded by the photoreal buildings the way a real marker would be. + * Draws annotations through the renderer's draw port, anchored to lon/lat. + * Because they live in the 3D scene they track the camera, sit at the right + * depth, and are occluded by the photoreal buildings the way a real marker + * would be. * * IMPORTANT — drawing on Google Photorealistic 3D Tiles: - * The Cesium globe is hidden, so there is no terrain to clamp to. Ground - * geometry (areas, rings, connectors) is draped onto the photoreal tiles with - * `classificationType: CESIUM_3D_TILE`; points clamp to the tile - * surface with `heightReference: CLAMP_TO_GROUND` (which requires the tileset - * to have `enableCollision = true`, set in initAnnotations). This keeps marks - * sitting ON the world instead of buried at sea level. + * The globe is hidden, so there is no terrain to clamp to. Ground geometry + * (areas, rings, connectors) is draped onto the photoreal tiles and the + * terrain alike (`clampTo: 'both'`); points clamp to the surface. This + * keeps marks sitting ON the world instead of buried at sea level. * - * Live alpha (fade in/out) and pulsing are driven by CallbackProperty so they - * animate every render without the engine touching them per frame. + * Fades follow the mark's alpha: the engine calls `sync` as it changes, and + * each mark's items take their new colours where they are. Pulsing fills + * are a declarative pulse the renderer runs; target rings follow the + * camera's height, read before each frame, and are sent again at the radius + * it gives when that changes. + * + * Each mark draws into sets of its own, so adding or removing one leaves + * the others' geometry alone. * * Renderer contract (shared with the screen-space renderer): * add(anno) / remove(anno) / sync(map) / destroy() */ +/** Each palette colour as `r, g, b`, 0..1. */ const PALETTE = { - primary: '#8be9ff', - amber: '#ffb547', - cyan: '#39d0ff', - green: '#5dff9f', - red: '#ff6b6b', + primary: rgb('#8be9ff'), + amber: rgb('#ffb547'), + cyan: rgb('#39d0ff'), + green: rgb('#5dff9f'), + red: rgb('#ff6b6b'), }; +const WHITE = [1, 1, 1]; /** - * What a draped mark is allowed to paint onto. - * - * This was CESIUM_3D_TILE, which is right with Google's photoreal tiles under - * the camera and wrong everywhere else: on a keyless boot (Esri or OSM imagery - * on Cesium's own globe) there are no 3D tiles to classify against, so every - * area fill, area outline, route and arrow rendered to nothing. The labels - * showed and the geometry did not, which reads as a broken feature rather than - * an unsupported surface — and it hit spoken annotations exactly as hard as - * hand-drawn ones. - * - * BOTH paints onto terrain AND onto 3D tiles, so one value covers both worlds. + * What a draped mark is allowed to paint onto: terrain AND 3D tiles, so one + * value covers a keyless boot (imagery on the globe, no tiles) and the + * photoreal world alike. Tiles alone rendered every area, route and arrow to + * nothing on a keyless boot. */ -const CLASSIFY = Cesium.ClassificationType.BOTH; -const CLAMP = Cesium.HeightReference.CLAMP_TO_GROUND; +const CLAMP_TO = 'both'; + +/** + * The pulse of a pulsing fill: its alpha swings between 60% and all of its + * own, a sine of about 0.8 Hz on the wall clock. + */ +const PULSE_MS = (2 * Math.PI) / 0.005; +const PULSE_LOW = 0.6; + +/** Target rings: 3% of the camera's height, between 14 m and 170 m. */ +const RING_RADIUS = Object.freeze({ factor: 0.03, min: 14, max: 170 }); + +/** Relative change of the ring radius under which rings are not redrawn. */ +const RING_RESIZE = 1e-3; + +/** + * A target ring's radius, metres, for a camera `height` metres above the + * ellipsoid; 1000 m stands in for a height the camera cannot give. + * @param {number} height + */ +export function ringRadiusAt(height) { + const h = Number.isFinite(height) ? height : 1000; + return Math.max( + RING_RADIUS.min, + Math.min(RING_RADIUS.max, h * RING_RADIUS.factor), + ); +} + +/** + * Each renderer's sets have ids of their own, unique across copies of this + * module on one viewer too. + */ +let rendererSeq = 0; +const MODULE_TOKEN = Math.random().toString(36).slice(2, 8); export function createWorldAnnotationRenderer(viewer) { - const dataSource = new Cesium.CustomDataSource('gev-annotations'); - viewer.dataSources.add(dataSource); + const draw = drawOf(viewer); + const instance = `${MODULE_TOKEN}${(rendererSeq += 1)}`; + let markSeq = 0; const osmAnnotations = new Set(); - // Every mark with entities on the globe, so sync() can take a hidden one out. + // Every mark with sets on the globe, so sync() can take a hidden one out. const drawn = new Set(); const pendingGround = new Map(); const groundQueue = []; - let observingGround = false; + let offGroundFrame = null; let destroyed = false; + // Marks with a target ring, and the radius they are drawn at. + const ringed = new Set(); + let offRingFrame = null; + let ringRadius = ringRadiusAt(cameraHeight()); + + /** The camera's height above the ellipsoid, or NaN when it has none. */ + function cameraHeight() { + try { + return findCamera(viewer)?.pose().height ?? Number.NaN; + } catch { + return Number.NaN; + } + } + + /** The current ring radius, for the items that draw rings. */ + const ringRadiusNow = () => ringRadius; + + /** + * Before each frame: when the camera's height gives the rings another + * radius, every shown mark's ring is sent again at it. A hidden mark's + * ring catches up when it shows (`sync`). + */ + function followRings() { + const radius = ringRadiusAt(cameraHeight()); + if (Math.abs(radius - ringRadius) <= RING_RESIZE * ringRadius) return; + ringRadius = radius; + for (const anno of ringed) if (!anno.hidden) resizeRing(anno); + } + + /** Send a mark's ring again at the current radius, when it differs. */ + function resizeRing(anno) { + const was = anno._drawn; + const set = anno._draw?.shapes; + if (!was?.ring || !set || was.ringRadius === ringRadius) return; + was.ringRadius = ringRadius; + set.upsert([was.ring(was.alpha)]); + } + + /** + * Keep the ring frame listener while any mark has a ring. A host with no + * frame port draws its rings at the radius they were added with. + */ + function watchRings() { + if (ringed.size && !offRingFrame) + offRingFrame = findFrame(viewer)?.on('preRender', followRings) ?? null; + else if (!ringed.size && offRingFrame) { + offRingFrame(); + offRingFrame = null; + } + } + + const requestRender = () => frameOf(viewer).requestRender('annotations'); function sampleBuilding(anno, options) { pendingGround.get(anno)?.finish('cancelled'); @@ -107,7 +199,7 @@ export function createWorldAnnotationRenderer(viewer) { // A task promoted outside a frame (its predecessor timed out or was // cancelled) still needs frames in request-render mode. try { - viewer.scene.requestRender?.(); + requestRender(); } catch { /* the enqueue path reports render failures */ } @@ -120,9 +212,9 @@ export function createWorldAnnotationRenderer(viewer) { clearTimeout(task.timer); if (position === 0) groundQueue[0]?.begin(); options.signal?.removeEventListener('abort', task.abort); - if (!groundQueue.length && observingGround) { - viewer.scene.postRender.removeEventListener(onGroundFrame); - observingGround = false; + if (!groundQueue.length && offGroundFrame) { + offGroundFrame(); + offGroundFrame = null; } timing.elapsedMs = performance.now() - (started ?? queuedAt); if (workTrace) { @@ -174,28 +266,25 @@ export function createWorldAnnotationRenderer(viewer) { const sliceStart = performance.now(); let error; try { - if ( - viewer.scene.clampToHeightSupported && - typeof viewer.scene.clampToHeight === 'function' - ) { + // Without depth support the surface answers nothing: the + // probes are skipped, and the fallback height is taken. + if (heightsOf(viewer).supported().surface) { const [lon, lat] = task.points[task.index++]; timing.probes += 1; try { - const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0); - let c; + let h; note?.('clampStart'); - if (detail) detail.clampResult = 'threw'; try { - c = viewer.scene.clampToHeight(position); - if (detail) detail.clampResult = 'returned'; + // The surface under the probe: the drawn tiles or terrain, + // never a mark (no draw set is in height queries). + h = heightsOf(viewer).now({ lon, lat }); + if (detail) + detail.clampResult = Number.isFinite(h) ? 'hit' : 'missed'; } finally { note?.('clampEnd'); } - if (c) { - const h = Cesium.Cartographic.fromCartesian(c).height; - if (Number.isFinite(h) && h > -430 && h < 9000) - task.samples.push(h); - } + if (Number.isFinite(h) && h > -430 && h < 9000) + task.samples.push(h); } catch { /* surface not ready: preserve the existing sample filter */ } @@ -240,7 +329,7 @@ export function createWorldAnnotationRenderer(viewer) { task.finish('installed'); } finally { // Commit includes sort/selection/add/deadline/finish or rollback, - // including intervening bookkeeping; it is not exclusive entity cost. + // including intervening bookkeeping; it is not exclusive draw cost. if (detail?.commitStatus === 'attempted') note('commitEnd'); if (workTrace) recordWorkSlice( @@ -257,12 +346,10 @@ export function createWorldAnnotationRenderer(viewer) { if (groundQueue[0] === task) task.begin(); options.signal?.addEventListener('abort', task.abort, { once: true }); if (!task.current()) return task.finish('cancelled'); - if (!observingGround) { - viewer.scene.postRender.addEventListener(onGroundFrame); - observingGround = true; - } try { - viewer.scene.requestRender?.(); + if (!offGroundFrame) + offGroundFrame = frameOf(viewer).on('postRender', onGroundFrame); + requestRender(); } catch (error) { task.finish('failed', error); } @@ -274,49 +361,43 @@ export function createWorldAnnotationRenderer(viewer) { const task = groundQueue[0]; try { task?.step(); - if (groundQueue.length) viewer.scene.requestRender?.(); + if (groundQueue.length) requestRender(); } catch (error) { for (const pending of [...groundQueue]) pending.finish('failed', error); } } - - // Register the GevRouteFlow fabric once so Cesium's Material.fromType() can build the - // material the route pipeline renders. The animated `time` uniform is read straight - // from performance.now() inside FlowMaterialProperty.getValue (which Cesium calls each - // rendered frame with the live uniforms object), so the dashes flow with no extra - // per-frame bookkeeping. - ensureFlowFabricRegistered(); - - function colorFor(anno) { - return Cesium.Color.fromCssColorString( - PALETTE[anno.color] || PALETTE.primary, - ); + /** + * The mark's draw sets, made on first use: shapes (fills, volumes, rings), + * lines (outlines, routes, arrows) and points (markers). + */ + function setsOf(anno) { + if (!anno._draw) { + markSeq += 1; + const prefix = `annotations:${instance}:${markSeq}`; + anno._draw = { prefix, shapes: null, lines: null, points: null }; + } + return anno._draw; } - // Target-ring radius (meters) scaled to camera height so it reads at any - // altitude. Read once per frame for BOTH ellipse axes — camera height is - // constant within a frame, so semiMajor === semiMinor always holds. - function ringRadius() { - const h = viewer.camera.positionCartographic?.height ?? 1000; - return Math.max(14, Math.min(170, h * 0.03)); - } - - // A live color that follows the annotation's fade alpha and an optional pulse. - function liveColor(anno, base, { alpha = 0.9, pulse = false } = {}) { - return new Cesium.CallbackProperty(() => { - const a = (anno.alpha ?? 1) * alpha * (pulse ? pulseFactor() : 1); - return base.withAlpha(Math.max(0, Math.min(1, a))); - }, false); + function setOf(anno, kind) { + const sets = setsOf(anno); + if (!sets[kind]) { + sets[kind] = draw[kind]({ + id: `${sets.prefix}:${kind}`, + clampTo: CLAMP_TO, + show: !anno.hidden, + }); + } + return sets[kind]; } function add(anno, options = {}) { - const base = colorFor(anno); - // Published to the mark BEFORE anything is added, and mutated in place as - // each entity lands: a mid-add failure (bad geometry, lost context) must - // leave the entities that DID land visible to remove(), or the rollback - // path cannot reach them and they stay on the globe forever. - const entities = []; - anno._entities = entities; + // A destroyed renderer draws nothing more. + if (destroyed) return; + // Published to the mark BEFORE anything is drawn: a mid-add failure (bad + // geometry, lost context) must leave the sets that DID land visible to + // remove(), or the rollback path cannot reach them and they stay on the + // globe forever. drawn.add(anno); if ( @@ -327,253 +408,43 @@ export function createWorldAnnotationRenderer(viewer) { return sampleBuilding(anno, options); } - if ( - anno.ring && - anno.ring.length >= 3 && - anno.footprintKind === 'building' - ) { - const addBuildingEntity = (definition) => { - if (!(options.isCurrent?.() ?? true)) - throw new Error('Building install cancelled'); - const entity = dataSource.entities.add(definition); - if (!(options.isCurrent?.() ?? true)) { - dataSource.entities.remove(entity); - throw new Error('Building install cancelled'); - } - return entity; - }; - // Single building → the PRIMARY highlight is an extruded CLASSIFICATION - // volume that tints the real photogrammetry mesh (dome, walls, roof — - // everything inside the column) amber and pulses. A flat footprint - // extrusion is only 2.5D and misses domes; classification colors the - // actual tiles. A faint wireframe cage rides on top as a secondary cue. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const groundH = - options.sampledGroundHeight ?? - (Number.isFinite(anno.anchor.height) - ? anno.anchor.height - (anno.buildingHeight || 25) - : 0); - const baseH = groundH - 3; - // Tall headroom is free: classification only colors where tiles exist, so - // empty air above the roof isn't tinted — this just guarantees we cover - // under-tagged building heights. - const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; - const fillMaterial = new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.45, pulse: true }), - ); - const lineMaterial = new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.25, - color: liveColor(anno, base, { alpha: 0.7 }), - }); - for (const [outer, ...holes] of parts) { - const buffered = bufferRing(outer, 3); - const positions = Cesium.Cartesian3.fromDegreesArray(buffered.flat()); - // 1) Classification volume — tints the mesh amber, pulsing. - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - positions, - holes.map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - classificationType: CLASSIFY, - material: fillMaterial, - }, - }), - ); - // 2) Faint, SIMPLIFIED wireframe cage — secondary, lower opacity. Decimate - // the footprint so the extruded outline draws ~14 clean verticals, not one - // per (often 100+) ring vertex. - const cagePositions = Cesium.Cartesian3.fromDegreesArray( - decimateRing(buffered, 14).flat(), - ); - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy(cagePositions), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - fill: false, - outline: true, - outlineColor: liveColor(anno, base, { alpha: 0.32, pulse: true }), - }, - }), - ); - // 3) Crisp draped base outline so the footprint reads on the ground. - for (const ring of [outer, ...holes]) { - entities.push( - addBuildingEntity({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 3, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + // Rings not yet followed take the camera's height now. + if (!offRingFrame) ringRadius = ringRadiusAt(cameraHeight()); + const items = itemsOf(anno, options, ringRadiusNow); + anno._drawn = { + alpha: alphaOf(anno), + items, + ring: items.ring, + ringRadius, + }; + if (items.ring) ringed.add(anno); + else ringed.delete(anno); + watchRings(); + const current = () => options.isCurrent?.() ?? true; + const building = anno.footprintKind === 'building'; + for (const kind of ['shapes', 'lines', 'points']) { + if (!items[kind].length) { + // Added again as another kind: what it drew before goes. + disposeSet(anno, kind); + continue; } - } else if (anno.ring && anno.ring.length >= 3) { - // Larger area (district / compound / park / state) → flat fill draped on - // the tiles + a glowing outline. Draping is right here: you can't extrude - // a whole neighbourhood, and the GIS overlay shows the boundary clearly. - // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a - // hole in Brandenburg) draws every part with its holes. All parts share - // ONE fill and ONE line material, so Cesium batches the whole mark into a - // ground primitive per kind instead of one per island. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const fillMaterial = new Cesium.ColorMaterialProperty( - // Synthesized (approximate) areas get a fainter fill so they don't read as solid. - liveColor(anno, base, { - alpha: anno.synthesized ? 0.1 : 0.2, - pulse: true, - }), - ); - // Synthesized → DASHED outline (signals "approximate, not an authoritative - // boundary", research §8.4/§8.6); real footprints → solid glow. - const lineMaterial = anno.synthesized - ? new Cesium.PolylineDashMaterialProperty({ - color: liveColor(anno, base, { alpha: 0.95 }), - dashLength: 24, - }) - : new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.35, - color: liveColor(anno, base, { alpha: 1 }), - }); - for (const [outer, ...holes] of parts) { - if (!Array.isArray(outer) || outer.length < 3) continue; - const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; - entities.push( - dataSource.entities.add({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(outer.flat()), - rings - .slice(1) - .map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - material: fillMaterial, - classificationType: CLASSIFY, - }, - }), - ); - for (const ring of rings) { - entities.push( - dataSource.entities.add({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 6, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + if (building && !current()) throw new Error('Building install cancelled'); + setOf(anno, kind).set(items[kind].map((item) => item(anno._drawn.alpha))); + if (building && !current()) { + clearSets(anno); + throw new Error('Building install cancelled'); } - } else if ( - anno.type === 'route' && - Array.isArray(anno.path) && - anno.path.length >= 2 - ) { - // A real path (street-following) draped on the 3D tiles, with dashes that - // FLOW toward the destination (custom st.s + time material; works on the - // clamped/classified ground polyline). - const positions = Cesium.Cartesian3.fromDegreesArray( - anno.path.flatMap((p) => [p.lon, p.lat]), - ); - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 9, - material: new FlowMaterialProperty( - PALETTE[anno.color] || PALETTE.primary, - () => anno.alpha ?? 1, - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); + } + if (anno.type === 'route' && items.lines.length) { osmAnnotations.add(anno); showOsmCredit(viewer, anno); - } else if (anno.type === 'arrow' && anno.to) { - // Connector draped across the ground from origin to destination. - const positions = [ - Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - Cesium.Cartesian3.fromDegrees(anno.to.lon, anno.to.lat), - ]; - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 16, - material: new Cesium.PolylineArrowMaterialProperty( - liveColor(anno, base, { alpha: 0.95 }), - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } else { - // pin / highlight / label — a camera-proportional target ring + a marker. - if (anno.type !== 'label') { - // Radius scales with camera height so the ring reads at any altitude. - // semiMajor === semiMinor is required AND must hold every frame, so both - // axes read the SAME ringRadius() (camera height is constant per frame). - entities.push( - dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees( - anno.anchor.lon, - anno.anchor.lat, - ), - ellipse: { - semiMajorAxis: new Cesium.CallbackProperty(ringRadius, false), - semiMinorAxis: new Cesium.CallbackProperty(ringRadius, false), - material: new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.38, pulse: true }), - ), - outline: false, - classificationType: CLASSIFY, - }, - }), - ); - } - entities.push(pointMarker(anno, base)); } if ( - entities.length && + (items.shapes.length || items.lines.length || items.points.length) && anno.ring?.length >= 3 && !anno.synthesized && (anno.outlineCredit === 'tiles' || anno.outlineCredit === 'osm') && - (options.isCurrent?.() ?? true) + current() ) { // The actual world proxy owns both geometry and credit, including rollback. osmAnnotations.add(anno); @@ -583,19 +454,19 @@ export function createWorldAnnotationRenderer(viewer) { } } - // Captions belong to the hybrid renderer's screen-space callouts. - function pointMarker(anno, base) { - return dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - point: { - pixelSize: anno.type === 'label' ? 8 : 14, - color: liveColor(anno, base, { alpha: 1 }), - outlineColor: liveColor(anno, Cesium.Color.WHITE, { alpha: 0.95 }), - outlineWidth: 3, - heightReference: CLAMP, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + function disposeSet(anno, kind) { + const sets = anno?._draw; + if (!sets?.[kind]) return; + try { + sets[kind].dispose(); + } catch { + /* already gone */ + } + sets[kind] = null; + } + + function clearSets(anno) { + for (const kind of ['shapes', 'lines', 'points']) disposeSet(anno, kind); } function remove(anno) { @@ -603,27 +474,39 @@ export function createWorldAnnotationRenderer(viewer) { hideOsmCredit(viewer, anno); osmAnnotations.delete(anno); drawn.delete(anno); - if (!anno?._entities) return; - for (const entity of anno._entities) { - try { - dataSource.entities.remove(entity); - } catch { - /* already gone */ - } + ringed.delete(anno); + watchRings(); + clearSets(anno); + if (anno) { + anno._draw = null; + anno._drawn = null; } - anno._entities = null; } /** - * CallbackProperty drives per-frame alpha and pulse. A hidden mark is taken - * out whole, so no material that keeps its own colour (the route's flow), - * ground classification or pick can still show it. + * A hidden mark is taken out whole (its sets hidden), so no fill, line or + * pick can still show it; a mark whose alpha moved (fading in or out) + * takes its new colours in place. */ function sync() { for (const anno of drawn) { + const sets = anno._draw; + if (!sets) continue; const show = !anno.hidden; - for (const entity of anno._entities || []) - if (entity.show !== show) entity.show = show; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && sets[kind].show !== show) sets[kind].show = show; + const was = anno._drawn; + const alpha = alphaOf(anno); + if (!was || was.alpha === alpha) { + // Shown again: its ring catches up with the camera. + if (show) resizeRing(anno); + continue; + } + was.alpha = alpha; + was.ringRadius = ringRadius; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && was.items[kind].length) + sets[kind].upsert(was.items[kind].map((item) => item(alpha))); } } @@ -632,114 +515,234 @@ export function createWorldAnnotationRenderer(viewer) { for (const task of [...pendingGround.values()]) task.finish('cancelled'); for (const anno of osmAnnotations) hideOsmCredit(viewer, anno); osmAnnotations.clear(); - drawn.clear(); - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* scene torn down */ + ringed.clear(); + watchRings(); + for (const anno of drawn) { + clearSets(anno); + anno._draw = null; + anno._drawn = null; } + drawn.clear(); } return { add, remove, sync, destroy }; } -function pulseFactor() { - // 0.6 .. 1.0 sinusoid at ~0.8 Hz - return 0.8 + 0.2 * Math.sin(performance.now() * 0.005); -} +/** A mark's alpha as drawn, 0..1. */ +const alphaOf = (anno) => Math.max(0, Math.min(1, anno.alpha ?? 1)); -/** - * A custom Fabric polyline material whose dashes flow toward the destination. - * `materialInput.st.s` is the along-line coordinate (0 = origin, 1 = destination), - * so `fract(s*repeat - time*speed)` scrolls the pattern toward the end. Works on - * a clamped/classified ground polyline (PolylineMaterialAppearance supports it). - */ -function makeRouteFlowMaterial(colorCss) { - return new Cesium.Material({ - fabric: { - type: 'GevRouteFlow', - uniforms: { - color: Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95), - time: 0.0, - repeat: 64.0, // dash cells along the whole route - duty: 0.46, // fraction of each cell that is "on" - speed: 0.55, // cells per second toward the destination - }, - source: ` - czm_material czm_getMaterial(czm_materialInput materialInput) { - czm_material m = czm_getDefaultMaterial(materialInput); - float s = materialInput.st.s; // 0 origin -> 1 dest - float flow = fract(s * repeat - time * speed); // scroll toward dest - float on = smoothstep(duty + 0.08, duty - 0.08, flow); - // keep a faint baseline so the whole route stays readable between dashes - float a = max(on, 0.18); - m.diffuse = color.rgb; - m.emission = color.rgb * on * 0.9; // glow on the lit cells - m.alpha = color.a * a; - return m; - }`, - }, - }); -} +/** `[r, g, b, a]` for a palette colour at `alpha`. */ +const colour = (base, alpha) => [base[0], base[1], base[2], alpha]; -let _flowFabricRegistered = false; -/** Register the GevRouteFlow fabric ONCE so Cesium's `Material.fromType('GevRouteFlow')` - * can build the material the render pipeline uses. Constructing one Material with the - * fabric caches it under its type name. */ -export function ensureFlowFabricRegistered() { - if (_flowFabricRegistered) return; - makeRouteFlowMaterial('#ffffff'); // side effect: registers the 'GevRouteFlow' type - _flowFabricRegistered = true; -} - -/** - * MaterialProperty for the animated route. Cesium builds the rendered Material once - * from getType() (our registered GevRouteFlow fabric), then EACH FRAME calls - * getValue(time, material.uniforms) and uses whatever we write INTO that uniforms - * object — it ignores the return value. So getValue writes color/time/repeat/duty/ - * speed straight onto `result` (the live uniforms). Writing the animated `time` here - * is what actually makes the dashes flow on the GPU. (The prior versions either - * returned a standalone Material Cesium never rendered, or treated `result` as a - * Material — both left the real uniforms untouched, so nothing animated.) - */ -export function FlowMaterialProperty(colorCss, alphaOf = () => 1) { - this._color = Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95); - // The mark's live alpha (fade in and out, hidden), applied every frame. - this._alphaOf = alphaOf; - this._live = this._color.clone(); - this._definitionChanged = new Cesium.Event(); -} -Object.defineProperties(FlowMaterialProperty.prototype, { - isConstant: { - get() { - return false; - }, - }, // re-evaluated each frame → it animates - definitionChanged: { - get() { - return this._definitionChanged; - }, - }, +/** A fill or outline that pulses about `alpha`. */ +const pulse = (alpha) => ({ + property: 'alpha', + from: alpha * PULSE_LOW, + to: alpha, + periodMs: PULSE_MS, }); -FlowMaterialProperty.prototype.getType = function getType() { - return 'GevRouteFlow'; -}; -FlowMaterialProperty.prototype.getValue = function getValue(time, result) { - // `result` IS the live uniforms object Cesium renders — write into it directly. - // `time` is read straight from the wall clock so the dashes flow every rendered - // frame (the scene renders continuously; no requestRenderMode here). - if (!Cesium.defined(result)) result = {}; - this._live.alpha = this._color.alpha * this._alphaOf(); - result.color = this._live; - result.time = performance.now() / 1000; // the per-frame animated value - result.repeat = 64.0; - result.duty = 0.46; - result.speed = 0.55; - return result; -}; -FlowMaterialProperty.prototype.equals = function equals(other) { - return this === other; -}; + +/** + * What a mark draws, as item makers by kind, each taking the mark's alpha: + * built once per add, called again on each fade step. `ring` is the target + * ring's maker among the shapes, drawn at `ringRadiusNow()`. + */ +function itemsOf(anno, options, ringRadiusNow) { + const base = PALETTE[anno.color] || PALETTE.primary; + const shapes = []; + const lines = []; + const points = []; + const meta = { annotation: anno.id }; + let ring = null; + const draped = (id, positions, widthPx, style) => (alpha) => ({ + id, + positions, + widthPx, + mode: 'draped', + clampTo: CLAMP_TO, + style: style(alpha), + meta, + }); + if (anno.ring?.length >= 3 && anno.footprintKind === 'building') { + // Single building → the PRIMARY highlight is a translucent extruded + // column round the building that pulses, from just under its ground to + // well over its roof, with a faint wireframe cage on it as a secondary + // cue and a crisp draped base outline. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + const groundH = + options.sampledGroundHeight ?? + (Number.isFinite(anno.anchor.height) + ? anno.anchor.height - (anno.buildingHeight || 25) + : 0); + const baseH = groundH - 3; + // Tall headroom so under-tagged building heights are covered too. + const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; + const at = (ring) => + ring.map(([lon, lat]) => ({ lon, lat, height: baseH })); + parts.forEach(([outer, ...holes], p) => { + const buffered = bufferRing(outer, 3); + // Built once: a fade step only changes colours. + const volume = { kind: 'polygon', rings: [buffered, ...holes].map(at) }; + shapes.push((alpha) => ({ + id: `volume:${p}`, + geometry: volume, + fill: colour(base, 0.45 * alpha), + animate: pulse(0.45 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + // Faint, SIMPLIFIED wireframe cage: the footprint decimated so the + // extruded outline draws ~14 clean verticals, not one per (often + // 100+) ring vertex. + const cage = { + kind: 'polygon', + rings: [at(decimateRing(buffered, 14))], + }; + shapes.push((alpha) => ({ + id: `cage:${p}`, + geometry: cage, + outline: colour(base, 0.32 * alpha), + outlineOnly: true, + animate: pulse(0.32 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + [outer, ...holes].forEach((ring, r) => + lines.push( + draped(`base:${p}:${r}`, ecefOf(closedRing(ring)), 3, (alpha) => ({ + kind: 'glow', + color: colour(base, 0.7 * alpha), + power: 0.25, + })), + ), + ); + }); + } else if (anno.ring?.length >= 3) { + // Larger area (district / compound / park / state) → flat fill draped on + // the tiles + a glowing outline. Draping is right here: you can't extrude + // a whole neighbourhood, and the GIS overlay shows the boundary clearly. + // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a + // hole in Brandenburg) draws every part with its holes. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + // Synthesized (approximate) areas get a fainter fill so they don't read + // as solid, and a DASHED outline (signals "approximate, not an + // authoritative boundary", research §8.4/§8.6); real footprints a solid + // glow. + const fillAlpha = anno.synthesized ? 0.1 : 0.2; + const style = anno.synthesized + ? (alpha) => ({ + kind: 'dash', + color: colour(base, 0.95 * alpha), + length: 24, + }) + : (alpha) => ({ kind: 'glow', color: colour(base, alpha), power: 0.35 }); + parts.forEach(([outer, ...holes], p) => { + if (!Array.isArray(outer) || outer.length < 3) return; + const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; + const area = { + kind: 'polygon', + rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))), + }; + shapes.push((alpha) => ({ + id: `fill:${p}`, + geometry: area, + fill: colour(base, fillAlpha * alpha), + animate: pulse(fillAlpha * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + })); + rings.forEach((ring, r) => + lines.push( + draped(`outline:${p}:${r}`, ecefOf(closedRing(ring)), 6, style), + ), + ); + }); + } else if ( + anno.type === 'route' && + Array.isArray(anno.path) && + anno.path.length >= 2 + ) { + // A real path (street-following) draped on the surface, with dashes that + // FLOW toward the destination. + lines.push( + draped( + 'route', + anno.path.map((p) => fromDegrees(p.lon, p.lat, 0)), + 9, + (alpha) => ({ + kind: 'flow', + color: colour(base, 0.95 * alpha), + repeat: 64, + duty: 0.46, + speed: 0.55, + }), + ), + ); + } else if (anno.type === 'arrow' && anno.to) { + // Connector draped across the ground from origin to destination. + lines.push( + draped( + 'arrow', + [ + fromDegrees(anno.anchor.lon, anno.anchor.lat, 0), + fromDegrees(anno.to.lon, anno.to.lat, 0), + ], + 16, + (alpha) => ({ kind: 'arrow', color: colour(base, 0.95 * alpha) }), + ), + ); + } else { + // pin / highlight / label — a camera-proportional target ring + a marker. + const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat }; + if (anno.type !== 'label') { + ring = (alpha) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: pos, + semiMajor: ringRadiusNow(), + semiMinor: ringRadiusNow(), + }, + fill: colour(base, 0.38 * alpha), + animate: pulse(0.38 * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + }); + shapes.push(ring); + } + // Captions belong to the hybrid renderer's screen-space callouts. + points.push((alpha) => ({ + id: 'marker', + pos, + height: 'clampGround', + pixelSize: anno.type === 'label' ? 8 : 14, + color: colour(base, alpha), + outlineColor: colour(WHITE, 0.95 * alpha), + outlineWidth: 3, + disableDepthTest: Number.POSITIVE_INFINITY, + meta, + })); + } + return { shapes, lines, points, ring }; +} + +/** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */ +const ecefOf = (ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0)); + +function rgb(css) { + const n = parseInt(css.slice(1), 16); + return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; +} /** The ring with its first vertex repeated at the end, so an outline closes. */ function closedRing(ring) { @@ -763,7 +766,7 @@ function decimateRing(ring, n) { function groundProbePositions(ring) { const { lon: clon, lat: clat } = ringCentroid(ring); const latS = 111320; - const lonS = latS * Math.cos(Cesium.Math.toRadians(clat)); + const lonS = latS * Math.cos((clat * Math.PI) / 180); let maxR = 0; for (const [lon, lat] of ring) { maxR = Math.max(maxR, Math.hypot((lon - clon) * lonS, (lat - clat) * latS)); @@ -801,7 +804,7 @@ function bufferRing(ring, meters) { clon /= ring.length; clat /= ring.length; const latScale = 111320; - const lonScale = latScale * Math.cos(Cesium.Math.toRadians(clat)); + const lonScale = latScale * Math.cos((clat * Math.PI) / 180); return ring.map(([lon, lat]) => { const dx = (lon - clon) * lonScale; const dy = (lat - clat) * latScale; diff --git a/src/annotations/worldAnnotationRenderer.test.mjs b/src/annotations/worldAnnotationRenderer.test.mjs index a05c52373f..62e0b65749 100644 --- a/src/annotations/worldAnnotationRenderer.test.mjs +++ b/src/annotations/worldAnnotationRenderer.test.mjs @@ -1,70 +1,448 @@ -// A mark hidden from Draw's list leaves the globe whole: every entity it put -// there is taken out on sync and comes back when shown, and the line's -// flowing stroke, which keeps its own colour, follows the mark's alpha. +// The world renderer draws each mark through the draw port, in sets of its +// own: a hidden mark has its sets hidden on sync and shown again; a fading +// mark takes its new colours in place; every kind draws what it drew as +// entities, draped and clamped to terrain and tiles alike. import test from 'node:test'; import assert from 'node:assert/strict'; -import * as C from 'cesium'; -import { - FlowMaterialProperty, - createWorldAnnotationRenderer, -} from './worldAnnotationRenderer.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js'; -const noop = () => {}; -function viewer(t) { - for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) { - const original = globalThis[name]; - globalThis[name] = class {}; - t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; }); - } - const before = globalThis.document; - globalThis.document = { addEventListener: noop, removeEventListener: noop }; - t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; }); +/** + * A viewer with a fake draw port, frame, camera and query bound. The camera + * stands at `camera.height`; `preRender()` runs the frame's preRender + * listeners, `emit()` its postRender ones. + */ +function viewer(t, { heights = () => null } = {}) { + const draw = fakeDrawPort(); + const frames = new Set(); + const before = new Set(); + const v = { requests: 0 }; + const frame = { + on(phase, cb) { + const listeners = + phase === 'postRender' ? frames : phase === 'preRender' ? before : null; + if (!listeners) return () => {}; + listeners.add(cb); + return () => listeners.delete(cb); + }, + requestRender() { + v.requests += 1; + }, + }; + const camera = { height: 2000, pose: () => ({ height: camera.height }) }; + const query = { sampleHeightNow: (point) => heights(point) }; + const unbind = bindRenderer(v, { draw, frame, query, camera }); + t.after(unbind); return { - creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop }, - entities: new C.EntityCollection(), - dataSources: new C.DataSourceCollection(), - camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } }, - scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(), - primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } }, + v, + draw, + frames, + before, + camera, + emit: () => [...frames].forEach((cb) => cb()), + preRender: () => [...before].forEach((cb) => cb()), }; } const marks = () => [ - { id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] }, - { id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] }, - { id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } }, + { + id: 'route', + type: 'route', + color: 'amber', + alpha: 1, + anchor: { lat: 0, lon: 0 }, + path: [ + { lat: 0, lon: 0 }, + { lat: 0.01, lon: 0.01 }, + ], + }, + { + id: 'area', + type: 'area', + color: 'green', + alpha: 1, + anchor: { lat: 0.005, lon: 0.005 }, + ring: [ + [0, 0], + [0.01, 0], + [0.01, 0.01], + [0, 0], + ], + }, + { + id: 'pin', + type: 'pin', + color: 'primary', + alpha: 1, + anchor: { lat: 0.02, lon: 0.02 }, + }, ]; -test('a hidden mark has every entity taken off on sync, and back when shown', (t) => { - const renderer = createWorldAnnotationRenderer(viewer(t)); +/** The live sets a mark draws into. */ +const setsOf = (draw, anno) => + [...draw.sets.values()].filter( + (record) => + !record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`), + ); + +test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); const [route, area, pin] = marks(); for (const anno of [route, area, pin]) renderer.add(anno); - const shown = (anno) => anno._entities.map((entity) => entity.show); - for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id); + for (const anno of [route, area, pin]) + assert.ok(setsOf(draw, anno).length > 0, anno.id); + const shown = (anno) => setsOf(draw, anno).map((record) => record.show); route.hidden = true; area.hidden = true; renderer.sync(); - assert.ok(shown(route).every((show) => show === false), 'the line is off'); - assert.ok(shown(area).every((show) => show === false), 'the area is off'); - assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays'); + assert.ok( + shown(route).every((show) => show === false), + 'the line is off', + ); + assert.ok( + shown(area).every((show) => show === false), + 'the area is off', + ); + assert.ok( + shown(pin).every((show) => show === true), + 'a visible mark stays', + ); route.hidden = false; renderer.sync(); - assert.ok(shown(route).every((show) => show === true), 'the line is back'); + assert.ok( + shown(route).every((show) => show === true), + 'the line is back', + ); + const areaSets = setsOf(draw, area); renderer.remove(area); + assert.ok( + areaSets.every((record) => record.disposed), + 'a removed mark lets its sets go', + ); renderer.sync(); - assert.equal(area._entities, null, 'a removed mark is no longer synced'); + renderer.destroy(); + assert.equal( + [...draw.sets.values()].filter((record) => !record.disposed).length, + 0, + ); +}); + +test('a fading mark takes its new colours in place, its pulses with them', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + renderer.add(route); + renderer.add(area); + const line = () => [...setsOf(draw, route)[0].items.values()][0]; + const fill = () => + setsOf(draw, area) + .find((r) => r.kind === 'shapes') + .items.get('fill:0'); + assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9); + assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9); + route.alpha = 0.5; + area.alpha = 0.5; + renderer.sync(); + assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading'); + assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9); + assert.deepEqual( + [fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)), + [60, 100], + 'its pulse swings between 60% and all of its alpha', + ); + route.alpha = 0; + renderer.sync(); + assert.equal(line().style.color[3], 0, 'faded out: nothing painted'); renderer.destroy(); }); -test('the line\'s flowing stroke follows its mark\'s alpha', () => { - let alpha = 1; - const material = new FlowMaterialProperty('#ffb547', () => alpha); - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9); - alpha = 0; - assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted'); - alpha = 0.5; - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading'); - assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before'); +test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { + id: 'arrow', + type: 'arrow', + color: 'red', + alpha: 1, + anchor: { lon: 0, lat: 0 }, + to: { lon: 0.01, lat: 0 }, + }; + const label = { + id: 'label', + type: 'label', + color: 'amber', + alpha: 1, + anchor: { lon: 0.03, lat: 0 }, + }; + for (const anno of [route, area, pin, synth, arrow, label]) + renderer.add(anno); + const items = (anno, kind) => [ + ...(setsOf(draw, anno) + .find((r) => r.kind === kind) + ?.items.values() ?? []), + ]; + for (const record of [...draw.sets.values()]) + assert.equal(record.spec.clampTo, 'both'); + + const [flow] = items(route, 'lines'); + assert.equal(flow.mode, 'draped'); + assert.equal(flow.widthPx, 9); + assert.deepEqual( + { ...flow.style, color: undefined }, + { kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 }, + ); + + const [areaFill] = items(area, 'shapes'); + assert.equal(areaFill.height, 'clampGround'); + assert.equal(areaFill.animate.property, 'alpha'); + assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9); + const [areaLine] = items(area, 'lines'); + assert.deepEqual( + [areaLine.widthPx, areaLine.style.kind, areaLine.style.power], + [6, 'glow', 0.35], + ); + const [synthLine] = items(synth, 'lines'); + assert.deepEqual( + [synthLine.style.kind, synthLine.style.length], + ['dash', 24], + ); + assert.ok( + Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9, + 'an approximate area is fainter', + ); + + const [arrowLine] = items(arrow, 'lines'); + assert.deepEqual( + [arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind], + ['draped', 16, 'arrow'], + ); + + const [ring] = items(pin, 'shapes'); + assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height'); + assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor); + const [marker] = items(pin, 'points'); + assert.deepEqual( + [ + marker.pixelSize, + marker.height, + marker.outlineWidth, + marker.disableDepthTest, + ], + [14, 'clampGround', 3, Infinity], + ); + assert.equal(items(label, 'shapes').length, 0, 'a label has no ring'); + assert.equal(items(label, 'points')[0].pixelSize, 8); + renderer.destroy(); +}); + +test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => { + const { v, draw, camera, preRender, before } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [, , pin] = marks(); + const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } }; + renderer.add(pin); + renderer.add(other); + const ringOf = (anno) => + setsOf(draw, anno) + .find((r) => r.kind === 'shapes') + .items.get('ring'); + // Writes to the rings' sets since they were drawn. + const shapeSets = [pin, other].map((anno) => + setsOf(draw, anno).find((r) => r.kind === 'shapes'), + ); + const upserts = { + get length() { + return shapeSets.reduce((n, record) => n + record.writes - 1, 0); + }, + }; + assert.equal(ringOf(pin).geometry.semiMajor, 60); + assert.equal(before.size, 1, 'one listener for every ring'); + // The camera has not moved: nothing is sent. + preRender(); + assert.equal(upserts.length, 0); + // It climbs: both rings are sent at the new radius, once. + camera.height = 4000; + preRender(); + preRender(); + assert.equal(upserts.length, 2); + assert.equal(ringOf(pin).geometry.semiMajor, 120); + assert.equal(ringOf(pin).geometry.semiMinor, 120); + assert.equal(ringOf(other).geometry.semiMajor, 120); + // A change under 0.1% sends nothing. + camera.height = 4002; + preRender(); + assert.equal(upserts.length, 2); + // Held within 14 m and 170 m. + camera.height = 1e6; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 170); + camera.height = 10; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 14); + // A hidden mark waits, and catches up when shown. + other.hidden = true; + renderer.sync(); + camera.height = 3000; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 90); + assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent'); + other.hidden = false; + renderer.sync(); + assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up'); + // The last ring gone, the listener goes with it. + renderer.remove(pin); + renderer.remove(other); + assert.equal(before.size, 0); + renderer.destroy(); +}); + +test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => { + const { v, draw, emit, frames } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const ring = [ + [0, 0], + [0.001, 0], + [0.001, 0.001], + [0, 0.001], + [0, 0], + ]; + const anno = { + id: 'b', + type: 'area', + color: 'amber', + alpha: 1, + footprintKind: 'building', + buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, + ring, + }; + const done = renderer.add(anno); + assert.equal(frames.size, 1, 'probing on the frames'); + assert.equal( + setsOf(draw, anno).length, + 0, + 'nothing until its ground is known', + ); + for (let i = 0; i < 8; i++) emit(); + assert.equal((await done).status, 'installed'); + assert.equal(frames.size, 0, 'done probing'); + const shapes = [ + ...setsOf(draw, anno) + .find((r) => r.kind === 'shapes') + .items.values(), + ]; + const volume = shapes.find((s) => s.id === 'volume:0'); + assert.equal(volume.extrudeHeight, 150 + 40 + 24); + assert.equal(volume.geometry.rings[0][0].height, 147); + assert.equal(volume.height, 'absolute'); + const cage = shapes.find((s) => s.id === 'cage:0'); + assert.equal(cage.outlineOnly, true); + assert.ok(cage.geometry.rings[0].length <= 14); + const [base] = setsOf(draw, anno) + .find((r) => r.kind === 'lines') + .items.values(); + assert.deepEqual( + [base.mode, base.widthPx, base.style.kind, base.style.power], + ['draped', 3, 'glow', 0.25], + ); + renderer.destroy(); +}); + +test('each kind paints the alphas it painted as entities, at full alpha', (t) => { + const { v, draw } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { + id: 'arrow', + type: 'arrow', + color: 'red', + alpha: 1, + anchor: { lon: 0, lat: 0 }, + to: { lon: 0.01, lat: 0 }, + }; + const ring = Array.from({ length: 40 }, (_, i) => [ + 0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI), + 0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI), + ]); + const building = { + id: 'b', + type: 'area', + color: 'amber', + alpha: 1, + footprintKind: 'building', + buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, + ring, + }; + for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno); + renderer.add(building, { sampledGroundHeight: 150 }); + const items = (anno, kind) => [ + ...(setsOf(draw, anno) + .find((r) => r.kind === kind) + ?.items.values() ?? []), + ]; + const alpha = (c) => Math.round(c[3] * 1000) / 1000; + assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(area, 'lines')[0].style.color), 1); + assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38); + const marker = items(pin, 'points')[0]; + assert.deepEqual( + [alpha(marker.color), alpha(marker.outlineColor)], + [1, 0.95], + ); + assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]); + const [volume, cage] = items(building, 'shapes'); + assert.equal(alpha(volume.fill), 0.45); + assert.equal(alpha(cage.outline), 0.32); + assert.equal( + Math.round(cage.animate.from * 1000) / 1000, + 0.192, + 'the cage pulses too', + ); + assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14'); + assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7); + renderer.destroy(); +}); + +test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => { + const { v, draw } = viewer(t); + const first = createWorldAnnotationRenderer(v); + const second = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + first.add(route); + const prefix = route._draw.prefix; + first.remove(route); + assert.doesNotThrow(() => first.add(route)); + assert.notEqual(route._draw.prefix, prefix, 'fresh sets'); + assert.doesNotThrow(() => second.add(area)); + assert.ok( + !area._draw.prefix.startsWith( + route._draw.prefix.split(':').slice(0, 2).join(':') + ':', + ), + ); + // Added again as another kind, its old sets go. + const kinds = () => + setsOf(draw, route) + .map((r) => r.kind) + .sort(); + assert.deepEqual(kinds(), ['lines']); + Object.assign(route, { type: 'pin', path: undefined }); + first.add(route); + assert.deepEqual(kinds(), ['points', 'shapes']); + assert.doesNotThrow(() => first.remove(null)); + first.destroy(); + second.destroy(); + assert.equal(route._draw, null); + first.add(route); + assert.equal(route._draw, null, 'a destroyed renderer draws nothing more'); + assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0); }); diff --git a/src/app/application.test.mjs b/src/app/application.test.mjs index c01878d891..00807c0972 100644 --- a/src/app/application.test.mjs +++ b/src/app/application.test.mjs @@ -2,20 +2,74 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { createApplication } from './application.js'; +import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js'; import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js'; import * as Cesium from 'cesium'; -import { - installFreeLookHeightLimit, - installGlobeInViewRecovery, - installTrackpadPinchZoom, -} from './viewer.js'; -import { - FREE_LOOK_MAX_HEIGHT_METERS, - globeFrameShare, - globeOutOfFrame, - lookAngleWithinFrame, - lookStepLosesGlobe, -} from '../globeInView.js'; +import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js'; +import { installGlobeInViewRecovery } from './globeInViewRecovery.js'; +import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js'; +import * as globeInView from '../globeInView.js'; +import { createCesiumCamera } from '../render/cesium/camera.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { entityFollowTarget } from '../data/followed.js'; + +/** The camera port bound over each real Cesium camera a test makes. */ +const cameraPorts = new WeakMap(); + +/** + * Bind `viewer` the Cesium renderer's own camera port over its real camera, + * with the camera's own `moveStart` and `moveEnd` so a test raises them, and + * a frame port that counts render requests on the scene. + */ +function bindCameraPorts(viewer) { + const { camera, scene } = viewer; + const noEvent = { addEventListener: () => () => {} }; + const real = createCesiumCamera({ + scene: { + postUpdate: noEvent, + preUpdate: noEvent, + get screenSpaceCameraController() { + return scene.screenSpaceCameraController; + }, + requestRender: () => scene.requestRender?.(), + }, + camera, + report: (error) => { + throw error; + }, + }).port; + const port = Object.create(real, { + on: { value: (event, cb) => camera[event].addEventListener(cb) }, + }); + cameraPorts.set(camera, port); + bindRenderer(viewer, { + camera: port, + get canvas() { + return scene.canvas; + }, + frame: { + on: () => () => {}, + requestRender: () => scene.requestRender?.(), + }, + }); +} + +// The frame measures take a camera pose; these take the test's camera. +const poseOf = (camera) => cameraPorts.get(camera).pose(); +const LOOKS = { + lookUp: 'up', + lookDown: 'down', + lookLeft: 'left', + lookRight: 'right', +}; +const globeFrameShare = (camera, options) => + globeInView.globeFrameShare(poseOf(camera), options); +const globeOutOfFrame = (camera, options) => + globeInView.globeOutOfFrame(poseOf(camera), options); +const lookAngleWithinFrame = (camera, look, angle, options) => + globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options); +const lookStepLosesGlobe = (camera, look, angle, options) => + globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options); const phases = ['Scene', 'Controls', 'Data', 'Tools']; function fixture(overrides = {}) { @@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer', }); test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => { - const { applicationViewerOptions } = await import('./viewer.js'); - const { StarrySky } = await import('../sky/starrySky.js'); + const { applicationViewerOptions } = + await import('../render/cesium/applicationViewer.js'); + const { StarrySky } = await import('../render/cesium/starrySky.js'); const creditContainer = {}; const options = applicationViewerOptions(creditContainer); // CesiumWidget skips scene.sun and scene.moon when skyBox is false. @@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) { return { viewer, controller, container, handlers, relayed, createEvent }; } -test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => { +test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => { const original = [1, 2, 3]; const f = pinchFixture({ zoomEventTypes: original }); - const dispose = installTrackpadPinchZoom(f.viewer, { + const dispose = installTrackpadPinchRelay(f.viewer, { createWheelEvent: (_type, init) => f.createEvent(init), }); - assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original); - assert.equal(f.controller.zoomEventTypes.length, 4); + assert.equal(f.controller.zoomEventTypes, original); const plain = f.createEvent({ deltaY: 2 }); f.container.emit(plain); @@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs test('trackpad pinch relays pixel deltas once with bounded amplification', () => { const f = pinchFixture({ zoomEventTypes: [1, 2, 3] }); - installTrackpadPinchZoom(f.viewer, { + installTrackpadPinchRelay(f.viewer, { createWheelEvent: (_type, init) => f.createEvent(init), }); @@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () => test('trackpad pinch falls back to the original event when relay construction fails', () => { const f = pinchFixture({ zoomEventTypes: [1, 2, 3] }); - installTrackpadPinchZoom(f.viewer, { + installTrackpadPinchRelay(f.viewer, { createWheelEvent() { throw new Error('unsupported'); }, @@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) { test('free look follows camera height and is restored on dispose', () => { const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal(f.controller.enableLook, true); f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1); @@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => { test('drags that start on the stars orbit above the free-look height', () => { // Below Cesium's trackball height such a drag turns the camera in place. const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal( f.controller.minimumTrackBallHeight, FREE_LOOK_MAX_HEIGHT_METERS, @@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => { const lower = freeLookFixture({ height: 500 }); lower.controller.minimumTrackBallHeight = 500_000; - const disposeLower = installFreeLookHeightLimit(lower.viewer); + const disposeLower = installFreeLookHeightLimit( + lower.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal( lower.controller.minimumTrackBallHeight, 500_000, @@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => { assert.equal(lower.controller.minimumTrackBallHeight, 500_000); const later = freeLookFixture({ height: 500 }); - const disposeLater = installFreeLookHeightLimit(later.viewer); + const disposeLater = installFreeLookHeightLimit( + later.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); later.controller.minimumTrackBallHeight = 2_000_000; disposeLater(); assert.equal( @@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => { test('free look keeps a setting other code makes after it is installed', () => { const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); f.controller.enableLook = false; f.frame(10); assert.equal(f.controller.enableLook, false, 'turned off stays off'); @@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => { test('free look stays off when the viewer had it disabled', () => { const f = freeLookFixture({ enableLook: false, height: 500 }); - installFreeLookHeightLimit(f.viewer); + installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS); f.frame(10); assert.equal(f.controller.enableLook, false); }); @@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) { }; const camera = new Cesium.Camera(scene); camera.frustum.aspectRatio = width / height; - return { camera, scene, viewer: { camera, scene } }; + const viewer = { camera, scene }; + bindCameraPorts(viewer); + return { camera, scene, viewer }; } function aim( @@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => { Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3), ); assert.equal(globeOutOfFrame(camera), false); - assert.equal(scene.renders, 1); + // One render for the new view, one the recovery asks for itself. + assert.equal(scene.renders, 2, 'the turned view is drawn'); // Looking up near the ground, then zoomed out past the limit. aim(camera, { alt: 3_834_000, pitch: 10 }); @@ -602,7 +674,7 @@ function moveEndKeepsView(camera) { return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9); } -test('globe recovery leaves partial, low, locked and 2D views alone', () => { +test('globe recovery leaves partial, low, locked and following views alone', () => { for (const view of partialGlobeViews) { const { camera, viewer } = realCamera(); installGlobeInViewRecovery(viewer); @@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => { assert.equal(globeOutOfFrame(locked.camera), true); assert.ok(moveEndKeepsView(locked.camera), 'locked camera'); - // Tracking an entity that has no position yet keeps an identity transform. + // Following an entity that has no position yet keeps an identity transform. const tracked = realCamera(); - tracked.viewer.trackedEntity = { id: 'pending-fix' }; + const pending = entityFollowTarget( + { id: 'pending-fix' }, + { position: () => null }, + ); + Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', { + get: () => pending, + }); installGlobeInViewRecovery(tracked.viewer); aim(tracked.camera, reportedStuckView); assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera'); - - const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW }); - installGlobeInViewRecovery(flat.viewer); - flat.scene.mode = Cesium.SceneMode.SCENE3D; - aim(flat.camera, reportedStuckView); - flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; - assert.ok(moveEndKeepsView(flat.camera), 'Columbus view'); }); test('the look limit from orbit tolerates grid noise and never reaches zero', () => { diff --git a/src/app/controls.js b/src/app/controls.js index 16da2c2959..bec189ed31 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -1,8 +1,11 @@ import { catalogControlServices } from './catalog.js'; import { StyleManager } from '../ui/composition.js'; -import { flyToAustin } from '../camera.js'; -import { installZoomOutGuard } from './zoomOutGuard.js'; +import { applyStartView, START_VIEW } from '../camera.js'; import { initCockpitCloudEffects } from '../cockpitCloudEffects.js'; +import { createViewSky } from '../viewSky.js'; +import { findGlobe } from '../render/rendererOf.js'; +import { useDisplayStore } from '../ui/stores/display.js'; +import { applicationPinia } from '../ui/vueRuntime.js'; import { t } from '../i18n/index.js'; /** @@ -10,12 +13,13 @@ import { t } from '../i18n/index.js'; * opens a share code (the `` of `/share/`) at start-up, for a host * whose address does not carry one. `localePicker: false` removes the language * picker, for a host that offers its own language choice (`switchLocale` from - * the `./i18n` entry). + * the `./i18n` entry). `startView` is where the camera starts (the whole + * planet by default; a host may pass a city); a shared view flies from there. * `services.cockpitSubjects` adds the application's own first-person subjects * to the Cockpit (src/cockpitSubjectProviders.js). */ export function createApplicationControls({ - scene: { viewer, mapStackController, operations }, + scene: { viewer, mapStackController, operations, viewerDrawsEntity }, loaderStatus, Controls = StyleManager, services, @@ -24,7 +28,10 @@ export function createApplicationControls({ defer, initialShareCode = null, localePicker = true, + startView = START_VIEW, }) { + // Every boot starts from the same view, before share restoration flies on. + applyStartView(viewer, startView); // Initialize the style manager (post-processing, HUD, locations, share links) const styleManager = new Controls(viewer, { services: { @@ -34,6 +41,8 @@ export function createApplicationControls({ fetchRegionalBrief: (...args) => operations.requests.regional.getBrief(...args), ...catalogControlServices(catalog), + // Whether an entity is one of the viewer's own; the scene answers it. + viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity, }, requestServices: operations.requests, mapStackController, @@ -45,28 +54,27 @@ export function createApplicationControls({ defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); defer(() => styleManager.dispose()); - defer( - installZoomOutGuard(viewer, { - subscribeCameraHandoff: (listener) => - styleManager.subscribeCameraHandoff?.(listener), - }), - ); // The previous multi-canvas weather compositor remains disabled. Cockpit // clouds use a separate, capped low-resolution GPU pass that never attaches // Cesium fog or post-process stages and is fully stopped in map mode. const weatherEffects = null; - const cockpitCloudEffects = initCockpitCloudEffects(viewer, { - weatherService: operations.requests.weather, - }); + // Where the renderer draws weather, it draws the cockpit's clouds too. + const cockpitCloudEffects = findGlobe(viewer)?.weather + ? null + : initCockpitCloudEffects(viewer, { + weatherService: operations.requests.weather, + }); defer(() => cockpitCloudEffects?.destroy()); + // The atmosphere, sun lighting, sun, moon, stars and Milky Way the user + // chooses in the Display panel. + const viewSky = createViewSky(viewer, { + store: useDisplayStore(applicationPinia()), + }); + defer(() => viewSky.destroy()); - // If no share link state, do default fly-to Austin - if (!styleManager.hasShareState) { - loaderStatus.textContent = t('Flying to Austin, TX...'); - defer(flyToAustin(viewer)); - } else { - loaderStatus.textContent = t('Restoring shared view...'); - } + loaderStatus.textContent = styleManager.hasShareState + ? t('Restoring shared view...') + : t('Loading'); return { styleManager, weatherEffects, cockpitCloudEffects }; } diff --git a/src/app/controls.test.mjs b/src/app/controls.test.mjs index 3db3b7d8b8..ebf847b077 100644 --- a/src/app/controls.test.mjs +++ b/src/app/controls.test.mjs @@ -1,9 +1,8 @@ import test, { after, before } from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import '../testSupport/stubMgrs.mjs'; import { installVueDom } from '../testSupport/vueDom.mjs'; -import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; const { createApplicationControls } = await import('./controls.js'); @@ -13,35 +12,20 @@ before(() => { }); after(() => uninstallDom()); -test('application controls install the zoom-out guard and remove it on teardown', () => { - const canvas = document.createElement('canvas'); - const controller = { maximumZoomDistance: Infinity }; - const scene = { - mode: Cesium.SceneMode.SCENE3D, - screenSpaceCameraController: controller, - preRender: new Cesium.Event(), - postUpdate: new Cesium.Event(), - }; - const camera = { - position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000), - positionCartographic: { height: 1_000_000 }, - }; - const viewer = { scene, camera, canvas }; - const handoffs = new Set(); +test('the application controls start and stop', () => { class Controls { hasShareState = true; orbitController = { stop() {} }; hud = { destroy() {} }; dispose() {} - subscribeCameraHandoff(listener) { - handoffs.add(listener); - return () => handoffs.delete(listener); - } } const cleanups = []; createApplicationControls({ scene: { - viewer, + viewer: bindFakeCesiumCamera({ + isDestroyed: () => false, + camera: { setView() {} }, + }), mapStackController: {}, operations: { surface: { controlServices: {} }, @@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown' catalog: { get: (id) => ({ id }) }, defer: (cleanup) => cleanups.push(cleanup), }); - - assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M); - assert.equal(scene.preRender.numberOfListeners, 1); - assert.equal(scene.postUpdate.numberOfListeners, 1); - assert.equal(handoffs.size, 1); - for (const cleanup of cleanups.reverse()) cleanup(); - assert.equal(controller.maximumZoomDistance, Infinity); - assert.equal(scene.preRender.numberOfListeners, 0); - assert.equal(scene.postUpdate.numberOfListeners, 0); - assert.equal(handoffs.size, 0); }); diff --git a/src/app/data.js b/src/app/data.js index 022839cd21..7e20f13150 100644 --- a/src/app/data.js +++ b/src/app/data.js @@ -15,7 +15,7 @@ export function createApplicationData({ const dataManager = new LayerLifecycle(viewer, { allowQaRegistration, // A panel's host may report it hidden while it is on screen; its layers - // keep polling (see keepPanelRendering in embed.js). + // keep polling (see keepPanelRendering in app/panelRendering.js). visibilityTarget: panelAwareVisibility(document), getSourceAvailability: catalog?.getSourceAvailability, }); diff --git a/src/app/embed.js b/src/app/embed.js index 32541f85a0..c30731d895 100644 --- a/src/app/embed.js +++ b/src/app/embed.js @@ -11,13 +11,14 @@ * embedded or not. */ -import * as Cesium from 'cesium'; import { announceNavigationAuthority, watchCameraOwner, } from '../navigationPolicy.js'; +import { toRadians } from '../geo/index.js'; import { t, translateKnown } from '../i18n/index.js'; import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js'; +import { cameraOf } from '../render/rendererOf.js'; import { annotationsFromParams, createView, @@ -69,7 +70,8 @@ function isFreshPanelResult() { /** * `doc`'s visibility for work that pauses in a hidden page. A panel's host - * may report it hidden while it is on screen (see keepPanelRendering), so an + * may report it hidden while it is on screen (see keepPanelRendering in + * render/cesium/panelRendering.js), so an * inline panel always reads as visible. */ export function panelAwareVisibility(doc = globalThis.document) { @@ -89,52 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) { }; } -// A panel keeps drawing at about this rate when its host stops animation -// frames; see keepPanelRendering. -const PANEL_FRAME_MS = 33; -const MISSED_FRAMES_MS = 250; - -/** - * Keep the globe drawing in an inline panel. Some hosts report a panel on - * screen as hidden, which stops the browser's animation frames and with them - * Cesium's render loop; while frames stop arriving, draw from a timer. - * Returns a function that stops it. - */ -export function keepPanelRendering( - viewer, - { windowRef = globalThis.window, now = () => performance.now() } = {}, -) { - let lastFrame = now(); - let frameRequest = null; - const onFrame = () => { - lastFrame = now(); - frameRequest = windowRef.requestAnimationFrame(onFrame); - }; - frameRequest = windowRef.requestAnimationFrame(onFrame); - // Cesium stops its render loop after a render error, and the timer stops - // with it; Retry restarts both. The render failure notice logs the error - // (src/ui/renderFailure.js). - const timer = windowRef.setInterval(() => { - if ( - viewer.useDefaultRenderLoop === false || - now() - lastFrame < MISSED_FRAMES_MS || - viewer.isDestroyed?.() - ) - return; - try { - viewer.resize(); - viewer.render(); - } catch { - // Raised as a render error by now (src/ui/renderFailure.js), which - // stops this timer; thrown on, it would only reach the host page. - } - }, PANEL_FRAME_MS); - return () => { - windowRef.clearInterval(timer); - windowRef.cancelAnimationFrame(frameRequest); - }; -} - const delay = (ms, signal) => new Promise((resolve) => { const timer = setTimeout(resolve, ms); @@ -152,21 +108,19 @@ const delay = (ms, signal) => function flyTo(viewer, camera) { announceNavigationAuthority('embed-view'); return new Promise((resolve) => { - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees( - camera.lon, - camera.lat, - camera.altitude_m, - ), - orientation: { - heading: Cesium.Math.toRadians(camera.heading_deg), - pitch: Cesium.Math.toRadians(camera.pitch_deg), - roll: 0, + cameraOf(viewer).flyTo( + { lon: camera.lon, lat: camera.lat, height: camera.altitude_m }, + { + orientation: { + heading: toRadians(camera.heading_deg), + pitch: toRadians(camera.pitch_deg), + roll: 0, + }, + durationS: FLIGHT_SECONDS, + onComplete: () => resolve(true), + onCancel: () => resolve(false), }, - duration: FLIGHT_SECONDS, - complete: () => resolve(true), - cancel: () => resolve(false), - }); + ); }); } @@ -314,6 +268,9 @@ export async function applyView( /** * Install embed mode when the page asks for it, and draw any annotations the * opening link carries. Returns a function that removes the message handler. + * `keepRendering({windowRef})` keeps the globe drawing in an inline panel + * whose host stops animation frames, and returns a function that stops it; + * the application scene gives it (`keepPanelRendering`). */ export function installViews({ shell, @@ -321,6 +278,7 @@ export function installViews({ dataManager, run, signal, + keepRendering = null, terrain = null, location = globalThis.location, windowRef = globalThis.window, @@ -433,9 +391,10 @@ export function installViews({ windowRef.document.body.classList.add('ui-embed'); shell.setCleanView?.(true); - const stopRendering = isEmbeddedInline() - ? keepPanelRendering(viewer, { windowRef }) - : () => {}; + const stopRendering = + isEmbeddedInline() && keepRendering + ? keepRendering({ windowRef }) + : () => {}; // A framing page talks to the app across frames; an inline panel shares // the page with it and talks through the page's own window. const peer = isEmbeddedInline() ? windowRef : windowRef.parent; diff --git a/src/app/embed.test.mjs b/src/app/embed.test.mjs index e4e8a1d220..1889c906ab 100644 --- a/src/app/embed.test.mjs +++ b/src/app/embed.test.mjs @@ -1,10 +1,10 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import assert from 'node:assert/strict'; import test from 'node:test'; import { applyView, installViews, isEmbedded, - keepPanelRendering, panelAwareVisibility, } from './embed.js'; import { LayerLifecycle } from '../data/lifecycle.js'; @@ -12,7 +12,7 @@ import { createView, viewToParams } from '../view/index.js'; const fakeViewer = () => { const flights = []; - return { + return bindFakeCesiumCamera({ flights, camera: { flyTo(options) { @@ -20,7 +20,7 @@ const fakeViewer = () => { options.complete(); }, }, - }; + }); }; const fakeLayers = (enabled) => ({ getAll: () => @@ -329,6 +329,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn globalThis.GEV_EMBED_INLINE = true; try { assert.equal(isEmbedded({ search: '' }), true); + const kept = []; const remove = installViews({ shell: { initialRestorePromise: Promise.resolve() }, viewer: fakeViewer(), @@ -336,7 +337,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn run: recorder().run, location: { search: '', hash: '' }, windowRef, + // The scene's panel rendering, kept on while the views are installed. + keepRendering: (options) => { + kept.push(options.windowRef === windowRef); + return () => kept.push('stopped'); + }, }); + assert.deepEqual(kept, [true]); await new Promise((resolve) => setTimeout(resolve, 0)); assert.deepEqual(posted, [{ type: 'gev:ready' }]); const event = new Event('message'); @@ -349,6 +356,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn assert.equal(posted[1].id, 7); assert.equal(posted[1].ok, true); remove(); + assert.deepEqual(kept, [true, 'stopped']); } finally { delete globalThis.GEV_EMBED_INLINE; } @@ -427,60 +435,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async ]); }); -test('a panel keeps drawing from a timer while animation frames stop', () => { - let clock = 0; - let tick = null; - let frame = null; - const windowRef = { - requestAnimationFrame: (fn) => ((frame = fn), 1), - cancelAnimationFrame: () => (frame = null), - setInterval: (fn) => ((tick = fn), 1), - clearInterval: () => (tick = null), - }; - const drawn = []; - const viewer = { - resize: () => drawn.push('resize'), - render: () => drawn.push('render'), - }; - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); - // Frames arrive: the render loop draws, so the timer does nothing. - clock = 100; - frame(); - tick(); - assert.deepEqual(drawn, []); - // Frames stop, as in a panel its host reports hidden: the timer draws. - clock = 400; - tick(); - assert.deepEqual(drawn, ['resize', 'render']); - stop(); - assert.equal(tick, null); - assert.equal(frame, null); -}); - -test('a panel stops drawing while its render loop is stopped', () => { - let tick = null; - const windowRef = { - requestAnimationFrame: () => 1, - cancelAnimationFrame() {}, - setInterval: (fn) => ((tick = fn), 1), - clearInterval() {}, - }; - const drawn = []; - const viewer = { resize() {}, render: () => drawn.push('render') }; - let clock = 0; - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); - // Cesium stops its render loop after a render error. - viewer.useDefaultRenderLoop = false; - clock = 1000; - tick(); - assert.deepEqual(drawn, []); - // Retry restarts it, and the timer draws again. - viewer.useDefaultRenderLoop = true; - tick(); - assert.deepEqual(drawn, ['render']); - stop(); -}); - test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => { const viewer = fakeViewer(); const { calls, run } = recorder(); diff --git a/src/app/globeInViewRecovery.js b/src/app/globeInViewRecovery.js new file mode 100644 index 0000000000..91c1c3062a --- /dev/null +++ b/src/app/globeInViewRecovery.js @@ -0,0 +1,181 @@ +/** + * @module app/globeInViewRecovery + * @description Turns the camera back to the planet when a move ends looking + * away from it, through the renderer's camera and frame ports. + */ +import { PI_OVER_TWO } from '../geo/vector.js'; +import { + FREE_LOOK_MAX_HEIGHT_METERS, + globeOutOfFrame, + isFreeGlobeCamera, +} from '../globeInView.js'; +import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js'; + +/** Whether two vectors agree to `tolerance` in every component. */ +const within = (a, b, tolerance) => + Math.abs(a.x - b.x) <= tolerance && + Math.abs(a.y - b.y) <= tolerance && + Math.abs(a.z - b.z) <= tolerance; + +// How often a moving camera is sampled to see whether it has come to rest, how +// far a pose may drift between samples and still count as at rest, and how +// long after the camera last moved the check gives up if the camera never +// raises moveEnd. +const SETTLE_SAMPLE_MS = 250; +const SETTLE_POSITION_TOLERANCE_M = 1e-3; +const SETTLE_DIRECTION_TOLERANCE = 1e-9; +const SETTLE_GIVE_UP_MS = 5 * 60_000; + +/** + * Turn the camera back to the planet when a move ends above `minHeight` with + * no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about + * one sample cell thick can count as none), and return the disposer. Views with + * more surface, such as an oblique orbital shot, are left as they are. This + * catches a saved or shared view that looked away, or any other move that ends + * looking away from the planet. + * Heading and position are kept. Following cameras, locked ones (a target's + * frame), a camera flight in progress, a pointer held down on the canvas + * (a drag held still), and any time `paused` + * returns true (an authored scene playing) are left alone; a check they defer + * runs once they end, however long they last. + * `keyholeRadius` + * returns the radius of the visible circle when a scope mask hides the rest of + * the frame (see `globeFrameShare`), or 0; it is read at every check. + * + * The camera's `moveEnd` alone is not enough: the default renderer compares + * the camera with the last frame's to the last rounding error, and at some of + * these poses the camera drifts by a rounding error every frame, so it never + * sees it stop. + * So each `moveStart` also starts a check of its own that samples the pose + * every 250 ms, with a tolerance for that drift, and once the pose has held + * for half a second after moving runs the same recovery. It keeps watching + * until the camera raises `moveEnd`, since under that drift it raises no new + * `moveStart` for a later move, and gives up five minutes after the camera + * last moved. + * `setTimeout` and `clearTimeout` can be injected for tests. + */ +export function installGlobeInViewRecovery( + viewer, + { + minHeight = FREE_LOOK_MAX_HEIGHT_METERS, + keyholeRadius = () => 0, + paused = () => false, + setTimeout: schedule = globalThis.setTimeout, + clearTimeout: unschedule = globalThis.clearTimeout, + } = {}, +) { + const camera = findCamera(viewer); + if (!camera) throw new TypeError('A viewer with a camera is required'); + + // A pointer held on the globe is a gesture in progress, even when it holds + // still for half a second: the check waits until every pointer pressed on + // it (each finger of a pinch) is released. A release the page never sees, + // outside the window, is taken as given when the window loses focus, the + // page is hidden, the canvas loses the pointer's capture, or the pointer + // moves with no button down. + const canvas = canvasOf(viewer); + const releaseTarget = canvas?.ownerDocument ?? canvas; + const releaseWindow = canvas?.ownerDocument?.defaultView; + const heldPointers = new Set(); + const onPointerDown = (event) => heldPointers.add(event?.pointerId); + const onPointerUp = (event) => heldPointers.delete(event?.pointerId); + const onPointerMove = (event) => { + if (event?.buttons === 0) heldPointers.delete(event.pointerId); + }; + const releaseAll = () => heldPointers.clear(); + const onVisibilityChange = () => { + if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll(); + }; + const listeners = [ + [canvas, 'pointerdown', onPointerDown], + [canvas, 'lostpointercapture', onPointerUp], + [releaseTarget, 'pointerup', onPointerUp], + [releaseTarget, 'pointercancel', onPointerUp], + [releaseTarget, 'pointermove', onPointerMove], + [canvas?.ownerDocument, 'visibilitychange', onVisibilityChange], + [releaseWindow, 'blur', releaseAll], + ]; + for (const [target, type, listener] of listeners) + target?.addEventListener?.(type, listener); + + // Returns false while a flight, a paused scene or a held pointer defers the + // check, so the caller can try again once it ends. + const recover = () => { + if (!isFreeGlobeCamera(viewer)) return true; + if (camera.flying || paused() || heldPointers.size > 0) return false; + const pose = camera.pose(); + if ( + !(pose.height > minHeight) || + !globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() }) + ) + return true; + camera.setView({ + orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 }, + }); + findFrame(viewer)?.requestRender?.('globe-in-view'); + return true; + }; + + let lastPosition = null; + let lastDirection = null; + const remember = () => { + ({ position: lastPosition, direction: lastDirection } = camera.pose()); + }; + let settleTimer = null; + let settleElapsed = 0; + let restingSamples = 0; + let movedSinceCheck = false; + const stopSettling = () => { + if (settleTimer !== null) unschedule(settleTimer); + settleTimer = null; + }; + const sample = () => { + settleTimer = null; + settleElapsed += SETTLE_SAMPLE_MS; + const now = camera.pose(); + const atRest = + within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) && + within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE); + restingSamples = atRest ? restingSamples + 1 : 0; + if (!atRest) { + movedSinceCheck = true; + settleElapsed = 0; + } + // Two quiet samples in a row after a move: at rest for half a second, as + // for moveEnd. + if (restingSamples >= 2 && movedSinceCheck) { + if (recover()) movedSinceCheck = false; + // A flight or a playing scene bounds its own deferral. + else settleElapsed = 0; + } + if (settleElapsed >= SETTLE_GIVE_UP_MS) return; + remember(); + settleTimer = schedule(sample, SETTLE_SAMPLE_MS); + }; + const startSettling = () => { + stopSettling(); + settleElapsed = 0; + restingSamples = 0; + movedSinceCheck = true; + remember(); + settleTimer = schedule(sample, SETTLE_SAMPLE_MS); + }; + const removeMoveEnd = camera.on('moveEnd', () => { + if (recover()) stopSettling(); + // Deferred: keep sampling so the check runs once the flight or scene ends. + else if (settleTimer === null) startSettling(); + }); + const removeMoveStart = camera.on('moveStart', startSettling); + + let active = true; + return () => { + if (!active) return; + active = false; + stopSettling(); + removeMoveEnd(); + removeMoveStart(); + for (const [target, type, listener] of listeners) + target?.removeEventListener?.(type, listener); + heldPointers.clear(); + }; +} diff --git a/src/app/layers/droneAirspace.js b/src/app/layers/droneAirspace.js index f3472fec49..c9db27a57f 100644 --- a/src/app/layers/droneAirspace.js +++ b/src/app/layers/droneAirspace.js @@ -1,8 +1,6 @@ -import * as Cesium from 'cesium'; import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire FAA special-use airspace into the application catalog. */ export function createApplicationDroneAirspace(options) { @@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/firms.js b/src/app/layers/firms.js index 6e64148784..4bb6518967 100644 --- a/src/app/layers/firms.js +++ b/src/app/layers/firms.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js'; import * as render from '../../renderGovernor.js'; import * as sprites from '../../data/spriteOrder.js'; @@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: - options.screenSpaceEventHandlerFactory ?? - ((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)), }); } diff --git a/src/app/layers/ghostMaps.js b/src/app/layers/ghostMaps.js index ccca188507..56387a80fb 100644 --- a/src/app/layers/ghostMaps.js +++ b/src/app/layers/ghostMaps.js @@ -1,8 +1,6 @@ -import * as Cesium from 'cesium'; import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire the S2 Underground GhostMaps layer into the application catalog. */ export function createApplicationGhostMaps(options) { @@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) { hitTest: overlays.hitTestWorldOverlay, }, openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/perimeters.js b/src/app/layers/perimeters.js index f5110f630d..dd1230ce46 100644 --- a/src/app/layers/perimeters.js +++ b/src/app/layers/perimeters.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createFirePerimetersLayer, createInciwebIndexSource, @@ -6,7 +5,6 @@ import { } from '../../layers/perimeters/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire WFIGS fire perimeters into the application catalog. */ export function createApplicationFirePerimeters(options) { @@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) { inciwebSource: createInciwebIndexSource(), inciwebPublications: createInciwebPublicationSource(), openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/rail.js b/src/app/layers/rail.js index 87fccde18f..883b5f8771 100644 --- a/src/app/layers/rail.js +++ b/src/app/layers/rail.js @@ -4,7 +4,6 @@ import { fleetModelServices } from './fleetModels.js'; import * as sprites from '../../data/spriteOrder.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { applyTrackedCameraFrame } from '../../data/trackedCamera.js'; import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js'; import { railFeedCredit, @@ -52,7 +51,6 @@ export function createApplicationRail({ camera: { framing: WORLD_FOCUS_FRAMING.train, requestWorldFocus, - applyTrackedCameraFrame, isCockpitActive: () => globalThis.document?.body?.classList?.contains('cockpit-mode') === true, diff --git a/src/app/layers/shipwrecks.js b/src/app/layers/shipwrecks.js index ece2d2dce4..8f91289f18 100644 --- a/src/app/layers/shipwrecks.js +++ b/src/app/layers/shipwrecks.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; @@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) { hitTest: overlays.hitTestWorldOverlay, }, openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, pointer: { isPointerFree }, ...options, diff --git a/src/app/layers/streetLevel.js b/src/app/layers/streetLevel.js index 268216eaaf..3b7c7cc0b9 100644 --- a/src/app/layers/streetLevel.js +++ b/src/app/layers/streetLevel.js @@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js'; import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js'; import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js'; -import * as sprites from '../../data/spriteOrder.js'; import * as picking from '../../data/pickRegistry.js'; -import * as input from '../../data/inputOwnership.js'; import * as scenePick from '../../data/scenePick.js'; import * as render from '../../renderGovernor.js'; @@ -37,6 +35,6 @@ export function createApplicationStreetLevel({ }) { return createStreetLevelLayer({ providers, - services: { sprites, picking, input, scenePick, render }, + services: { picking, scenePick, render }, }); } diff --git a/src/app/layers/submarineCables.js b/src/app/layers/submarineCables.js index b84c072dbb..1f6dd7d817 100644 --- a/src/app/layers/submarineCables.js +++ b/src/app/layers/submarineCables.js @@ -1,12 +1,9 @@ -import * as Cesium from 'cesium'; import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js'; import { overlayHost } from './overlayHost.js'; /** Wire cable source geometry to the application overlay host. */ export function createApplicationCables(options) { return createSubmarineCableLayer({ overlayHost, - screenSpaceEventHandlerFactory: (canvas) => - new Cesium.ScreenSpaceEventHandler(canvas), mapStackEventTarget: typeof window !== 'undefined' ? window : null, ...options, }); diff --git a/src/app/layers/wildlifeSightings.js b/src/app/layers/wildlifeSightings.js index 6d181f2c72..6ce091c553 100644 --- a/src/app/layers/wildlifeSightings.js +++ b/src/app/layers/wildlifeSightings.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; @@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, pointer: { isPointerFree }, sprites, diff --git a/src/app/localGeojsonServices.js b/src/app/localGeojsonServices.js index 8103f3b353..a9607e192b 100644 --- a/src/app/localGeojsonServices.js +++ b/src/app/localGeojsonServices.js @@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; import { governorRequestRender } from '../renderGovernor.js'; import { clearSelectedEntityContextForLayer, + getSelectedEntityContext, registerEntityContext, removeEntityContextsForLayer, selectEntityContext, @@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({ setVisible: setOverlaySourceVisible, }), clearSelectedEntityContextForLayer, + getSelectedEntityContext, registerEntityContext, removeEntityContextsForLayer, selectEntityContext, diff --git a/src/app/mapLifecycle.test.mjs b/src/app/mapLifecycle.test.mjs index ef015bf52a..6286ca71d9 100644 --- a/src/app/mapLifecycle.test.mjs +++ b/src/app/mapLifecycle.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { MapStackController } from '../mapStackController.js'; +import '../render/cesium/mapEngine.js'; import { installRenderGovernor, uninstallRenderGovernor, @@ -8,6 +9,7 @@ import { governorRequestRender, getRenderGovernorDiagnostics, } from '../renderGovernor.js'; +import { framePortFor } from '../testSupport/fakeFramePort.mjs'; test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => { let resolveProvider; @@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests }, }, }; - installRenderGovernor(viewer); + installRenderGovernor(framePortFor(viewer.scene)); holdContinuousRender('fixture'); - uninstallRenderGovernor({}); + uninstallRenderGovernor(framePortFor({})); assert.equal(getRenderGovernorDiagnostics().installed, true); - uninstallRenderGovernor(viewer); + uninstallRenderGovernor(framePortFor(viewer.scene)); const before = renders; governorRequestRender('late'); assert.equal(renders, before); diff --git a/src/app/panelRendering.js b/src/app/panelRendering.js new file mode 100644 index 0000000000..1b3688eb12 --- /dev/null +++ b/src/app/panelRendering.js @@ -0,0 +1,74 @@ +/** + * @module app/panelRendering + * @description Keeping the globe drawing in an inline panel whose host stops + * animation frames (`src/app/embed.js`, embed mode), through the ports alone: the + * application scene hands it to the embed views (`src/app/scene.js`). + */ + +// A panel keeps drawing at about this rate when its host stops animation +// frames; see keepPanelRendering. +const PANEL_FRAME_MS = 33; +const MISSED_FRAMES_MS = 250; + +/** A render error's details, including the plain objects workers report. */ +function describeError(error) { + if (error instanceof Error) + return `${error.name}: ${error.message}\n${error.stack}`; + try { + return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {})); + } catch { + return String(error); + } +} + +/** + * Keep `renderer` drawing in an inline panel. Some hosts report a panel on + * screen as hidden, which stops the browser's animation frames and with them + * the renderer's own loop; while frames stop arriving, draw from a timer + * (`resize`, then a frame of the loop, `frame.renderNow({ifDue: true})`: the + * camera moves, input and the clock run, and it draws when due). While the + * renderer's loop is stopped after a failed frame (`stopped` in its frame + * diagnostics) the timer waits, and goes on once a retry starts the loop + * again; the render failure notice reports the error + * (src/render/cesium/renderFailure.js). Where the renderer never says so, a frame + * that fails stops the timer, its error reported in full. Returns a + * function that stops it. + * @param {import('../render/contract/renderer').Renderer} renderer + * @param {{windowRef?: Window, now?: () => number}} [options] + * @returns {() => void} + */ +export function keepPanelRendering( + renderer, + { windowRef = globalThis.window, now = () => performance.now() } = {}, +) { + let lastFrame = now(); + let frameRequest = null; + const onFrame = () => { + lastFrame = now(); + frameRequest = windowRef.requestAnimationFrame(onFrame); + }; + frameRequest = windowRef.requestAnimationFrame(onFrame); + let failed = false; + const stopped = () => renderer.frame.diagnostics?.().stopped; + const timer = windowRef.setInterval(() => { + if (failed || now() - lastFrame < MISSED_FRAMES_MS || stopped()) return; + try { + renderer.resize(); + renderer.frame.renderNow({ ifDue: true }); + } catch (error) { + // Stopped by now: the render failure notice has the error. + if (stopped() !== undefined) return; + // Report the error in full: workers report plain objects, which + // would print as [object Object]. + failed = true; + console.error( + "[God's Eye View panel] render error:", + describeError(error), + ); + } + }, PANEL_FRAME_MS); + return () => { + windowRef.clearInterval(timer); + windowRef.cancelAnimationFrame(frameRequest); + }; +} diff --git a/src/app/panelRendering.test.mjs b/src/app/panelRendering.test.mjs new file mode 100644 index 0000000000..49af8b2aa0 --- /dev/null +++ b/src/app/panelRendering.test.mjs @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { keepPanelRendering } from './panelRendering.js'; + +const windowWith = () => { + const handles = { tick: null, frame: null }; + handles.windowRef = { + requestAnimationFrame: (fn) => ((handles.frame = fn), 1), + cancelAnimationFrame: () => (handles.frame = null), + setInterval: (fn) => ((handles.tick = fn), 1), + clearInterval: () => (handles.tick = null), + }; + return handles; +}; + +test('a panel keeps drawing from a timer while animation frames stop', () => { + let clock = 0; + const handles = windowWith(); + const drawn = []; + const renderer = { + resize: () => drawn.push('resize'), + frame: { + renderNow: (options) => + drawn.push(options?.ifDue ? 'loop frame' : 'forced frame'), + }, + }; + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + // Frames arrive: the render loop draws, so the timer does nothing. + clock = 100; + handles.frame(); + handles.tick(); + assert.deepEqual(drawn, []); + // Frames stop, as in a panel its host reports hidden: the timer draws. + clock = 400; + handles.tick(); + // A frame of the loop, as the loop's own: the camera moves, input and + // the clock run, and it draws when due. + assert.deepEqual(drawn, ['resize', 'loop frame']); + stop(); + assert.equal(handles.tick, null); + assert.equal(handles.frame, null); +}); + +test('a panel reports a failed frame in full and stops drawing', () => { + const handles = windowWith(); + let renders = 0; + const renderer = { + resize() {}, + frame: { + renderNow() { + renders += 1; + // Workers report plain objects. + throw { name: 'RuntimeError', message: 'worker failed' }; + }, + }, + }; + const logged = []; + const original = console.error; + console.error = (...args) => logged.push(args.join(' ')); + try { + let clock = 0; + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + clock = 1000; + handles.tick(); + assert.match(logged[0], /render error: .*"message":"worker failed"/); + handles.tick(); + assert.equal(renders, 1, 'no frame after the one that failed'); + stop(); + } finally { + console.error = original; + } +}); + +test('a panel waits while its renderer’s loop is stopped after a failed frame, and draws again once it restarts', () => { + let clock = 0; + const handles = windowWith(); + let stopped = false; + let fail = false; + let renders = 0; + const renderer = { + resize() {}, + frame: { + diagnostics: () => ({ stopped }), + renderNow() { + renders += 1; + if (fail) { + // The renderer stops its loop as the frame fails. + stopped = true; + throw new Error('frame failed'); + } + }, + }, + }; + const errors = []; + const error = console.error; + console.error = (...args) => errors.push(args); + try { + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + clock = 1000; + fail = true; + handles.tick(); + assert.equal(renders, 1); + // Stopped: the timer waits, and leaves the error to the notice. + handles.tick(); + assert.equal(renders, 1); + assert.deepEqual(errors, []); + // A retry starts the loop again: the timer draws again. + stopped = false; + fail = false; + handles.tick(); + assert.equal(renders, 2); + stop(); + } finally { + console.error = error; + } +}); diff --git a/src/app/renderFailureInlineRetry.test.mjs b/src/app/renderFailureInlineRetry.test.mjs index fa84e880fa..31dff45918 100644 --- a/src/app/renderFailureInlineRetry.test.mjs +++ b/src/app/renderFailureInlineRetry.test.mjs @@ -1,11 +1,13 @@ // Retry in an inline panel whose host stops animation frames, so the panel // draws from keepPanelRendering's timer. Drives Cesium's real startRenderLoop -// and useDefaultRenderLoop setter (CesiumWidget.prototype). +// and useDefaultRenderLoop setter (CesiumWidget.prototype), through the +// Cesium frame port. import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { keepPanelRendering } from './embed.js'; -import { renderLoopFixture } from '../ui/renderLoopFixture.mjs'; +import { keepPanelRendering } from './panelRendering.js'; +import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs'; +import { createSceneFrame } from '../render/cesium/frame.js'; function setup() { let tick = null; @@ -23,6 +25,7 @@ function setup() { const scene = { renderError: new Cesium.Event(), preUpdate: new Cesium.Event(), + preRender: new Cesium.Event(), postRender: new Cesium.Event(), requestRender() {}, initializeFrame() {}, @@ -46,7 +49,16 @@ function setup() { }, notice: { allowReload: false }, }); - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); + const frame = createSceneFrame(viewer); + const renderer = { resize: () => viewer.resize(), frame: frame.port }; + const stopPanel = keepPanelRendering(renderer, { + windowRef, + now: () => clock, + }); + const stop = () => { + stopPanel(); + frame.dispose(); + }; viewer.useDefaultRenderLoop = true; const timerFrame = () => { clock += 400; diff --git a/src/app/scene.js b/src/app/scene.js index 0224d9a269..63012fb663 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -1,30 +1,66 @@ import { createApplicationOperations } from './operations.js'; -import * as Cesium from 'cesium'; -import { - createApplicationViewer, - installFreeLookHeightLimit, - installTrackpadPinchZoom, -} from '../app/viewer.js'; import { registerDataCredits } from '../data/dataCredits.js'; -import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; +import { mountCreditsView } from '../ui/creditsView.js'; import { MapStackController } from '../mapStackController.js'; -import { loadPhotorealisticTileset } from '../mapStartup.js'; +import { mapEngineFor } from '../maps/engine.js'; import { initLogoGaze } from '../logoGaze.js'; +import { inputFor } from '../input/dispatcher.js'; import { + holdContinuousRender, + installRenderGovernor, uninstallRenderGovernor, governorRequestRender, - holdContinuousRender, releaseContinuousRender, } from '../renderGovernor.js'; import { describeError } from './errors.js'; import { isEmbeddedInline } from './embed.js'; -import { installRenderFailureNotice } from '../ui/renderFailure.js'; import { worldClock, worldTimeFor } from '../time/worldClock.js'; import { followWorldTime } from '../time/viewerClock.js'; -import { onLocaleChange, t } from '../i18n/index.js'; +import { t } from '../i18n/index.js'; +import { + applicationHooksOf, + provideApplicationHooks, +} from '../render/applicationHooks.js'; +import { keepPanelRendering } from './panelRendering.js'; +import { useStatusStore } from '../ui/stores/status.js'; +import { applicationPinia } from '../ui/vueRuntime.js'; +import { createSceneHost } from '../render/rendererOf.js'; -/** Construct the application globe using the caller's local configuration. */ +let defaultLoad = null; + +/** + * The application's composition root picks the renderer: the one given, else + * the default (Cesium), loaded only then, so a page on the stub never + * loads it. This is the only part of an adapter the application imports. A + * page that starts on the default calls this as it starts, so the renderer + * loads beside the rest of the page rather than after it. + * @returns {Promise} The default `RendererPlugin`. + */ +export function loadDefaultRenderer() { + if (defaultLoad) return defaultLoad; + const load = (async () => { + const { cesiumRenderer } = await import('../render/cesium/application.js'); + return cesiumRenderer; + })(); + defaultLoad = load; + // A load that failed is tried again by the next call. + load.catch(() => { + if (defaultLoad === load) defaultLoad = null; + }); + return load; +} + +/** + * Construct the application globe using the caller's local configuration. + * `renderer` is the `RendererPlugin` that draws it, or a promise of one + * (default: Cesium, `loadDefaultRenderer`). The + * application runs on a renderer with only the contract's required members: + * what a renderer's plugin hands it beside the contract + * (`src/render/applicationHooks.js`) it uses where given, and does without + * where not. + */ export async function createApplicationScene({ + renderer: givenPlugin, requestServices, googleApiKey, googleTokens = null, @@ -51,26 +87,76 @@ export async function createApplicationScene({ }); } loaderStatus.textContent = t('Configuring viewer...'); - // Provider attribution stays visible, including clean-view and recording. - const creditContainer = document.createElement('div'); - creditContainer.id = 'cesium-credits'; - document.body.appendChild(creditContainer); - defer(() => creditContainer.remove()); - const viewer = createApplicationViewer({ - container: 'cesiumContainer', - creditContainer, - // The render failure notice below replaces Cesium's dead-end panel. - showRenderLoopErrors: false, + const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer()); + signal.throwIfAborted(); + const container = document.getElementById('cesiumContainer'); + const renderer = await rendererPlugin.create({ + container, + googleApiKey: googleApiKey || undefined, + googleTokens: googleTokens + ? (options) => googleTokens.token(options) + : undefined, + worldDataToken: cesiumToken || undefined, + signal, }); + // The scene object every layer and tool is handed: the application's own, + // bound to the renderer. + const scene = createSceneHost(renderer, { container }); + const viewer = scene.host; + // The governor keeps its holds on the renderer's frame port. The loop + // draws every frame until the application's tools are up (they release + // 'boot'), as it did before anything could hold it. A camera move holds + // it drawing every frame too. + installRenderGovernor(renderer.frame, { camera: renderer.camera }); + holdContinuousRender('boot'); defer(() => { - uninstallRenderGovernor(viewer); - if (!viewer.isDestroyed()) viewer.destroy(); + try { + uninstallRenderGovernor(renderer.frame); + } finally { + try { + renderer.destroy(); + } finally { + scene.release(); + } + } }); - // An inline panel must not reload or navigate its host's page. - defer( - installRenderFailureNotice(viewer, { allowReload: !isEmbeddedInline() }), - ); - defer(installTrackpadPinchZoom(viewer)); + // What the plugin hands the application beside the contract, each hook + // optional (render/applicationHooks.js). + if (typeof rendererPlugin.applicationHooks === 'function') + provideApplicationHooks( + renderer, + rendererPlugin.applicationHooks(renderer), + ); + const hooks = applicationHooksOf(renderer); + // The renderer follows its container's size (`Renderer.resize`). + if (typeof ResizeObserver === 'function' && container) { + const resizes = new ResizeObserver(() => renderer.resize()); + resizes.observe(container); + defer(() => resizes.disconnect()); + } + // Before any layer binds a click: every layer and tool shares this one. + // Deferred after the renderer, so it is released before the renderer goes. + const input = inputFor(viewer); + defer(() => input.destroy()); + // Ctrl+wheel and trackpad pinches zoom the globe, not the page. + const { controls } = renderer.camera; + if (!controls.zoomInputs.includes('ctrlWheel')) + controls.zoomInputs = [...controls.zoomInputs, 'ctrlWheel']; + // The user's outward zooms stop at a whole-Earth view, which stays framed. + if (renderer.capabilities.has('keepEarthFramed')) { + controls.keepEarthFramed = true; + defer(() => { + controls.keepEarthFramed = false; + }); + } + // The renderer's own notice when the globe stops drawing, in place of a + // dead-end panel; an inline panel must not reload or navigate its host's + // page. + const offRenderFailure = hooks.renderFailureNotice?.({ + allowReload: !isEmbeddedInline(), + store: useStatusStore(applicationPinia()), + }); + if (offRenderFailure) defer(offRenderFailure); defer( followWorldTime(viewer, worldTimeFor('sky'), { subscribe: worldClock.subscribe, @@ -83,32 +169,35 @@ export async function createApplicationScene({ : releaseContinuousRender('world-time'), }), ); - defer(installFreeLookHeightLimit(viewer)); registerDataCredits(viewer, credits); - configureCreditKeyboardAccess(document); - defer(onLocaleChange(() => configureCreditKeyboardAccess(document))); + // The credits, in the application's own line, unless the renderer shows + // them in a display of its own. + if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer)); loaderStatus.textContent = googleApiKey || googleTokens || cesiumToken ? t('Loading Google 3D Tiles...') : t('Loading the keyless globe...'); - const photoreal = await loadPhotorealisticTileset(Cesium, { + // The map stacks, and the photoreal base among them, switch through the + // scene's map engine: the renderer's own, or its globe port. + const engine = mapOptions.engine ?? mapEngineFor(viewer); + const photoreal = (await engine.loadPhotoreal?.(viewer, { googleApiKey, googleTokens, cesiumToken, - }); + })) ?? { tileset: null, route: 'none', errors: [] }; const tileset = photoreal.tileset; // A provider can finish after cancellation; retain ownership of its result. defer(() => { - if (tileset && !tileset.isDestroyed()) { - if (!viewer.scene.primitives.remove(tileset)) tileset.destroy(); - } + if (!tileset || engine.isDestroyed(tileset)) return; + engine.removeTileset(viewer, tileset); + engine.release(tileset); }); signal.throwIfAborted(); if (tileset) { - viewer.scene.primitives.add(tileset); + engine.addTileset(viewer, tileset); // NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom. // Google Photorealistic 3D Tiles provide their own terrain/elevation. - viewer.scene.globe.show = false; + renderer.globe.setGlobeVisible(false); console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`); } else { if (photoreal.errors.length) { @@ -125,7 +214,7 @@ export async function createApplicationScene({ }, ); } - viewer.scene.globe.show = true; + renderer.globe.setGlobeVisible(true); } loaderStatus.textContent = t('Initializing systems...'); @@ -133,6 +222,7 @@ export async function createApplicationScene({ const mapStackController = new MapController(viewer, { requestRender: governorRequestRender, ...mapOptions, + engine, googleTileset: tileset, cesiumToken, initialStack: tileset ? 'photoreal' : 'esri-imagery', @@ -154,5 +244,22 @@ export async function createApplicationScene({ }); signal.throwIfAborted(); - return { viewer, tileset, mapStackController, operations }; + return { + renderer, + viewer, + tileset, + mapStackController, + operations, + input, + // Keeps the globe drawing in an inline panel whose host stops animation + // frames (embed mode, src/app/embed.js); returns its disposer. + keepPanelRendering: (options) => keepPanelRendering(renderer, options), + // What the renderer's plugin hands the application beside the contract, + // each optional: trims stale draw commands, says whether an entity is + // the renderer's own, and what QA scripts read + // (render/applicationHooks.js). + trimStaleCommands: hooks.trimStaleCommands, + viewerDrawsEntity: hooks.viewerDrawsEntity, + qaHandles: hooks.qaHandles, + }; } diff --git a/src/app/scene.test.mjs b/src/app/scene.test.mjs new file mode 100644 index 0000000000..b19dac0f81 --- /dev/null +++ b/src/app/scene.test.mjs @@ -0,0 +1,152 @@ +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createApplicationScene } from './scene.js'; +import { createApplicationRequestServices } from '../services/requests.js'; +import { createStubRendererPlugin } from '../render/stub/index.js'; +import { rendererOf } from '../render/rendererOf.js'; + +/** Start the scene on a stub renderer with `capabilities`. */ +async function startOnStub(t, { capabilities = [], ...rest } = {}) { + document.body.innerHTML = '
'; + const made = []; + const deferred = []; + t.after(async () => { + for (const fn of deferred.reverse()) await fn(); + }); + const scene = await createApplicationScene({ + renderer: createStubRendererPlugin({ capabilities }, (renderer) => + made.push(renderer), + ), + requestServices: createApplicationRequestServices(), + loaderStatus: { textContent: '' }, + signal: new AbortController().signal, + defer: (fn) => deferred.push(fn), + ...rest, + }); + return { scene, renderer: made[0], deferred }; +} + +test('the scene runs on a renderer with only the required members', async (t) => { + const { scene, renderer, deferred } = await startOnStub(t); + assert.equal(scene.renderer, renderer); + assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound'); + assert.equal( + scene.viewer.container, + document.getElementById('cesiumContainer'), + ); + assert.equal(scene.viewer.isDestroyed(), false); + assert.ok( + scene.viewer.container.contains(renderer.canvas), + 'the renderer fills the container', + ); + // Nothing of the engine on the scene object. + assert.deepEqual(Object.keys(scene.viewer).sort(), [ + 'container', + 'isDestroyed', + ]); + // No hooks: each is left out, not faked. + for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles']) + assert.equal(scene[name], undefined, name); + // What the renderer does through its ports. + assert.equal(typeof scene.keepPanelRendering, 'function'); + assert.equal( + renderer.camera.controls.keepEarthFramed, + undefined, + 'no framing on a renderer without it', + ); + // Keyless, the map stack shows Esri on the globe through the globe port. + assert.equal(scene.tileset, null); + assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery'); + const layers = renderer.globe.imagery.list(); + assert.equal(layers.length, 1, 'one base imagery layer'); + assert.ok( + renderer.testing.calls.some( + (call) => + call.port === 'globe' && + call.member === 'imagery.add' && + call.args[0]?.url?.includes('World_Imagery'), + ), + 'Esri imagery through the port', + ); + assert.equal(scene.mapStackController.getDrapeSurface(), 'globe'); + // The credits show in the application's own line: the Esri base's on it, + // the data credits in the list it opens. + const line = document.getElementById('gev-credits'); + assert.ok(line, 'a credits line'); + assert.match(line.textContent, /Esri/); + assert.ok( + document.querySelectorAll('#gev-credits-panel li').length > 10, + 'the data credits', + ); + + // Switching stacks goes through the port too. + await scene.mapStackController.setStack('osm'); + assert.equal(scene.mapStackController.getActiveId(), 'osm'); + assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way'); + + for (const fn of deferred.splice(0).reverse()) await fn(); + assert.equal(scene.viewer.isDestroyed(), true); + assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer'); + assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released'); + assert.equal(document.getElementById('gev-credits'), null, 'credits gone'); +}); + +test('the scene keeps the Earth framed where the renderer can', async (t) => { + const { renderer, deferred } = await startOnStub(t, { + capabilities: ['keepEarthFramed'], + }); + assert.equal(renderer.camera.controls.keepEarthFramed, true); + const controls = renderer.camera.controls; + for (const fn of deferred.splice(0).reverse()) await fn(); + assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown'); +}); + +test("the scene takes a plugin's application hooks", async (t) => { + const stub = createStubRendererPlugin({ capabilities: [] }); + const given = []; + const handles = Object.freeze({ probe: 'qa' }); + const { scene } = await startOnStub(t, { + renderer: { + id: 'stub-with-hooks', + create: (options) => stub.create(options), + applicationHooks(made) { + given.push(made); + return { qaHandles: handles, ownCreditDisplay: true }; + }, + }, + }); + assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer'); + assert.equal(scene.qaHandles, handles, 'QA scripts read its handles'); + assert.equal( + document.getElementById('gev-credits'), + null, + 'its own display shows the credits', + ); +}); + +test('with credentials, the photoreal base loads through the globe port', async (t) => { + const { scene, renderer } = await startOnStub(t, { + capabilities: ['photoreal', 'globeVisibility'], + googleApiKey: 'stub-key', + }); + assert.ok(scene.tileset, 'a photoreal base'); + assert.equal(scene.mapStackController.getActiveId(), 'photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden'); + const photoreal = renderer.testing.calls.filter( + (call) => call.port === 'globe' && call.member === 'setPhotoreal', + ); + assert.equal(photoreal[0]?.args[0]?.key, 'stub-key'); + + // A globe stack hides photoreal through the port, and shows the globe. + await scene.mapStackController.setStack('esri-imagery'); + assert.equal(renderer.globe.isGlobeVisible(), true); + assert.equal( + renderer.testing.calls + .filter((call) => call.port === 'globe' && call.member === 'setPhotoreal') + .at(-1).args[0], + null, + ); + await scene.mapStackController.setStack('photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false); +}); diff --git a/src/app/sourceComposition.test.mjs b/src/app/sourceComposition.test.mjs index 466572d843..e5a3bcb6ee 100644 --- a/src/app/sourceComposition.test.mjs +++ b/src/app/sourceComposition.test.mjs @@ -1,3 +1,5 @@ +// The click dispatcher's input port over a viewer double: the Cesium adapter's. +import '../render/cesium/input.js'; import assert from 'node:assert/strict'; import test from 'node:test'; import { diff --git a/src/app/startupCamera.test.mjs b/src/app/startupCamera.test.mjs index 721f9964b1..0c1767cef2 100644 --- a/src/app/startupCamera.test.mjs +++ b/src/app/startupCamera.test.mjs @@ -1,25 +1,41 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { flyToAustin } from '../camera.js'; +import { applyStartView, START_VIEW } from '../camera.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; -test('teardown before the initial camera delay prevents a late flight', (t) => { - t.mock.timers.enable({ apis: ['setTimeout'] }); - let flights = 0; - let cancelled = 0; - const stop = flyToAustin({ +function viewerRecording(views) { + return bindFakeCesiumCamera({ isDestroyed: () => false, camera: { - setView() {}, - flyTo() { - flights++; + setView(view) { + views.push(view); }, - cancelFlight() { - cancelled++; + flyTo() { + assert.fail('a start view is set, not flown to'); }, }, }); - stop(); - t.mock.timers.tick(1000); - assert.equal(flights, 0); - assert.equal(cancelled, 1); +} + +test('the camera starts over the whole planet, looking straight down', () => { + const views = []; + applyStartView(viewerRecording(views)); + assert.equal(views.length, 1); + assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view'); + assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9); + assert.equal(views[0].orientation.heading, 0); +}); + +test('a host can start the camera at a city instead', () => { + const views = []; + applyStartView(viewerRecording(views), { + lon: 2.35, + lat: 48.86, + height: 5000, + heading: 90, + pitch: -30, + }); + assert.equal(views.length, 1); + assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9); + assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9); }); diff --git a/src/app/tools.js b/src/app/tools.js index 476e252a54..1aae7ab8d5 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -1,3 +1,4 @@ +import { onFollowChanged } from '../data/followed.js'; import { SceneDirector } from '../scenes/director.js'; import { initAnnotations } from '../annotations/index.js'; import { initDrawTool } from '../annotations/drawTool.js'; @@ -24,17 +25,22 @@ import { isScopeMaskEnabled, } from '../scopeMask.js'; import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js'; -import { installGlobeInViewRecovery } from './viewer.js'; +import { installGlobeInViewRecovery } from './globeInViewRecovery.js'; import { installLayerReleaseTrim } from '../sceneCommandRelease.js'; import { - installRenderGovernor, getRenderGovernorDiagnostics, governorRequestRender, holdContinuousRender, releaseContinuousRender, } from '../renderGovernor.js'; +import { entityRecord, readEntityRecord } from '../data/entityRecords.js'; +import { overlayHost } from './layers/overlayHost.js'; -/** Attach scene tools, rendering listeners and the application debug handle. */ +/** + * Attach scene tools, rendering listeners and the application debug handle. + * `scene` is what `createApplicationScene` returns; its `trimStaleCommands` + * runs after each layer disable (a scene without one keeps that memory). + */ export function createApplicationTools({ scene, controls, @@ -49,11 +55,11 @@ export function createApplicationTools({ signal, defer, }) { - const { viewer, tileset, mapStackController, operations } = scene; + const { viewer, renderer, tileset, mapStackController, operations } = scene; const { styleManager, weatherEffects, cockpitCloudEffects } = controls; const { dataManager } = data; const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, { - dataPacks: sceneDataPacks, + dataPacks: { overlayHost, ...sceneDataPacks }, isMapStackAvailable: (id) => mapStackController?.isStackAvailable(id) === true, }); @@ -198,19 +204,21 @@ export function createApplicationTools({ } if (startChrome) defer(startChrome({ loadingScreen, styleManager, dataManager, signal })); - // Idle render governor: flips the scene into requestRenderMode whenever - // nothing animates per frame. Installed AFTER every module above has had - // its chance to register pre-install holds. (perf wave 2) - installRenderGovernor(viewer); - // Cesium keeps a turned-off layer's draw commands (and so all its entities) - // alive in reused per-pass arrays; trim them after each disable. - defer( - installLayerReleaseTrim({ - scene: viewer.scene, - dataManager, - requestRender: governorRequestRender, - }), - ); + // Idle render governor: the loop draws on demand whenever nothing animates + // per frame. It goes idle only now, after every module above has had its + // chance to hold. (perf wave 2) + releaseContinuousRender('boot'); + // The renderer may keep a turned-off layer's draw commands (and so all its + // entities) alive; trim them after each disable. + if (scene.trimStaleCommands) + defer( + installLayerReleaseTrim({ + frame: renderer.frame, + dataManager, + requestRender: governorRequestRender, + trim: scene.trimStaleCommands, + }), + ); // Install the explicit scope mask used by the DISPLAY controls. installScopeMask(viewer); @@ -218,12 +226,10 @@ export function createApplicationTools({ // The follow camera recomputes the tracked target's dead-reckon position // every frame — tracking anything is a per-frame animation. (perf wave 2) - const removeTrackingListener = viewer.trackedEntityChanged.addEventListener( - () => { - if (viewer.trackedEntity) holdContinuousRender('tracked-entity'); - else releaseContinuousRender('tracked-entity'); - }, - ); + const removeTrackingListener = onFollowChanged(viewer, (followed) => { + if (followed) holdContinuousRender('tracked-entity'); + else releaseContinuousRender('tracked-entity'); + }); // Hidden-state suspension (perf wave 2): when the window/tab is hidden, // stop the default render loop outright — a hidden canvas repaints for @@ -232,9 +238,9 @@ export function createApplicationTools({ // the loop, refresh the one DOM surface we gated, render a frame. const syncVisibilitySuspension = () => { // A panel's host may report it hidden while it is on screen; the panel - // keeps drawing itself (see keepPanelRendering in embed.js). + // keeps drawing itself (see keepPanelRendering in app/panelRendering.js). const hidden = document.hidden && !isEmbeddedInline(); - viewer.useDefaultRenderLoop = !hidden; + renderer.frame.suspend(hidden); cockpitCloudEffects?.setSuspended?.(hidden); if (!hidden) { data.presentation.flushVisible(); @@ -267,6 +273,10 @@ export function createApplicationTools({ getRenderGovernorDiagnostics, surfaceServices: operations.surface, requestRender: governorRequestRender, + entityRecords: { read: readEntityRecord, write: entityRecord }, + // What the renderer's plugin lets QA scripts read (the Cesium viewer, + // for the default renderer), in place of the scene object above. + ...scene.qaHandles, }; const debug = window.__godsEyeView; defer(() => { @@ -299,11 +309,13 @@ export function createApplicationTools({ run: (name, args, options = {}) => voiceCommands.runner(name, args, { ...options, signal }), signal, + keepRendering: scene.keepPanelRendering, terrain: operations.requests.terrain, }), ); - // An application's own tool takes the pointer as Draw does, and its own - // click handlers yield while a tool holds it, as the layers' do + // Any other tool takes the pointer as Draw does (the newest + // claim takes over; `claim(owner, {onLost})` tells the tool it replaces), + // and its own click handlers yield while a tool holds it, as the layers' do // (data/inputOwnership.js). return { sceneDirector, diff --git a/src/app/viewer.js b/src/app/viewer.js deleted file mode 100644 index 85a4e12851..0000000000 --- a/src/app/viewer.js +++ /dev/null @@ -1,447 +0,0 @@ -import * as Cesium from 'cesium'; -import { IDLE_FRAME_RATE } from '../renderGovernor.js'; -import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js'; -import { StarrySky } from '../sky/starrySky.js'; -import { - FREE_LOOK_MAX_HEIGHT_METERS, - globeOutOfFrame, - isFreeGlobeCamera, -} from '../globeInView.js'; - -/** - * At the farthest a hand can zoom out, the globe is this share of the - * screen's height across. Cesium sets no limit, so zooming on left the globe - * a speck among the stars. - */ -const MIN_GLOBE_SHARE = 0.3; - -/** - * The farthest a hand can zoom out, in metres above the ellipsoid, for a - * vertical field of view. It follows the screen's shape, as the app's own - * whole-globe view does, so that view always lies within it. - * @param {number} fovy Vertical field of view, radians. - */ -export function zoomOutLimit(fovy) { - const radius = Cesium.Ellipsoid.WGS84.maximumRadius; - const angular = Math.atan(MIN_GLOBE_SHARE * Math.tan(fovy / 2)); - return radius / Math.sin(angular) - radius; -} - -/** - * Hold a hand's zoom out to `zoomOutLimit` on the globe, each frame, since the - * field of view follows the screen's shape. The limit never sits below the - * camera: one already past it (a flight, a screen turned) stops there rather - * than jumping in at the next zoom. Flat maps keep Cesium's own, unlimited. - * @returns {() => void} Stop limiting. - */ -export function limitZoomOut(viewer) { - const { scene, camera } = viewer; - return scene.preRender.addEventListener(() => { - const controller = scene.screenSpaceCameraController; - const fovy = camera.frustum.fovy; - if (scene.mode !== Cesium.SceneMode.SCENE3D || !Number.isFinite(fovy)) { - controller.maximumZoomDistance = Number.POSITIVE_INFINITY; - return; - } - controller.maximumZoomDistance = Math.max( - zoomOutLimit(fovy), - camera.positionCartographic?.height ?? 0, - ); - }); -} - -const PINCH_ZOOM_MULTIPLIER = 8; -const MAX_PINCH_PIXEL_DELTA = 120; - -function boundedPinchDelta(delta) { - if (!Number.isFinite(delta) || delta === 0) return delta; - return ( - Math.sign(delta) * - Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA) - ); -} - -/** - * Add browser trackpad pinch to Cesium's zoom inputs and return its disposer. - * Browsers expose this gesture as a small pixel-mode Ctrl+wheel event. - */ -export function installTrackpadPinchZoom( - viewer, - { createWheelEvent = (type, init) => new WheelEvent(type, init) } = {}, -) { - const controller = viewer?.scene?.screenSpaceCameraController; - const container = viewer?.container; - const canvas = viewer?.canvas; - if (!controller || !container || !canvas) - throw new TypeError('A complete Cesium viewer is required'); - - const originalZoomEventTypes = controller.zoomEventTypes; - const zoomEventTypes = Array.isArray(originalZoomEventTypes) - ? originalZoomEventTypes - : originalZoomEventTypes === undefined - ? [] - : [originalZoomEventTypes]; - const alreadyHandlesControlWheel = zoomEventTypes.some( - (binding) => - binding?.eventType === Cesium.CameraEventType.WHEEL && - binding?.modifier === Cesium.KeyboardEventModifier.CTRL, - ); - const configuredZoomEventTypes = alreadyHandlesControlWheel - ? originalZoomEventTypes - : [ - ...zoomEventTypes, - { - eventType: Cesium.CameraEventType.WHEEL, - modifier: Cesium.KeyboardEventModifier.CTRL, - }, - ]; - if (!alreadyHandlesControlWheel) - controller.zoomEventTypes = configuredZoomEventTypes; - - const relayedEvents = new WeakSet(); - const relayPinch = (event) => { - if ( - !event.ctrlKey || - relayedEvents.has(event) || - event.deltaMode !== 0 || - !Number.isFinite(event.deltaY) || - event.deltaY === 0 - ) - return; - let relayed; - try { - relayed = createWheelEvent('wheel', { - deltaX: event.deltaX, - deltaY: boundedPinchDelta(event.deltaY), - deltaZ: event.deltaZ, - deltaMode: event.deltaMode, - screenX: event.screenX, - screenY: event.screenY, - clientX: event.clientX, - clientY: event.clientY, - ctrlKey: true, - bubbles: true, - cancelable: true, - view: globalThis.window, - }); - } catch { - // The registered Ctrl+wheel binding can still consume the original. - return; - } - relayedEvents.add(relayed); - event.preventDefault(); - event.stopPropagation(); - canvas.dispatchEvent(relayed); - }; - container.addEventListener('wheel', relayPinch, { - capture: true, - passive: false, - }); - - let active = true; - return () => { - if (!active) return; - active = false; - container.removeEventListener('wheel', relayPinch, true); - if ( - !alreadyHandlesControlWheel && - controller.zoomEventTypes === configuredZoomEventTypes - ) - controller.zoomEventTypes = originalZoomEventTypes; - }; -} - -/** - * Allow Cesium's free look only below `maxHeight` and return its disposer. - * Orbit, tilt and zoom stay available at every height. A value other code - * sets later is kept as the one to allow below that height, and restored on - * dispose; a `false` written while the camera is above `maxHeight` cannot be - * told apart from this limit's own write, so dispose restores the earlier - * value then. `enableLook` gates the Shift+drag binding only: below its trackball - * height Cesium also turns the camera in place for a drag that starts on the - * stars. That height is lowered to `maxHeight` too, so above it such a drag - * orbits the globe, as it does above Cesium's own 7,500 km. - */ -export function installFreeLookHeightLimit( - viewer, - maxHeight = FREE_LOOK_MAX_HEIGHT_METERS, -) { - const scene = viewer?.scene; - const controller = scene?.screenSpaceCameraController; - const camera = viewer?.camera; - if (!controller || !camera || !scene?.preUpdate) - throw new TypeError('A complete Cesium viewer is required'); - - const originalTrackBallHeight = controller.minimumTrackBallHeight; - const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight); - controller.minimumTrackBallHeight = trackBallHeight; - let wanted = controller.enableLook; - let written; - const sync = () => { - if (written !== undefined && controller.enableLook !== written) - wanted = controller.enableLook; - const height = camera.positionCartographic?.height; - written = wanted && !(Number.isFinite(height) && height > maxHeight); - controller.enableLook = written; - }; - sync(); - const removeListener = scene.preUpdate.addEventListener(sync); - - let active = true; - return () => { - if (!active) return; - active = false; - removeListener(); - if (controller.enableLook === written) controller.enableLook = wanted; - if (controller.minimumTrackBallHeight === trackBallHeight) - controller.minimumTrackBallHeight = originalTrackBallHeight; - }; -} - -// How often a moving camera is sampled to see whether it has come to rest, how -// far a pose may drift between samples and still count as at rest, and how -// long after the camera last moved the check gives up if Cesium never raises -// moveEnd. -const SETTLE_SAMPLE_MS = 250; -const SETTLE_POSITION_TOLERANCE_M = 1e-3; -const SETTLE_DIRECTION_TOLERANCE = 1e-9; -const SETTLE_GIVE_UP_MS = 5 * 60_000; - -/** - * Turn the camera back to the planet when a move ends above `minHeight` with - * no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about - * one sample cell thick can count as none), and return the disposer. Views with - * more surface, such as an oblique orbital shot, are left as they are. This - * catches a saved or shared view that looked away, or any other move that ends - * looking away from the planet. - * Heading and position are kept. Tracked cameras, locked ones (non-identity - * transform), a camera flight in progress, a pointer held down on the canvas - * (a drag held still), the 2D and Columbus modes, and any time `paused` - * returns true (an authored scene playing) are left alone; a check they defer - * runs once they end, however long they last. - * `keyholeRadius` - * returns the radius of the visible circle when a scope mask hides the rest of - * the frame (see `globeFrameShare`), or 0; it is read at every check. - * - * Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the - * last frame's to the last rounding error, and at some of these poses the - * camera drifts by a rounding error every frame, so Cesium never sees it stop. - * So each `moveStart` also starts a check of its own that samples the pose - * every 250 ms, with a tolerance for that drift, and once the pose has held - * for half a second after moving runs the same recovery. It keeps watching - * until Cesium raises `moveEnd`, since under that drift Cesium raises no new - * `moveStart` for a later move, and gives up five minutes after the camera - * last moved. - * `setTimeout` and `clearTimeout` can be injected for tests. - */ -export function installGlobeInViewRecovery( - viewer, - { - minHeight = FREE_LOOK_MAX_HEIGHT_METERS, - keyholeRadius = () => 0, - paused = () => false, - setTimeout: schedule = globalThis.setTimeout, - clearTimeout: unschedule = globalThis.clearTimeout, - } = {}, -) { - const scene = viewer?.scene; - const camera = viewer?.camera; - if (!scene || !camera?.moveEnd || !camera?.moveStart) - throw new TypeError('A complete Cesium viewer is required'); - - // A pointer held on the globe is a gesture in progress, even when it holds - // still for half a second: the check waits until every pointer pressed on - // it (each finger of a pinch) is released. A release the page never sees, - // outside the window, is taken as given when the window loses focus, the - // page is hidden, the canvas loses the pointer's capture, or the pointer - // moves with no button down. - const canvas = scene.canvas; - const releaseTarget = canvas?.ownerDocument ?? canvas; - const releaseWindow = canvas?.ownerDocument?.defaultView; - const heldPointers = new Set(); - const onPointerDown = (event) => heldPointers.add(event?.pointerId); - const onPointerUp = (event) => heldPointers.delete(event?.pointerId); - const onPointerMove = (event) => { - if (event?.buttons === 0) heldPointers.delete(event.pointerId); - }; - const releaseAll = () => heldPointers.clear(); - const onVisibilityChange = () => { - if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll(); - }; - const listeners = [ - [canvas, 'pointerdown', onPointerDown], - [canvas, 'lostpointercapture', onPointerUp], - [releaseTarget, 'pointerup', onPointerUp], - [releaseTarget, 'pointercancel', onPointerUp], - [releaseTarget, 'pointermove', onPointerMove], - [canvas?.ownerDocument, 'visibilitychange', onVisibilityChange], - [releaseWindow, 'blur', releaseAll], - ]; - for (const [target, type, listener] of listeners) - target?.addEventListener?.(type, listener); - - // Returns false while a flight, a paused scene or a held pointer defers the - // check, so the caller can try again once it ends. - const recover = () => { - if (!isFreeGlobeCamera(viewer)) return true; - // Cesium has no public running-flight flag. - if (camera._currentFlight || paused() || heldPointers.size > 0) - return false; - const height = camera.positionCartographic?.height; - if ( - !(height > minHeight) || - !globeOutOfFrame(camera, { keyholeRadius: keyholeRadius() }) - ) - return true; - camera.setView({ - orientation: { - heading: camera.heading, - pitch: -Cesium.Math.PI_OVER_TWO, - roll: 0, - }, - }); - scene.requestRender?.(); - return true; - }; - - const lastPosition = new Cesium.Cartesian3(); - const lastDirection = new Cesium.Cartesian3(); - let settleTimer = null; - let settleElapsed = 0; - let restingSamples = 0; - let movedSinceCheck = false; - const stopSettling = () => { - if (settleTimer !== null) unschedule(settleTimer); - settleTimer = null; - }; - const sample = () => { - settleTimer = null; - settleElapsed += SETTLE_SAMPLE_MS; - const atRest = - Cesium.Cartesian3.equalsEpsilon( - camera.positionWC, - lastPosition, - 0, - SETTLE_POSITION_TOLERANCE_M, - ) && - Cesium.Cartesian3.equalsEpsilon( - camera.directionWC, - lastDirection, - 0, - SETTLE_DIRECTION_TOLERANCE, - ); - restingSamples = atRest ? restingSamples + 1 : 0; - if (!atRest) { - movedSinceCheck = true; - settleElapsed = 0; - } - // Two quiet samples in a row after a move: at rest for half a second, as - // for moveEnd. - if (restingSamples >= 2 && movedSinceCheck) { - if (recover()) movedSinceCheck = false; - // A flight or a playing scene bounds its own deferral. - else settleElapsed = 0; - } - if (settleElapsed >= SETTLE_GIVE_UP_MS) return; - Cesium.Cartesian3.clone(camera.positionWC, lastPosition); - Cesium.Cartesian3.clone(camera.directionWC, lastDirection); - settleTimer = schedule(sample, SETTLE_SAMPLE_MS); - }; - const startSettling = () => { - stopSettling(); - settleElapsed = 0; - restingSamples = 0; - movedSinceCheck = true; - Cesium.Cartesian3.clone(camera.positionWC, lastPosition); - Cesium.Cartesian3.clone(camera.directionWC, lastDirection); - settleTimer = schedule(sample, SETTLE_SAMPLE_MS); - }; - const removeMoveEnd = camera.moveEnd.addEventListener(() => { - if (recover()) stopSettling(); - // Deferred: keep sampling so the check runs once the flight or scene ends. - else if (settleTimer === null) startSettling(); - }); - const removeMoveStart = camera.moveStart.addEventListener(startSettling); - - let active = true; - return () => { - if (!active) return; - active = false; - stopSettling(); - removeMoveEnd(); - removeMoveStart(); - for (const [target, type, listener] of listeners) - target?.removeEventListener?.(type, listener); - heldPointers.clear(); - }; -} - -/** - * Cesium.Viewer options of the standard globe viewer. `showRenderLoopErrors` - * false leaves render errors to the caller's own notice instead of Cesium's - * panel. - */ -export function applicationViewerOptions( - creditContainer, - { showRenderLoopErrors = true } = {}, -) { - return { - timeline: false, - animation: false, - baseLayerPicker: false, - geocoder: false, - homeButton: false, - sceneModePicker: false, - navigationHelpButton: false, - fullscreenButton: false, - vrButton: false, - selectionIndicator: false, - infoBox: false, - baseLayer: false, - // Replaces the blocky Tycho-2 default. An option, not `skyBox: false`, - // which would also stop CesiumWidget from creating the Sun and Moon. - skyBox: new StarrySky(), - creditContainer, - msaaSamples: 4, - contextOptions: { webgl: { preserveDrawingBuffer: true } }, - showRenderLoopErrors, - }; -} - -/** Create the standard globe viewer in caller-owned, visible containers. */ -export function createApplicationViewer({ - container, - creditContainer, - showRenderLoopErrors, -}) { - if (!container || !creditContainer) - throw new TypeError('Viewer and credit containers are required'); - const viewer = new Cesium.Viewer( - container, - applicationViewerOptions(creditContainer, { showRenderLoopErrors }), - ); - try { - // Until the render governor takes over (app/tools.js), tick at the idle - // rate so the startup load does not compete with drawing at 240 fps. - viewer.targetFrameRate = IDLE_FRAME_RATE; - // A phone pinch spans fewer screen pixels than desktop zoom gestures. - // Keep Cesium's distance-aware zoom and collision limits, with less travel - // required on touch-first screens. Mouse/trackpad sensitivity stays native. - if (globalThis.matchMedia?.('(pointer: coarse)').matches) - viewer.scene.screenSpaceCameraController.zoomFactor *= 3; - limitZoomOut(viewer); - // Before any tile builds a draw command: Cesium's per-vertex model - // atmosphere fails to LINK on Apple's Metal backend and kills the - // render loop. See app/atmosphereCompat.js. - applyModelAtmosphereWorkaround(viewer.scene); - viewer.scene.globe.show = false; - viewer.scene.skyAtmosphere.show = true; - viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18; - viewer.scene.skyAtmosphere.saturationShift = -0.12; - viewer.scene.skyAtmosphere.brightnessShift = -0.08; - return viewer; - } catch (error) { - viewer.destroy(); - throw error; - } -} diff --git a/src/awarenessEcho.js b/src/awarenessEcho.js index 44a5e37fa7..c0f712543a 100644 --- a/src/awarenessEcho.js +++ b/src/awarenessEcho.js @@ -6,11 +6,12 @@ * awareness policy of its own: the publisher passes radius, pulse timing and * echo styling in, so the overlay never imports awareness internals. */ -import * as Cesium from 'cesium'; +import { scaleToGeodeticSurface } from './geo/ellipsoid.js'; +import { distance } from './geo/vector.js'; /** * @typedef {object} AwarenessEchoField - * @property {Cesium.Cartesian3} center Subject's ground point. The publisher + * @property {{x: number, y: number, z: number}} center Subject's ground point. The publisher * may move it in place; it is read on every query. * @property {number} radiusM Range the pulses grow to. * @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse @@ -22,7 +23,6 @@ import * as Cesium from 'cesium'; /** @type {AwarenessEchoField|null} */ let field = null; let layerIds = new Set(); -const groundScratch = new Cesium.Cartesian3(); /** * Start (or replace) the echo field. @@ -104,7 +104,7 @@ export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) { * field is set or the layer does not echo. Distance is measured between * ground points, so an aircraft's altitude does not shift its echo. * @param {string} layerId Owning layer of the contact. - * @param {Cesium.Cartesian3} position Contact's world position. + * @param {{x: number, y: number, z: number}} position Contact's world position. * @param {number} nowMs Monotonic clock in milliseconds. * @returns {number} 0 to 1. */ @@ -112,16 +112,13 @@ export function awarenessEchoAt(layerId, position, nowMs) { if (!field || !position || !layerIds.has(layerId)) return 0; const level = field.level?.(nowMs) ?? 1; if (!(level > 0)) return 0; - const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( - position, - groundScratch, - ); + const ground = scaleToGeodeticSurface(position); if (!ground) return 0; return ( level * awarenessEchoStrength( nowMs, - Cesium.Cartesian3.distance(field.center, ground), + distance(field.center, ground), field.radiusM, field.pulse, field.echo, @@ -138,7 +135,7 @@ export function awarenessEchoAt(layerId, position, nowMs) { * outside the contact's bracket, 0 as the front arrives, growing to the * field's `spreadPx` as it fades. * @param {string} layerId Owning layer of the contact. - * @param {Cesium.Cartesian3} position Contact's world position. + * @param {{x: number, y: number, z: number}} position Contact's world position. * @param {number} nowMs Monotonic clock in milliseconds. * @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1. * @param {number} steps Alpha bands the overlay batches by. diff --git a/src/camera.js b/src/camera.js index 3fd49b58c0..57547071a2 100644 --- a/src/camera.js +++ b/src/camera.js @@ -1,36 +1,29 @@ -import * as Cesium from 'cesium'; +import { toRadians } from './geo/index.js'; +import { cameraOf } from './render/rendererOf.js'; /** - * Set camera to Austin on load with a cinematic fly-in. - * @returns {Function} Cancels the pending or active startup flight. + * The view the renderer starts from: the whole planet, looking straight + * down, centred where Cesium's default view rectangle is. */ -export function flyToAustin(viewer) { - // Start from a high altitude, then fly down - viewer.camera.setView({ - destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 25000), +export const START_VIEW = Object.freeze({ + lon: -82.5, + lat: 35, + height: 23000000, +}); + +/** + * Put the camera at a start view without a flight. A host may pass a city + * (`{ lon, lat, height, heading?, pitch? }`, angles in degrees) instead of + * the planet. + */ +export function applyStartView(viewer, view = START_VIEW) { + const { lon, lat, height, heading = 0, pitch = -90 } = view; + cameraOf(viewer).setView({ + destination: { lon, lat, height }, orientation: { - heading: Cesium.Math.toRadians(0), - pitch: Cesium.Math.toRadians(-90), - roll: 0.0, + heading: toRadians(heading), + pitch: toRadians(pitch), + roll: 0, }, }); - - // Cinematic fly-in after a brief pause - const timer = setTimeout(() => { - if (viewer.isDestroyed()) return; - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600), - orientation: { - heading: Cesium.Math.toRadians(15), - pitch: Cesium.Math.toRadians(-30), - roll: 0.0, - }, - duration: 4.0, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - }); - }, 500); - return () => { - clearTimeout(timer); - if (!viewer.isDestroyed()) viewer.camera.cancelFlight(); - }; } diff --git a/src/cameraGlobeRotation.test.mjs b/src/cameraGlobeRotation.test.mjs index 8c3f20df23..1952f25e3e 100644 --- a/src/cameraGlobeRotation.test.mjs +++ b/src/cameraGlobeRotation.test.mjs @@ -1,3 +1,14 @@ +import { + bindFakeCesiumCamera, + followEntity, + followedEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { rendererOf } from './render/rendererOf.js'; +import { followedOf } from './data/followed.js'; +import { + fakeSceneFrame, + fakeSceneQuery, +} from './testSupport/fakeCesiumScene.mjs'; import { GLOBE_VIEW } from './locations.js'; import { projectEarthDiscToViewport } from './celestialRing.js'; import assert from 'node:assert/strict'; @@ -13,11 +24,24 @@ import { moveCamera, } from './cameraVerbs.js'; import { getRenderGovernorDiagnostics } from './renderGovernor.js'; -import { - MIN_GLOBE_FRAME_SHARE, - globeFrameShare, - globeOutOfFrame, -} from './globeInView.js'; +import { MIN_GLOBE_FRAME_SHARE } from './globeInView.js'; +import * as globeInView from './globeInView.js'; + +// The frame measures take a camera pose; these read it off the real camera. +const framePose = (camera) => ({ + position: camera.positionWC, + direction: camera.directionWC, + up: camera.upWC, + right: camera.rightWC, + fovy: camera.frustum.fovy, + aspectRatio: camera.frustum.aspectRatio, + height: camera.positionCartographic.height, + pitch: camera.pitch, +}); +const globeFrameShare = (camera, options) => + globeInView.globeFrameShare(framePose(camera), options); +const globeOutOfFrame = (camera, options) => + globeInView.globeOutOfFrame(framePose(camera), options); import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js'; import { setScopeMaskEnabled } from './scopeMask.js'; @@ -136,7 +160,7 @@ function harness( mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL, mode: Cesium.SceneMode.SCENE3D, pixelRatio: 1, - tweens: [], + preUpdate: new Cesium.Event(), requestRender() {}, }; const camera = new Cesium.Camera(scene); @@ -154,13 +178,37 @@ function harness( roll: radians(roll), }, }); - const viewer = { + const double = { camera, scene, - trackedEntity: undefined, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. trackedEntityChanged: new Cesium.Event(), - clock: { onTick: new Cesium.Event() }, + entities: {}, }; + const viewer = bindFakeCesiumCamera(double, { + query: fakeSceneQuery(double), + frame: fakeSceneFrame(double), + }); + // Count who listens for the port's follow changes. + const renderer = rendererOf(viewer); + const port = renderer.camera; + let followListeners = 0; + renderer.camera = Object.create(port, { + on: { + value(event, cb, options) { + const off = port.on(event, cb, options); + if (event !== 'followChanged') return off; + followListeners += 1; + let live = true; + return () => { + if (live) followListeners -= 1; + live = false; + off(); + }; + }, + }, + }); const target = Cesium.Cartesian3.fromDegrees( longitudeDeg, latitude, @@ -174,73 +222,21 @@ function harness( }); const tick = (seconds = 0.1) => { nowMs += seconds * 1000; - viewer.clock.onTick.raiseEvent(viewer.clock); + viewer.scene.preUpdate.raiseEvent(viewer.scene); }; const finishOnce = () => { for (let i = 0; i < 20 && getActiveCameraMotion(); i += 1) tick(); assert.equal(getActiveCameraMotion(), null, 'once motion must finish'); }; - return { viewer, camera, canvas, target, tick, finishOnce }; -} - -for (const [name, sceneMode] of [ - ['2D', Cesium.SceneMode.SCENE2D], - ['Columbus', Cesium.SceneMode.COLUMBUS_VIEW], - ['morphing', Cesium.SceneMode.MORPHING], -]) { - test(`globe rotation refuses ${name} before changing the prior owner`, (t) => { - const { viewer, camera } = harness(t); - assert.equal( - moveCamera({ motion: 'rotate', direction: 'right', mode: 'continuous' }) - .ok, - true, - ); - const priorId = activeCameraMotionId(); - const before = pose(camera); - const transform = Cesium.Matrix4.clone(camera.transform); - viewer.scene.mode = sceneMode; - let handoffs = 0; - let cancellations = 0; - camera.cancelFlight = () => { - cancellations += 1; - }; - for (const mode of ['once', 'continuous']) { - const result = moveCamera( - { motion: 'rotate_globe', direction: 'left', mode }, - () => { - handoffs += 1; - return { ok: true }; - }, - ); - assert.equal(result.ok, false); - assert.match(result.error, /3D/); - } - assert.equal(handoffs, 0); - assert.equal(cancellations, 0); - assert.equal(activeCameraMotionId(), priorId); - assert.equal(hasRenderHold(), true); - assert.ok(Cesium.Matrix4.equals(camera.transform, transform)); - samePose(camera, before); - }); - - test(`active globe rotation yields to ${name} without changing the camera`, (t) => { - const { viewer, camera, tick } = harness(t); - assert.equal( - moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, - true, - ); - viewer.scene.mode = sceneMode; - const before = pose(camera); - let rotations = 0; - camera.rotate = () => { - rotations += 1; - }; - tick(); - assert.equal(rotations, 0); - assert.equal(getActiveCameraMotion(), null); - assert.equal(hasRenderHold(), false); - samePose(camera, before); - }); + return { + viewer, + camera, + canvas, + target, + tick, + finishOnce, + followListeners: () => followListeners, + }; } test('globe rotation yields to tracking acquired and cleared before the next tick', (t) => { @@ -251,15 +247,13 @@ test('globe rotation yields to tracking acquired and cleared before the next tic ); const before = pose(camera); const entity = { id: 'cockpit-aircraft', position: {} }; - viewer.trackedEntity = entity; - viewer.trackedEntityChanged.raiseEvent(entity); + followEntity(viewer, entity); assert.equal( getActiveCameraMotion(), null, 'tracking acquisition must synchronously yield', ); - viewer.trackedEntity = undefined; - viewer.trackedEntityChanged.raiseEvent(undefined); + followEntity(viewer, null); tick(); samePose(camera, before); assert.equal(hasRenderHold(), false); @@ -272,33 +266,34 @@ test('tracking event keeps legacy yaw and an untracked globe rotation active', ( true, ); const yawId = activeCameraMotionId(); - viewer.trackedEntityChanged.raiseEvent({ id: 'aircraft' }); + followEntity(viewer, { id: 'aircraft' }); assert.equal(activeCameraMotionId(), yawId); + followEntity(viewer, null); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, true, ); const globeId = activeCameraMotionId(); - viewer.trackedEntityChanged.raiseEvent(undefined); + followEntity(viewer, null); assert.equal(activeCameraMotionId(), globeId); }); test('replaced viewer releases the old tracking listener without duplicate subscriptions', (t) => { const first = harness(t); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 1); initCameraVerbs(first.viewer); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 1); const next = harness(t); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 0); - assert.equal(next.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 0); + assert.equal(next.followListeners(), 1); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, true, ); const id = activeCameraMotionId(); - first.viewer.trackedEntityChanged.raiseEvent({ id: 'stale-aircraft' }); + followEntity(first.viewer, { id: 'stale-aircraft' }); assert.equal(activeCameraMotionId(), id); - next.viewer.trackedEntityChanged.raiseEvent({ id: 'new-aircraft' }); + followEntity(next.viewer, { id: 'new-aircraft' }); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); }); @@ -534,7 +529,7 @@ test('replacement motion rejects a stale globe owner cancellation', (t) => { assert.equal(hasRenderHold(), false); }); -test('replacing the viewer retires globe motion and its old clock listener', (t) => { +test('replacing the viewer retires globe motion and its old frame listener', (t) => { const { viewer, camera, tick } = harness(t); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, @@ -542,15 +537,16 @@ test('replacing the viewer retires globe motion and its old clock listener', (t) ); tick(); const before = pose(camera); - const nextViewer = { - ...viewer, - clock: { onTick: new Cesium.Event() }, - }; + const nextScene = { ...viewer.scene, preUpdate: new Cesium.Event() }; + const nextViewer = bindFakeCesiumCamera( + { ...viewer, scene: nextScene }, + { frame: fakeSceneFrame({ scene: nextScene }) }, + ); initCameraVerbs(nextViewer); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); tick(); - nextViewer.clock.onTick.raiseEvent(nextViewer.clock); + nextScene.preUpdate.raiseEvent(nextScene); samePose(camera, before); }); @@ -580,7 +576,7 @@ for (const mode of ['once', 'continuous']) { tick(); assert.equal(hasRenderHold(), true); const tracked = { id: 'new-tracked-aircraft' }; - if (acquisition === 'tracking') viewer.trackedEntity = tracked; + if (acquisition === 'tracking') followEntity(viewer, tracked); else camera.lookAt( target, @@ -591,10 +587,9 @@ for (const mode of ['once', 'continuous']) { tick(); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); - assert.equal( - viewer.trackedEntity, - acquisition === 'tracking' ? tracked : undefined, - ); + if (acquisition === 'tracking') + assert.equal(followedEntity(viewer), tracked); + else assert.equal(followedOf(viewer), null); assert.equal(Cesium.Matrix4.equals(camera.transform, transform), true); samePose(camera, before); tick(); @@ -605,7 +600,7 @@ for (const mode of ['once', 'continuous']) { test('direct globe rotation refuses a tracked camera without disturbing its reference frame', (t) => { const { viewer, camera, target } = harness(t); - viewer.trackedEntity = { id: 'tracked-aircraft' }; + followEntity(viewer, { id: 'tracked-aircraft', name: 'tracked-aircraft' }); camera.lookAt(target, new Cesium.HeadingPitchRange(0, radians(-40), 1_000)); const before = pose(camera); const transform = Cesium.Matrix4.clone(camera.transform); @@ -676,18 +671,19 @@ test('close-up refusal preserves an inherited target frame', (t) => { }); test('navigation callback never releases tracking for globe rotation', (t) => { const { viewer, camera } = harness(t); - const tracked = (viewer.trackedEntity = { id: 'tracked-aircraft' }); + const tracked = { id: 'tracked-aircraft' }; + followEntity(viewer, tracked); const before = pose(camera); let calls = 0; assert.equal( moveCamera({ motion: 'rotate_globe' }, () => { calls++; - viewer.trackedEntity = undefined; + followEntity(viewer, null); }).ok, false, ); assert.equal(calls, 0); - assert.equal(viewer.trackedEntity, tracked); + assert.equal(followedEntity(viewer), tracked); samePose(camera, before); }); test('direct globe request refuses Cockpit before navigation mutation', (t) => { @@ -878,8 +874,8 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) height: owner === 'close-up' ? 5000 : GLOBE_VIEW.heightM, }); const before = pose(camera); - if (owner === 'tracking') viewer.trackedEntity = { id: 'tracked-aircraft' }; - const tracked = viewer.trackedEntity; + if (owner === 'tracking') followEntity(viewer, { id: 'tracked-aircraft' }); + const tracked = followedEntity(viewer); let releases = 0, stamps = 0; const styleManager = { @@ -893,7 +889,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) }, release() { releases++; - viewer.trackedEntity = undefined; + followEntity(viewer, null); }, navigate, }); @@ -915,7 +911,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) assert.equal(result.ok, false); assert.equal(releases, 0); assert.equal(stamps, 0); - assert.equal(viewer.trackedEntity, tracked); + assert.equal(followedEntity(viewer), tracked); samePose(camera, before); if (owner === 'close-up') { assert.equal(result.reason, 'globe-view-required'); @@ -926,29 +922,6 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) } }); -for (const [label, ellipsoid] of [ - ['nonfinite radii', { minimumRadius: 1, maximumRadius: Infinity }], - ['nonpositive radii', { minimumRadius: 0, maximumRadius: 1 }], - ['non-WGS84 radii', new Cesium.Ellipsoid(30_000_000, 30_000_000, 1_000_000)], -]) - test(`globe rotation refuses ${label} before handoff`, (t) => { - const { viewer, camera } = harness(t, { height: 100_000_000 }); - const before = pose(camera); - viewer.scene.globe.ellipsoid = ellipsoid; - let handedOff = false; - const result = moveCamera({ motion: 'rotate_globe' }, () => { - handedOff = true; - }); - assert.equal(result.ok, false); - assert.equal( - result.reason, - label === 'non-WGS84 radii' ? 'unsupported-view' : 'unsafe-ellipsoid', - ); - assert.equal(handedOff, false); - assert.equal(hasRenderHold(), false); - samePose(camera, before); - }); - test('an external radius change retires globe rotation without another write', (t) => { const { camera, tick } = harness(t); moveCamera({ motion: 'rotate_globe', mode: 'continuous' }); @@ -960,16 +933,6 @@ test('an external radius change retires globe rotation without another write', ( samePose(camera, changed); }); -test('a non-WGS84 ellipsoid fails closed rather than borrowing the WGS84 silhouette', (t) => { - const ellipsoid = new Cesium.Ellipsoid(10_000_000, 10_000_000, 8_000_000); - const { camera } = harness(t, { ellipsoid, latitude: 60 }); - const before = pose(camera); - const result = moveCamera({ motion: 'rotate_globe' }); - assert.equal(result.ok, false); - assert.equal(result.reason, 'unsupported-view'); - samePose(camera, before); -}); - test('untouched polar framing permits repeated direction and speed changes below preset altitude', (t) => { const { camera, finishOnce, tick } = harness(t, { latitude: 90 }); const radius = Cesium.Cartesian3.magnitude(camera.positionWC); @@ -1874,7 +1837,7 @@ test('a voice turn reported as done turns at least the half degree its check pro /** Track an entity below `camera`, locking it into that entity's frame. */ function trackFrom(viewer, camera) { - viewer.trackedEntity = { id: 'high-satellite' }; + followEntity(viewer, { id: 'high-satellite' }); const below = Cesium.Cartesian3.fromDegrees(10, 20, 400_000); camera.lookAtTransform(Cesium.Transforms.eastNorthUpToFixedFrame(below)); } @@ -1900,7 +1863,7 @@ test('a voice turn that releases a tracked camera is checked as released', (t) = }); trackFrom(viewer, camera); const releaseThenRun = (start) => { - viewer.trackedEntity = undefined; + followEntity(viewer, null); camera.lookAtTransform(Cesium.Matrix4.IDENTITY); return start(); }; @@ -1941,14 +1904,14 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => { for (let j = 0; j < 600 && getActiveCameraMotion(); j += 1) tick(1 / 60); } trackFrom(viewer, camera); - const tracked = viewer.trackedEntity; + const tracked = followedEntity(viewer); const transform = Cesium.Matrix4.clone(camera.transform); let released = false; const result = moveCamera( { motion: 'tilt', direction: 'up', mode: 'once' }, (start) => { released = true; - viewer.trackedEntity = undefined; + followEntity(viewer, null); camera.lookAtTransform(Cesium.Matrix4.IDENTITY); return start(); }, @@ -1957,7 +1920,7 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => { assert.equal(result.ok, false, label); assert.match(result.error, /globe out of view/, label); assert.equal(released, false, label); - assert.equal(viewer.trackedEntity, tracked, label); + assert.equal(followedEntity(viewer), tracked, label); assert.ok(Cesium.Matrix4.equals(camera.transform, transform), label); } }); @@ -1988,27 +1951,6 @@ test('a turn proven at one position is checked again after a release moves the c assert.match(result.error, /globe out of view/); }); -test('the voice frame limit leaves Columbus view alone', (t) => { - // At its limit in 3D a further tilt up is refused; the same tilt in Columbus - // view is not limited by the frame. - withScope(t, false); - const { viewer, finishOnce } = harness(t, { - pitch: -80, - viewportWidth: 1600, - viewportHeight: 900, - }); - assert.equal( - moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }).ok, - true, - ); - finishOnce(); - const refused = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); - assert.match(refused.error || '', /globe out of view/); - viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; - const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); - assert.doesNotMatch(result.error || '', /globe out of view/); -}); - test('voice tilt below the free-look height is not limited by the frame', (t) => { const { camera, finishOnce } = harness(t, { height: 500_000, pitch: -60 }); const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); diff --git a/src/cameraGroundGuard.js b/src/cameraGroundGuard.js index 3f9de0cabe..07c5431eaa 100644 --- a/src/cameraGroundGuard.js +++ b/src/cameraGroundGuard.js @@ -14,8 +14,11 @@ * lifts the eye if it sits below a usable clearance. Heading and pitch are * held, so the correction reads as the shot settling. */ -import * as Cesium from 'cesium'; +import { onFollowChanged } from './data/followed.js'; import { ownCameraArrival } from './data/cameraArrival.js'; +import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js'; +import { heightsOf } from './queries/heights.js'; +import { canvasOf, findCamera } from './render/rendererOf.js'; /** Minimum eye height above the rendered surface for a usable view. */ export const MIN_EYE_CLEARANCE_M = 120; @@ -24,35 +27,79 @@ const GUARD_ATTEMPTS = 8; const GUARD_INTERVAL_MS = 600; /** Ignore sub-metre noise rather than nudging the camera forever. */ const GUARD_EPSILON_M = 2; - -const probeScratch = new Cesium.Cartographic(); +/** Eye travel (m) and turn (cosine) that mean another owner moved the camera. */ +const MOVED_M = 0.01; +const TURNED_COS = 1 - 1e-9; /** * Highest rendered surface across a few cells, with how many cells answered. * A cell whose tiles are not streamed yet contributes nothing. - * @param {Cesium.Scene} scene Live scene. + * @param {import('./queries/heights.js').HeightService|null} heights The + * scene's height service. * @param {Array<{lat: number, lon: number}>} cells Cells to probe. * @returns {{heightM: number, sampled: number}} Reading. */ -function sampleSurfaceM(scene, cells) { +function sampleSurfaceM(heights, cells) { let heightM = Number.NaN; let sampled = 0; - if (typeof scene?.sampleHeight !== 'function') return { heightM, sampled }; + if (!heights) return { heightM, sampled }; for (const cell of cells) { - try { - const height = scene.sampleHeight( - Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch), - ); - if (!Number.isFinite(height)) continue; - sampled += 1; - heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; - } catch { - /* tiles not ready for this cell */ - } + // A miss is a cell whose tiles are not ready. + const height = heights.now(cell); + if (!Number.isFinite(height)) continue; + sampled += 1; + heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; } return { heightM, sampled }; } +/** + * The eye as the camera port poses it: where it is (from its position) and + * which way it looks; null when the pose cannot be read. + */ +function eyeOf(camera) { + try { + const pose = camera?.pose(); + const at = pose?.position && toLonLatH(pose.position); + if (!at || !pose.direction || !pose.up) return null; + return { ...pose, lon: at.lon, lat: at.lat, height: at.height }; + } catch { + return null; + } +} + +/** The eye's ground point (height 0), its height, and which way it looks. */ +function poseOf(eye) { + if (!eye) return null; + return { + ground: fromDegrees(eye.lon, eye.lat), + height: eye.height, + direction: { ...eye.direction }, + up: { ...eye.up }, + }; +} + +/** + * Whether another owner has moved the camera off `pose`: across the ground, + * down, or around. A pure rise is not one: the renderer's terrain collision + * lifts a buried eye straight up as tiles load, which is the case the guard + * exists for, so `pose` follows the highest eye seen and the guard keeps + * measuring. + */ +function moved(now, pose) { + if (!now) return true; + const ground = fromDegrees(now.lon, now.lat); + if ( + distance(ground, pose.ground) > MOVED_M || + now.height < pose.height - MOVED_M || + dot(now.direction, pose.direction) < TURNED_COS || + dot(now.up, pose.up) < TURNED_COS + ) + return true; + pose.height = Math.max(pose.height, now.height); + return false; +} + /** * How far the camera must rise to clear the ground, given a measured surface. * Pure so the policy is testable without a scene. @@ -76,9 +123,11 @@ export function groundClearanceDeficitM( * Watch an arrival and lift the camera once the real surface can be measured. * * Stops quietly on a clear view, exhausted attempts, the user taking the - * controls (pointer or wheel on the canvas), or `isStale()` reporting that a - * newer arrival owns the camera. - * @param {Cesium.Viewer} viewer Live viewer. + * controls (pointer or wheel on the canvas), `isStale()` reporting that a + * newer arrival owns the camera, or any other caller moving the camera or + * starting a flight in the meantime: the guard only ever corrects the pose it + * was started on. + * @param {object} viewer Live viewer. * @param {{lat: number, lon: number}} at Destination being framed. * @param {{clearanceM?: number, attempts?: number, intervalMs?: number, * isStale?: () => boolean, onLift?: (liftM: number) => void}} [options] @@ -92,12 +141,16 @@ export function guardCameraAboveGround(viewer, at, options = {}) { isStale = () => false, onLift = null, } = options; - if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon)) + if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon)) return () => {}; + // Without a readable pose the guard could not tell a later owner's move. + const arrival = poseOf(eyeOf(findCamera(viewer))); + if (!arrival) return () => {}; + let timer = null; let done = false; - const canvas = viewer.scene.canvas; + const canvas = canvasOf(viewer); const documentRef = canvas?.ownerDocument; const removers = []; let release = () => {}; @@ -112,32 +165,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) { release(); }; release = ownCameraArrival(viewer, stop); - // Direct camera API callers (including duration-zero flights) must yield - // before moving the eye. Restore the exact method ownership on completion. - for (const name of [ - 'flyTo', - 'flyToBoundingSphere', - 'setView', - 'lookAt', - 'cancelFlight', - ]) { - const camera = viewer.camera; - const original = camera[name]; - if (typeof original !== 'function') continue; - const descriptor = Object.getOwnPropertyDescriptor(camera, name); - const wrapped = function (...args) { - stop(); - return original.apply(this, args); - }; - camera[name] = wrapped; - removers.push(() => { - if (camera[name] !== wrapped) return; - if (descriptor) Object.defineProperty(camera, name, descriptor); - else delete camera[name]; - }); - } - const removeTracking = viewer.trackedEntityChanged?.addEventListener(stop); - if (removeTracking) removers.push(removeTracking); + removers.push(onFollowChanged(viewer, stop)); documentRef?.addEventListener?.('keydown', stop, true); // A manual gesture ends the guard, as it interrupts camera motion elsewhere. for (const type of ['pointerdown', 'wheel']) @@ -147,40 +175,33 @@ export function guardCameraAboveGround(viewer, at, options = {}) { const attempt = () => { if (done) return; if (isStale() || viewer.isDestroyed?.()) return stop(); + const camera = findCamera(viewer); + const now = eyeOf(camera); + // Another caller owns the camera now; lifting would undo its move. + if (!camera || camera.flying || moved(now, arrival)) return stop(); remaining -= 1; - const camera = viewer.camera; - const carto = camera.positionCartographic; // The eye must clear both the framed target and the ground beneath it. - const below = { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; - const { heightM, sampled } = sampleSurfaceM(viewer.scene, [ - { lat: at.lat, lon: at.lon }, - below, - ]); + const below = { lat: now.lat, lon: now.lon }; + const { heightM, sampled } = sampleSurfaceM( + viewer ? heightsOf(viewer) : null, + [{ lat: at.lat, lon: at.lon }, below], + ); if (sampled > 0 && Number.isFinite(heightM)) { - const deficit = groundClearanceDeficitM( - carto.height, - heightM, - clearanceM, - ); + const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM); if (deficit > 0) { stop(); - camera.flyTo({ - destination: Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height + deficit, - ), - orientation: { - heading: camera.heading, - pitch: camera.pitch, - roll: camera.roll, + camera.flyTo( + { lon: now.lon, lat: now.lat, height: now.height + deficit }, + { + orientation: { + heading: now.heading, + pitch: now.pitch, + roll: now.roll, + }, + durationS: 0.9, + easing: 'cubicInOut', }, - duration: 0.9, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - }); + ); try { onLift?.(deficit); } catch { diff --git a/src/cameraGroundGuard.test.mjs b/src/cameraGroundGuard.test.mjs index 5c8f530303..fb751ce2a3 100644 --- a/src/cameraGroundGuard.test.mjs +++ b/src/cameraGroundGuard.test.mjs @@ -3,6 +3,12 @@ // Arrival framing is computed before the destination's tiles exist, so it // works from a predicted ground height. The guard measures the real surface // after arrival and lifts the eye; these tests pin when it acts. +import { + bindFakeCesiumCamera, + followEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { rendererOf } from './render/rendererOf.js'; +import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; @@ -47,24 +53,71 @@ test('the clearance frames a subject without turning into an overflight', () => assert.ok(MIN_EYE_CLEARANCE_M <= 250); }); -function fakeViewer({ cameraHeightM, surfaceM }) { +/** + * Count the listeners for `viewer`'s camera port follow changes, from now on. + * @returns {() => number} + */ +function countFollowListeners(viewer) { + const renderer = rendererOf(viewer); + const port = renderer.camera; + let listeners = 0; + renderer.camera = Object.create(port, { + on: { + value(event, cb, options) { + const off = port.on(event, cb, options); + if (event !== 'followChanged') return off; + listeners += 1; + let live = true; + return () => { + if (live) listeners -= 1; + live = false; + off(); + }; + }, + }, + }); + return () => listeners; +} + +function fakeViewer({ cameraHeightM, surfaceM, tracks = false }) { const flights = []; - const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM); - return { + const position = Cesium.Cartographic.fromDegrees( + -97.7603, + 30.3141, + cameraHeightM, + ); + const viewer = { flights, scene: { canvas: null, + sampleHeightSupported: true, sampleHeight: (carto) => typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM, }, camera: { positionCartographic: position, + positionWC: Cesium.Cartographic.toCartesian(position), + directionWC: new Cesium.Cartesian3(0, 0, -1), + upWC: new Cesium.Cartesian3(0, 1, 0), heading: 0.5, pitch: -0.55, roll: 0, - flyTo: (options) => flights.push(options), + // As Cesium does: a flight is under way until it completes. + _currentFlight: undefined, + flyTo(options) { + flights.push(options); + this._currentFlight = {}; + }, }, }; + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. + if (tracks) + Object.assign(viewer, { + trackedEntityChanged: new Cesium.Event(), + entities: {}, + }); + return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) }); } test('the guard lifts a buried arrival once the surface answers', async () => { @@ -104,7 +157,11 @@ test('the guard waits for streaming tiles and yields to a newer arrival', async test('the guard leaves a clear view untouched', async () => { const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 }); - guardCameraAboveGround(viewer, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 1 }, + ); await new Promise((resolve) => setTimeout(resolve, 20)); assert.equal(viewer.flights.length, 0); }); @@ -116,39 +173,85 @@ import { LayerLifecycle } from './data/lifecycle.js'; function handoffFixture(t) { t.mock.timers.enable({ apis: ['setTimeout'] }); - const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + const viewer = fakeViewer({ + cameraHeightM: 172, + surfaceM: 171, + tracks: true, + }); + const followListeners = countFollowListeners(viewer); viewer.scene.canvas = new EventTarget(); viewer.scene.canvas.ownerDocument = new EventTarget(); - viewer.trackedEntityChanged = new Cesium.Event(); viewer.camera.cancelFlight = () => {}; viewer.camera.lookAtTransform = () => {}; - viewer.camera.flyToBoundingSphere = () => {}; - viewer.camera.setView = () => {}; + viewer.camera.flyToBoundingSphere = function () { + this._currentFlight = {}; + }; + viewer.camera.setView = function () { + this.positionWC = Cesium.Cartesian3.add( + this.positionWC, + new Cesium.Cartesian3(0, 0, 50), + new Cesium.Cartesian3(), + ); + }; const originalFly = viewer.camera.flyTo; const navigation = new NavigationController({ viewer, - tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer', - 'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer', - 'rocketLaunchesLayer'].map((key) => [key, {}])), - cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {}, - getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {}, - isCockpitActive: () => false, showToast() {}, + tracking: Object.fromEntries( + [ + 'flightsLayer', + 'militaryFlightsLayer', + 'satellitesLayer', + 'aisLiveVesselsLayer', + 'militaryAwarenessLayer', + 'rocketLaunchesLayer', + ].map((key) => [key, {}]), + ), + cancelOrientation() {}, + clearLocation() {}, + cancelShareSelection() {}, + getDataManager() {}, + interruptCameraMotion() {}, + stopOrbit() {}, + isCockpitActive: () => false, + showToast() {}, }); guardCameraAboveGround(viewer, { lat: 30.3, lon: -97.7 }); - return { viewer, navigation, originalFly }; + return { viewer, navigation, originalFly, followListeners }; } -for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI', - 'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) { +for (const handoff of [ + 'Director', + 'tracking', + 'follow', + 'keyboard', + 'UI', + 'flyTo', + 'flyToBoundingSphere', + 'setView', + 'layer-disable', + 'layer-destroy', + 'app-stop', +]) { test(`arrival guard relinquishes and removes hooks on ${handoff}`, async (t) => { - const { viewer, navigation, originalFly } = handoffFixture(t); + const { viewer, navigation, originalFly, followListeners } = + handoffFixture(t); + const methods = [ + 'flyTo', + 'flyToBoundingSphere', + 'setView', + 'lookAt', + 'cancelFlight', + ].map((name) => viewer.camera[name]); if (handoff === 'Director') { SceneDirector.prototype._claimCameraOwnership.call({ - viewer, styleManager: { runImmediateNavigation: (noun, fn) => - navigation._runExplicitNavigation(noun, fn) }, + viewer, + styleManager: { + runImmediateNavigation: (noun, fn) => + navigation._runExplicitNavigation(noun, fn), + }, }); } else if (handoff === 'tracking') { - viewer.trackedEntityChanged.raiseEvent({ id: 'contact' }); + followEntity(viewer, { id: 'contact' }); } else if (handoff === 'follow' || handoff === 'UI') { navigation._stampNavigation({ cancelPendingSelection: false }); } else if (handoff === 'keyboard') { @@ -156,16 +259,81 @@ for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI', } else if (handoff === 'app-stop') navigation.stop(); else if (handoff.startsWith('layer-')) { const lifecycle = new LayerLifecycle(viewer); - lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} }); + lifecycle.register({ + id: 'test', + init() {}, + enable() {}, + disable() {}, + destroy() {}, + }); await lifecycle.setEnabled('test', true); - if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false); + if (handoff === 'layer-disable') + await lifecycle.setEnabled('test', false); else await lifecycle.destroyLayer('test'); } else viewer.camera[handoff]({}); + // A direct flyTo is itself one recorded flight; the guard adds none. const priorFlights = viewer.flights.length; t.mock.timers.tick(10000); - assert.equal(viewer.flights.length, priorFlights, 'the old probe cannot fly'); - assert.equal(viewer.camera.flyTo, originalFly, 'direct-call hook is removed'); - assert.equal(viewer.trackedEntityChanged.numberOfListeners, 0); + assert.equal( + viewer.flights.length, + priorFlights, + 'the old probe cannot fly', + ); + assert.equal(viewer.camera.flyTo, originalFly); + assert.deepEqual( + ['flyTo', 'flyToBoundingSphere', 'setView', 'lookAt', 'cancelFlight'].map( + (name) => viewer.camera[name], + ), + methods, + 'the guard never replaces camera methods', + ); + assert.equal(followListeners(), 0); navigation.destroy(); }); } + +test('the guard yields to a camera moved without any camera method', async () => { + const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + // A cockpit or follow frame writes the pose directly. + viewer.camera.directionWC = new Cesium.Cartesian3(1, 0, 0); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(viewer.flights.length, 0, 'the moved view is not corrected'); +}); + +test('Cesium lifting a buried eye straight up is not another owner', async () => { + const viewer = fakeViewer({ cameraHeightM: 104, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + // Terrain collision raises the eye to just above the loaded ground. + const raised = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 172); + viewer.camera.positionCartographic = raised; + viewer.camera.positionWC = Cesium.Cartographic.toCartesian(raised); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(viewer.flights.length, 1, 'the guard still lifts the eye'); + const lifted = Cesium.Cartographic.fromCartesian( + viewer.flights[0].destination, + ); + assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5); +}); + +test('another owner lowering the eye is not corrected', async () => { + const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + const lowered = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 150); + viewer.camera.positionCartographic = lowered; + viewer.camera.positionWC = Cesium.Cartographic.toCartesian(lowered); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(viewer.flights.length, 0); +}); diff --git a/src/cameraHandoff.test.mjs b/src/cameraHandoff.test.mjs index 1c41139c8a..747a2f0a97 100644 --- a/src/cameraHandoff.test.mjs +++ b/src/cameraHandoff.test.mjs @@ -44,8 +44,8 @@ test('Cockpit takeover invalidates deferred work before camera cancellation', () ordered(enter, [ 'if (!info || (!vessel && !satellite && !entity?.position)) return false;', 'this.onCameraTakeover?.();', - 'this.viewer.camera.cancelFlight();', - 'this.viewer.trackedEntity = undefined;', + 'cameraOf(this.viewer).cancelFlight();', + 'stopFollowing(this.viewer);', ], 'Cockpit takeover'); assert.match( ui, @@ -97,7 +97,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () => // The transaction has exactly two camera-owner mutations, and each one // stamps: // 1. selectedLayer.trackById(id) -> viewer.trackedEntity - // -> viewer.trackedEntityChanged -> _stampNavigation() + // -> onFollowChanged(viewer) -> _stampNavigation() // 2. cockpitView.enter() -> onCameraTakeover() -> _stampNavigation() const transaction = body( cockpitTracking, @@ -118,7 +118,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () => // Seam 1: any tracker handoff stamps, so the adoption step is covered. assert.match( ui, - /viewer\.trackedEntityChanged\.addEventListener\(\s*\(entity\) => \{\s*if \(entity && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/, + /onFollowChanged\(\s*this\.viewer,\s*\(followed\) => \{\s*if \(followed && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/, 'tracker handoff must stamp', ); // Seam 2 is pinned by "Cockpit takeover invalidates deferred work" above. @@ -191,10 +191,10 @@ test('accepted navigation releases through PR15-aware ownership before flight', 'origin: trackingOrigin', 'satellitesLayer.stopTracking?.({ origin: trackingOrigin })', 'rocketLaunchesLayer.releaseCameraOwnership?.()', - 'this.viewer.trackedEntity = undefined;', + 'stopFollowing(this.viewer);', "interruptCameraMotion('explicit-navigation')", - 'this.viewer.camera.cancelFlight();', - 'this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);', + 'camera?.cancelFlight();', + 'camera?.release();', ], 'follow release'); assert.match(release, /flightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/); assert.match(release, /militaryFlightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/); @@ -282,11 +282,11 @@ test('a direct globe gesture retires delayed camera and selection restore only', ); assert.match( ui, - /viewer\?\.canvas\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/, + /canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/, ); assert.match( ui, - /viewer\?\.canvas\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/, + /canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/, ); assert.match( ui, @@ -399,7 +399,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () => } const vesselClick = body( vessels, - /handler\.setInputAction\(\s*\(click\) => \{([\s\S]*?)\n\s*\},\s*Cesium\.ScreenSpaceEventType\.LEFT_CLICK,?\s*\);/, + /inputFor\(viewer\)\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/, 'vessel click', ); ordered(vesselClick, [ @@ -415,7 +415,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () => assert.match(vesselFocus, /requestWorldFocus\(\{/); const fireClick = body( firms, - /_clickHandler\.setInputAction\(\(click\) => \{([\s\S]*?)\n \}, Cesium\.ScreenSpaceEventType\.LEFT_CLICK\);/, + /input\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/, 'fire click', ); ordered(fireClick, [ diff --git a/src/cameraTilt.test.mjs b/src/cameraTilt.test.mjs index 8a3d1447f0..cac0d7e14f 100644 --- a/src/cameraTilt.test.mjs +++ b/src/cameraTilt.test.mjs @@ -9,6 +9,14 @@ import { moveCamera, } from './cameraVerbs.js'; import { createGevActionRunner } from './voice/gevActions.js'; +import { + bindFakeCesiumCamera, + followEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { + fakeSceneFrame, + fakeSceneQuery, +} from './testSupport/fakeCesiumScene.mjs'; const radians = Cesium.Math.toRadians; const degrees = Cesium.Math.toDegrees; @@ -39,6 +47,7 @@ function harness( mode: Cesium.SceneMode.SCENE3D, pixelRatio: 1, tweens: [], + preUpdate: new Cesium.Event(), requestRender() {}, }; const camera = new Cesium.Camera(scene); @@ -47,13 +56,21 @@ function harness( destination: Cesium.Cartesian3.fromDegrees(-0.1276, 51.5072, height), orientation: { heading: radians(heading), pitch: radians(pitch), roll: 0 }, }); - const viewer = { + const double = { camera, scene, - trackedEntity: undefined, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. trackedEntityChanged: new Cesium.Event(), + entities: {}, clock: { onTick: new Cesium.Event() }, }; + // The Cesium renderer's own camera port over the real camera; frames from + // the scene's preUpdate. + const viewer = bindFakeCesiumCamera(double, { + query: fakeSceneQuery(double), + frame: fakeSceneFrame(double), + }); // The app's view target: the ground point under the screen centre. const viewTarget = () => { const ray = new Cesium.Ray(camera.positionWC, camera.directionWC); @@ -68,7 +85,7 @@ function harness( }); const tick = (seconds = 1 / 30) => { nowMs += seconds * 1000; - viewer.clock.onTick.raiseEvent(viewer.clock); + viewer.scene.preUpdate.raiseEvent(viewer.scene); }; const finish = () => { for (let i = 0; i < 600 && getActiveCameraMotion(); i += 1) tick(); @@ -239,9 +256,7 @@ test('a pivoting tilt yields when tracking takes the camera', (t) => { const h = harness(t); assert.equal(moveCamera({ motion: 'tilt', pitchDeg: -45 }).ok, true); h.tick(); - const entity = { id: 'tracked' }; - h.viewer.trackedEntity = entity; - h.viewer.trackedEntityChanged.raiseEvent(entity); + followEntity(h.viewer, { id: 'tracked' }); assert.equal(getActiveCameraMotion(), null); }); @@ -548,10 +563,10 @@ test('a regional tilt-up nudge goes to the camera horizon limit', (t) => { test('a voice tilt from a tracked view judges its limit from the camera pitch', (t) => { const h = harness(t, { height: 20000, pitch: -5.2 }); - h.viewer.trackedEntity = { id: 'tracked' }; + followEntity(h.viewer, { id: 'tracked' }); // Voice releases the follow camera before the motion starts. const release = (start) => { - h.viewer.trackedEntity = undefined; + followEntity(h.viewer, null); return start(); }; const result = moveCamera({ motion: 'tilt', direction: 'up' }, release); diff --git a/src/cameraVerbs.js b/src/cameraVerbs.js index 5ac86bc365..ce61912b88 100644 --- a/src/cameraVerbs.js +++ b/src/cameraVerbs.js @@ -18,13 +18,14 @@ * globe motion, opposite to the camera's travel around Earth. */ -import * as Cesium from 'cesium'; +import { followedOf, isFollowing, onFollowChanged } from './data/followed.js'; import { GLOBE_VIEW } from './locations.js'; import { globeFrameShare, isFreeGlobeCamera, lookAngleWithinFrame, lookStepLosesGlobe, + lookedPose, } from './globeInView.js'; import { projectEarthDiscToViewport, @@ -37,6 +38,43 @@ import { holdContinuousRender, releaseContinuousRender, } from './renderGovernor.js'; +import { + PI_OVER_TWO, + WGS84, + add, + clamp, + cross, + distance, + dot, + eastNorthUp, + framePoint, + fromAxisAngle, + fromDegrees, + fromRadians, + frameVector, + geodeticSurfaceNormal, + headingPitchRollFrame, + inverseFramePoint, + lerpInto, + magnitude, + negativePiToPi, + normalize, + scale, + sub, + toAxes, + toCartographicRadians, + toDegrees, + toRadians, + vec, +} from './geo/index.js'; +import { eyeMoved, eyeRotatedAbout, eyeTurned } from './geo/eyeMoves.js'; +import { heightsOf } from './queries/heights.js'; +import { + cameraOf, + canvasOf, + findCamera, + findFrame, +} from './render/rendererOf.js'; let _isCockpitActive = null; /** °/s by speed word — orbit; pan uses fractions of view height/s. */ @@ -54,8 +92,8 @@ const ONCE = { panViewFraction: 0.25, durationS: 0.9, }; -const PITCH_MIN = Cesium.Math.toRadians(-89); -const PITCH_MAX = Cesium.Math.toRadians(-5); +const PITCH_MIN = toRadians(-89); +const PITCH_MAX = toRadians(-5); /** A bare "tilt the camera" / "oblique view" settles here. */ const TILT_DEFAULT_PITCH_DEG = -45; /** °/s for a tilt to a requested angle; short ones keep the once duration. */ @@ -82,7 +120,7 @@ const TILT_PIVOT_RANGE_SLACK_M = 1; * place's horizon; tilting the rest in place there would lift the crosshair * onto the sky, so the swing stops with the place this far above it. */ -const TILT_MIN_PIVOT_ELEVATION = Cesium.Math.toRadians(0.5); +const TILT_MIN_PIVOT_ELEVATION = toRadians(0.5); /* ── Route dolly: cinematic tuning ────────────────────────────────────────── * Every knob an owner may want to retune lives in this block. The shaping is @@ -341,30 +379,30 @@ export const ROUTE_CINEMA = Object.freeze({ /* ── Route dolly geometry ────────────────────────────────────────────────── */ -const _arcA = new Cesium.Cartesian3(); -const _arcB = new Cesium.Cartesian3(); -const _chordVertical = new Cesium.Cartesian3(); -const _turnCross = new Cesium.Cartesian3(); -const _framePos = new Cesium.Cartesian3(); -const _frameAheadPos = new Cesium.Cartesian3(); -const _frameUp = new Cesium.Cartesian3(); -const _frameIn = new Cesium.Cartesian3(); -const _frameOut = new Cesium.Cartesian3(); -const _frameGaze = new Cesium.Cartesian3(); -const _frameRight = new Cesium.Cartesian3(); -const _frameLevelUp = new Cesium.Cartesian3(); -const _frameDir = new Cesium.Cartesian3(); -const _frameEye = new Cesium.Cartesian3(); -const _frameBankedUp = new Cesium.Cartesian3(); -const _frameCarto = new Cesium.Cartographic(); -const _frameAheadCarto = new Cesium.Cartographic(); -const _bankQuat = new Cesium.Quaternion(); -const _bankMatrix = new Cesium.Matrix3(); -const _headingQuat = new Cesium.Quaternion(); -const _headingMatrix = new Cesium.Matrix3(); -const _warmPos = new Cesium.Cartesian3(); -const _warmCarto = new Cesium.Cartographic(); -const _probeCarto = new Cesium.Cartographic(); +/** Scratch points for the per-frame arc reads. */ +const _arcA = vec(); +const _arcB = vec(); +const _framePos = vec(); +const _frameAheadPos = vec(); +const _warmPos = vec(); + +/** `v` turned by `angle` radians about `axis`: quaternion, then its axes. */ +const rotateAbout = (v, axis, angle) => + frameVector(toAxes(fromAxisAngle(axis, angle)), v); + +/** `v` less its part along unit `up`. */ +function horizontalPart(v, up) { + const along = dot(v, up); + return vec(v.x - up.x * along, v.y - up.y * along, v.z - up.z * along); +} + +/** The ellipsoid's unit normal at geodetic `lon`, `lat` (radians). */ +function surfaceNormal(lon, lat) { + const cosLat = Math.cos(lat); + return normalize( + vec(cosLat * Math.cos(lon), cosLat * Math.sin(lon), Math.sin(lat)), + ); +} /** Point at arc length `s` along the polyline (binary search — queries jump * backwards for the inbound chord, so a forward cursor would not do). */ @@ -381,23 +419,17 @@ function arcPoint(state, s, result) { const segLen = cumM[lo + 1] - cumM[lo]; const t = segLen > 1e-6 ? Math.min(1, Math.max(0, (clamped - cumM[lo]) / segLen)) : 0; - return Cesium.Cartesian3.lerp(pts[lo], pts[lo + 1], t, result); + return lerpInto(pts[lo], pts[lo + 1], t, result); } /** Unit horizontal direction from arc `sA` to arc `sB`, or null when degenerate. */ -function horizontalChord(state, sA, sB, up, result) { +function horizontalChord(state, sA, sB, up) { const a = arcPoint(state, sA, _arcA); const b = arcPoint(state, sB, _arcB); - Cesium.Cartesian3.subtract(b, a, result); - const vertical = Cesium.Cartesian3.multiplyByScalar( - up, - Cesium.Cartesian3.dot(result, up), - _chordVertical, - ); - Cesium.Cartesian3.subtract(result, vertical, result); - const len = Cesium.Cartesian3.magnitude(result); + const horizontal = horizontalPart(vec(b.x - a.x, b.y - a.y, b.z - a.z), up); + const len = magnitude(horizontal); if (!(len > 1e-3)) return null; - return Cesium.Cartesian3.divideByScalar(result, len, result); + return vec(horizontal.x / len, horizontal.y / len, horizontal.z / len); } /** @@ -407,15 +439,14 @@ function horizontalChord(state, sA, sB, up, result) { * floating-point signed zeros, so an out-and-back route would flip the bank * direction frame to frame. A U-turn is resolved as a RIGHT turn, always — * arbitrary, but deterministic, which is the property that matters. - * @param {Cesium.Cartesian3} a Unit horizontal direction turned FROM. - * @param {Cesium.Cartesian3} b Unit horizontal direction turned TO. - * @param {Cesium.Cartesian3} up Local up, the axis the turn is measured about. + * @param {{x: number, y: number, z: number}} a Unit horizontal direction turned FROM. + * @param {{x: number, y: number, z: number}} b Unit horizontal direction turned TO. + * @param {{x: number, y: number, z: number}} up Local up, the axis the turn is measured about. * @returns {number} Radians, + = right. */ export function signedTurnRad(a, b, up) { - const cross = Cesium.Cartesian3.cross(a, b, _turnCross); - const sinLeft = Cesium.Cartesian3.dot(cross, up); - const cosTurn = Cesium.Cartesian3.dot(a, b); + const sinLeft = dot(cross(a, b), up); + const cosTurn = dot(a, b); if (cosTurn <= -1 + ANTIPODAL_EPS && Math.abs(sinLeft) < ANTIPODAL_EPS) return Math.PI; return -Math.atan2(sinLeft, cosTurn); @@ -447,14 +478,9 @@ export function routeCorridorCells( s <= end + 1e-6 && out.length < maxCells; s += ROUTE_WARM_STEP_M ) { - const point = arcPoint(state, s, _warmPos); - const carto = Cesium.Cartographic.fromCartesian( - point, - Cesium.Ellipsoid.WGS84, - _warmCarto, - ); - const lat = Number(Cesium.Math.toDegrees(carto.latitude).toFixed(3)); - const lon = Number(Cesium.Math.toDegrees(carto.longitude).toFixed(3)); + const carto = toCartographicRadians(arcPoint(state, s, _warmPos)); + const lat = Number(toDegrees(carto.lat).toFixed(3)); + const lon = Number(toDegrees(carto.lon).toFixed(3)); const key = `${lat},${lon}`; if (seen.has(key)) continue; seen.add(key); @@ -587,32 +613,24 @@ function acquireCorridorFloor(state, takeWhole) { * Highest rendered surface across a handful of corridor cells, with the number * of cells that actually answered — a cell whose tiles are not streamed yet * contributes nothing, and the caller must not mistake silence for flat ground. - * @param {Cesium.Scene|undefined} scene The live scene. + * @param {object|undefined} viewer The live scene object, asked through its + * renderer's heights (`heightsOf`). * @param {Array<{lat: number, lon: number}>} cells Cells to probe. * @returns {{heightM: number, sampled: number, requested: number}} The reading. */ -export function probeMeshFloorM(scene, cells) { +export function probeMeshFloorM(viewer, cells) { const requested = Array.isArray(cells) ? cells.length : 0; const empty = { heightM: Number.NaN, sampled: 0, requested }; - if (!scene || typeof scene.sampleHeight !== 'function' || !requested) - return empty; + if (!viewer || !requested) return empty; + const heights = heightsOf(viewer); let heightM = Number.NaN; let sampled = 0; for (const cell of cells) { - try { - const carto = Cesium.Cartographic.fromDegrees( - cell.lon, - cell.lat, - 0, - _probeCarto, - ); - const height = scene.sampleHeight(carto); - if (!Number.isFinite(height)) continue; - sampled += 1; - heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; - } catch { - /* tiles not ready for this cell */ - } + // A miss is a cell whose tiles are not ready. + const height = heights.now({ lon: cell.lon, lat: cell.lat }); + if (height === null) continue; + sampled += 1; + heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; } return { heightM, sampled, requested }; } @@ -620,7 +638,8 @@ export function probeMeshFloorM(scene, cells) { /** * Build the state for one cinematic route flight. * @param {Object} options - * @param {Cesium.Cartesian3[]} options.pts Route vertices. + * @param {Array<{x: number, y: number, z: number}>} options.pts Route + * vertices, ECEF. * @param {number[]} options.cumM Cumulative arc length per vertex. * @param {string} [options.speed] slow | normal | fast. * @param {Function|null} [options.floorFn] (latDeg, lonDeg) => floor metres. @@ -649,11 +668,7 @@ export function createRouteFlight({ // the mean: routes under 10 m (slow) / 20 m (normal) / 45 m (fast) fly slower // than asked. Those are shorter than the camera is tall — nothing to see. const durationS = Math.max(0.5, totalM / cruiseMps); - const pathHeightM = Cesium.Cartographic.fromCartesian( - pts[0], - Cesium.Ellipsoid.WGS84, - _warmCarto, - ).height; + const pathHeightM = toCartographicRadians(pts[0]).height; const state = { kind: 'route', mode: 'continuous', @@ -712,8 +727,8 @@ export function createRouteFlight({ * the viewer (so this stays testable without one). * @param {Object} state From createRouteFlight(). * @param {number} dt Seconds elapsed. - * @returns {{finished: boolean, eye: Cesium.Cartesian3, direction: Cesium.Cartesian3, - * up: Cesium.Cartesian3, bankDeg: number, heightM: number, aglM: number, + * @returns {{finished: boolean, eye: Object, direction: Object, + * up: Object, bankDeg: number, heightM: number, aglM: number, * groundSpeedMps: number, progress: number}} The frame. */ export function advanceRouteFlight(state, dt) { @@ -747,37 +762,17 @@ export function advanceRouteFlight(state, dt) { state.groundSpeedMps = cruiseMps * profile.speed; const pos = arcPoint(state, traveled, _framePos); - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - _frameCarto, - ); - const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormalCartographic( - carto, - _frameUp, - ); + const carto = toCartographicRadians(pos); + const up = surfaceNormal(carto.lon, carto.lat); // Planned turn: compare where we came from with where we are going, over a // window centred on the camera. Peaks AT the corner, tapers either side. const halfWindowM = Math.max(20, (ROUTE_BANK_WINDOW_S * cruiseMps) / 2); - const inbound = horizontalChord( - state, - traveled - halfWindowM, - traveled, - up, - _frameIn, - ); - const outbound = horizontalChord( - state, - traveled, - traveled + halfWindowM, - up, - _frameOut, - ); + const inbound = horizontalChord(state, traveled - halfWindowM, traveled, up); + const outbound = horizontalChord(state, traveled, traveled + halfWindowM, up); const turnRateDegS = inbound && outbound - ? Cesium.Math.toDegrees(signedTurnRad(inbound, outbound, up)) / - ROUTE_BANK_WINDOW_S + ? toDegrees(signedTurnRad(inbound, outbound, up)) / ROUTE_BANK_WINDOW_S : 0; const bankTarget = routeBankTargetDeg(turnRateDegS, state.reducedMotion); state.bankLeadDeg = approachValue( @@ -805,11 +800,10 @@ export function advanceRouteFlight(state, dt) { Math.max(ROUTE_LOOKAHEAD_MIN_M, ROUTE_LOOKAHEAD_S * cruiseMps), ); const gaze = - horizontalChord(state, traveled, traveled + lookaheadM, up, _frameGaze) || + horizontalChord(state, traveled, traveled + lookaheadM, up) || outbound || inbound; - if (gaze && !state.headingDir) - state.headingDir = Cesium.Cartesian3.clone(gaze); + if (gaze && !state.headingDir) state.headingDir = vec(gaze.x, gaze.y, gaze.z); else if (gaze) { // Rotate the heading TOWARD the gaze about the local up, rather than // lerping the two vectors. A Cartesian lerp cannot cross an antipodal pair @@ -820,67 +814,34 @@ export function advanceRouteFlight(state, dt) { const turnToGaze = signedTurnRad(state.headingDir, gaze, up); // signedTurnRad is + for a RIGHT turn; a positive rotation about up is a // LEFT turn, so the step is negated. - const rotation = Cesium.Matrix3.fromQuaternion( - Cesium.Quaternion.fromAxisAngle(up, -turnToGaze * k, _headingQuat), - _headingMatrix, - ); - const turned = Cesium.Matrix3.multiplyByVector( - rotation, - state.headingDir, - _frameDir, - ); - const vertical = Cesium.Cartesian3.multiplyByScalar( + const turned = horizontalPart( + rotateAbout(state.headingDir, up, -turnToGaze * k), up, - Cesium.Cartesian3.dot(turned, up), - _chordVertical, ); - Cesium.Cartesian3.subtract(turned, vertical, turned); - if (Cesium.Cartesian3.magnitude(turned) > 1e-6) { - Cesium.Cartesian3.normalize(turned, state.headingDir); - } + if (magnitude(turned) > 1e-6) state.headingDir = normalize(turned); } // A path with no horizontal extent (identical lat/lon, differing heights) // has no azimuth to fly: point east so the frame stays orthonormal. if (!state.headingDir) { - const east = Cesium.Cartesian3.fromElements(-pos.y, pos.x, 0, _frameGaze); - state.headingDir = - Cesium.Cartesian3.magnitude(east) > 1e-6 - ? Cesium.Cartesian3.normalize(east, new Cesium.Cartesian3()) - : Cesium.Cartesian3.fromElements(1, 0, 0, new Cesium.Cartesian3()); + const east = vec(-pos.y, pos.x, 0); + state.headingDir = magnitude(east) > 1e-6 ? normalize(east) : vec(1, 0, 0); } const heading = state.headingDir; // Locked pitch: heading gives the azimuth, the pitch never wanders. - const pitch = Cesium.Math.toRadians(ROUTE_PITCH_DEG); - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.add( - Cesium.Cartesian3.multiplyByScalar(heading, Math.cos(pitch), _frameDir), - Cesium.Cartesian3.multiplyByScalar(up, Math.sin(pitch), _frameLevelUp), - _frameDir, - ), - _frameDir, + const pitch = toRadians(ROUTE_PITCH_DEG); + const direction = normalize( + add(scale(heading, Math.cos(pitch)), scale(up, Math.sin(pitch))), ); // Orthonormal camera frame, then roll it about its own forward axis: a // positive rotation drops the right wing, which is what a right turn wants. - const right = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.cross(direction, up, _frameRight), - _frameRight, - ); - const levelUp = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.cross(right, direction, _frameLevelUp), - _frameLevelUp, - ); - const bankRad = Cesium.Math.toRadians(appliedBankDeg); - let bankedUp = levelUp; - if (Math.abs(bankRad) > 1e-6) { - const quat = Cesium.Quaternion.fromAxisAngle(direction, bankRad, _bankQuat); - const rotation = Cesium.Matrix3.fromQuaternion(quat, _bankMatrix); - bankedUp = Cesium.Matrix3.multiplyByVector( - rotation, - levelUp, - _frameBankedUp, - ); - } + const right = normalize(cross(direction, up)); + const levelUp = normalize(cross(right, direction)); + const bankRad = toRadians(appliedBankDeg); + const bankedUp = + Math.abs(bankRad) > 1e-6 + ? rotateAbout(levelUp, direction, bankRad) + : levelUp; // Keep the corridor ahead of the camera warm. The batch dedupes to coarse // cells, skips warm ones and queues contenders, so a repeat costs nothing. @@ -894,20 +855,14 @@ export function advanceRouteFlight(state, dt) { // the camera reaches it. Both are cached reads — nothing samples the mesh. let sampledFloor = Number.NaN; if (typeof state.floorFn === 'function') { - const aheadPos = arcPoint(state, traveled + lookaheadM / 2, _frameAheadPos); - const aheadCarto = Cesium.Cartographic.fromCartesian( - aheadPos, - Cesium.Ellipsoid.WGS84, - _frameAheadCarto, + const aheadCarto = toCartographicRadians( + arcPoint(state, traveled + lookaheadM / 2, _frameAheadPos), ); try { - const here = state.floorFn( - Cesium.Math.toDegrees(carto.latitude), - Cesium.Math.toDegrees(carto.longitude), - ); + const here = state.floorFn(toDegrees(carto.lat), toDegrees(carto.lon)); const ahead = state.floorFn( - Cesium.Math.toDegrees(aheadCarto.latitude), - Cesium.Math.toDegrees(aheadCarto.longitude), + toDegrees(aheadCarto.lat), + toDegrees(aheadCarto.lon), ); const warm = [here, ahead].filter((value) => Number.isFinite(value)); if (warm.length) sampledFloor = Math.max(...warm); @@ -971,13 +926,7 @@ export function advanceRouteFlight(state, dt) { ); } state.appliedHeightM = heightM; - const eye = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - heightM, - Cesium.Ellipsoid.WGS84, - _frameEye, - ); + const eye = fromRadians(carto.lon, carto.lat, heightM); state.appliedBankDeg = appliedBankDeg; return { @@ -997,6 +946,8 @@ let _viewer = null; let _getTarget = null; let _active = null; // { kind, motion, direction, speed, mode, motionId, ...state } let _tickRemover = null; +/** The frame port `_tickRemover` listens to. */ +let _tickPort = null; let _trackingRemover = null; let _inputRemovers = []; /** Monotonic id for the motion currently running; 0 means "no motion". */ @@ -1006,7 +957,7 @@ let _manualInputCount = 0; /** * Lets a caller holding a motion back (behind a fly-to) see whether the user - * took the camera meanwhile; Cesium does not cancel a flight on input. + * took the camera meanwhile; the camera does not cancel a flight on input. * @returns {number} Manual camera inputs so far. */ export function manualCameraInputCount() { @@ -1024,11 +975,25 @@ function setActiveMotion(state) { if (state) { _motionSeq += 1; state.motionId = _motionSeq; + listenForFrames(); } _active = state; return state; } +/** + * Run the motions on the frames of the viewer's frame port, the one there + * is now: a renderer bound after `initCameraVerbs` (which replaces the + * port the viewer had) is picked up when the next motion starts. + */ +function listenForFrames() { + const port = _viewer ? findFrame(_viewer) : null; + if (port === _tickPort) return; + _tickRemover?.(); + _tickPort = port; + _tickRemover = port?.on('preUpdate', onTick) ?? null; +} + /** * @returns {number} Id of the running motion, or 0 when the camera is idle. */ @@ -1066,7 +1031,7 @@ let _lookBaseline = null; // in view: which way, from which position and direction. A motion that starts from that // pose turns at least that far, so a request reported as done really moves // even when a smaller first step lands in a dip of the sampled share. -const PROVEN_TURN_RAD = Cesium.Math.toRadians(0.5); +const PROVEN_TURN_RAD = toRadians(0.5); let _provenLook = null; /** The part of the frame a viewer can see: the scope keyhole when it is on. */ @@ -1074,46 +1039,44 @@ function visibleFrame() { return { keyholeRadius: isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0 }; } -/** The frame share an in-place turn from `cam`'s pose is limited against. */ -function lookBaselineShare(cam) { - const share = globeFrameShare(cam, visibleFrame()); +/** Whether two vectors agree to `tolerance` in every component. */ +const within = (a, b, tolerance) => + Math.abs(a.x - b.x) <= tolerance && + Math.abs(a.y - b.y) <= tolerance && + Math.abs(a.z - b.z) <= tolerance; + +/** The frame share an in-place turn from `pose` is limited against. */ +function lookBaselineShare(pose) { + const share = globeFrameShare(pose, visibleFrame()); const continues = _lookBaseline && - Cesium.Cartesian3.equalsEpsilon( - _lookBaseline.position, - cam.positionWC, - 0, - 1, - ) && - Cesium.Cartesian3.equalsEpsilon( - _lookBaseline.direction, - cam.directionWC, - 0, - 1e-9, - ); + within(_lookBaseline.position, pose.position, 1) && + within(_lookBaseline.direction, pose.direction, 1e-9); _lookBaseline = { - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), + position: pose.position, + direction: pose.direction, share: continues ? Math.max(_lookBaseline.share, share) : share, }; return _lookBaseline.share; } /** - * One in-place look step of motion `m`. From orbit a free globe camera turns - * only as far as keeps the planet in frame, measured against the baseline the - * turn started from, then the motion ends there. + * One in-place look step of motion `m` (`look`: 'up', 'down', 'left' or + * 'right'). From orbit a free globe camera turns only as far as keeps the + * planet in frame, measured against the baseline the turn started from, then + * the motion ends there. */ -function lookWithinFrame(cam, m, look, angle) { +function lookWithinFrame(camera, m, look, angle) { let allowed = angle; if (isFreeGlobeCamera(_viewer)) { + const pose = camera.pose(); if (m.globeShareAtStart === undefined) { - m.globeShareAtStart = lookBaselineShare(cam); - m.provenTurnRad = lookProven(cam, look) ? PROVEN_TURN_RAD : 0; + m.globeShareAtStart = lookBaselineShare(pose); + m.provenTurnRad = lookProven(pose, look) ? PROVEN_TURN_RAD : 0; m.turnedRad = 0; } _provenLook = null; - allowed = lookAngleWithinFrame(cam, look, angle, { + allowed = lookAngleWithinFrame(pose, look, angle, { ...visibleFrame(), startShare: m.globeShareAtStart, }); @@ -1121,45 +1084,46 @@ function lookWithinFrame(cam, m, look, angle) { if (allowed < owed) allowed = owed; m.turnedRad += allowed; } - if (allowed > 0) cam[look](allowed); + if (allowed > 0) camera.setView(eyeTurned(camera.pose(), look, allowed)); // The pose this turn leaves, for a turn that continues from it. - if (_lookBaseline) - Cesium.Cartesian3.clone(cam.directionWC, _lookBaseline.direction); + if (_lookBaseline) _lookBaseline.direction = camera.pose().direction; if (allowed < angle) interruptCameraMotion('globe-out-of-frame'); } /** * The in-place look a pitch change from `fromPitch` to `goalPitch` makes: - * 'lookUp', 'lookDown', or null when it does not move. A tilt is judged by - * the way its pitch moves, whatever form or direction word it came in. + * 'up', 'down', or null when it does not move. A tilt is judged by the way + * its pitch moves, whatever form or direction word it came in. */ function tiltLook(fromPitch, goalPitch) { if (!Number.isFinite(fromPitch) || !Number.isFinite(goalPitch)) return null; - if (goalPitch > fromPitch) return 'lookUp'; - return goalPitch < fromPitch ? 'lookDown' : null; + if (goalPitch > fromPitch) return 'up'; + return goalPitch < fromPitch ? 'down' : null; } /** Tilt `m` in place to `goalPitch`, as far as the frame limit allows. */ -function tiltInPlaceWithinFrame(cam, m, goalPitch) { - const look = tiltLook(cam.pitch, goalPitch); - if (look) lookWithinFrame(cam, m, look, Math.abs(goalPitch - cam.pitch)); +function tiltInPlaceWithinFrame(camera, m, goalPitch) { + const pitch = camera.pose().pitch; + const look = tiltLook(pitch, goalPitch); + if (look) lookWithinFrame(camera, m, look, Math.abs(goalPitch - pitch)); } /** - * The pitch an in-place tilt from `cam`'s pose toward `goalPitch` reaches - * before the frame limit stops it, judged as its steps will be: `goalPitch` - * itself when the planet stays in frame the whole way, or the camera is not a - * free globe camera. The steps run on a copy of the camera, each looking by - * the pitch still to go as the tilt's frames do, because a rolled camera's - * look turns its pitch by less than the look angle. + * The pitch an in-place tilt from the camera's pose toward `goalPitch` + * reaches before the frame limit stops it, judged as its steps will be: + * `goalPitch` itself when the planet stays in frame the whole way, or the + * camera is not a free globe camera. The steps run on a copy of the pose, each + * looking by the pitch still to go as the tilt's frames do, because a rolled + * camera's look turns its pitch by less than the look angle. */ -function tiltPitchWithinFrame(cam, goalPitch) { - const look = tiltLook(cam.pitch, goalPitch); +function tiltPitchWithinFrame(camera, goalPitch) { + const pose = camera.pose(); + const look = tiltLook(pose.pitch, goalPitch); if (!look || !isFreeGlobeCamera(_viewer)) return goalPitch; - const frame = { ...visibleFrame(), startShare: lookBaselineShare(cam) }; + const frame = { ...visibleFrame(), startShare: lookBaselineShare(pose) }; // A proven half degree is turned whatever the sampled share says. - let owed = lookProven(cam, look) ? PROVEN_TURN_RAD : 0; - const probe = Cesium.Camera.clone(cam); + let owed = lookProven(pose, look) ? PROVEN_TURN_RAD : 0; + let probe = pose; for (let i = 0; i < 32; i += 1) { if (tiltLook(probe.pitch, goalPitch) !== look) return goalPitch; const angle = Math.abs(goalPitch - probe.pitch); @@ -1169,7 +1133,7 @@ function tiltPitchWithinFrame(cam, goalPitch) { Math.min(angle, owed), ); owed -= allowed; - if (allowed > 0) probe[look](allowed); + if (allowed > 0) probe = lookedPose(probe, look, allowed); if (allowed < angle) return probe.pitch; } return probe.pitch; @@ -1177,31 +1141,22 @@ function tiltPitchWithinFrame(cam, goalPitch) { /** The reply's note for a tilt the frame limit stops short of its angle. */ function tiltFrameNote(pitch) { - return `Stopped at ${Math.round(Cesium.Math.toDegrees(pitch))}°: from this height a shallower angle would turn the globe out of view. Zoom in to tilt further.`; + return `Stopped at ${Math.round(toDegrees(pitch))}°: from this height a shallower angle would turn the globe out of view. Zoom in to tilt further.`; } -/** True when the pre-check proved a half-degree `look` from `cam`'s pose. */ -function lookProven(cam, look) { +/** True when the pre-check proved a half-degree `look` from `pose`. */ +function lookProven(pose, look) { return ( _provenLook?.look === look && - Cesium.Cartesian3.equalsEpsilon( - _provenLook.position, - cam.positionWC, - 0, - 1, - ) && - Cesium.Cartesian3.equalsEpsilon( - _provenLook.direction, - cam.directionWC, - 0, - 1e-9, - ) + pose != null && + within(_provenLook.position, pose.position, 1) && + within(_provenLook.direction, pose.direction, 1e-9) ); } /** - * The check a voice in-place turn (`look`: 'lookUp', 'lookDown', 'lookLeft' - * or 'lookRight') must pass from orbit: refused when even half a degree would + * The check a voice in-place turn (`look`: 'up', 'down', 'left' or 'right') + * must pass from orbit: refused when even half a degree would * cross the frame limit, otherwise proven for that half degree from this pose. * With `released`, the turn runs through a navigation that first releases a * tracked or locked camera and keeps its world pose. The frame measure and the @@ -1212,13 +1167,13 @@ function lookProven(cam, look) { */ function checkLookFromOrbit(look, { released = false } = {}) { _provenLook = null; - if (_viewer.scene.mode !== Cesium.SceneMode.SCENE3D) return null; - const cam = _viewer.camera; if (!released && !isFreeGlobeCamera(_viewer)) return null; + const pose = findCamera(_viewer)?.pose(); + if (!pose) return null; if ( - lookStepLosesGlobe(cam, look, PROVEN_TURN_RAD, { + lookStepLosesGlobe(pose, look, PROVEN_TURN_RAD, { ...visibleFrame(), - startShare: lookBaselineShare(cam), + startShare: lookBaselineShare(pose), }) ) return { @@ -1229,15 +1184,15 @@ function checkLookFromOrbit(look, { released = false } = {}) { }; _provenLook = { look, - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), + position: pose.position, + direction: pose.direction, }; return null; } function clearLookAt() { try { - _viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); + findCamera(_viewer)?.release(); } catch { /* teardown race */ } @@ -1246,7 +1201,7 @@ function clearLookAt() { /** * Put the horizon back. * - * The route dolly is the only motion that rolls the camera, and Cesium keeps + * The route dolly is the only motion that rolls the camera, and the camera keeps * whatever world-space up vector it was last handed — so releasing a flight * mid-bank leaves the user holding a tilted horizon until some later motion * happens to level it. Heading, pitch and position are preserved; only the @@ -1255,13 +1210,11 @@ function clearLookAt() { */ function levelCameraRoll() { try { - const cam = _viewer?.camera; - if (!cam || typeof cam.setView !== 'function') return false; - const roll = Cesium.Math.negativePiToPi(cam.roll || 0); - if (Math.abs(roll) < 1e-5) return false; - cam.setView({ - orientation: { heading: cam.heading, pitch: cam.pitch, roll: 0 }, - }); + const camera = findCamera(_viewer); + if (!camera) return false; + const { heading, pitch, roll } = camera.pose(); + if (Math.abs(negativePiToPi(roll || 0)) < 1e-5) return false; + camera.setView({ orientation: { heading, pitch, roll: 0 } }); return true; } catch { return false; // teardown race @@ -1274,7 +1227,7 @@ export function interruptCameraMotion(reason = 'interrupt') { // While an entity is TRACKED, the follow camera owns the reference frame — // resetting the lookAt transform here flings the camera into space (field // finding). Leave the transform to the tracker; it re-asserts every frame. - const tracking = Boolean(_viewer?.trackedEntity); + const tracking = isFollowing(_viewer); const wasRoute = wasActive && _active.kind === 'route'; if ( wasActive && @@ -1316,6 +1269,9 @@ export function getActiveCameraMotion() { return info; } +/** A pan's direction as the camera move it makes; any other is down. */ +const PAN_MOVES = Object.freeze({ left: 'left', right: 'right', up: 'up' }); + function onTick() { if (!_active || !_viewer) return; // Wall-clock dt: clock.currentTime FREEZES when the app clock isn't @@ -1326,7 +1282,6 @@ function onTick() { Math.max(0.001, (nowMs - (_active.lastMs ?? nowMs)) / 1000), ); _active.lastMs = nowMs; - const cam = _viewer.camera; const m = _active; // `once` motions ease out and self-stop on budget exhaustion. @@ -1341,6 +1296,7 @@ function onTick() { } try { + const camera = cameraOf(_viewer); if (m.kind === 'orbit' && m.pending) { // Armed but target-less (started mid-flight, e.g. "fly to X and orbit // it"): keep trying for a ground target until the camera settles. @@ -1350,11 +1306,11 @@ function onTick() { return; } // pickEllipsoid hits the globe from ANY altitude — target existence - // alone is not arrival. Camera flights are scene tweens, and multi-stage - // flights have GAPS between tweens: require the tween queue quiet for a + // alone is not arrival. Multi-stage flights have GAPS between flights: + // require the camera out of any flight for a // continuous 0.8 s before capturing the orbit framing at the REAL // destination (field finding: Eiffel chain orbited from mid-flight). - if (_viewer.scene.tweens.length > 0) { + if (cameraFlying()) { m.settledS = 0; return; } @@ -1362,86 +1318,74 @@ function onTick() { if (m.settledS < 0.8) return; const target = _getTarget?.(_viewer); if (!target) return; - const cam2 = _viewer.camera; - const range = Cesium.Cartesian3.distance(cam2.positionWC, target); - const carto2 = Cesium.Cartographic.fromCartesian(cam2.positionWC); - const tCarto2 = Cesium.Cartographic.fromCartesian(target); - const dh2 = carto2.height - tCarto2.height; + const pose = camera.pose(); m.target = target; - m.hpr = new Cesium.HeadingPitchRange( - cam2.heading, - -Math.asin(Math.min(1, Math.max(-1, dh2 / Math.max(1, range)))), - range, - ); - m.hprStartHeading = cam2.heading; + m.hpr = orbitFraming(pose, target); + m.hprStartHeading = pose.heading; m.pending = false; m.elapsed = 0; // once-mode budget starts when the orbit actually begins return; } if (m.kind === 'orbit') { const rate = - Cesium.Math.toRadians(ORBIT_DEG_S[m.speed]) * - (m.direction === 'left' ? -1 : 1); + toRadians(ORBIT_DEG_S[m.speed]) * (m.direction === 'left' ? -1 : 1); if (m.mode === 'once') { const total = - Cesium.Math.toRadians(ONCE.orbitDeg) * - (m.direction === 'left' ? -1 : 1); + toRadians(ONCE.orbitDeg) * (m.direction === 'left' ? -1 : 1); m.hpr.heading = m.hprStartHeading + total * scale; } else { m.hpr.heading += rate * dt; } - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); } else if (m.kind === 'pan') { - const heightM = Math.max(50, cam.positionCartographic.height); + const heightM = Math.max(50, camera.pose().height); const step = m.mode === 'once' ? heightM * ONCE.panViewFraction * (scale - (m.lastScale || 0)) : heightM * PAN_VIEW_FRACTION_S[m.speed] * dt; m.lastScale = scale; - if (m.direction === 'left') cam.moveLeft(step); - else if (m.direction === 'right') cam.moveRight(step); - else if (m.direction === 'up') cam.moveUp(step); - else cam.moveDown(step); + camera.setView( + eyeMoved(camera.pose(), PAN_MOVES[m.direction] ?? 'down', step), + ); } else if (m.kind === 'tilt') { - tickTilt(cam, m, scale, dt); + tickTilt(camera, m, scale, dt); } else if (m.kind === 'rotate' || m.kind === 'rotate_globe') { const degS = TILT_DEG_S[m.speed]; const stepRad = m.mode === 'once' - ? Cesium.Math.toRadians(ONCE.rotateDeg) * (scale - (m.lastScale || 0)) - : Cesium.Math.toRadians(degS) * dt; + ? toRadians(ONCE.rotateDeg) * (scale - (m.lastScale || 0)) + : toRadians(degS) * dt; m.lastScale = scale; if (m.kind === 'rotate_globe') { // Tracking can acquire the camera without going through navigation. // Yield without resetting its pose/frame: the world-space arc proof - // only describes Cesium's rotation while the frame is identity. + // only describes the camera's rotation while the frame is identity. + const pose = camera.pose(); if (!isFreeGlobeCamera(_viewer) || _isCockpitActive?.()) { interruptCameraMotion('globe-camera-owner-changed'); return; } - // Cesium rotates both position and basis about the reference-frame + // The camera rotates both position and basis about the reference-frame // origin. The captured screen-up axis keeps left/right horizontal even // in a tilted or rolled view; a positive angle moves the globe right. const angle = m.direction === 'left' ? -stepRad : stepRad; - if (globeRotationFitsKeyhole() !== true) { + if (globeRotationFitsKeyhole(liveView(camera, pose)) !== true) { interruptCameraMotion('globe-framing-changed'); return; } if ( - !globeRotationHasClearance(cam.positionWC) || - Math.abs( - Cesium.Cartesian3.magnitude(cam.positionWC) - m.rotationRadius, - ) > 0.01 + !globeRotationHasClearance(pose.position) || + Math.abs(magnitude(pose.position) - m.rotationRadius) > 0.01 ) { interruptCameraMotion('globe-surface-limit'); return; } - cam.rotate(m.rotationAxis, angle); + camera.setView(eyeRotatedAbout(pose, m.rotationAxis, angle)); } else { lookWithinFrame( - cam, + camera, m, - m.direction === 'left' ? 'lookLeft' : 'lookRight', + m.direction === 'left' ? 'left' : 'right', stepRad, ); } @@ -1453,7 +1397,7 @@ function onTick() { // user left it rather than teleporting to an altitude derived from // nothing. An interrupt during the arm is still instant. if (frame.arming) return; - cam.setView({ + camera.setView({ destination: frame.eye, orientation: { direction: frame.direction, up: frame.up }, }); @@ -1467,6 +1411,25 @@ function onTick() { } } +/** Whether the camera is in a flight. */ +const cameraFlying = () => Boolean(findCamera(_viewer)?.flying); + +/** + * An orbit offset that reproduces the current framing of `target` exactly: + * the view's heading, and pitch and range from the geometry. + */ +function orbitFraming(pose, target) { + const range = distance(pose.position, target); + const dh = + toCartographicRadians(pose.position).height - + toCartographicRadians(target).height; + return { + heading: pose.heading, + pitch: -Math.asin(Math.min(1, Math.max(-1, dh / Math.max(1, range)))), + range, + }; +} + /** * One frame of tilt. With a ground pivot the camera swings about it (lookAt), * so the place under the crosshair stays centred; without one it looks up or @@ -1481,15 +1444,14 @@ function onTick() { * keeps the place centred: tilting in place there would lift the crosshair * onto the sky. */ -function tickTilt(cam, m, scale, dt) { - const from = cam.pitch; +function tickTilt(camera, m, scale, dt) { + const pitchNow = () => camera.pose().pitch; + const from = pitchNow(); const want = m.mode === 'once' ? m.startPitch + (m.goalPitch - m.startPitch) * scale : from + - Cesium.Math.toRadians(TILT_DEG_S[m.speed]) * - dt * - (m.direction === 'up' ? 1 : -1); + toRadians(TILT_DEG_S[m.speed]) * dt * (m.direction === 'up' ? 1 : -1); const up = want > from; const limited = up ? Math.min(want, Math.max(from, PITCH_MAX)) @@ -1498,25 +1460,25 @@ function tickTilt(cam, m, scale, dt) { if (m.hpr) { // Apply a range a zoom set since the last frame, even when the pitch // then has nowhere to go (a zoom in to the clearance ends the pivot). - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); // Up toward the horizon the swing lowers the camera: hold the clearance, // and keep the place below the horizon. const cap = up ? Math.max(m.hpr.pitch, tiltPivotPitchMax(m.hpr.range)) : Infinity; - for (let i = 0; i < 3 && Math.abs(limited - cam.pitch) > 1e-6; i += 1) { + for (let i = 0; i < 3 && Math.abs(limited - pitchNow()) > 1e-6; i += 1) { const pitch = Math.min( cap, - Math.max(-Cesium.Math.PI_OVER_TWO, m.hpr.pitch + limited - cam.pitch), + Math.max(-PI_OVER_TWO, m.hpr.pitch + limited - pitchNow()), ); if (pitch === m.hpr.pitch) break; m.hpr.pitch = pitch; - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); } // A once motion that just completed released the lookAt frame before // this last step re-took it. if (_active !== m) clearLookAt(); - if (up && m.hpr.pitch >= cap && cam.pitch < limited - 1e-6) { + if (up && m.hpr.pitch >= cap && pitchNow() < limited - 1e-6) { if (tiltClearanceBinds(m.hpr.range)) { // Down to its clearance: let go of the pivot and tilt the rest in // place, which keeps the height. @@ -1529,7 +1491,7 @@ function tickTilt(cam, m, scale, dt) { } } } - if (!m.hpr) tiltInPlaceWithinFrame(cam, m, limited); + if (!m.hpr) tiltInPlaceWithinFrame(camera, m, limited); if (m.mode !== 'once' && (limited !== want || atLimit)) interruptCameraMotion('tilt-clamp'); } @@ -1580,36 +1542,27 @@ function tiltUpLimit({ target, pivot }) { /** The camera pitch lookAt gives for this pivot at the given pivot pitch. */ function pivotCameraPitch(target, { heading, range }, pitch) { - const offset = new Cesium.Cartesian3( - -range * Math.cos(pitch) * Math.sin(heading), - -range * Math.cos(pitch) * Math.cos(heading), - -range * Math.sin(pitch), - ); - const eye = Cesium.Matrix4.multiplyByPoint( - Cesium.Transforms.eastNorthUpToFixedFrame(target), - offset, - new Cesium.Cartesian3(), - ); - const look = Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()); - Cesium.Cartesian3.normalize(look, look); - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - const upAtEye = ellipsoid.geodeticSurfaceNormal(eye, new Cesium.Cartesian3()); - return Math.asin( - Cesium.Math.clamp(Cesium.Cartesian3.dot(look, upAtEye), -1, 1), - ); + const eye = framePoint(eastNorthUp(target), { + x: -range * Math.cos(pitch) * Math.sin(heading), + y: -range * Math.cos(pitch) * Math.cos(heading), + z: -range * Math.sin(pitch), + }); + const look = normalize(sub(target, eye)); + return Math.asin(clamp(dot(look, geodeticSurfaceNormal(eye)), -1, 1)); } /** * Where a tilt starts. It swings about the ground under the crosshair so the * place stays centred. It tilts in place with no ground there, from globe - * range, or while an entity is tracked (the follow camera owns that frame; + * range, or while something is followed (the follow camera owns that frame; * voice releases it before moving, so a voice tilt still pivots). */ -function tiltStartFrame(cam) { - const target = _viewer.trackedEntity ? null : _getTarget?.(_viewer); - let pivot = target ? tiltPivot(cam, target) : null; +function tiltStartFrame(camera) { + const pose = camera.pose(); + const target = isFollowing(_viewer) ? null : _getTarget?.(_viewer); + let pivot = target ? tiltPivot(pose, target) : null; if (pivot && !tiltPivotInReach(pivot.range)) pivot = null; - return { target, pivot, from: cam.pitch }; + return { target, pivot, from: pose.pitch }; } /** Whether a tilt may pivot at this range: up to and including the cutoff. */ @@ -1619,87 +1572,84 @@ function tiltPivotInReach(range) { /** The reply's note for a tilt the place's horizon stops short of its angle. */ function tiltHorizonNote(pitch) { - return `Stopped at ${Math.round(Cesium.Math.toDegrees(pitch))}°: from this range a shallower angle puts the place past the horizon. Zoom in to tilt further.`; + return `Stopped at ${Math.round(toDegrees(pitch))}°: from this range a shallower angle puts the place past the horizon. Zoom in to tilt further.`; } /** Ground pivot for a tilt: heading, pitch and range in the target's own frame. */ -function tiltPivot(cam, target) { - const local = Cesium.Matrix4.multiplyByPoint( - Cesium.Matrix4.inverseTransformation( - Cesium.Transforms.eastNorthUpToFixedFrame(target), - new Cesium.Matrix4(), - ), - cam.positionWC, - new Cesium.Cartesian3(), - ); - const range = Cesium.Cartesian3.magnitude(local); +function tiltPivot(pose, target) { + const local = inverseFramePoint(eastNorthUp(target), pose.position); + const range = magnitude(local); if (!(range > 1) || local.z <= 0) return null; // Near straight overhead the offset's heading is float noise (it flipped a // north-up London view to south); keep the camera's own. const heading = Math.hypot(local.x, local.y) > range * 0.01 ? Math.atan2(-local.x, -local.y) - : cam.heading; - return new Cesium.HeadingPitchRange( + : pose.heading; + return { heading, - -Math.asin(Math.min(1, local.z / range)), + pitch: -Math.asin(Math.min(1, local.z / range)), range, - ); + }; } -/** Rigid origin-centred rotation stays outside the actual ellipsoid's bounding sphere. */ +/** Rigid origin-centred rotation stays outside the ellipsoid's bounding sphere. */ function globeRotationHasClearance(position) { - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - const { minimumRadius, maximumRadius } = ellipsoid; - const radius = Cesium.Cartesian3.magnitude(position); - return ( - Number.isFinite(minimumRadius) && - minimumRadius > 0 && - Number.isFinite(maximumRadius) && - maximumRadius >= minimumRadius && - Number.isFinite(radius) && - radius > maximumRadius * (1 + 1e-12) - ); + const radius = magnitude(position); + return Number.isFinite(radius) && radius > WGS84.radii.x * (1 + 1e-12); } +/** + * The camera's view for the keyhole test: its pose, its projection, and + * whether it is the live camera (whose Earth disc the overlay projects). + */ +function liveView(camera, pose = camera.pose()) { + let projection = null; + try { + projection = camera.matrices().projection; + } catch { + /* no projection for these depth limits: unsupported below */ + } + return { ...pose, projection, live: true }; +} + +/** + * Whether a projection is a perspective one centred on the view: what the + * keyhole cone below assumes. Column-major, so element 11 is row 3 of + * column 2 (−1 for a perspective divide), 15 row 3 of column 3 (0), and 8 + * and 9 the off-centre shifts. + */ +const centredPerspective = (p) => + p?.[11] === -1 && p[15] === 0 && p[8] === 0 && p[9] === 0; + /** Use the existing WGS84/CSS-pixel projection; null means unsupported, not close-up. */ -function globeRotationFitsKeyhole(camera = _viewer.camera) { - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - if (!Cesium.Cartesian3.equals(ellipsoid.radii, Cesium.Ellipsoid.WGS84.radii)) - return null; - const canvas = _viewer.scene.canvas; +function globeRotationFitsKeyhole(view) { + const canvas = canvasOf(_viewer); const width = canvas.clientWidth; const height = canvas.clientHeight; - const frustum = camera.frustum; if ( !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0 || - !(frustum instanceof Cesium.PerspectiveFrustum) || - !Number.isFinite(frustum.near) || - frustum.near <= 0 || - !Number.isFinite(frustum.far) || - frustum.far <= frustum.near || - frustum.xOffset !== 0 || - frustum.yOffset !== 0 + !centredPerspective(view.projection) || + !Number.isFinite(view.near) || + view.near <= 0 || + !Number.isFinite(view.far) || + view.far <= view.near ) return null; try { - const cam = camera; - const distance = Cesium.Cartesian3.magnitude(cam.positionWC); - const sphereRadius = ellipsoid.maximumRadius; - if (!Number.isFinite(distance) || distance <= 0) return null; - if (distance <= sphereRadius) return false; // Near-surface polar views are close-up too. - const radiusPx = earthDiscScreenRadius(distance, height, frustum.fovy); + const distanceM = magnitude(view.position); + const sphereRadius = WGS84.radii.x; + if (!Number.isFinite(distanceM) || distanceM <= 0) return null; + if (distanceM <= sphereRadius) return false; // Near-surface polar views are close-up too. + const radiusPx = earthDiscScreenRadius(distanceM, height, view.fovy); if (!radiusPx) return null; const keyhole = getKeyholeGeometry(width, height); // The known nadir reset probe uses the same exact cone below; projecting - // through SceneTransforms would read the live scene.camera instead. - if ( - camera === _viewer.camera && - !projectEarthDiscToViewport(_viewer, width, height) - ) { + // through the query port would read the live camera instead. + if (view.live && !projectEarthDiscToViewport(_viewer, width, height)) { // A near-surface horizon view cannot fit even when pointed at Earth; // an orbital camera looking away is unsupported, not a close-up offer. return radiusPx > Math.min(keyhole.radius, width / 2, height / 2) @@ -1710,33 +1660,26 @@ function globeRotationFitsKeyhole(camera = _viewer.camera) { // against the existing keyhole cone. Canvas-edge clipping does not change // framing during rigid globe rotation and is not a clearance condition, // without changing the UI projection or defining another keyhole/mask. - const toCenter = Cesium.Cartesian3.negate( - cam.positionWC, - new Cesium.Cartesian3(), - ); - const depth = Cesium.Cartesian3.dot(toCenter, cam.directionWC); - const right = Math.abs(Cesium.Cartesian3.dot(toCenter, cam.rightWC)); - const up = Math.abs(Cesium.Cartesian3.dot(toCenter, cam.upWC)); - const focalY = height / (2 * Math.tan(frustum.fovy / 2)); - const focalX = - width / (2 * Math.tan(frustum.fovy / 2) * frustum.aspectRatio); + const toCenter = vec(-view.position.x, -view.position.y, -view.position.z); + const depth = dot(toCenter, view.direction); + const right = Math.abs(dot(toCenter, view.right)); + const up = Math.abs(dot(toCenter, view.up)); + const focalY = height / (2 * Math.tan(view.fovy / 2)); + const focalX = width / (2 * Math.tan(view.fovy / 2) * view.aspectRatio); if ( ![depth, right, up, focalX, focalY].every(Number.isFinite) || focalX <= 0 || focalY <= 0 ) return null; - const halfAngle = Math.asin(sphereRadius / distance); + const halfAngle = Math.asin(sphereRadius / distanceM); const centerAngle = Math.atan2(Math.hypot(right, up), depth); const keyholeAngle = Math.atan(keyhole.radius / Math.max(focalX, focalY)); // No overlay visibility hysteresis: a fully contained smaller globe needs no reset. const framed = centerAngle + halfAngle <= keyholeAngle; if (!framed) return false; // Projection alone does not prove that a tiny globe is within depth planes. - if ( - depth - sphereRadius < frustum.near || - depth + sphereRadius > frustum.far - ) + if (depth - sphereRadius < view.near || depth + sphereRadius > view.far) return null; return true; } catch { @@ -1744,25 +1687,36 @@ function globeRotationFitsKeyhole(camera = _viewer.camera) { } } -/** Check the unchanged reset destination without moving the live camera. */ +/** + * Check the unchanged reset destination without moving the live camera: the + * view the Globe View preset sets above the current point, with the live + * camera's projection. Its axes are the camera convention's: heading, + * pitch and roll in the east-north-up frame, the view along the frame's x + * once heading is turned a quarter back. + */ function globeResetFitsKeyhole() { try { - const camera = Cesium.Camera.clone(_viewer.camera); - const { longitude, latitude } = _viewer.camera.positionCartographic; - camera.setView({ - destination: Cesium.Cartesian3.fromRadians( - longitude, - latitude, - GLOBE_VIEW.heightM, - ), - orientation: { - heading: 0, - pitch: Cesium.Math.toRadians(GLOBE_VIEW.pitchDeg), - roll: 0, - }, - endTransform: Cesium.Matrix4.IDENTITY, + const camera = cameraOf(_viewer); + const pose = camera.pose(); + const here = toCartographicRadians(pose.position); + const position = fromRadians(here.lon, here.lat, GLOBE_VIEW.heightM); + const axes = headingPitchRollFrame(position, { + heading: 0 - Math.PI / 2, + pitch: toRadians(GLOBE_VIEW.pitchDeg), + roll: 0, }); - return globeRotationFitsKeyhole(camera) === true; + const direction = axes.x; + const up = axes.z; + return ( + globeRotationFitsKeyhole({ + ...liveView(camera, pose), + live: false, + position, + direction, + up, + right: cross(direction, up), + }) === true + ); } catch { return false; } @@ -1809,21 +1763,20 @@ export function initCameraVerbs( typeof isCockpitActive === 'function' ? isCockpitActive : null; _viewer = viewer; _lookBaseline = null; - if (_tickRemover) _tickRemover(); - _tickRemover = viewer.clock.onTick.addEventListener(onTick); + listenForFrames(); if (_trackingRemover) _trackingRemover(); // Cockpit can acquire then clear tracking before the next clock tick. // Yield on acquisition itself without changing legacy camera motions. - _trackingRemover = viewer.trackedEntityChanged?.addEventListener((entity) => { - if (entity && _active?.kind === 'rotate_globe') + _trackingRemover = onFollowChanged(viewer, (followed) => { + if (followed && _active?.kind === 'rotate_globe') interruptCameraMotion('globe-camera-owner-changed'); // A pivoting tilt's lookAt would fight the follow camera every frame. - else if (entity && _active?.kind === 'tilt' && _active.hpr) + else if (followed && _active?.kind === 'tilt' && _active.hpr) interruptCameraMotion('tilt-camera-owner-changed'); }); for (const rm of _inputRemovers) rm(); _inputRemovers = []; - const canvas = viewer.scene.canvas; + const canvas = canvasOf(viewer); // ANY manual camera input reclaims control — the cancelFlight reflex. for (const evt of ['pointerdown', 'touchstart', 'wheel']) { const h = () => { @@ -1850,14 +1803,8 @@ function requestedTiltPitch(args, direction) { // The camera never looks above the horizon, so a positive angle can only // mean the same angle below it ("tilt 45 degrees" sent as 45). if (Number.isFinite(requested)) - return Cesium.Math.clamp( - Cesium.Math.toRadians(-Math.abs(requested)), - PITCH_MIN, - PITCH_MAX, - ); - return direction === null - ? Cesium.Math.toRadians(TILT_DEFAULT_PITCH_DEG) - : null; + return clamp(toRadians(-Math.abs(requested)), PITCH_MIN, PITCH_MAX); + return direction === null ? toRadians(TILT_DEFAULT_PITCH_DEG) : null; } /** @@ -1958,14 +1905,11 @@ export function moveCamera(args = {}, runNavigation = null) { if (motion === 'tilt' && tiltToPitch !== null) { // Angles and limits are the camera's own pitch, whatever the swing pivots // about; releasing the follow camera does not change it. - const from = _viewer.camera.pitch; + const from = cameraOf(_viewer).pose().pitch; // -89 or -90 means top-down, which a -90° view already is: the clamp // must not tilt it up 1°. const atTopDown = tiltToPitch <= PITCH_MIN && from <= PITCH_MIN; - if ( - atTopDown || - Math.abs(tiltToPitch - from) < Cesium.Math.toRadians(0.5) - ) { + if (atTopDown || Math.abs(tiltToPitch - from) < toRadians(0.5)) { // Still a camera request: it stops a running motion and releases the // follow camera, as a tilt that moves would. const hold = () => { @@ -1974,9 +1918,7 @@ export function moveCamera(args = {}, runNavigation = null) { ok: true, action: 'move_camera', motion, - pitchDeg: Math.round( - Cesium.Math.toDegrees(atTopDown ? from : tiltToPitch), - ), + pitchDeg: Math.round(toDegrees(atTopDown ? from : tiltToPitch)), unchanged: true, }; }; @@ -1986,8 +1928,8 @@ export function moveCamera(args = {}, runNavigation = null) { // as {direction:'down', pitchDeg:10} would tilt up from -45°. const towards = tiltToPitch > from ? 'up' : 'down'; if ((direction === 'up' || direction === 'down') && direction !== towards) { - const target = Math.round(Cesium.Math.toDegrees(tiltToPitch)); - const now = Math.round(Cesium.Math.toDegrees(from)); + const target = Math.round(toDegrees(tiltToPitch)); + const now = Math.round(toDegrees(from)); return { ok: false, action: 'move_camera', @@ -1996,25 +1938,20 @@ export function moveCamera(args = {}, runNavigation = null) { } if ( towards === 'up' && - from >= - tiltUpLimit(tiltStartFrame(_viewer.camera)) - Cesium.Math.toRadians(0.5) + from >= tiltUpLimit(tiltStartFrame(cameraOf(_viewer))) - toRadians(0.5) ) return tiltUpLimitRefusal(); } else if (motion === 'tilt') { // Honest limits: at the clamp a tilt is a no-op — say so instead of // reporting success and letting the model gaslight itself (field test). - const pitch = _viewer.camera.pitch; + const pitch = cameraOf(_viewer).pose().pitch; if ( direction === 'up' && - pitch >= - tiltUpLimit(tiltStartFrame(_viewer.camera)) - Cesium.Math.toRadians(0.5) + pitch >= tiltUpLimit(tiltStartFrame(cameraOf(_viewer))) - toRadians(0.5) ) { return tiltUpLimitRefusal(); } - if ( - direction === 'down' && - pitch <= PITCH_MIN + Cesium.Math.toRadians(0.5) - ) { + if (direction === 'down' && pitch <= PITCH_MIN + toRadians(0.5)) { return { ok: false, action: 'move_camera', @@ -2027,16 +1964,15 @@ export function moveCamera(args = {}, runNavigation = null) { const look = motion === 'tilt' ? tiltLook( - _viewer.camera.pitch, + cameraOf(_viewer).pose().pitch, tiltToPitch ?? - _viewer.camera.pitch + - Cesium.Math.toRadians(ONCE.tiltDeg) * - (direction === 'up' ? 1 : -1), + cameraOf(_viewer).pose().pitch + + toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1), ) : motion === 'rotate' ? direction === 'left' - ? 'lookLeft' - : 'lookRight' + ? 'left' + : 'right' : null; // Honest limits from orbit too: a stopped turn rests within 0.05° of its // limit, so one that cannot go half a degree further is refused rather than @@ -2053,15 +1989,14 @@ export function moveCamera(args = {}, runNavigation = null) { if ( (motion === 'rotate_globe' || (motion === 'orbit' && typeof runNavigation !== 'function')) && - _viewer?.trackedEntity + isFollowing(_viewer) ) { // The follow camera owns a tracked view; a lookAt orbit fights it frame // by frame and stop rips the camera out (field finding). Honest refusal // until tracked-orbit rides the follow camera natively (roadmap). + const followed = followedOf(_viewer); const label = - _viewer.trackedEntity?.name || - _viewer.trackedEntity?.id || - 'the tracked target'; + followed?.name || followed?.labelModel?.title || 'the tracked target'; return { ok: false, action: 'move_camera', @@ -2070,19 +2005,23 @@ export function moveCamera(args = {}, runNavigation = null) { } let globePose; if (motion === 'rotate_globe') { - if (_viewer.scene.mode !== Cesium.SceneMode.SCENE3D) { + const camera = cameraOf(_viewer); + let pose; + try { + pose = camera.pose(); + } catch { + // A frustum the camera cannot describe (depth limits out of order). return { ok: false, action: 'move_camera', - error: 'Globe rotation requires a 3D view.', + reason: 'unsupported-view', + error: 'Globe rotation requires a supported perspective view.', }; } - const cam = _viewer.camera; globePose = { - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), - up: Cesium.Cartesian3.normalize(cam.upWC, new Cesium.Cartesian3()), - right: Cesium.Cartesian3.clone(cam.rightWC), + position: vec(pose.position.x, pose.position.y, pose.position.z), + direction: vec(pose.direction.x, pose.direction.y, pose.direction.z), + up: normalize(pose.up), }; if (_isCockpitActive?.()) return { @@ -2091,14 +2030,7 @@ export function moveCamera(args = {}, runNavigation = null) { reason: 'camera-owned', error: 'Exit Cockpit before rotating the globe.', }; - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - if (!( - Number.isFinite(ellipsoid.minimumRadius) && - ellipsoid.minimumRadius > 0 && - Number.isFinite(ellipsoid.maximumRadius) && - ellipsoid.maximumRadius >= ellipsoid.minimumRadius && - Number.isFinite(Cesium.Cartesian3.magnitude(globePose.position)) - )) + if (!Number.isFinite(magnitude(globePose.position))) return { ok: false, action: 'move_camera', @@ -2106,7 +2038,7 @@ export function moveCamera(args = {}, runNavigation = null) { error: 'Globe rotation requires a finite supported ellipsoid and a clear globe view.', }; - const fits = globeRotationFitsKeyhole(); + const fits = globeRotationFitsKeyhole(liveView(camera, pose)); if (fits === null) return { ok: false, @@ -2140,7 +2072,7 @@ export function moveCamera(args = {}, runNavigation = null) { interruptCameraMotion('replaced'); // Checked again only if the release left the camera somewhere other than // where the check above expected it. - if (look && !lookProven(_viewer.camera, look)) { + if (look && !lookProven(findCamera(_viewer)?.pose(), look)) { const refusal = checkLookFromOrbit(look); if (refusal) return refusal; } @@ -2151,7 +2083,7 @@ export function moveCamera(args = {}, runNavigation = null) { mode, }; if (motion === 'tilt') { - const frame = tiltStartFrame(_viewer.camera); + const frame = tiltStartFrame(cameraOf(_viewer)); const { target, pivot, from } = frame; if (pivot) { state.target = target; @@ -2170,7 +2102,7 @@ export function moveCamera(args = {}, runNavigation = null) { // From orbit an in-place tilt stops where the planet would leave the // frame: aim it there, and say so. if (!pivot) { - const framed = tiltPitchWithinFrame(_viewer.camera, goal); + const framed = tiltPitchWithinFrame(cameraOf(_viewer), goal); if (framed !== goal) { goal = framed; stopNote = tiltFrameNote(goal); @@ -2184,13 +2116,12 @@ export function moveCamera(args = {}, runNavigation = null) { state.askedPitch = tiltToPitch; state.durationS = Math.max( ONCE.durationS, - Math.abs(Cesium.Math.toDegrees(goal - from)) / TILT_TO_DEG_S, + Math.abs(toDegrees(goal - from)) / TILT_TO_DEG_S, ); if (goal !== tiltToPitch) stoppedAt = goal; } else { // A nudge stops at the limit it travels toward. - const step = - Cesium.Math.toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1); + const step = toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1); state.goalPitch = step > 0 ? Math.min(from + step, Math.max(from, upLimit)) @@ -2200,21 +2131,28 @@ export function moveCamera(args = {}, runNavigation = null) { if (motion === 'rotate_globe') { // Convert an inherited ground-target frame without changing the world // pose. Rotation must pivot about Earth, never the previous local target. - const cam = _viewer.camera; - cam.cancelFlight(); - cam.lookAtTransform(Cesium.Matrix4.IDENTITY); - // Handoff may level a route's bank. Keep the caller's exact world pose. - // Copy the basis directly: setView's heading/pitch conversion is singular - // at nadir and can change the captured orientation near the poles. - Cesium.Cartesian3.clone(globePose.position, cam.position); - Cesium.Cartesian3.clone(globePose.direction, cam.direction); - Cesium.Cartesian3.clone(globePose.up, cam.up); - Cesium.Cartesian3.clone(globePose.right, cam.right); + const camera = cameraOf(_viewer); + camera.cancelFlight(); + camera.release(); + // Handoff may level a route's bank. Keep the caller's world pose, but + // write it only when the handoff changed it: a heading and pitch + // conversion inside the camera is singular at nadir, so an unchanged + // pose is left exactly as it is. + const now = camera.pose(); + if ( + distance(now.position, globePose.position) > 1e-6 || + distance(now.direction, globePose.direction) > 1e-9 || + distance(normalize(now.up), globePose.up) > 1e-9 + ) + camera.setView({ + destination: globePose.position, + orientation: { direction: globePose.direction, up: globePose.up }, + }); state.rotationAxis = globePose.up; - state.rotationRadius = Cesium.Cartesian3.magnitude(globePose.position); + state.rotationRadius = magnitude(globePose.position); } if (motion === 'orbit') { - if (_viewer.scene.tweens.length > 0) { + if (cameraFlying()) { // A camera flight is in progress — ALWAYS arm and capture at the // destination; a target existing right now is meaningless (the globe // is always under the crosshair). The voice runner already holds an @@ -2260,18 +2198,11 @@ export function moveCamera(args = {}, runNavigation = null) { armed: 'waiting-for-arrival', }; } - const cam = _viewer.camera; - const range = Cesium.Cartesian3.distance(cam.positionWC, target); // Pitch from geometry so lookAt reproduces the CURRENT framing exactly. - const carto = Cesium.Cartographic.fromCartesian(cam.positionWC); - const tCarto = Cesium.Cartographic.fromCartesian(target); - const dh = carto.height - tCarto.height; - const pitch = -Math.asin( - Math.min(1, Math.max(-1, dh / Math.max(1, range))), - ); + const pose = cameraOf(_viewer).pose(); state.target = target; - state.hpr = new Cesium.HeadingPitchRange(cam.heading, pitch, range); - state.hprStartHeading = cam.heading; + state.hpr = orbitFraming(pose, target); + state.hprStartHeading = pose.heading; } setActiveMotion(state); // Verb motion drives the camera per clock tick — hold until interrupted; @@ -2285,15 +2216,13 @@ export function moveCamera(args = {}, runNavigation = null) { speed, mode: state.mode, ...(tiltToPitch !== null && { - pitchDeg: Math.round(Cesium.Math.toDegrees(stoppedAt ?? tiltToPitch)), + pitchDeg: Math.round(toDegrees(stoppedAt ?? tiltToPitch)), }), ...(stopNote !== null && { note: stopNote }), }; }; const preserveCameraFlight = - motion === 'orbit' && - _viewer.scene.tweens.length > 0 && - !_viewer.trackedEntity; + motion === 'orbit' && cameraFlying() && !isFollowing(_viewer); return typeof runNavigation === 'function' ? runNavigation(start, { preserveCameraFlight }) : start(); @@ -2344,7 +2273,7 @@ export function adjustOrbitRange(factor) { function retargetTiltAfterZoom(m) { if (m.kind !== 'tilt' || m.mode !== 'once' || m.askedPitch === undefined) return {}; - let from = _viewer.camera.pitch; + let from = cameraOf(_viewer).pose().pitch; if (!(m.askedPitch > from)) return {}; if (m.hpr) { // At the same pivot pitch a longer range looks down more steeply (the @@ -2356,11 +2285,7 @@ function retargetTiltAfterZoom(m) { for (let i = 0; i < 4; i += 1) { const error = from - pivotCameraPitch(m.target, m.hpr, m.hpr.pitch); if (Math.abs(error) < 1e-7) break; - const pitch = Cesium.Math.clamp( - m.hpr.pitch + error, - -Cesium.Math.PI_OVER_TWO, - cap, - ); + const pitch = clamp(m.hpr.pitch + error, -PI_OVER_TWO, cap); if (pitch === m.hpr.pitch) break; m.hpr.pitch = pitch; } @@ -2380,14 +2305,14 @@ function retargetTiltAfterZoom(m) { m.elapsed = 0; m.durationS = Math.max( ONCE.durationS, - Math.abs(Cesium.Math.toDegrees(goal - from)) / TILT_TO_DEG_S, + Math.abs(toDegrees(goal - from)) / TILT_TO_DEG_S, ); const limited = goal !== m.askedPitch; return { - pitchDeg: Math.round(Cesium.Math.toDegrees(goal)), + pitchDeg: Math.round(toDegrees(goal)), note: limited ? tiltHorizonNote(goal) - : `The tilt now reaches ${Math.round(Cesium.Math.toDegrees(goal))}°.`, + : `The tilt now reaches ${Math.round(toDegrees(goal))}°.`, }; } @@ -2462,12 +2387,10 @@ export function flyRoute( error: 'The selected route has an invalid waypoint.', }; } - const pts = route.path.map((p) => - Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0), - ); + const pts = route.path.map((p) => fromDegrees(p.lon, p.lat, p.height || 0)); const cumM = [0]; for (let i = 1; i < pts.length; i += 1) { - cumM.push(cumM[i - 1] + Cesium.Cartesian3.distance(pts[i - 1], pts[i])); + cumM.push(cumM[i - 1] + distance(pts[i - 1], pts[i])); } if (!Number.isFinite(cumM.at(-1)) || cumM.at(-1) <= 0) { return { @@ -2485,8 +2408,8 @@ export function flyRoute( speed, floorFn, warmFn, - probeFn: (cells) => probeMeshFloorM(_viewer?.scene, cells), - cameraHeightM: _viewer?.camera?.positionCartographic?.height, + probeFn: (cells) => probeMeshFloorM(_viewer, cells), + cameraHeightM: findCamera(_viewer)?.pose().height, reducedMotion: prefersReducedMotion(), }), ); diff --git a/src/cctvFocusPolicy.js b/src/cctvFocusPolicy.js index e11c1e1caa..1cabba37f3 100644 --- a/src/cctvFocusPolicy.js +++ b/src/cctvFocusPolicy.js @@ -1,22 +1,23 @@ /** * Activates the nearest CCTV record on layer enable and flies only when no - * aircraft tracker or cockpit camera owns the view. + * followed target or cockpit camera owns the view. * @param {Object} options Layer-enable focus inputs. - * @param {*} options.trackedEntity Current Cesium tracked entity, if any. + * @param {*} options.followed What the camera follows, if anything + * (`followedOf`). * @param {boolean} options.cockpitActive Whether cockpit mode owns the camera. * @param {() => (string|null)} options.activate Nearest-camera activation. * @param {(cameraId: string) => *} options.fly Optional camera flight. * @returns {*} Activated camera ID for a held view, or the flight result. */ export function runCctvLayerEnableFocus({ - trackedEntity = null, + followed = null, cockpitActive = false, activate, fly, } = {}) { const cameraId = activate?.(); if (!cameraId) return false; - if (trackedEntity || cockpitActive) return cameraId; + if (followed || cockpitActive) return cameraId; return fly?.(cameraId); } @@ -25,11 +26,11 @@ export function runCctvLayerEnableFocus({ * chain. Either observation suppresses the optional CCTV focus flight. * @param {Object} [before={}] Ownership immediately before the await. * @param {Object} [after={}] Ownership immediately after the await. - * @returns {{ trackedEntity: *, cockpitActive: boolean }} Conservative ownership. + * @returns {{ followed: *, cockpitActive: boolean }} Conservative ownership. */ function mergeCctvEnableOwnership(before = {}, after = {}) { return { - trackedEntity: before.trackedEntity || after.trackedEntity || null, + followed: before.followed || after.followed || null, cockpitActive: !!(before.cockpitActive || after.cockpitActive), }; } @@ -60,7 +61,7 @@ export async function runCctvLayerEnableTransition({ const ownershipBefore = readOwnership?.() || {}; if (target === true) { debug?.('[UI:CCTV] ownership before setEnabled await', { - trackedId: ownershipBefore.trackedEntity?.id ?? null, + trackedId: ownershipBefore.followed?.key ?? null, cockpitActive: !!ownershipBefore.cockpitActive, }); } @@ -68,7 +69,7 @@ export async function runCctvLayerEnableTransition({ const ownershipAfter = readOwnership?.() || {}; if (target === true) { debug?.('[UI:CCTV] ownership after setEnabled await', { - trackedId: ownershipAfter.trackedEntity?.id ?? null, + trackedId: ownershipAfter.followed?.key ?? null, cockpitActive: !!ownershipAfter.cockpitActive, }); } diff --git a/src/cctvFocusPolicy.test.mjs b/src/cctvFocusPolicy.test.mjs index 333926a0f9..fd0913294d 100644 --- a/src/cctvFocusPolicy.test.mjs +++ b/src/cctvFocusPolicy.test.mjs @@ -8,8 +8,8 @@ import { test('CCTV layer enable activates nearest without stealing a tracked or cockpit view', () => { for (const ownership of [ - { trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }, - { trackedEntity: null, cockpitActive: true }, + { followed: { key: 'tracked-plane' }, cockpitActive: false }, + { followed: null, cockpitActive: true }, ]) { const calls = []; const result = runCctvLayerEnableFocus({ @@ -48,15 +48,15 @@ test('CCTV layer enable activates nearest without stealing a tracked or cockpit }); test('CCTV enable retains a pre-await tracking snapshot when tracking clears during enable', async () => { - let trackedEntity = { id: 'tracked-plane' }; + let followed = { key: 'tracked-plane' }; let flyCalls = 0; const diagnostics = []; const result = await runCctvLayerEnableTransition({ target: true, - readOwnership: () => ({ trackedEntity, cockpitActive: false }), + readOwnership: () => ({ followed, cockpitActive: false }), setEnabled: async () => { await Promise.resolve(); - trackedEntity = null; + followed = null; }, shouldFocus: () => true, activate: () => 'cam-near', @@ -83,7 +83,7 @@ test('CCTV disable transition does not emit enable-ownership diagnostics', async const result = await runCctvLayerEnableTransition({ target: false, - readOwnership: () => ({ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }), + readOwnership: () => ({ followed: { key: 'tracked-plane' }, cockpitActive: false }), setEnabled: async (target) => transitions.push(target), shouldFocus: () => true, activate: () => 'cam-near', diff --git a/src/celestialRing.js b/src/celestialRing.js index 525ded44ef..65e128ea85 100644 --- a/src/celestialRing.js +++ b/src/celestialRing.js @@ -1,5 +1,25 @@ -import * as Cesium from 'cesium'; import { governorRequestRender } from './renderGovernor.js'; +import { + cameraOf, + canvasOf, + findCamera, + findFrame, + findQuery, +} from './render/rendererOf.js'; +import { + moonPositionInertial, + sunPositionInertial, + temeToPseudoFixed, +} from './geo/celestial.js'; +import { WGS84 } from './geo/ellipsoid.js'; +import { frameVector } from './geo/frames.js'; +import { + dot, + magnitude, + normalize, + PI_OVER_TWO, + toRadians, +} from './geo/vector.js'; import { worldClock, worldTimeFor } from './time/worldClock.js'; // The ring shows the sun and moon at the time the sky is drawn. @@ -38,7 +58,13 @@ const EPHEMERIS_WORLD_STEP_MS = 60_000; const RING_INSET_PX = 11; const MARKER_INSET_PX = 36; const COLLIDING_MARKER_EXTRA_INSET_PX = 32; -const MARKER_COLLISION_ANGLE = Cesium.Math.toRadians(6); +const MARKER_COLLISION_ANGLE = toRadians(6); +/** The ellipsoid's largest radius, metres. */ +const EARTH_MAX_RADIUS_M = Math.max( + WGS84.radii.x, + WGS84.radii.y, + WGS84.radii.z, +); const FULL_GLOBE_RADIUS_RATIO = 0.61; const TAU = Math.PI * 2; // This overlay is a secondary HUD treatment. Keep it smooth while reserving @@ -218,7 +244,7 @@ export function isFullGlobeInsideKeyhole(geometry, wasVisible = false) { /** Return the Earth-disc radius in CSS pixels for a perspective camera. */ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) { - const earthRadiusM = Cesium.Ellipsoid.WGS84.maximumRadius; + const earthRadiusM = EARTH_MAX_RADIUS_M; if ( !Number.isFinite(cameraDistance) || cameraDistance <= earthRadiusM || @@ -234,15 +260,19 @@ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) { return Number.isFinite(radius) && radius > 0 ? radius : null; } +const EARTH_CENTRE = Object.freeze({ x: 0, y: 0, z: 0 }); + /** - * Project the visible Earth disc into viewport coordinates. + * Project the visible Earth disc into viewport coordinates, through the + * renderer's camera pose and its query port's projection. * Shared by full-globe UI treatments that must agree on visual containment. * - * @param {object} viewer - Cesium Viewer-like object. + * @param {object} viewer - The scene object the renderer is found from. * @param {number} width - Viewport width in CSS pixels. * @param {number} height - Viewport height in CSS pixels. - * @param {object} [scratchCenter] - Reusable Cesium Cartesian2 result. - * @param {object} [scratchToCenter] - Reusable Cesium Cartesian3 result. + * @param {{x:number,y:number}} [scratchCenter] - Takes the projected centre. + * @param {{x:number,y:number,z:number}} [scratchToCenter] - Takes the + * vector from the eye to the Earth's centre. * @returns {object|null} */ export function projectEarthDiscToViewport( @@ -252,36 +282,32 @@ export function projectEarthDiscToViewport( scratchCenter = undefined, scratchToCenter = undefined, ) { - const camera = viewer?.camera; - const scene = viewer?.scene; - if (!camera || !scene || !(width > 0) || !(height > 0)) return null; + const camera = findCamera(viewer); + if (!camera || !(width > 0) || !(height > 0)) return null; + const pose = camera.pose(); + const eye = pose.position; - const distance = Cesium.Cartesian3.magnitude(camera.positionWC); + const distance = magnitude(eye); + if (!Number.isFinite(distance) || distance <= EARTH_MAX_RADIUS_M) return null; + + const toCenter = scratchToCenter || { x: 0, y: 0, z: 0 }; + toCenter.x = -eye.x; + toCenter.y = -eye.y; + toCenter.z = -eye.z; + if (dot(pose.direction, toCenter) <= 0) return null; + + const projected = findQuery(viewer)?.project(EARTH_CENTRE); if ( - !Number.isFinite(distance) || - distance <= Cesium.Ellipsoid.WGS84.maximumRadius + !projected || + !Number.isFinite(projected.x) || + !Number.isFinite(projected.y) ) return null; + const center = scratchCenter || { x: 0, y: 0 }; + center.x = projected.x; + center.y = projected.y; - const toCenter = Cesium.Cartesian3.negate( - camera.positionWC, - scratchToCenter || new Cesium.Cartesian3(), - ); - if (Cesium.Cartesian3.dot(camera.directionWC, toCenter) <= 0) return null; - - const center = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - Cesium.Cartesian3.ZERO, - scratchCenter, - ); - if (!center || !Number.isFinite(center.x) || !Number.isFinite(center.y)) - return null; - - const earthRadius = earthDiscScreenRadius( - distance, - height, - camera.frustum?.fovy, - ); + const earthRadius = earthDiscScreenRadius(distance, height, pose.fovy); if (!earthRadius) return null; const keyhole = getKeyholeGeometry(width, height); @@ -396,14 +422,23 @@ let rings = 0; */ export class CelestialRing { /** - * @param {Cesium.Viewer} viewer - * @param {{enabled?:boolean,onAutoDisable?:Function,store:object}} options + * @param {object} viewer - The scene object the renderer is found from; + * the ring reads its canvas and container (DOM) and reaches the rest + * through the renderer's camera, frame and query ports. + * @param {{enabled?:boolean,onAutoDisable?:Function,store:object,preciseFrameAt?:Function}} options * `store` is the celestial ring store (src/ui/stores/celestialRing.js); * the keyhole helpers here stay free of Vue for the packages that use - * them. + * them. `preciseFrameAt(ms)` gives the ICRF-to-fixed rotation as axes, + * or null while its tables have not loaded; without it, or while it has + * no answer, the ring uses the pseudo-fixed frame. */ - constructor(viewer, { enabled = true, onAutoDisable = null, store }) { + constructor( + viewer, + { enabled = true, onAutoDisable = null, store, preciseFrameAt = null }, + ) { this.viewer = viewer; + this._preciseFrameAt = + typeof preciseFrameAt === 'function' ? preciseFrameAt : null; this.enabled = !!enabled; this.visible = false; this._onAutoDisable = @@ -426,18 +461,14 @@ export class CelestialRing { this._moonCanvas = null; this._moonCtx = null; - this._sunInertial = new Cesium.Cartesian3(); - this._moonInertial = new Cesium.Cartesian3(); - this._sunFixed = new Cesium.Cartesian3(); - this._moonFixed = new Cesium.Cartesian3(); - this._toCenter = new Cesium.Cartesian3(); - this._screenCenter = new Cesium.Cartesian2(); - this._fixedMatrix = new Cesium.Matrix3(); + this._sunFixed = { x: 0, y: 0, z: 0 }; + this._moonFixed = { x: 0, y: 0, z: 0 }; + this._toCenter = { x: 0, y: 0, z: 0 }; + this._screenCenter = { x: 0, y: 0 }; this._initView(store); - this._removePostRender = viewer.scene.postRender.addEventListener(() => - this._draw(), - ); + this._removePostRender = + findFrame(viewer)?.on('postRender', () => this._draw()) ?? null; // Pre-existing staleness fix (perf wave 2 review): the ephemeris was // sampled once per visible-enable from the FROZEN app clock, so the // sun/moon markers aged with the app. Resample real wall time each @@ -453,8 +484,6 @@ export class CelestialRing { governorRequestRender('celestial-ephemeris'); }, 60_000); // A jump in the world time moves the sun and moon at once. - this._skyDate = new Date(); - this._skyTime = new Cesium.JulianDate(); // Played through, the sky moves on each minute of world time it passes. this._ephemerisWorldMs = null; this._unsubscribeWorldTime = worldClock.subscribe(({ timeMs }) => { @@ -554,9 +583,14 @@ export class CelestialRing { }); } + /** The renderer's canvas; a viewer with no renderer bound, its own. */ + _canvas() { + return canvasOf(this.viewer); + } + /** Whether the current camera already frames the complete globe inside the keyhole. */ isGlobeFullyVisible() { - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const width = canvas.clientWidth || canvas.width; const height = canvas.clientHeight || canvas.height; if (!(width > 0 && height > 0)) return false; @@ -571,13 +605,15 @@ export class CelestialRing { * @returns {boolean} Whether a valid camera flight was started. */ focusFullGlobe({ duration = 2.4 } = {}) { - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const height = canvas.clientHeight || canvas.height; - const cartographic = this.viewer.camera.positionCartographic; - const fovy = this.viewer.camera.frustum?.fovy; + const camera = cameraOf(this.viewer); + const pose = camera.pose(); + const fovy = pose.fovy; if ( !(height > 0) || - !cartographic || + !Number.isFinite(pose.lon) || + !Number.isFinite(pose.lat) || !Number.isFinite(fovy) || fovy <= 0 || fovy >= Math.PI @@ -585,7 +621,7 @@ export class CelestialRing { return false; } - const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius; + const earthRadius = EARTH_MAX_RADIUS_M; const keyholeRadius = getKeyholeGeometry( canvas.clientWidth || canvas.width, height, @@ -600,27 +636,25 @@ export class CelestialRing { this._focusInProgress = true; const finishFocus = () => { this._focusInProgress = false; - this.viewer.scene.requestRender?.(); + findFrame(this.viewer)?.requestRender('celestial-focus'); }; - this.viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromRadians( - cartographic.longitude, - cartographic.latitude, - altitude, - ), - orientation: { - heading: this.viewer.camera.heading, - pitch: -Cesium.Math.PI_OVER_TWO, - roll: 0, + camera.flyTo( + { lon: pose.lon, lat: pose.lat, height: altitude }, + { + orientation: { + heading: pose.heading, + pitch: -PI_OVER_TWO, + roll: 0, + }, + durationS: duration, + easing: 'cubicInOut', + onComplete: finishFocus, + onCancel: () => { + finishFocus(); + if (!this.isGlobeFullyVisible()) this._autoDisable(); + }, }, - duration, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - complete: finishFocus, - cancel: () => { - finishFocus(); - if (!this.isGlobeFullyVisible()) this._autoDisable(); - }, - }); + ); return true; } @@ -671,31 +705,16 @@ export class CelestialRing { /** * Sample Earth-fixed directions once per enable. Camera movement only * re-projects these cached vectors; it never re-runs the planetary model. + * The precise ICRF frame serves once its tables have loaded, the + * pseudo-fixed one before. + * @param {number} ms Epoch milliseconds. */ - _updateEphemeris(time) { + _updateEphemeris(ms) { if (!this._ephemerisDirty) return true; - Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( - time, - this._sunInertial, - ); - Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( - time, - this._moonInertial, - ); - const matrix = - Cesium.Transforms.computeIcrfToFixedMatrix(time, this._fixedMatrix) || - Cesium.Transforms.computeTemeToPseudoFixedMatrix(time, this._fixedMatrix); - if (!matrix) return false; - - Cesium.Matrix3.multiplyByVector(matrix, this._sunInertial, this._sunFixed); - Cesium.Matrix3.multiplyByVector( - matrix, - this._moonInertial, - this._moonFixed, - ); - Cesium.Cartesian3.normalize(this._sunFixed, this._sunFixed); - Cesium.Cartesian3.normalize(this._moonFixed, this._moonFixed); + const frame = this._preciseFrameAt?.(ms) ?? temeToPseudoFixed(ms); + this._sunFixed = normalize(frameVector(frame, sunPositionInertial(ms))); + this._moonFixed = normalize(frameVector(frame, moonPositionInertial(ms))); this._ephemerisDirty = false; this._ephemerisUpdateCount += 1; return true; @@ -792,7 +811,7 @@ export class CelestialRing { const now = performance.now(); if (now < this._nextDrawAt) return; this._nextDrawAt = now + 1000 / CELESTIAL_MAX_FRAME_RATE; - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const width = canvas.clientWidth || canvas.width; const height = canvas.clientHeight || canvas.height; if (!(width > 0 && height > 0)) return; @@ -822,19 +841,17 @@ export class CelestialRing { return; } - this._skyDate.setTime(skyTime()); - const time = Cesium.JulianDate.fromDate(this._skyDate, this._skyTime); - if (!this._updateEphemeris(time)) return; + if (!this._updateEphemeris(skyTime())) return; this._present({ ephemerisUpdates: String(this._ephemerisUpdateCount) }); - const camera = this.viewer.camera; + const pose = cameraOf(this.viewer).pose(); const sunProjection = celestialScreenAngle( - Cesium.Cartesian3.dot(this._sunFixed, camera.rightWC), - Cesium.Cartesian3.dot(this._sunFixed, camera.upWC), + dot(this._sunFixed, pose.right), + dot(this._sunFixed, pose.up), this._sunAngle, ); const moonProjection = celestialScreenAngle( - Cesium.Cartesian3.dot(this._moonFixed, camera.rightWC), - Cesium.Cartesian3.dot(this._moonFixed, camera.upWC), + dot(this._moonFixed, pose.right), + dot(this._moonFixed, pose.up), this._moonAngle, ); if (sunProjection.stable) this._sunAngle = sunProjection.angle; diff --git a/src/celestialRingView.test.mjs b/src/celestialRingView.test.mjs index c834ed53a6..841f42d746 100644 --- a/src/celestialRingView.test.mjs +++ b/src/celestialRingView.test.mjs @@ -9,7 +9,14 @@ import { createPinia } from 'pinia'; import { useCelestialRingStore } from './ui/stores/celestialRing.js'; import CelestialRingView from './ui/views/panels/CelestialRing.vue'; import * as Cesium from 'cesium'; -import { CelestialRing } from './celestialRing.js'; +import { + CelestialRing, + earthDiscScreenRadius, + projectEarthDiscToViewport, +} from './celestialRing.js'; +import { bindRenderer } from './render/rendererOf.js'; +import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs'; +import { fakeSceneFrame } from './testSupport/fakeCesiumScene.mjs'; // happy-dom has no 2D context; a stand-in takes every drawing call. const context = new Proxy( @@ -19,18 +26,26 @@ const context = new Proxy( globalThis.HTMLCanvasElement.prototype.getContext = () => context; function fakeViewer(container) { - return { + const canvas = { + clientWidth: 400, + clientHeight: 300, + width: 400, + height: 300, + }; + const viewer = { container, + canvas, camera: { rightWC: new Cesium.Cartesian3(1, 0, 0), upWC: new Cesium.Cartesian3(0, 1, 0), }, scene: { - canvas: { clientWidth: 400, clientHeight: 300, width: 400, height: 300 }, + canvas, postRender: { addEventListener: () => () => {} }, requestRender() {}, }, }; + return bindFakeCesiumCamera(viewer, { frame: fakeSceneFrame(viewer) }); } function fixture(t) { @@ -157,8 +172,7 @@ const FRAMED = { /** Run one rendered frame, past the frame-rate throttle. */ function frame(ring, disc) { ring._projectedEarthDisc = () => disc; - // Fixed sun and moon directions; Cesium's own model would fetch its - // orientation data. + // Fixed sun and moon directions, so markers do not move with the clock. ring._updateEphemeris = () => { if (ring._ephemerisDirty) { Cesium.Cartesian3.clone(new Cesium.Cartesian3(1, 0, 0), ring._sunFixed); @@ -249,3 +263,119 @@ test('a ring the store no longer shows stops drawing', async (t) => { assert.equal(earlier.enabled, true); assert.equal(disabled, 0); }); + +test('the sun and moon directions are the planetary model in the pseudo-fixed frame', () => { + const pinia = createPinia(); + const ring = new CelestialRing(fakeViewer({}), { + enabled: false, + store: useCelestialRingStore(pinia), + // The precise frame's tables have not loaded. + preciseFrameAt: () => null, + }); + const ms = Date.UTC(2026, 10, 7, 12, 30); + ring._ephemerisDirty = true; + assert.equal(ring._updateEphemeris(ms), true); + // Cesium's own, before the sky has loaded the precise frame's tables. + const time = Cesium.JulianDate.fromDate(new Date(ms)); + const matrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time); + const expected = (inertial) => + Cesium.Cartesian3.normalize( + Cesium.Matrix3.multiplyByVector( + matrix, + inertial, + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + const sun = expected( + Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( + time, + ), + ); + const moon = expected( + Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( + time, + ), + ); + for (const [got, want] of [ + [ring._sunFixed, sun], + [ring._moonFixed, moon], + ]) + for (const axis of ['x', 'y', 'z']) + assert.ok(Object.is(got[axis], want[axis]), axis); + assert.equal(ring._ephemerisUpdateCount, 1); + ring.destroy(); +}); + +test('the projected disc reads the camera and query ports', () => { + const canvas = { clientWidth: 800, clientHeight: 600 }; + const viewer = { canvas }; + const distance = 3 * 6378137; + const pose = { + position: { x: distance, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, + fovy: Math.PI / 3, + }; + const unbind = bindRenderer(viewer, { + canvas, + camera: { pose: () => pose }, + query: { project: () => ({ x: 410, y: 290 }) }, + }); + const toCenter = { x: 0, y: 0, z: 0 }; + const centre = { x: 0, y: 0 }; + const disc = projectEarthDiscToViewport(viewer, 800, 600, centre, toCenter); + assert.equal(disc.earthCenterX, 410); + assert.equal(disc.earthCenterY, 290); + assert.deepEqual(centre, { x: 410, y: 290 }); + // The scratch takes the eye-to-centre vector, as callers read it after. + assert.deepEqual(toCenter, { x: -distance, y: -0, z: -0 }); + assert.ok( + Math.abs( + disc.earthRadius - earthDiscScreenRadius(distance, 600, pose.fovy), + ) < 1e-9, + ); + // Facing away: null, with the eye-to-centre vector still written, as + // radio navigation reads it after. + pose.direction = { x: 1, y: 0, z: 0 }; + const away = { x: 0, y: 0, z: 0 }; + assert.equal(projectEarthDiscToViewport(viewer, 800, 600, null, away), null); + assert.deepEqual(away, { x: -distance, y: -0, z: -0 }); + // Inside the ellipsoid's largest radius: null, the scratch untouched. + pose.position = { x: 6378137, y: 0, z: 0 }; + const inside = { x: 1, y: 2, z: 3 }; + assert.equal( + projectEarthDiscToViewport(viewer, 800, 600, null, inside), + null, + ); + assert.deepEqual(inside, { x: 1, y: 2, z: 3 }); + unbind(); +}); + +test('the precise frame serves once it answers', () => { + const pinia = createPinia(); + // A quarter turn about z: x goes to y. + const quarter = { + x: { x: 0, y: 1, z: 0 }, + y: { x: -1, y: 0, z: 0 }, + z: { x: 0, y: 0, z: 1 }, + }; + const ring = new CelestialRing(fakeViewer({}), { + enabled: false, + store: useCelestialRingStore(pinia), + preciseFrameAt: () => quarter, + }); + const ms = Date.UTC(2026, 10, 7, 12, 30); + ring._ephemerisDirty = true; + ring._updateEphemeris(ms); + const time = Cesium.JulianDate.fromDate(new Date(ms)); + const sun = Cesium.Cartesian3.normalize( + Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( + time, + ), + new Cesium.Cartesian3(), + ); + assert.ok(Math.abs(ring._sunFixed.x + sun.y) < 1e-12); + assert.ok(Math.abs(ring._sunFixed.y - sun.x) < 1e-12); + assert.ok(Math.abs(ring._sunFixed.z - sun.z) < 1e-12); + ring.destroy(); +}); diff --git a/src/cockpitCloudEffects.js b/src/cockpitCloudEffects.js index c1cc796b45..db1495391d 100644 --- a/src/cockpitCloudEffects.js +++ b/src/cockpitCloudEffects.js @@ -1,5 +1,6 @@ import { applicationServices } from './services/application.js'; -import * as Cesium from 'cesium'; +import { toRadians } from './geo/vector.js'; +import { findCamera } from './render/rendererOf.js'; import { greatCircleMeters } from './geoDistance.js'; import { deriveWeatherEffectProfile, @@ -341,15 +342,14 @@ class CockpitCloudEffectsController { } cameraPoint() { - const cartographic = this.viewer?.camera?.positionCartographic; - if (!cartographic) return null; - const latitude = Cesium.Math.toDegrees(cartographic.latitude); - const longitude = Cesium.Math.toDegrees(cartographic.longitude); + const pose = this.viewer ? findCamera(this.viewer)?.pose() : null; + if (!pose) return null; + const { lat: latitude, lon: longitude } = pose; if (![latitude, longitude].every(Number.isFinite)) return null; return { latitude, longitude, - altitudeM: Math.max(0, Number(cartographic.height) || 0), + altitudeM: Math.max(0, Number(pose.height) || 0), }; } @@ -543,7 +543,7 @@ class CockpitCloudEffectsController { render(timeSec) { const gl = this.gl; if (!gl || !this.program || !this.locations) return; - const windRadians = Cesium.Math.toRadians(this.windDirectionDeg); + const windRadians = toRadians(this.windDirectionDeg); const windScale = 0.008 + this.windStrength * 0.022; gl.useProgram(this.program); gl.uniform2f( diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 791fdbdb28..3c1e3ed142 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -225,7 +225,7 @@ test('Cockpit Escape handling precedes form-control shortcut suppression and foc assert.doesNotMatch(exit, /applyTrackedCameraFrame/); assert.match( ui, - /restoreTrackingFrame: \(entity\) => \{[\s\S]*?gevTrackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, + /restoreTrackingFrame: \(entity\) => \{[\s\S]*?readEntityRecord\(entity\)\?\.trackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, 'Cockpit exit must return camera-frame ownership through the source layer so Contact Focus cannot accumulate a second owner', ); }); @@ -291,14 +291,14 @@ test('the Contact panel never hides itself out from under its own NEXT button', ); }); -test('the cockpit reads its aircraft from the layer that owns Cesium tracking', () => { +test('the cockpit reads its aircraft from the layer the camera follows', () => { const read = readAircraftInfo.toString(); assert.ok(read, 'readAircraftInfo is missing'); assert.match(read, /resolveTrackedAircraftInfo\(\{/); - assert.match(read, /gevTrackedId/); - // In cockpit mode the controller moves the entity off viewer.trackedEntity, - // so its own handle is the tracked identity there. - assert.match(read, /this\.viewer\?\.trackedEntity \|\| this\.trackedEntity/); + assert.match(read, /trackedId: followed\?\.key/); + // In cockpit mode the controller stops the camera following, so its own + // handle is the tracked identity there. + assert.match(read, /followedOf\(this\.viewer\) \|\| this\.trackedFollow/); }); test('programmatic Context layer changes cannot bypass explicit expansion policy', () => { @@ -1173,7 +1173,7 @@ test('cockpit route direction uses self-contained vector artwork, not a font lig test('cockpit aircraft handoff invalidates the prior world-position anchor', () => { const match = _adoptTrackedEntity.toString(); assert.ok(match, 'cockpit tracked-entity handoff block is missing'); - assert.match(match, /this\.viewer\.trackedEntity = undefined;/); + assert.match(match, /stopFollowing\(this\.viewer\);/); assert.match(match, /this\.cockpitAnchorValid = false;/); assert.match( match, diff --git a/src/cockpitMath.js b/src/cockpitMath.js index c304cac75f..05a69904c7 100644 --- a/src/cockpitMath.js +++ b/src/cockpitMath.js @@ -412,7 +412,7 @@ export function relativeBearing(bearing, heading) { * Resolve which flight layer owns the cockpit's tracked aircraft. * * Both layers can briefly describe a tracked aircraft during a cross-layer - * handoff, so the viewer's normalized tracked identity (`gevTrackedId`) is the + * handoff, so the viewer's normalized tracked identity (the entity record's `trackedId`) is the * tie-breaker — the same rule `militaryAwareness.currentTrackedFlightSubject` * uses. Layer precedence remains the fallback when no normalized identity is * available, so tracking paths that never stamp one keep working. diff --git a/src/cockpitMath.test.mjs b/src/cockpitMath.test.mjs index 104190fa88..29c2654c6c 100644 --- a/src/cockpitMath.test.mjs +++ b/src/cockpitMath.test.mjs @@ -432,7 +432,7 @@ test('tracked-identity resolution falls back to layer precedence', () => { const civilian = { icao24: 'aaa077' }; const military = { icao24: 'ae01ce' }; // No stamped identity (or one that matches neither layer) keeps the historic - // civilian-first order so tracking paths without gevTrackedId still work. + // civilian-first order so tracking paths without an entity record trackedId still work. assert.equal(resolveTrackedAircraftInfo({ civilian, military }).layerId, 'flights'); assert.equal( resolveTrackedAircraftInfo({ civilian, military, trackedId: 'satellites:25544' }).layerId, diff --git a/src/cockpitTracking.js b/src/cockpitTracking.js index 97aa50d8e1..240b56ab45 100644 --- a/src/cockpitTracking.js +++ b/src/cockpitTracking.js @@ -1,7 +1,7 @@ /* * Cockpit aircraft metadata itself is resolved by `resolveTrackedAircraftInfo` * in `cockpitMath.js` — the landed owner of that rule. It keeps layer - * precedence as the fallback when no normalized `gevTrackedId` is available, + * precedence as the fallback when the entity record has no normalized `trackedId`, * so tracking paths that never stamp one keep working; `readAircraftInfo` is * pinned to it by `cockpitMarkup.test.mjs`. This module owns only the * multi-step ENTRY TRANSACTION (adopt → enter → roll back). diff --git a/src/cockpitTracking.test.mjs b/src/cockpitTracking.test.mjs index fd6a171cc0..b3a711167b 100644 --- a/src/cockpitTracking.test.mjs +++ b/src/cockpitTracking.test.mjs @@ -5,6 +5,7 @@ import { enterCockpitWithTracking, restoreAircraftTrackingOwner, } from './cockpitTracking.js'; +import { readEntityRecord, withEntityRecord } from './data/entityRecords.js'; /** * Model the two production stamping seams that sit under this transaction: @@ -22,7 +23,7 @@ function stampingWorld({ entryAllowed = true } = {}) { layerId, trackById(id) { if (!trackable) return false; - world.trackedEntity = { gevTrackedId: `${layerId}:${id}` }; + world.trackedEntity = withEntityRecord({}, { trackedId: `${layerId}:${id}` }); stamp('trackedEntityChanged'); // the ui.js listener return true; }, @@ -80,7 +81,7 @@ test('a refused Cockpit entry still stamps for the tracker it already moved', () // Adoption stamped, and the rollback re-track stamped again. assert.deepEqual(world.stamps, ['trackedEntityChanged', 'trackedEntityChanged']); assert.equal(world.generation, 2); - assert.equal(world.trackedEntity.gevTrackedId, 'military:ae01ce'); + assert.equal(readEntityRecord(world.trackedEntity)?.trackedId, 'military:ae01ce'); }); test('a Cockpit entry that mutates nothing takes no camera authority', () => { diff --git a/src/cyberSonar.js b/src/cyberSonar.js index e4148a43c4..e50369908b 100644 --- a/src/cyberSonar.js +++ b/src/cyberSonar.js @@ -206,6 +206,71 @@ export function createCyberSonarSampler( }; } +// The contact tint: a cool grey outside the sector, warm inside it, each +// mixed in at this strength over the contact's own colour. +const CYBER_SONAR_DIM_RGB = [0.62, 0.68, 0.72]; +const CYBER_SONAR_LIT_RGB = [1, 0.84, 0.84]; +const CYBER_SONAR_TINT_STRENGTH = 0.72; +/** How far toward the warm tint contacts sit while the sweep is off. */ +const CYBER_SONAR_NEUTRAL_COVERAGE = 0.46; + +const hexOf = (rgb) => + `#${rgb + .map((c) => + Math.round(clamp01(c) * 255) + .toString(16) + .padStart(2, '0'), + ) + .join('')}`; + +/** + * The renderer's screen modulation sector for the Cyber contact sweep over + * a `width` x `height` CSS-pixel map: the same band `createCyberSonarSampler` + * samples. Not sweeping (Sonar OFF, reduced motion), a radius of 0 holds + * every contact at the neutral level the sweep rests at. + * @param {number} width + * @param {number} height + * @param {number} nowMs + * @param {{sweeping?: boolean, root?: object}} [options] + * @returns {import('./render/contract/effects').ModulationSector} + */ +export function cyberSonarSector( + width, + height, + nowMs, + { sweeping = true, root = globalThis.document?.documentElement } = {}, +) { + const settings = readCyberSonarSettings(root); + const floor = settings.opacity / 100; + const center = { x: width / 2, y: height / 2 }; + const widthRad = (settings.sector * Math.PI) / 180; + if (!sweeping) { + const coverage = floor >= 0.9999 ? 1 : CYBER_SONAR_NEUTRAL_COVERAGE; + return { + center, + angle: 0, + width: widthRad, + radius: 0, + floor: floor + (1 - floor) * CYBER_SONAR_NEUTRAL_COVERAGE, + strength: CYBER_SONAR_TINT_STRENGTH, + color: hexOf( + CYBER_SONAR_DIM_RGB.map( + (c, i) => c + (CYBER_SONAR_LIT_RGB[i] - c) * coverage, + ), + ), + }; + } + return { + center, + angle: (cyberSonarAngleDeg(nowMs) * Math.PI) / 180, + width: widthRad, + radius: (Math.min(width * 0.4, height * 0.52) * settings.range) / 100, + floor, + strength: CYBER_SONAR_TINT_STRENGTH, + color: hexOf(CYBER_SONAR_LIT_RGB), + }; +} + /** Remaining delay before the next contact-projection refresh is due. */ export function cyberSonarFrameDelay( lastPaintAt, diff --git a/src/cyberSonarGpu.js b/src/cyberSonarGpu.js deleted file mode 100644 index bb4aff4d68..0000000000 --- a/src/cyberSonarGpu.js +++ /dev/null @@ -1,295 +0,0 @@ -import * as Cesium from 'cesium'; - -// Narrow, version-tested engine adapter. Cesium has no public custom shader -// option for native point/billboard collections. Do not patch its prototypes or -// access EntityCluster's private collections. An engine upgrade must revalidate -// this adapter; unsupported versions keep the original commands unchanged. -export const CYBER_SONAR_CESIUM_VERSION = '1.138.0'; - -// Follow every public DrawCommand setter, including pick/shadow/culling flags. -// Copying native.dirty would keep derived pipelines dirty forever: the scene -// consumes our command, so it never clears that flag on the native command. -const commandProperties = Object.entries( - Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype), -) - .filter( - ([key, descriptor]) => - descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap', - ) - .map(([key]) => key); - -export function syncCyberSonarCommand( - native, - record, - program, - uniforms, - labelBackground, -) { - if (!record.command) { - record.command = new Cesium.DrawCommand(); - record.uniformMap = { - ...uniforms, - u_gevSonarLabelBackground: () => record.labelBackground, - }; - } - const command = record.command; - record.labelBackground = labelBackground; - // Uniform values (angle/viewport/etc.) change through stable callbacks, not - // new maps/functions. Owner callback replacement and removal still propagate. - for (const key in record.uniformMap) { - if ( - !(key in uniforms) && - key !== 'u_gevSonarLabelBackground' && - !(key in native.uniformMap) - ) { - delete record.uniformMap[key]; - command.dirty = true; - } - } - for (const key in native.uniformMap) { - if (record.uniformMap[key] !== native.uniformMap[key]) { - record.uniformMap[key] = native.uniformMap[key]; - command.dirty = true; - } - } - for (const key of commandProperties) command[key] = native[key]; - command.shaderProgram = program; - command.uniformMap = record.uniformMap; - return command; -} - -export function sonarVertexSource(source, kind) { - const text = source.sources.join('\n'); - const attribute = - kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale'; - const lowAttribute = - kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation'; - if ( - !text.includes(attribute) || - !text.includes(lowAttribute) || - !text.includes('v_color') || - !/void\s+main\s*\(\s*\)/.test(text) - ) - return null; - const next = source.clone(); - next.sources = [ - text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'), - ` -uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled -uniform vec2 u_gevSonarViewport; -uniform float u_gevSonarSector; -uniform float u_gevSonarLabelBackground; -void main() { - gev_sonar_main(); - // All corners/glyphs share the contact anchor, before native screen offsets. - // Leave gl_Position untouched so appearance never changes geometry or picks. - vec4 anchor = czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz); - if (anchor.w <= 0.0) return; - vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5; - float floorValue = u_gevSonar.z; - float factor = floorValue + (1.0 - floorValue) * 0.46; - if (u_gevSonar.w > 0.5) { - float distanceSquared = dot(pixel, pixel); - float radiusSquared = u_gevSonar.y * u_gevSonar.y; - float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0); - if (delta > 359.9999) delta = 0.0; - factor = floorValue; - if (distanceSquared < radiusSquared * 0.000625) factor = 1.0; - else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector) - factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42)); - } - #ifdef SDF - factor = (1.0 + factor) * 0.5; - #else - if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5; - #endif - float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0); - if (u_gevSonarLabelBackground < 0.5) - v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72; - // Apply before native fragment pass classification, never after main(). - v_color.a *= factor; - ${kind === 'point' ? 'v_outlineColor.a *= factor;' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'} -} -`, - ]; - return next; -} - -// Use native batch bounds, never individual contacts, for idle render demand. -// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta). -export function isCyberSonarCommandVisible(command, frameState, culling) { - const bounds = command.boundingVolume; - if (!bounds || !command.cull) return true; - culling ??= new Cesium.CullingVolume( - frameState.cullingVolume.planes.slice(0, 5), - ); - if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE) - return false; - return !( - frameState.mode === Cesium.SceneMode.SCENE3D && - frameState.occluder && - command.occlude && - bounds.isOccluded(frameState.occluder) - ); -} - -/** Work scales with draw commands, not the number of contacts in a collection. - * Source programs, colors, pick IDs, render states and other scenes stay owned - * by Cesium. Only this scene's rendered command slice receives derived shaders. - */ -export function createCyberSonarGpu(scene, readFrame) { - const root = scene.primitives; - const original = root.update; - const programs = new Map(); - let commands = new WeakMap(); - let disposed = false; - const stats = { - commands: 0, - visibleCommands: 0, - programs: 0, - supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION, - error: null, - }; - const uniforms = new Cesium.Cartesian4(); - const viewport = new Cesium.Cartesian2(); - let sector = 24; - const sonarUniforms = { - u_gevSonar: () => uniforms, - u_gevSonarViewport: () => viewport, - u_gevSonarSector: () => sector, - }; - const culling = new Cesium.CullingVolume(); - const used = new Set(); - const replaced = []; - const release = () => { - for (const { program } of programs.values()) - if (!program.isDestroyed()) program.destroy(); - programs.clear(); - commands = new WeakMap(); - used.clear(); - replaced.length = 0; - stats.programs = 0; - }; - const wrapped = function (frameState) { - const start = frameState.commandList.length; - original.call(this, frameState); - stats.commands = 0; - stats.visibleCommands = 0; - if ( - disposed || - !stats.supported || - !frameState.passes.render || - frameState.passes.pick - ) - return; - const frame = readFrame(); - if (!frame.enabled) { - if (programs.size) release(); - return; - } - viewport.x = scene.drawingBufferWidth; - viewport.y = scene.drawingBufferHeight; - uniforms.x = frame.angle; - uniforms.y = - (Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100; - uniforms.z = frame.opacity / 100; - uniforms.w = frame.active ? 1 : 0; - sector = frame.sector; - used.clear(); - replaced.length = 0; - if (frameState.cullingVolume) - for (let i = 0; i < 5; i++) - culling.planes[i] = frameState.cullingVolume.planes[i]; - try { - for (let i = start; i < frameState.commandList.length; i++) { - const native = frameState.commandList[i]; - const kind = - native.owner instanceof Cesium.PointPrimitiveCollection - ? 'point' - : native.owner instanceof Cesium.BillboardCollection - ? 'billboard' - : null; - if (!kind || !native.shaderProgram || !native.uniformMap) continue; - const source = native.shaderProgram; - // Label backgrounds are non-SDF billboard batches. The version-tested - // engine pick association distinguishes them without enumerating labels - // or reaching into EntityCluster. One representative per draw batch; - // Cesium's label glyph/background collections are homogeneous. - const labelBackground = - kind === 'billboard' && - !source.vertexShaderSource.defines.includes('SDF') && - native.owner.length > 0 && - native.owner.get(0).pickPrimitive instanceof Cesium.Label - ? 1 - : 0; - let entry = programs.get(source); - if (!entry) { - const vertex = sonarVertexSource(source.vertexShaderSource, kind); - if (!vertex) throw new Error('Unsupported native contact shader'); - const attributes = Object.fromEntries( - Object.entries(source.vertexAttributes).map(([name, value]) => [ - name, - value.index, - ]), - ); - const program = Cesium.ShaderProgram.fromCache({ - context: frameState.context, - vertexShaderSource: vertex, - fragmentShaderSource: source.fragmentShaderSource, - attributeLocations: attributes, - }); - // Compile while errors can still leave the whole native command slice - // intact, rather than stopping the viewer's render loop at draw time. - try { - void program.allUniforms; - } catch (error) { - program.destroy(); - throw error; - } - programs.set(source, (entry = { program })); - } - used.add(source); - let record = commands.get(native); - if (!record) commands.set(native, (record = {})); - const derived = syncCyberSonarCommand( - native, - record, - entry.program, - sonarUniforms, - labelBackground, - ); - replaced.push(i, native); - frameState.commandList[i] = derived; - stats.commands++; - if (isCyberSonarCommandVisible(native, frameState, culling)) - stats.visibleCommands++; - } - for (const [source, entry] of programs) - if (!used.has(source)) { - if (!entry.program.isDestroyed()) entry.program.destroy(); - programs.delete(source); - } - stats.programs = programs.size; - } catch (error) { - // Recover the original commands already replaced in this slice. - for (let i = 0; i < replaced.length; i += 2) - frameState.commandList[replaced[i]] = replaced[i + 1]; - stats.supported = false; - stats.commands = 0; - stats.visibleCommands = 0; - stats.error = String(error?.message || error); - release(); - } - }; - root.update = wrapped; - return { - stats, - destroy() { - if (disposed) return; - disposed = true; - if (root.update === wrapped && !root.isDestroyed?.()) - root.update = original; - release(); - }, - }; -} diff --git a/src/cyberSonarGpu.test.mjs b/src/cyberSonarGpu.test.mjs deleted file mode 100644 index 8507620bab..0000000000 --- a/src/cyberSonarGpu.test.mjs +++ /dev/null @@ -1,354 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; -import { - createCyberSonarGpu, - sonarVertexSource, - CYBER_SONAR_CESIUM_VERSION, - isCyberSonarCommandVisible, - syncCyberSonarCommand, -} from './cyberSonarGpu.js'; - -test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => { - const native = new Cesium.DrawCommand({ - count: 6, - uniformMap: { value: () => 1 }, - }); - const record = {}, - program = {}, - uniforms = { u_gevSonar: () => 42 }; - const derived = syncCyberSonarCommand(native, record, program, uniforms, 0); - const map = derived.uniformMap; - derived.dirty = false; - derived.lastDirtyTime = 7; - assert.equal(native.dirty, true); - assert.equal( - syncCyberSonarCommand(native, record, program, uniforms, 1), - derived, - ); - assert.equal( - derived.dirty, - false, - 'stale native dirty flag must not rebuild pipelines', - ); - assert.equal(derived.lastDirtyTime, 7); - assert.equal(derived.uniformMap, map); - assert.equal(map.u_gevSonarLabelBackground(), 1); - for (const [key, value] of Object.entries({ - count: 12, - offset: 2, - instanceCount: 3, - pickId: 'pick', - pass: Cesium.Pass.TRANSLUCENT, - cull: false, - occlude: false, - castShadows: true, - receiveShadows: true, - pickOnly: true, - renderState: {}, - vertexArray: {}, - modelMatrix: Cesium.Matrix4.IDENTITY, - framebuffer: {}, - })) { - derived.dirty = false; - native[key] = value; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(derived[key], value, key); - assert.equal(derived.dirty, true, key); - } - native.uniformMap.value = () => 2; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(map.value(), 2); - native.uniformMap = { replacement: () => 3 }; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(map.value, undefined); - assert.equal(map.replacement(), 3); - assert.equal(map.u_gevSonar(), 42); - const nextProgram = {}; - syncCyberSonarCommand(native, record, nextProgram, uniforms, 0); - assert.equal(derived.shaderProgram, nextProgram); - assert.equal(native.shaderProgram, undefined); -}); - -test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => { - assert.equal( - Cesium.VERSION, - CYBER_SONAR_CESIUM_VERSION, - 'engine upgrades require GPU revalidation', - ); - for (const [kind, attr, low] of [ - ['point', 'positionHighAndSize', 'positionLowAndOutline'], - ['billboard', 'positionHighAndScale', 'positionLowAndRotation'], - ]) { - const source = new Cesium.ShaderSource({ - defines: ['SDF'], - sources: [ - `in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`, - ], - }); - const original = source.sources[0]; - const next = sonarVertexSource(source, kind); - assert.equal(source.sources[0], original); - assert.notEqual(next, source); - assert.deepEqual(next.defines, ['SDF']); - assert.match(next.sources[0], /void gev_sonar_main/); - assert.match(next.sources[1], /v_color.a \*= factor/); - assert.match(next.sources[1], /u_gevSonarSector/); - assert.match(next.sources[1], /floorValue \+ \(1.0 - floorValue\) \* 0.46/); - assert.ok( - next.sources[1].includes( - `czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`, - ), - ); - assert.match(next.sources[1], /anchor.xy \/ anchor.w/); - assert.doesNotMatch(next.sources[1], /gl_Position\s*[=\/]/); - } - assert.equal( - sonarVertexSource( - new Cesium.ShaderSource({ sources: ['void main() {}'] }), - 'point', - ), - null, - ); -}); - -test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => { - const planes = Array.from( - { length: 6 }, - (_, i) => new Cesium.Cartesian4(1, 0, 0, i), - ); - const frame = { - cullingVolume: { planes }, - mode: Cesium.SceneMode.SCENE3D, - occluder: {}, - }; - let intersections = 0; - let occluded = false; - const command = { - cull: true, - occlude: true, - boundingVolume: { - intersectPlane(plane) { - intersections++; - return plane.distance === 5 - ? Cesium.Intersect.OUTSIDE - : Cesium.Intersect.INSIDE; - }, - isOccluded() { - return occluded; - }, - }, - }; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - assert.equal(intersections, 5); - occluded = true; - assert.equal(isCyberSonarCommandVisible(command, frame), false); - frame.mode = Cesium.SceneMode.SCENE2D; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE; - assert.equal(isCyberSonarCommandVisible(command, frame), false); - command.cull = false; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - assert.equal(isCyberSonarCommandVisible({}, frame), true); -}); - -test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => { - let calls = 0; - const original = function (fs) { - assert.equal(this, root); - calls++; - fs.commandList.push({ owner: {}, id: 'terrain' }); - }; - const root = { update: original }; - const other = { update: original }; - const adapter = createCyberSonarGpu({ primitives: root }, () => ({ - enabled: false, - })); - const frame = { commandList: [], passes: { render: true, pick: false } }; - root.update(frame); - assert.equal(calls, 1); - assert.equal(frame.commandList[0].id, 'terrain'); - assert.equal(other.update, original); - root.update({ commandList: [], passes: { render: false, pick: true } }); - assert.equal(calls, 2); - adapter.destroy(); - adapter.destroy(); - assert.equal(root.update, original); -}); - -test('unknown native shaders fail closed without losing native commands', () => { - const points = new Cesium.PointPrimitiveCollection(); - const command = { - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }; - const root = { - update(fs) { - fs.commandList.push(command); - }, - }; - const adapter = createCyberSonarGpu( - { primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 }, - () => ({ - enabled: true, - active: true, - angle: 0, - range: 100, - opacity: 84, - sector: 24, - }), - ); - const frame = { commandList: [], passes: { render: true } }; - root.update(frame); - assert.equal(frame.commandList[0], command); - assert.equal(adapter.stats.supported, false); - assert.match(adapter.stats.error, /Unsupported native contact shader/); - assert.equal(adapter.stats.programs, 0); - adapter.destroy(); - points.destroy(); -}); - -test('program swaps, layer removal and late shader failure release only adapter resources', () => { - const points = new Cesium.PointPrimitiveCollection(); - const source = () => ({ - vertexShaderSource: new Cesium.ShaderSource({ - sources: [ - 'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}', - ], - }), - vertexAttributes: {}, - fragmentShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }); - const native = new Cesium.DrawCommand({ - owner: points, - uniformMap: {}, - shaderProgram: source(), - cull: false, - vertexArray: { generation: 1 }, - pickId: 'native-pick', - }); - const unknown = new Cesium.DrawCommand({ - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }); - let nativeCommands = [native]; - let enabled = true; - const root = { - update(frame) { - frame.commandList.push(...nativeCommands); - }, - }; - const fromCache = Cesium.ShaderProgram.fromCache; - const created = []; - Cesium.ShaderProgram.fromCache = () => { - const program = { - allUniforms: {}, - destroyed: false, - isDestroyed() { - return this.destroyed; - }, - destroy() { - assert.equal(this.destroyed, false); - this.destroyed = true; - }, - }; - created.push(program); - return program; - }; - const adapter = createCyberSonarGpu( - { primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 }, - () => ({ - enabled, - active: true, - angle: 0, - range: 100, - opacity: 84, - sector: 24, - }), - ); - const draw = () => { - const frame = { commandList: [], passes: { render: true } }; - root.update(frame); - return frame.commandList; - }; - try { - const first = draw()[0]; - assert.notEqual(first, native); - first.dirty = false; - assert.equal(draw()[0], first); - assert.equal(first.dirty, false); - assert.equal(created.length, 1, 'stable draws reuse the program'); - const buffer = { generation: 2 }; - native.vertexArray = buffer; - native.shaderProgram = source(); - const swapped = draw()[0]; - assert.equal(swapped, first); - assert.equal(swapped.vertexArray, buffer); - assert.equal(swapped.pickId, 'native-pick'); - assert.equal(swapped.shaderProgram, created[1]); - assert.equal(created[0].destroyed, true); - assert.equal(adapter.stats.programs, 1); - nativeCommands = []; - draw(); - assert.equal(created[1].destroyed, true); - assert.equal( - adapter.stats.programs, - 0, - 'disabled layers retain no adapter program', - ); - nativeCommands = [native]; - draw(); - enabled = false; - assert.equal(draw()[0], native); - assert.equal( - created[2].destroyed, - true, - 'theme/cockpit exit releases the derived program', - ); - enabled = true; - nativeCommands = [native, unknown]; - assert.deepEqual( - draw(), - nativeCommands, - 'a later failure rolls back earlier replacements in the same slice', - ); - assert.equal(created[3].destroyed, true); - assert.equal(adapter.stats.supported, false); - assert.equal(adapter.stats.programs, 0); - assert.equal(adapter.stats.commands, 0); - assert.equal(adapter.stats.visibleCommands, 0); - assert.deepEqual(draw(), nativeCommands); - assert.equal( - created.length, - 4, - 'unsupported draws do not retry compilation', - ); - } finally { - adapter.destroy(); - Cesium.ShaderProgram.fromCache = fromCache; - points.destroy(); - } -}); - -test('disposal does not overwrite a successor update owner', () => { - const root = { update() {} }; - const adapter = createCyberSonarGpu({ primitives: root }, () => ({ - enabled: false, - })); - const successor = () => {}; - root.update = successor; - adapter.destroy(); - assert.equal(root.update, successor); -}); diff --git a/src/cyberSonarScene.js b/src/cyberSonarScene.js index f07159cbf9..75b21e78ef 100644 --- a/src/cyberSonarScene.js +++ b/src/cyberSonarScene.js @@ -1,211 +1,141 @@ -import * as Cesium from 'cesium'; -import { createCyberSonarGpu } from './cyberSonarGpu.js'; +/** + * The Cyber contact sweep on the map's markers, through the renderer's + * `effects.screenModulation` (`src/render/contract/effects.d.ts`). This + * keeps the sweep's clock and settings; the renderer shades the markers. + * + * Each tick, before the renderer decides whether to draw: a change of the + * theme, the sweep, its settings or the map's size sets the sector at once; + * while sweeping, the sector moves to the current angle on every tick that + * draws anyway, and at least every `CYBER_SONAR_RENDER_INTERVAL_MS` (which + * then asks for a frame). Out of the theme the sector is cleared. + * + * A renderer without the capability, or one that does not list the pass + * once a sector is set, leaves markers as they are: the document's + * `cyberSonarGpu` says `unsupported`, so the HUD overlays skip their own + * sweep too, and the sonar status says so. + * + * The frame and effects ports are looked up once, when the scene is made: + * bind the renderer to the viewer before creating it. + */ import { - applyCyberSonarPrimitive, - createCyberSonarSampler, - isCyberContactThemeActive, - isCyberContactSonarActive, + CYBER_SONAR_RENDER_INTERVAL_MS, + cyberSonarSector, + isCyberMapThemeActive, isCyberSonarActive, readCyberSonarSettings, - cyberSonarAngleDeg, syncCyberSonarAnimation, - CYBER_SONAR_RENDER_INTERVAL_MS, } from './cyberSonar.js'; +import { canvasOf, findEffects, findFrame } from './render/rendererOf.js'; -const alive = (value) => value && !value.isDestroyed?.(); -const diagnostics = new WeakMap(); -export const getCyberSonarSceneDiagnostics = (viewer) => ({ - ...diagnostics.get(viewer), -}); +const UNSUPPORTED_MESSAGE = + 'Contact GPU unavailable. Native contacts remain visible.'; -export function visitCyberSonarModels(primitive, visit, visible = true) { - if (!alive(primitive)) return; - visible = visible && primitive.show !== false; - if (primitive instanceof Cesium.PrimitiveCollection) { - for (let i = 0; i < primitive.length; i++) - visitCyberSonarModels(primitive.get(i), visit, visible); - } else if (primitive instanceof Cesium.Model) { - visit(primitive, primitive, 'model', visible && primitive.ready); - } -} - -/** Native dots, icons and glyphs use GPU draw-command treatment. Models retain - * their existing reversible CPU color treatment without walking native records. +/** + * @param {object} viewer The scene object the renderer is bound to. + * @param {{subscribe?: Function}} [manager] Layer visibility changes ask + * for a frame, so markers shown or hidden draw with the sweep. + * @returns {() => void} Clears the sector and lets go. */ export function createCyberSonarScene(viewer, manager) { - const scene = viewer?.scene; - if ( - !scene?.postUpdate?.addEventListener || - !scene?.preRender?.addEventListener - ) - return () => {}; - const tracked = new Map(); - const matrix = new Cesium.Matrix4(); - const position = new Cesium.Cartesian3(); - let epoch = 0, - timer = null, - disposed = false; - let sampler, width, height, active, count; - const stats = { contacts: 0, updateMs: 0, frames: 0 }; - const root = globalThis.document?.documentElement; - const gpu = createCyberSonarGpu(scene, () => ({ - ...readCyberSonarSettings(), - enabled: isCyberContactThemeActive(), - active: isCyberContactSonarActive(), - angle: cyberSonarAngleDeg(performance.now()), - })); - stats.gpu = gpu.stats; - let gpuSupported = gpu.stats.supported; - diagnostics.set(viewer, stats); - const restore = (visual, state) => { - if (!alive(state.owner)) return; - for (const key of state.keys) - applyCyberSonarPrimitive(visual, 1, false, undefined, key); - }; - const visit = (visual, owner, kind, visible) => { - let state = tracked.get(visual); - if (!visible) { - if (state) { - restore(visual, state); - tracked.delete(visual); - } - return; - } - let p = visual.position; - if (kind === 'model') - p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position); - else if ( - p && - owner.modelMatrix && - !Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY) - ) - p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position); - if (!p) return; - const w = matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15]; - const x = - (matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / w; - const y = - (matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / w; - if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return; - if (!state) { - state = { - owner, - keys: - kind === 'label' - ? ['fillColor', 'outlineColor', 'backgroundColor'] - : kind === 'marker' && visual.outlineColor - ? ['color', 'outlineColor'] - : ['color'], - epoch, - }; - tracked.set(visual, state); - } - state.epoch = epoch; - const factor = active - ? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5) - : sampler.neutral; - for (const key of state.keys) { - if (key === 'outlineColor' && visual.outlineWidth === 0) continue; - if (key === 'backgroundColor' && !visual.showBackground) continue; - applyCyberSonarPrimitive( - visual, - kind === 'label' ? sampler.label(factor) : factor, - true, - sampler, - key, - kind === 'model', - ); - } - count++; - }; - const update = () => { - if (disposed) return; - if (timer !== null) { - clearTimeout(timer); - timer = null; - } - if (!isCyberContactThemeActive()) { - for (const [visual, state] of tracked) restore(visual, state); - tracked.clear(); - stats.contacts = 0; - stats.updateMs = 0; - return; - } - const started = performance.now(); - width = scene.canvas.clientWidth; - height = scene.canvas.clientHeight; - sampler = createCyberSonarSampler(width, height, started); - active = isCyberContactSonarActive(); - Cesium.Matrix4.multiply( - scene.camera.frustum.projectionMatrix, - scene.camera.viewMatrix, - matrix, - ); - epoch++; - count = 0; - visitCyberSonarModels(scene.primitives, visit); - for (const [visual, state] of tracked) - if (state.epoch !== epoch) { - restore(visual, state); - tracked.delete(visual); - } - stats.contacts = count; - stats.updateMs = performance.now() - started; - stats.frames++; - // No contacts, no scanner-owned render demand. In continuous scenes the - // next rendered frame cancels this timer; parked scenes refresh at fleet - // cadence. Idle update-only ticks must not continually postpone the timer. - }; - let removeRender; - // Aircraft fleet writers run in preRender, while tracked models and entity - // visualizers update earlier. Compose AFTER all those owners and BEFORE - // Cesium uploads primitive attributes for this draw. Requeue at postUpdate - // so writers installed later (enable/re-enable/track) cannot overwrite sonar. - // This only reorders one callback; the contact walk runs once per actual draw. - const removeUpdate = scene.postUpdate.addEventListener(() => { - if (isCyberSonarActive()) syncCyberSonarAnimation(); - const supportChanged = gpuSupported !== gpu.stats.supported; - gpuSupported = gpu.stats.supported; - const support = gpu.stats.supported ? 'supported' : 'unsupported'; + const frame = findFrame(viewer); + if (!frame) return () => {}; + const effects = findEffects(viewer); + const doc = globalThis.document; + const root = doc?.documentElement; + let failed = typeof effects?.screenModulation !== 'function'; + let current = null; + let key = null; + let lastSetAt = Number.NEGATIVE_INFINITY; + let disposed = false; + + const publish = () => { + const support = failed ? 'unsupported' : 'supported'; if (root?.dataset && root.dataset.cyberSonarGpu !== support) root.dataset.cyberSonarGpu = support; - // Shader setup runs after preRender's model tint. If it fails while the - // scene is parked (including Sonar OFF/reduced motion), draw once more so - // the now-unsupported contact path restores models before becoming idle. - if (supportChanged) scene.requestRender(); - const status = globalThis.document?.getElementById?.('cyber-sonar-status'); - const message = gpu.stats.supported - ? '' - : 'Contact GPU unavailable. Native contacts remain visible.'; + const status = doc?.getElementById?.('cyber-sonar-status'); + const message = failed ? UNSUPPORTED_MESSAGE : ''; if (status && status.textContent !== message) status.textContent = message; - removeRender?.(); - removeRender = scene.preRender.addEventListener(update); - }); - const removePostRender = scene.postRender?.addEventListener(() => { - if (timer !== null) clearTimeout(timer); - timer = null; - if (isCyberContactSonarActive() && (count || gpu.stats.visibleCommands)) - timer = setTimeout(() => { - timer = null; - if (!disposed && isCyberContactSonarActive()) scene.requestRender(); - }, CYBER_SONAR_RENDER_INTERVAL_MS); + }; + + /** The renderer cannot draw the pass: markers stay as they are. */ + const fail = () => { + if (failed) return; + failed = true; + const had = current; + current = null; + key = null; + if (had) effects.screenModulation(null); + publish(); + }; + + const set = (sector, at) => { + const had = current; + // Before the call: its change listeners read `current`. + current = sector; + lastSetAt = at; + effects.screenModulation(sector); + // A first sector set but not listed is unsupported; a pass that stops + // later is caught by the change listener. + if ( + sector && + !had && + !effects.diagnostics().passes.includes('screenModulation') + ) + fail(); + }; + + const offTick = frame.on('preUpdate', (t) => { + if (disposed) return; + // The HUD's own sweep keeps its clock whether or not markers are shaded. + const active = isCyberSonarActive(); + if (active) syncCyberSonarAnimation(); + if (failed) return; + const theme = isCyberMapThemeActive(); + const sweeping = theme && active; + if (!theme) { + if (current) set(null, lastSetAt); + key = null; + return; + } + const canvas = canvasOf(viewer); + // The sector is in CSS pixels. + const width = canvas?.clientWidth ?? 0; + const height = canvas?.clientHeight ?? 0; + const settings = readCyberSonarSettings(root); + const next = `${sweeping}|${settings.range}|${settings.opacity}|${settings.sector}|${width}|${height}`; + const now = performance.now(); + if ( + next === key && + !( + sweeping && + (now - lastSetAt >= CYBER_SONAR_RENDER_INTERVAL_MS || t.rendering) + ) + ) + return; + key = next; + set(cyberSonarSector(width, height, now, { sweeping, root }), now); }); + + const offChange = failed + ? null + : effects.on('change', (diagnostics) => { + if (current && !diagnostics.passes.includes('screenModulation')) fail(); + }); + const unsubscribe = manager?.subscribe?.((change) => { - if (change.type !== 'visibility') return; - scene.requestRender(); + if (change.type === 'visibility') frame.requestRender('cyber-sonar'); }); + + publish(); return () => { if (disposed) return; disposed = true; - removeUpdate(); - removeRender?.(); - removePostRender?.(); - gpu.destroy(); - if (root?.dataset) delete root.dataset.cyberSonarGpu; + offTick(); + offChange?.(); unsubscribe?.(); - if (timer !== null) clearTimeout(timer); - for (const [visual, state] of tracked) restore(visual, state); - tracked.clear(); - diagnostics.delete(viewer); + const had = current; + current = null; + if (had) effects.screenModulation(null); + if (root?.dataset) delete root.dataset.cyberSonarGpu; }; } diff --git a/src/cyberSonarScene.test.mjs b/src/cyberSonarScene.test.mjs index 7d0db85516..595964554e 100644 --- a/src/cyberSonarScene.test.mjs +++ b/src/cyberSonarScene.test.mjs @@ -1,19 +1,16 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import { + CYBER_SONAR_RENDER_INTERVAL_MS, + applyCyberSonarSettings, createCyberSonarSampler, cyberSonarIntensityAtScreenPoint, - applyCyberSonarPrimitive, - applyCyberSonarSettings, + cyberSonarSector, isCyberContactSonarActive, isCyberSonarActive, } from './cyberSonar.js'; -import { - createCyberSonarScene, - visitCyberSonarModels, - getCyberSonarSceneDiagnostics, -} from './cyberSonarScene.js'; +import { createCyberSonarScene } from './cyberSonarScene.js'; +import { bindRenderer } from './render/rendererOf.js'; test('frame sampler matches reference without per-contact settings access', () => { let reads = 0; @@ -47,44 +44,7 @@ test('frame sampler matches reference without per-contact settings access', () = ); }); -test('model walk never enumerates native contact or EntityCluster records', () => { - const root = new Cesium.PrimitiveCollection(); - const points = root.add(new Cesium.PointPrimitiveCollection()); - points.add(); - points.get = () => { - throw new Error('must not enumerate contacts'); - }; - const cluster = root.add(new Cesium.EntityCluster()); - Object.defineProperty(cluster, '_billboardCollection', { - get() { - throw new Error('must not access cluster internals'); - }, - configurable: true, - }); - const seen = []; - visitCyberSonarModels(root, (...v) => seen.push(v)); - assert.equal(seen.length, 0); - delete cluster._billboardCollection; - root.destroy(); -}); - -test('models retain render-pass alpha and owner refresh survives teardown', () => { - const frame = createCyberSonarSampler(1000, 800, 0); - const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) }; - applyCyberSonarPrimitive(model, 0.5, true, frame, 'color', true); - assert.equal(model.color.alpha, 1); - assert.ok(model.color.red < 1); - const owner = new Cesium.Color(0.2, 0.3, 0.4, 0.7); - model.color = owner; - applyCyberSonarPrimitive(model, 1, false); - assert.equal(model.color, owner); - const unset = {}; - applyCyberSonarPrimitive(unset, 0.5, true, frame, 'color', true); - applyCyberSonarPrimitive(unset, 1, false); - assert.equal(unset.color, undefined); -}); - -test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail closed', () => { +test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => { const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } }; const options = { root, @@ -106,209 +66,269 @@ test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail cl assert.equal(isCyberContactSonarActive(options), false); }); -test('native owner colors remain untouched and scene teardown releases listeners', () => { - const previous = globalThis.document; +test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => { + const root = { + dataset: { + cyberSonarOpacity: '62', + cyberSonarSector: '40', + cyberSonarRange: '110', + }, + }; + const s = cyberSonarSector(1000, 800, 1300, { root }); + assert.deepEqual(s.center, { x: 500, y: 400 }); + assert.ok(Math.abs(s.angle - Math.PI / 2) < 1e-9, 'a quarter period'); + assert.ok(Math.abs(s.width - (40 * Math.PI) / 180) < 1e-12); + assert.ok(Math.abs(s.radius - 440) < 1e-9); + assert.equal(s.floor, 0.62); + assert.equal(s.strength, 0.72); + assert.equal(s.color, '#ffd6d6'); + const rest = cyberSonarSector(1000, 800, 1300, { root, sweeping: false }); + assert.equal(rest.radius, 0); + assert.ok(Math.abs(rest.floor - (0.62 + 0.38 * 0.46)) < 1e-12); +}); + +/** + * A document with the Cyber HUD shown, and a renderer fake bound to a + * viewer: its frame's preUpdate is ticked by hand and its effects record + * each sector. + */ +function fixture({ modulation = true, lists = true } = {}) { + const previous = { + document: globalThis.document, + matchMedia: globalThis.matchMedia, + }; const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } }; - let cockpit = false; + const status = { textContent: '' }; + const state = { cockpit: false, reducedMotion: false }; globalThis.document = { documentElement: root, - body: { classList: { contains: () => cockpit } }, - getElementById: () => ({ classList: { contains: () => true } }), + body: { classList: { contains: () => state.cockpit } }, + getElementById: (id) => + id === 'cyber-sonar-status' + ? status + : { classList: { contains: () => true } }, }; - const primitives = new Cesium.PrimitiveCollection(); - const points = primitives.add(new Cesium.PointPrimitiveCollection()); - const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) }); - const original = primitives.update; - const scene = { - primitives, - postUpdate: new Cesium.Event(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - canvas: { clientWidth: 1000, clientHeight: 800 }, - camera: { - frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY }, - viewMatrix: Cesium.Matrix4.IDENTITY, + globalThis.matchMedia = () => ({ matches: state.reducedMotion }); + const ticks = new Set(); + const changes = new Set(); + const sets = []; + const requests = []; + let drawing = null; + const effects = { + diagnostics: () => ({ + style: null, + passes: drawing && lists ? ['screenModulation'] : [], + }), + on(event, cb) { + changes.add(cb); + return () => changes.delete(cb); }, - requestRender() {}, }; - const viewer = { scene }; - const dispose = createCyberSonarScene(viewer); - try { - for (const enabled of ['on', 'off', 'on']) { - root.dataset.cyberSonar = enabled; - for (const opacity of [35, 84, 100]) { - root.dataset.cyberSonarOpacity = String(opacity); - point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7); - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - assert.equal(point.color.alpha, 0.7); - assert.equal(point.color.red, 0.6); - } - } - const previousTimeout = globalThis.setTimeout; - const previousClear = globalThis.clearTimeout; - let timers = 0; - globalThis.setTimeout = () => { - timers++; - return 1; + if (modulation) + effects.screenModulation = (sector) => { + const was = effects.diagnostics().passes.length; + drawing = sector; + sets.push(sector); + if (effects.diagnostics().passes.length !== was) + for (const cb of [...changes]) cb(effects.diagnostics()); }; - globalThis.clearTimeout = () => {}; - try { - const gpu = getCyberSonarSceneDiagnostics(viewer).gpu; - gpu.commands = 6; - gpu.visibleCommands = 0; - scene.postRender.raiseEvent(); - assert.equal(timers, 0, 'culled batches must not schedule a sonar draw'); - gpu.visibleCommands = 1; - scene.postRender.raiseEvent(); - assert.equal(timers, 1, 'a visible batch keeps the sweep moving'); - root.dataset.cyberSonar = 'off'; - scene.postRender.raiseEvent(); - assert.equal(timers, 1, 'OFF does not schedule contact draws'); - } finally { - globalThis.setTimeout = previousTimeout; - globalThis.clearTimeout = previousClear; - } - cockpit = true; - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - root.dataset.uiTheme = 'tactical'; - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); + const canvas = { clientWidth: 1000, clientHeight: 800 }; + const viewer = {}; + const unbind = bindRenderer(viewer, { + canvas, + effects, + frame: { + on(phase, cb) { + assert.equal(phase, 'preUpdate'); + ticks.add(cb); + return () => ticks.delete(cb); + }, + requestRender: (reason) => requests.push(reason), + }, + }); + return { + root, + status, + state, + sets, + requests, + canvas, + viewer, + ticks, + changes, + effects, + tick(rendering = false) { + for (const cb of [...ticks]) cb({ rendering }); + }, + restore() { + unbind(); + globalThis.document = previous.document; + globalThis.matchMedia = previous.matchMedia; + }, + }; +} + +test('a renderer without the capability leaves markers alone and says so', () => { + const f = fixture({ modulation: false }); + try { + const dispose = createCyberSonarScene(f.viewer); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.match(f.status.textContent, /Native contacts remain visible/); + f.tick(true); + assert.equal(f.changes.size, 0); dispose(); - dispose(); - assert.equal(primitives.update, original); - assert.equal(scene.postUpdate.numberOfListeners, 0); - assert.equal(scene.preRender.numberOfListeners, 0); - assert.equal(scene.postRender.numberOfListeners, 0); - assert.equal(root.dataset.cyberSonarGpu, undefined); + assert.equal(f.ticks.size, 0); + assert.equal(f.root.dataset.cyberSonarGpu, undefined); } finally { - dispose(); - primitives.destroy(); - globalThis.document = previous; + f.restore(); } }); -for (const reducedMotion of [false, true]) { - test(`shader failure requests one parked restoration draw with ${reducedMotion ? 'reduced motion' : 'Sonar OFF'}`, () => { - const previousDocument = globalThis.document; - const previousMatchMedia = globalThis.matchMedia; - const previousTimeout = globalThis.setTimeout; - const previousClear = globalThis.clearTimeout; - const root = { - dataset: { uiTheme: 'cyber', cyberSonar: reducedMotion ? 'on' : 'off' }, - }; - const status = { textContent: '' }; - globalThis.document = { - documentElement: root, - body: { classList: { contains: () => false } }, - getElementById: (id) => - id === 'cyber-sonar-status' - ? status - : { classList: { contains: () => true } }, - }; - globalThis.matchMedia = () => ({ matches: reducedMotion }); - let scheduled = 0; - globalThis.setTimeout = () => { - scheduled++; - return 1; - }; - globalThis.clearTimeout = () => {}; - // A model-shaped fixture exercises the actual scene walk without loading a - // glTF or allocating a WebGL context. Rendering remains the browser gate. - const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1); - const model = Object.create(Cesium.Model.prototype, { - ready: { value: true }, - show: { value: true }, - color: { value: nativeColor.clone(), writable: true }, - modelMatrix: { value: Cesium.Matrix4.IDENTITY }, - }); - const primitives = new Cesium.PrimitiveCollection({ - destroyPrimitives: false, - }); - primitives.add(model); - const points = new Cesium.PointPrimitiveCollection(); - const nativeCommand = { - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }; - primitives.update = (frame) => frame.commandList.push(nativeCommand); - let requests = 0; - const scene = { - primitives, - postUpdate: new Cesium.Event(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - canvas: { clientWidth: 1000, clientHeight: 800 }, - drawingBufferWidth: 1000, - drawingBufferHeight: 800, - camera: { - frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY }, - viewMatrix: Cesium.Matrix4.IDENTITY, - }, - requestRender() { - requests++; - }, - }; - const viewer = { scene }; - const dispose = createCyberSonarScene(viewer); - try { - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - assert.notDeepEqual( - model.color, - nativeColor, - 'Cyber neutral treatment precedes shader compilation', - ); - const frame = { commandList: [], passes: { render: true } }; - primitives.update(frame); - assert.equal(getCyberSonarSceneDiagnostics(viewer).gpu.supported, false); - assert.equal(frame.commandList[0], nativeCommand); - scene.postRender.raiseEvent(); - assert.equal( - scheduled, - 0, - 'inactive sweep has no timer to perform recovery', - ); - scene.postUpdate.raiseEvent(); - assert.equal(root.dataset.cyberSonarGpu, 'unsupported'); - assert.match(status.textContent, /Native contacts remain visible/); - assert.equal( - requests, - 1, - 'support loss explicitly wakes the parked scene', - ); - scene.preRender.raiseEvent(); - assert.deepEqual( - model.color, - nativeColor, - 'the requested draw restores native model color', - ); - assert.equal(getCyberSonarSceneDiagnostics(viewer).contacts, 0); - scene.postRender.raiseEvent(); - for (let i = 0; i < 3; i++) scene.postUpdate.raiseEvent(); - assert.equal( - requests, - 1, - 'unsupported idle ticks do not create a render loop', - ); - assert.equal(scheduled, 0); - dispose(); - scene.postUpdate.raiseEvent(); - assert.equal(requests, 1, 'disposed callbacks cannot wake the scene'); - } finally { - dispose(); - points.destroy(); - primitives.destroy(); - globalThis.document = previousDocument; - globalThis.matchMedia = previousMatchMedia; - globalThis.setTimeout = previousTimeout; - globalThis.clearTimeout = previousClear; - } - }); -} +test('the HUD sweep keeps its clock while markers cannot be shaded', () => { + const f = fixture({ modulation: false }); + const animation = { + animationName: 'cyber-sonar-sweep', + playState: 'running', + startTime: 500, + effect: { updateTiming() {} }, + }; + f.root.querySelector = (selector) => + selector === '.hud-sonar' + ? { isConnected: true, getAnimations: () => [animation] } + : null; + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(false); + assert.equal(animation.startTime, 0); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + dispose(); + } finally { + f.restore(); + } +}); + +test('the sweep sets its sector on drawing ticks and at the cadence, and changes at once', () => { + const f = fixture(); + const now = performance.now; + let clock = 1000; + performance.now = () => clock; + try { + const dispose = createCyberSonarScene(f.viewer); + assert.equal(f.root.dataset.cyberSonarGpu, 'supported'); + assert.equal(f.status.textContent, ''); + f.tick(); + assert.equal(f.sets.length, 1, 'the theme sets a sector'); + assert.deepEqual(f.sets[0], cyberSonarSector(1000, 800, 1000)); + clock += 10; + f.tick(false); + assert.equal(f.sets.length, 1, 'an idle tick before the cadence sets none'); + f.tick(true); + assert.equal(f.sets.length, 2, 'a tick that draws moves the angle'); + assert.deepEqual(f.sets[1], cyberSonarSector(1000, 800, 1010)); + clock += CYBER_SONAR_RENDER_INTERVAL_MS; + f.tick(false); + assert.equal(f.sets.length, 3, 'the cadence moves it on an idle tick'); + f.canvas.clientWidth = 600; + f.tick(false); + assert.equal(f.sets.length, 4, 'a resize sets it at once'); + assert.deepEqual(f.sets[3].center, { x: 300, y: 400 }); + f.root.dataset.cyberSonar = 'off'; + f.tick(false); + assert.equal(f.sets[4].radius, 0, 'Sonar OFF rests every contact'); + clock += 1000; + f.tick(true); + f.tick(false); + assert.equal(f.sets.length, 5, 'at rest only changes set it'); + f.root.dataset.cyberSonarOpacity = '50'; + f.tick(false); + assert.equal(f.sets.length, 6); + assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46); + f.state.cockpit = true; + f.tick(false); + assert.equal(f.sets[6], null, 'out of the map theme it clears'); + f.tick(true); + assert.equal(f.sets.length, 7, 'cleared once'); + f.state.cockpit = false; + f.root.dataset.cyberSonar = 'on'; + f.state.reducedMotion = true; + f.tick(false); + assert.equal(f.sets[7].radius, 0, 'reduced motion rests the sweep'); + f.state.reducedMotion = false; + f.root.dataset.uiTheme = 'tactical'; + f.tick(false); + assert.equal(f.sets[8], null, 'another HUD style clears it'); + f.tick(true); + assert.equal(f.sets.length, 9); + f.root.dataset.uiTheme = 'cyber'; + f.tick(false); + assert.ok(f.sets[9]?.radius > 0, 'back in Cyber it sweeps at once'); + assert.deepEqual(f.requests, [], 'the scene itself never asks for frames'); + dispose(); + assert.equal(f.sets[10], null, 'disposal clears it'); + assert.equal(f.ticks.size, 0); + assert.equal(f.changes.size, 0); + assert.equal(f.root.dataset.cyberSonarGpu, undefined); + dispose(); + assert.equal(f.sets.length, 11); + } finally { + performance.now = now; + f.restore(); + } +}); + +test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => { + const f = fixture({ lists: false }); + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(true); + assert.equal(f.sets.length, 2); + assert.equal(f.sets[1], null, 'cleared again'); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.match(f.status.textContent, /Native contacts remain visible/); + f.tick(true); + assert.equal(f.sets.length, 2, 'never set again'); + dispose(); + assert.equal(f.sets.length, 2); + } finally { + f.restore(); + } +}); + +test('a pass the renderer stops drawing on its own stops the sweep', () => { + const f = fixture(); + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(true); + assert.equal(f.sets.length, 1); + for (const cb of [...f.changes]) cb({ style: null, passes: [] }); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.equal(f.sets.at(-1), null); + const count = f.sets.length; + f.tick(true); + assert.equal(f.sets.length, count); + dispose(); + } finally { + f.restore(); + } +}); + +test('layer visibility changes ask for a frame', () => { + const f = fixture(); + let listener = null; + const manager = { + subscribe(cb) { + listener = cb; + return () => (listener = null); + }, + }; + try { + const dispose = createCyberSonarScene(f.viewer, manager); + listener({ type: 'visibility' }); + listener({ type: 'data' }); + assert.deepEqual(f.requests, ['cyber-sonar']); + dispose(); + assert.equal(listener, null); + } finally { + f.restore(); + } +}); diff --git a/src/data/aircraftEmergencyAnalyst.test.mjs b/src/data/aircraftEmergencyAnalyst.test.mjs index f26c28abc2..8b846222e1 100644 --- a/src/data/aircraftEmergencyAnalyst.test.mjs +++ b/src/data/aircraftEmergencyAnalyst.test.mjs @@ -1,8 +1,19 @@ -import * as Cesium from 'cesium'; import { TRACKED_ICON_COLOR } from '../layers/military/policy.js'; +import { TRACKED_CYAN } from '../layers/flights/policy.js'; import { createRendering as civilRendering } from '../layers/flights/rendering.js'; import { createRendering as militaryRendering } from '../layers/military/rendering.js'; import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js'; +import { createIcons as createMilitaryIcons } from '../layers/military/icons.js'; +import { createContactIcons } from './aircraftIconLayer.js'; +import { + aircraftMotionRegime, + createMotionRegime, + fixEpochMs, + fixPosition, + copyPosition, + historyFix, + julianAt, +} from './aircraftMotionRegime.js'; import { aircraftEmergency } from './aircraftEmergency.js'; // Source-to-voice provenance, status retention/clearing, contact-time contracts, // and civil/military billboard, Cockpit and model tint regressions. @@ -138,6 +149,7 @@ test('changed status without contact time retains general contact, including voi const runner = createGevActionRunner({ viewer: { clock: { onTick: { addEventListener: () => () => {} } }, + canvas: { addEventListener() {}, removeEventListener() {} }, scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, camera: { moveEnd: { addEventListener() {} }, @@ -444,7 +456,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do const red = rendering._fleetBillboardColor('civil', { emergency: aircraftEmergency({ squawk: '7700' }), }); - assert.ok(red.red > 0.9 && red.green < 0.5); + assert.ok(red[0] > 0.9 && red[1] < 0.5); flightState.records.data.set('civil', { emergency: aircraftEmergency({ squawk: '7700' }), }); @@ -454,27 +466,25 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do flightState._trackedIcao = 'civil'; assert.equal( rendering._modelColor('civil'), - factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR, + factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR, ); flightState._trackedIcao = null; flightState.records.data.set('civil', { emergency: null }); // An ordinary model draws its mesh's own colours, whatever the billboard's. - assert.equal(rendering._modelColor('civil'), Cesium.Color.WHITE); + assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]); } }); -test('GERMAN: an existing untracked military billboard repaints each poll without alpha loss', () => { +test('GERMAN: an existing untracked military icon repaints each poll without losing its fade', () => { const { flightState, rendering } = renderHarness(militaryRendering); - const bb = { - color: rendering._fleetBillboardColor('abc123').withAlpha(0.65), - }; Object.assign(flightState, { - _billboards: new Map([['abc123', bb]]), + _icons: createContactIcons(), _models: new Map(), _positionHistory: new Map(), - _cullPositions: new Map(), + _displayCourse: new Map(), _groundSnap: { forget() {} }, _cockpitContactMode: false, + _cockpitNearContacts: new Set(), }); const records = new MilitaryFlightRecords({ geoidHeight: () => 0, @@ -482,18 +492,51 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou floorAltitudeM: (value) => value, }); flightState.records = records; + const parts = { + rendering: { + ...rendering, + _iconKind: () => 'jet', + _syncModelToClass() {}, + }, + motion: { + _motionRegime: (history, info, renderTime) => + aircraftMotionRegime( + history, + info, + renderTime, + { speed: 'speedMps', track: 'track' }, + createMotionRegime(), + ), + _displayTimeAt: julianAt, + _fixEpochMs: fixEpochMs, + _fixPosition: fixPosition, + _copyPosition: copyPosition, + _historyFix: historyFix, + _refloorStaleGroundedContacts() {}, + _sampleMeshFloor() {}, + }, + }; + const icons = createMilitaryIcons({ + flightState, + services: { focus: { focusPassIsNeeded: () => false } }, + parts, + }); + const row = 'abc123'; + flightState._icons.put({ + id: row, + pos: { x: 0, y: 0, z: 0 }, + meta: { layer: 'military', id: row }, + }); + // The focus fade the fleet tick composes lives in its own field. + flightState._icons.setFocus(row, 0.65); const apply = createMilitarySnapshotRenderer({ flightState, records, - groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null }, - meshFloor: { sampleMeshFloorCells() {} }, + groundFloor: { warmGroundFloor() {} }, militaryRegistry: { registerMilitaryIcaos() {} }, - rendering: { - ...rendering, - _syncModelToClass() {}, - _applyFleetBillboardPresentation() {}, - }, - motion: {}, + rendering: parts.rendering, + motion: parts.motion, + icons, tracking: {}, queries: {}, }); @@ -519,7 +562,7 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou { observedAtMs: NOW_MS }, ); apply(snapshot, {}); - assert.equal(bb.color.green < 0.5, red); - assert.equal(bb.color.alpha, 0.65); + assert.equal(flightState._icons.item(row).color[1] < 0.5, red); + assert.ok(Math.abs(flightState._icons.focus(row) - 0.65) < 1e-6); } }); diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js new file mode 100644 index 0000000000..9abf527514 --- /dev/null +++ b/src/data/aircraftIconLayer.js @@ -0,0 +1,1104 @@ +import { + COAST_FLOOR_LIFT_M, + COURSE_HOLD_SPEED_MPS, + courseSlewCapDps, + RECOVER_MIN_M, + RECOVER_SNAP_M, + recoveryMs, +} from './motionModel.js'; +import { straightSegment } from './fixCurve.js'; +import { + norm180, + distance, + clone, + copyInto, + toDegrees, + vec, +} from '../geo/vector.js'; +import { fromRadians, toCartographicRadians } from '../geo/ellipsoid.js'; +import { horizonFrom, liftedForHorizon } from '../geo/horizon.js'; +import { createIconBook } from '../render/motion/iconBook.js'; +import { motionCourse, motionPosition } from '../render/motion/iconMotion.js'; +import { + drawOf, + findCamera, + findQuery, + rendererOf, +} from '../render/rendererOf.js'; +import { nearImageSwitchPx } from './iconAtlas.js'; +import { + aircraftIcon, + FLEET_ICON_PX, + TRACKED_ICON_PX, +} from './aircraftIcons.js'; +import { cockpitContactDotImage } from './cockpitContactDot.js'; +import { aircraftRecedeSpec } from './aircraftRecession.js'; +import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js'; + +/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ +const COCKPIT_DOT_PX = 16; +/** Fleet glyphs keep the established close-range 3× scale. */ +/** A contact icon's size before its scale, CSS px. */ +const FLEET_ICON_SIZE_PX = 20; +const NORMAL_SCALE_BY_DISTANCE = Object.freeze({ + near: 1000, + nearValue: 3.0, + far: 8000000, + farValue: 0.5, +}); +const COCKPIT_SCALE_BY_DISTANCE = Object.freeze({ + near: 1000, + nearValue: 1.15, + far: 8000000, + farValue: 0.65, +}); + +let cockpitDot = null; +/** + * The cockpit pip as an SVG of its own 16 px size around its PNG, so the + * draw port rasterises it at 16 px (as the icon set did) rather than at its + * few-pixel drawn size. + */ +function cockpitDotImage() { + if (cockpitDot) return cockpitDot; + const png = cockpitContactDotImage(); + const px = COCKPIT_DOT_PX; + cockpitDot = `data:image/svg+xml;charset=utf-8,${encodeURIComponent( + ``, + )}`; + return cockpitDot; +} + +/** A colour as the draw contract's `[r, g, b, a]`, from `{red, green, blue, alpha}`. */ +function rgba(color) { + if (!color || typeof color === 'string' || Array.isArray(color)) return color; + return [color.red, color.green, color.blue, color.alpha ?? 1]; +} + +/** Whether two plain values are the same, nested ones included. */ +function same(a, b) { + if (a === b) return true; + if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + for (const key of keys) if (!same(a[key], b[key])) return false; + return true; +} + +/** + * An aircraft layer's contact icons as it last drew them, over one icon + * draw set: each contact's icon item by its id, until when its motion holds + * (`render/motion/iconBook`), read back where it is drawn now. Writes go to + * the draw set together once the current task ends, so restyling and + * replanning a contact in one pass writes its item once. + * @param {import('../render/contract/draw').DrawSet|null} [drawSet] + * Where the icons are drawn; none keeps them only here (tests). + * @param {{capabilities?: ReadonlySet|null}} [options] + */ +export function createContactIcons(drawSet = null, { capabilities } = {}) { + const book = createIconBook(null, { capabilities }); + const pending = new Map(); + const removed = new Set(); + // Ids not drawn whatever their item says: following the clock, the time + // drawn is before the contact was there (`setUnseen`). + const unseen = new Set(); + /** The item as the draw set takes it: hidden while unseen. */ + const drawnItem = (item) => + unseen.has(item.id) && item.show !== false + ? { ...item, show: false } + : item; + // The ids the draw set holds. + const sent = new Set(); + let queued = false; + let disposed = false; + let shown = true; + + function flush() { + queued = false; + if (!drawSet || disposed) return; + if (pending.size) { + const items = [...pending.values()]; + pending.clear(); + // A write the set refuses throws here; what it holds stays as it was. + drawSet.upsert(items); + for (const item of items) sent.add(item.id); + } + if (removed.size) { + const ids = [...removed]; + removed.clear(); + for (const id of ids) sent.delete(id); + drawSet.remove(ids); + } + } + + function schedule() { + if (!drawSet || queued || disposed) return; + queued = true; + queueMicrotask(flush); + } + + const icons = { + /** The draw set's id, or null. */ + setId: drawSet?.id ?? null, + get count() { + return book.size; + }, + get show() { + return drawSet ? drawSet.show : shown; + }, + set show(value) { + if (drawSet) drawSet.show = value; + else shown = value; + }, + has: (id) => book.has(id), + /** The drawn ids, in the order first drawn. */ + ids: () => book.ids(), + item: (id) => book.item(id), + /** + * Until when (epoch ms on the display clock) an id's motion holds: + * Infinity when planned to hold, -Infinity while never planned. + */ + expires: (id) => book.expiresAt(id), + /** The ids whose motion ran out by `t`, to plan afresh. */ + due: (t) => book.due(t), + /** Where an id is drawn at `t` (into `result` when given), or null. */ + position(id, t, result) { + const p = book.position(id, t); + return p && result ? copyInto(p, result) : p; + }, + course: (id, t) => book.course(id, t), + shown: (id) => book.item(id)?.show !== false && !unseen.has(id), + focus: (id) => book.focus(id), + alpha: (id) => book.item(id)?.alpha ?? 1, + scale: (id) => book.item(id)?.scale ?? 1, + /** Draw an item as given (see `iconBook.put`). */ + put(item, options) { + book.put(item, options); + removed.delete(item.id); + pending.set(item.id, drawnItem(item)); + schedule(); + }, + /** + * Change some of an id's item; nothing is written when it already is + * so (and `expiresAt`, when given, is what it has). + * @returns {boolean} Whether anything was written. + */ + update(id, patch, options = {}) { + const item = book.item(id); + if (!item) return false; + let changed = + options.expiresAt !== undefined && + options.expiresAt !== book.expiresAt(id); + if (!changed) + for (const key of Object.keys(patch)) + if (!same(item[key], patch[key])) { + changed = true; + break; + } + if (!changed) return false; + icons.put({ ...item, ...patch }, options); + return true; + }, + setShown: (id, value) => icons.update(id, { show: value !== false }), + /** + * Keep an id from being drawn (true) whatever its item's `show` says, or + * draw it as its item says again (false). + */ + setUnseen(id, value) { + const item = book.item(id); + if (!item || unseen.has(id) === Boolean(value)) return; + if (value) unseen.add(id); + else unseen.delete(id); + pending.set(id, drawnItem(item)); + schedule(); + }, + /** Whether an id is kept from being drawn (`setUnseen`). */ + unseen: (id) => unseen.has(id), + setFocus: (id, factor) => icons.update(id, { focus: factor }), + remove(id) { + if (!book.has(id)) return; + book.remove(id); + unseen.delete(id); + pending.delete(id); + if (sent.has(id)) { + removed.add(id); + schedule(); + } + }, + clear() { + for (const id of book.ids()) book.remove(id); + unseen.clear(); + pending.clear(); + removed.clear(); + sent.clear(); + if (drawSet && !disposed) drawSet.clear(); + }, + /** Write what is waiting now. */ + flush, + dispose() { + for (const id of book.ids()) book.remove(id); + unseen.clear(); + pending.clear(); + removed.clear(); + sent.clear(); + disposed = true; + drawSet?.dispose(); + }, + }; + return icons; +} + +/** How far ahead (ms) a coast's ground is read each time it is planned. */ +export const COAST_FLOOR_LOOKAHEAD_MS = 10_000; +/** How far apart (ms) the ground under a coast is read, and how long each + * piece of a coast the ground lifts runs. */ +export const COAST_FLOOR_STEP_MS = 1_000; +/** A coast from above this height (m) never meets the ground: no terrain + * is this high, and a level coast only rises off the ellipsoid. */ +const COAST_ABOVE_TERRAIN_M = 9_000; + +/** + * How far the ground lifts an icon at `position`: metres to raise it to + * COAST_FLOOR_LIFT_M over the ground (0 or less: none), or null where the + * ground is not known. + */ +function floorLift(position, cachedGroundFloor) { + const carto = toCartographicRadians(position); + if (!carto) return null; + const ground = cachedGroundFloor(toDegrees(carto.lat), toDegrees(carto.lon)); + if (!Number.isFinite(ground)) return null; + return ground + COAST_FLOOR_LIFT_M - carto.height; +} + +/** `position` raised by `lift` metres (a copy). */ +function raised(position, lift) { + if (!(lift > 0)) return clone(position); + const carto = toCartographicRadians(position); + return fromRadians(carto.lon, carto.lat, carto.height + lift); +} + +/** + * A coast arc kept above the ground, as the CPU dead reckoning keeps it + * (`floorCoastedPosition`): past its fix an icon never draws lower than + * COAST_FLOOR_LIFT_M over the ground the layer's floor cache knows. The + * renderer cannot read that ground, so the coast is planned in pieces from + * the ground read along it: + * - clear of the ground for the lookahead, the arc as it is, planned again + * when the lookahead runs out (or never, with the ground known to the + * coast's end); + * - meeting the ground further on, the arc until a step before it; + * - where the ground lifts it within a step, a piece of the same arc from + * where it is drawn now, lifted, climbing to where the ground puts it a + * step on; + * - with the coast over, held where it stopped, lifted. + * Before its fix (a warm-up), an arc runs as it is until the fix. + * @param {object} arc The coast's `arc` motion segment. + * @param {number} t The display instant, epoch ms on the set's motion clock. + * @param {(latDeg: number, lonDeg: number) => number|null} cachedGroundFloor + * @returns {{motion?: object, pos?: object, course?: number, expiresAt: number}|null} + * A replacement motion where the ground lifts the icon, and until when the + * plan holds; null when the ground never matters to this arc. + */ +export function floorCoastArc(arc, t, cachedGroundFloor) { + if (!(arc.maxDtS > 0) || typeof cachedGroundFloor !== 'function') return null; + const fixCarto = toCartographicRadians(arc.fix); + if ( + fixCarto && + fixCarto.height > COAST_ABOVE_TERRAIN_M && + !((arc.climbMps ?? 0) < 0) + ) + return null; + const end = arc.t0 + arc.maxDtS * 1000; + if (t >= end) { + // The coast is over: it holds where it stopped. + const stopped = motionPosition(arc, null, end); + const lift = floorLift(stopped, cachedGroundFloor); + if (lift === null) return { expiresAt: t + COAST_FLOOR_LOOKAHEAD_MS }; + if (!(lift > 0)) return { expiresAt: Infinity }; + const courseDeg = motionCourse(arc, undefined, end); + return { + motion: { kind: 'hold', courseDeg }, + pos: raised(stopped, lift), + course: courseDeg, + expiresAt: Infinity, + }; + } + const start = Math.max(t, arc.t0); + const horizon = Math.min(end, start + COAST_FLOOR_LOOKAHEAD_MS); + let unknown = false; + let belowAt = null; + for (let at = start; ; at = Math.min(at + COAST_FLOOR_STEP_MS, horizon)) { + const lift = floorLift(motionPosition(arc, null, at), cachedGroundFloor); + if (lift === null) unknown = true; + else if (lift > 0) { + belowAt = at; + break; + } + if (at >= horizon) break; + } + if (belowAt === null) + return { + expiresAt: + horizon < end || unknown ? start + COAST_FLOOR_LOOKAHEAD_MS : Infinity, + }; + // A warm-up runs to its fix as it is; the coast is read again from there. + if (t < arc.t0) + return { expiresAt: Math.max(arc.t0, belowAt - COAST_FLOOR_STEP_MS) }; + if (belowAt - COAST_FLOOR_STEP_MS > t) + return { expiresAt: belowAt - COAST_FLOOR_STEP_MS }; + // The ground lifts it within a step: a piece from here to a step on. + const next = Math.min(t + COAST_FLOOR_STEP_MS, end); + const here = motionPosition(arc, null, t); + const there = motionPosition(arc, null, next); + const from = raised(here, floorLift(here, cachedGroundFloor) ?? 0); + const to = raised(there, floorLift(there, cachedGroundFloor) ?? 0); + const seconds = (next - t) / 1000; + const climbMps = + seconds > 0 + ? (toCartographicRadians(to).height - + toCartographicRadians(from).height) / + seconds + : 0; + const courseDeg = motionCourse(arc, undefined, t); + return { + motion: { + kind: 'arc', + fix: from, + t0: t, + minDtS: 0, + // On to the coast's end, should the next piece come late. + maxDtS: (end - t) / 1000, + speedMps: arc.speedMps, + trackDeg: courseDeg, + turnRateDps: arc.turnRateDps, + climbMps, + }, + pos: from, + course: courseDeg, + expiresAt: next, + }; +} + +let instances = 0; + +/** A plan that ran out longer ago than this (ms) is not eased away from. */ +const RECOVER_STALE_PLAN_MS = 1_000; + +/** How far ahead (ms) a placed contact's segment runs before it is asked again. */ +const PLACED_PLAN_MS = 1000; + +/** A display delay that never changes (ms). */ +function fixedDelay(ms) { + return { currentMs: ms, step: () => ms }; +} + +/** + * An aircraft layer's contacts as one icon draw set: each item's motion + * segment mirrors the layer's dead reckoning for the delayed display time, + * so the renderer moves every untracked contact between polls with no + * per-frame CPU pass. The layer keeps what it drew in `state._icons` + * (`createContactIcons`) and reads positions, courses, focus and expiry back + * from there. + * + * The layer's state supplies `_icons`, `_iconFocusActive`, + * `_positionHistory`, `_displayCourse`, `_groundSnap`, `_models`, + * `_trackedIcao`, `_viewer`, `_cockpitContactMode`, `_cockpitNearContacts` + * and `records` (`data`, `missingPolls`, `forget`). `parts.motion` supplies + * `_motionRegime`, `_displayTimeAt` and `_fixEpochMs`; `parts.rendering` + * the icon kind, scale, colours, and `_releaseModel`. + * + * @param {object} options + * @param {object} options.state The layer's mutable state. + * @param {object} options.services The layer's services (`focus`). + * @param {object} options.parts The layer's parts (`motion`, `rendering`). + * @param {string} options.layerId Pick and focus owner id. + * @param {{currentMs: number, step: (nowMs: number) => number}} [options.displayDelay] + * How far behind real time contacts draw (`data/displayDelay`), stepped + * once a frame; the renderer's motion clock follows it. + * @param {number} [options.renderDelaySec] A fixed delay instead. + * @param {() => boolean} [options.followsClock] True while the layer follows + * the world clock: contacts draw at the world's time (`state.now()`, the + * scene's time) with no delay. + * @param {number} [options.staleAlpha] A contact's alpha after a missed update. + * @param {number} options.courseMaxDps The fleet's course slew cap. + * @param {number} options.cockpitContactSizePx Cockpit far-contact pip size. + * @param {(icao24: string) => boolean} [options.holdsPlan] True while something + * else writes this row's segment (it is not planned). + * @param {(icao24: string) => void} [options.beforeSettle] Runs before a row is + * planned afresh. + * @param {(icao24: string) => void} [options.afterSettle] Runs after it. + * @param {(icao24: string) => void} [options.onForget] Drops the layer's own + * per-contact state when a contact goes. + * @param {((icao24: string, wallMs: number, info: object|undefined, + * history: object[], out: {x: number, y: number, z: number}) => + * {courseDeg: number, speedMps: number}|null)|null} [options.placeAt] + * 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. + */ +export function createAircraftIcons({ + state, + services, + parts, + layerId, + renderDelaySec = 0, + displayDelay = fixedDelay(renderDelaySec * 1000), + followsClock = () => false, + staleAlpha = 0.45, + courseMaxDps, + cockpitContactSizePx, + holdsPlan = () => false, + beforeSettle = () => {}, + afterSettle = () => {}, + onForget = () => {}, + placeAt = null, +}) { + const { focusPassIsNeeded } = services.focus; + // The near-image switch the rows were last written with (CSS px). + let switchPx = nearImageSwitchPx(1); + + /** The delayed instant (epoch ms) every untracked contact is drawn at. */ + const _displayMs = () => + followsClock() ? state.now() : Date.now() - displayDelay.currentMs; + /** The live draw set, whether its motion clock is the scene's, and the + * delay its live clock was last given. */ + let liveSet = null; + let sceneClock = false; + let sentDelayMs = NaN; + // The `recede` the set was last sent. + let sentRecede = null; + /** + * From when (display ms) each planned row's motion holds: a row whose + * motion starts after the time drawn is planned again when the time moves + * back before it (`_replanExpired`). + */ + const planFrom = new Map(); + /** The display time the rows were last checked against. */ + let replannedAt = -Infinity; + + /** The motion clock for whether the layer follows the world clock. */ + const motionClock = (scene) => + scene + ? { kind: 'scene' } + : { kind: 'live', delayMs: displayDelay.currentMs }; + + /** + * Once a frame: move the display delay on, and put the set's motion on + * the scene's clock (the world's time) while the layer follows the world + * clock, on the delayed live clock otherwise, with the delay as it is now. + */ + function _syncMotionClock() { + const scene = followsClock(); + if (!scene) displayDelay.step(Date.now()); + if (!liveSet) return; + if ( + scene === sceneClock && + (scene || sentDelayMs === displayDelay.currentMs) + ) + return; + sceneClock = scene; + sentDelayMs = scene ? NaN : displayDelay.currentMs; + liveSet.setOptions({ motionClock: motionClock(scene) }); + } + + /** The set recedes by the aircraft tuning: sent again when it changes. */ + function _syncRecede() { + if (!liveSet) return; + const recede = aircraftRecedeSpec(); + if (recede === sentRecede) return; + sentRecede = recede; + liveSet.setOptions({ recede }); + } + + /** + * Create the draw set for one layer lifetime, drawn over depth, culled at + * the horizon and receding toward the limb on the delayed live clock, + * stacked by the sprite order. + * @returns {string} The set's id. + */ + function _createIcons(viewer) { + sentRecede = aircraftRecedeSpec(); + const set = drawOf(viewer).icons({ + id: `${layerId}-icons:${++instances}`, + horizonCull: true, + recede: sentRecede, + motionClock: motionClock(followsClock()), + drawOrder: services.sprites?.spriteDrawOrder?.(layerId) ?? 0, + }); + // Columns of no rows put the set's host in the scene now, rather than + // with its first contact. + set.setColumns?.({ ids: [] }); + liveSet = set; + sceneClock = followsClock(); + sentDelayMs = sceneClock ? NaN : displayDelay.currentMs; + switchPx = _imageSwitchPx(viewer); + state._icons = createContactIcons(set, { + capabilities: rendererOf(viewer)?.capabilities ?? null, + }); + return set.id; + } + + /** Let the draw set go (the layer is destroyed). */ + function _disposeIcons() { + state._icons?.dispose(); + state._icons = null; + liveSet = null; + planFrom.clear(); + replannedAt = -Infinity; + } + + /** The near-image switch in CSS px for the scene's pixel ratio. */ + function _imageSwitchPx(viewer = state._viewer) { + return nearImageSwitchPx( + rendererOf(viewer)?.quality?.get?.()?.pixelRatio ?? 1, + ); + } + + /** Rewrite every row's image switch when the scene's pixel ratio moved. */ + function _syncImageSwitch() { + const next = _imageSwitchPx(); + if (next === switchPx || !state._icons) return; + switchPx = next; + for (const id of state._icons.ids()) _applyIconPresentation(id); + } + + /** Where a contact is drawn right now (into `result`), or null. */ + function _iconPosition(icao24, result) { + return state._icons?.position(icao24, _displayMs(), result) ?? null; + } + + /** The nose direction a contact is drawn with right now. */ + function _iconCourse(icao24) { + return state._icons?.course(icao24, _displayMs()) ?? null; + } + + /** Whether the layer draws this contact's icon (not tracked, not model-owned). */ + function _iconShown(icao24) { + const icons = state._icons; + return Boolean(icons?.has(icao24) && icons.shown(icao24)); + } + + /** Show or hide a contact's icon. */ + function _setIconShown(icao24, shown) { + state._icons?.setShown(icao24, shown); + } + + /** The ellipsoid's horizon from the eye, or null with no placed camera. */ + function _occluder() { + const pose = state._viewer ? findCamera(state._viewer)?.pose() : null; + return pose?.position ? horizonFrom(pose.position) : null; + } + + /** + * Whether an icon drawn at `position` clears the camera's horizon, judged + * as the draw port's horizon cull judges it (lifted to the cull height + * when drawn below it). No camera, no horizon. + */ + function _aboveHorizon(position, occluder) { + return !occluder || occluder.isPointVisible(liftedForHorizon(position)); + } + + /** + * Write the motion the layer's dead reckoning would follow from now on: + * interpolation between the bracketing fixes, the warm-up arc back from the + * oldest fix, or the coast arc past the newest. The displayed nose glides + * from where it is onto the new course at the fleet's slew cap; a hovering + * contact keeps its nose. The item expires when the regime would change. + * Following the clock, a contact not there yet at the time drawn + * (`regime.unseen`) is not drawn until its warm-up begins. + * @param {string} icao24 + * @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options] + * `fromCourseDeg`: nose to glide from when the row's own motion is not + * what was on screen (tracking handoff). `rewound`: the time drawn moved + * back before the row's motion; it is drawn where it was then, with no + * easing from where it is drawn now. + */ + function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) { + const icons = state._icons; + if (!icons?.has(icao24) || holdsPlan(icao24)) return; + const history = state._positionHistory.get(icao24); + if (!history?.length) return; + const info = state.records.data.get(icao24); + const t = _displayMs(); + const renderTime = parts.motion._displayTimeAt(t); + const fixMs = parts.motion._fixEpochMs; + const shownCourse = + fromCourseDeg ?? + (icons.expires(icao24) === -Infinity ? null : icons.course(icao24, t)); + + // A host-supplied placement decides where a live contact is drawn; with + // none, or no answer for this contact, the layer's own motion below does. + if (_planPlaced(icao24, info, history, t)) return; + + const regime = parts.motion._motionRegime(history, info, renderTime); + if (regime.unseen) { + // Held at its first fix, not drawn, until its warm-up begins. + const course = regime.heading; + icons.setUnseen(icao24, true); + icons.update( + icao24, + { + pos: clone(regime.fix.position), + course, + motion: { kind: 'hold', courseDeg: course }, + courseGlide: undefined, + }, + { expiresAt: fixMs(regime.fix) - TIMELINE_UNSEEN_MS }, + ); + planFrom.set(icao24, -Infinity); + return; + } + icons.setUnseen(icao24, false); + let speed; + let motion; + let pos; + let course; + let expiresAt = Infinity; + // From when the motion holds: before it, the time drawn has moved back. + let validFrom = t; + if (regime.kind === 'between' && regime.piece) { + // Along the curve between the two reports, a piece at a time. + const segment = regime.piece.segment; + speed = segment.speedMps; + motion = { ...segment, fix: clone(segment.fix) }; + pos = clone(segment.fix); + course = motionCourse(motion, undefined, t); + expiresAt = regime.piece.t1; + validFrom = regime.piece.t0; + } else if (regime.kind === 'between') { + const { a, b, span, trackFrom, trackTo, chordCourse } = regime; + speed = regime.speed; + const blend = chordCourse == null ? 0 : regime.blend; + pos = clone(b.position); + if (span > 0) { + course = trackFrom + blend * norm180((chordCourse ?? 0) - trackFrom); + motion = { + kind: 'lerp', + from: clone(a.position), + to: pos, + t0: fixMs(a), + t1: fixMs(b), + course0Deg: course, + courseSlopeDeg: norm180(trackTo - trackFrom) * (1 - blend), + }; + } else { + course = trackTo + blend * norm180((chordCourse ?? 0) - trackTo); + motion = { kind: 'hold', courseDeg: course }; + } + expiresAt = fixMs(b); + validFrom = fixMs(a); + } else { + const { fix, heading } = regime; + speed = regime.speed; + const t0 = fixMs(fix); + // A warm-up runs back to its start (a contact following the clock on + // its own fixes is unseen before that); a coast holds from its fix. + validFrom = + regime.maxDt === 0 && t0 > t + ? history[0].timeline === true + ? t0 - TIMELINE_UNSEEN_MS + : -Infinity + : t0; + pos = clone(fix.position); + course = heading; + motion = + speed === 0 + ? { kind: 'hold', courseDeg: heading } + : { + kind: 'arc', + fix: pos, + t0, + minDtS: regime.minDt, + maxDtS: regime.maxDt, + speedMps: speed, + trackDeg: heading, + turnRateDps: regime.turnRateDps, + }; + // A warm-up's arc ends at its fix, still ahead; a coast's runs to its + // limit, and a report that holds stays put until the next one. + if (regime.maxDt === 0 && t0 > t) expiresAt = t0; + // Past its fix a coast never goes below the ground. + if (motion.kind === 'arc') { + const floored = floorCoastArc( + motion, + t, + services.groundFloor?.cachedGroundFloor, + ); + if (floored) { + if (floored.motion) { + motion = floored.motion; + pos = floored.pos; + course = floored.course; + validFrom = t; + } + expiresAt = Math.min(expiresAt, floored.expiresAt); + } + } + } + // A new report that puts a moving contact somewhere else than it is + // drawn now (it was coasting past its newest report): it eases from + // where it is onto the new path instead of jumping, unless that is + // farther than a jump would be anyway. + // Only a row on screen whose plan is still running (a hidden row, or one + // whose motion ran out long ago, is simply drawn where it is now). + if ( + fromCourseDeg == null && + !rewound && + icons.shown(icao24) && + icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS + ) { + const prev = icons.item(icao24); + const drawn = motionPosition(prev.motion, prev.pos, t); + const next = motionPosition(motion, pos, t); + const errorM = distance(drawn, next); + if ( + errorM > RECOVER_MIN_M && + errorM < RECOVER_SNAP_M && + speed >= COURSE_HOLD_SPEED_MPS && + !same(prev.motion, motion) + ) { + const end = t + recoveryMs(errorM, speed); + // Where the new path has it by then, past this plan if need be. + const target = parts.motion._deadReckon( + icao24, + vec(), + parts.motion._displayTimeAt(end), + ); + motion = straightSegment(drawn, t, end, target ?? next); + pos = clone(drawn); + course = motionCourse(motion, undefined, t); + expiresAt = end; + validFrom = t; + } + } + // Below hover speed the nose holds what is on screen (or, for a new row, + // where this motion starts); above it, it glides on at the slew cap. + const hold = speed < COURSE_HOLD_SPEED_MPS; + let courseGlide; + if (hold || shownCourse != null) { + const rateDps = hold ? 0 : courseSlewCapDps(speed, courseMaxDps); + const prev = icons.item(icao24); + // The same motion at the same rate: the glide under way goes on, as + // one started now from the course on screen would. + courseGlide = + fromCourseDeg == null && + prev?.courseGlide?.rateDps === rateDps && + same(prev.motion, motion) + ? prev.courseGlide + : { + fromCourseDeg: shownCourse ?? motionCourse(motion, course, t), + t0: t, + rateDps, + }; + } + icons.update(icao24, { pos, course, motion, courseGlide }, { expiresAt }); + planFrom.set(icao24, validFrom); + } + + /** + * Plan a live contact a host-supplied placement places: from where it + * places it at `t` (display ms, the live clock's delayed time) to where it + * places it PLACED_PLAN_MS on, asked again when that runs out. Display + * time is wall time less the display delay, so the placement is asked at + * the wall times the segment's ends stand for. + * @returns {boolean} False when there is no placement, the layer follows + * the world clock, or it has no answer for this contact. + */ + function _planPlaced(icao24, info, history, t) { + if (!placeAt || followsClock()) return false; + const leadMs = displayDelay.currentMs; + const from = vec(); + const start = placeAt(icao24, t + leadMs, info, history, from); + if (!start) return false; + const { courseDeg: course } = start; + const t1 = t + PLACED_PLAN_MS; + const to = vec(); + const end = placeAt(icao24, t1 + leadMs, info, history, to); + const motion = end + ? { + kind: 'lerp', + from, + to, + t0: t, + t1, + course0Deg: course, + courseSlopeDeg: norm180(end.courseDeg - course), + } + : { kind: 'hold', courseDeg: course }; + state._icons.setUnseen(icao24, false); + state._icons.update( + icao24, + { pos: clone(from), course, motion, courseGlide: undefined }, + { expiresAt: t1 }, + ); + planFrom.set(icao24, t); + return true; + } + + /** + * Re-plan every row whose regime ended by `t` (epoch ms), and, following + * the clock, every row whose motion starts after `t` once the time drawn + * moved back (a seek, or the clock run backward): it is drawn where it was + * then, as it is when the time moves on. + */ + function _replanExpired(t) { + if (followsClock() && t < replannedAt) + for (const [icao24, from] of planFrom) + if (from > t) _planIcon(icao24, { rewound: true }); + replannedAt = t; + for (const icao24 of state._icons.due(t)) _planIcon(icao24); + } + + /** + * Advance focus de-emphasis for every drawn row (and every row a fleet model + * draws for, whose alpha reads it), only while a focus target exists or some + * row is still relaxing back to full emphasis. Each row whose emphasis moved + * is written as its item. + */ + function _focusIcons(t, nowMs, target) { + if (!focusPassIsNeeded(target, state._iconFocusActive)) return; + const { + advanceSpriteFocus, + focusAlphaNeedsWrite, + nearFarScalarValueAtDistance, + spriteFocusAtRest, + } = services.focus; + const icons = state._icons; + const viewer = state._viewer; + const query = viewer ? findQuery(viewer) : null; + const eye = viewer ? findCamera(viewer)?.pose()?.position : null; + let active = 0; + for (const id of icons.ids()) { + if (!icons.shown(id) && !state._models.has(id)) continue; + const item = icons.item(id); + const current = item.focus ?? 1; + // Nothing tracked and nothing pending: it stays at full emphasis. + if (!target && current === 1 && spriteFocusAtRest(item.meta)) continue; + const position = icons.position(id, t); + const cameraDistance = eye ? distance(eye, position) : Number.NaN; + const distanceScale = nearFarScalarValueAtDistance( + item.scaleByDistance, + cameraDistance, + ); + const half = (item.scale ?? 1) * distanceScale * 0.5; + const focus = advanceSpriteFocus(item.meta, { + screenPosition: query?.project(position) ?? null, + cameraDistance, + nowMs, + target, + spriteHalfWidthPx: item.size[0] * half, + spriteHalfHeightPx: item.size[1] * half, + }); + if (focus.active || focus.transitioning) active++; + if (focusAlphaNeedsWrite(current, focus.factor)) + icons.setFocus(id, focus.factor); + } + state._iconFocusActive = active; + } + + /** + * 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. + * @param {string} icao24 + * @param {object} [info] Its record. + * @returns {{image: string, imageLod: {near: string, switchPx: number}, + * size: [number, number], scale: number, scaleByDistance: object}} + */ + function _fleetLook(icao24, info = state.records.data.get(icao24)) { + const rendering = parts.rendering; + return { + image: aircraftIcon( + rendering._iconKind(icao24, info?.klass), + FLEET_ICON_PX, + ), + imageLod: { + near: aircraftIcon( + rendering._iconKind(icao24, info?.klass), + TRACKED_ICON_PX, + ), + switchPx, + }, + size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX], + scale: rendering._fleetBillboardScale(icao24, info?.klass), + scaleByDistance: NORMAL_SCALE_BY_DISTANCE, + }; + } + + /** Image, size, scale, tint and freshness for one row under the current + * normal/cockpit contract. Motion and course stay with `_planIcon`. */ + function _applyIconPresentation(icao24) { + const icons = state._icons; + if (!icons?.has(icao24)) return; + const rendering = parts.rendering; + const info = state.records.data.get(icao24); + const tracked = icao24 === state._trackedIcao; + const cockpitDot = + state._cockpitContactMode && + !tracked && + !state._cockpitNearContacts.has(icao24); + const look = cockpitDot + ? { + image: cockpitDotImage(), + imageLod: undefined, + size: [cockpitContactSizePx, cockpitContactSizePx], + scale: 1, + scaleByDistance: COCKPIT_SCALE_BY_DISTANCE, + color: rgba(rendering._cockpitContactColor(icao24, info)), + rotationMode: 'screen', + } + : { + ..._fleetLook(icao24, info), + color: rgba(rendering._fleetBillboardColor(icao24, info)), + rotationMode: 'course', + }; + look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1; + icons.update(icao24, look); + } + + /** Add a row for a new contact, hidden while it is the tracked one. */ + function _addIcon(icao24) { + state._icons.put(_baseItem(icao24, icao24 !== state._trackedIcao), { + expiresAt: -Infinity, + }); + _applyIconPresentation(icao24); + _settleIcon(icao24); + } + + /** A new contact's item before it is styled or planned: at the origin. */ + function _baseItem(icao24, show) { + return baseContactItem(layerId, icao24, show); + } + + /** + * Plan a row afresh, with the layer's own settle work on either side, and + * let a dimmed row relax: one that sat out the focus pass (tracked) may come + * back dimmed after the pass went idle, so it is counted to run the pass. + * @param {string} icao24 + * @param {{fromCourseDeg?: number}} [options] The course on screen to glide from. + */ + function _settleIcon(icao24, options) { + const icons = state._icons; + if (!icons?.has(icao24)) return; + beforeSettle(icao24); + if (icons.focus(icao24) < 1) state._iconFocusActive += 1; + _planIcon(icao24, options); + afterSettle(icao24); + } + + /** Drop a contact and everything the layer keeps for it. */ + function _forgetContact(icao24) { + state._icons?.remove(icao24); + planFrom.delete(icao24); + parts.rendering._releaseModel(icao24); + state.records.forget(icao24); + // The host-supplied placement, if any, forgets it as well. + services.placement?.forget(icao24); + state._positionHistory.delete(icao24); + state._displayCourse.delete(icao24); + state._groundSnap.forget(icao24); + onForget(icao24); + } + + /** Icon ids, so ray samples never land on an aircraft instead of the ground. */ + function _iconIds() { + return state._icons?.ids() ?? []; + } + + return { + _displayMs, + _syncMotionClock, + _syncRecede, + _createIcons, + _disposeIcons, + _syncImageSwitch, + _iconPosition, + _iconCourse, + _iconShown, + _setIconShown, + _occluder, + _aboveHorizon, + _planIcon, + _settleIcon, + _replanExpired, + _focusIcons, + _applyIconPresentation, + _fleetLook, + _addIcon, + _forgetContact, + _iconIds, + }; +} + +/** + * A contact's icon item before it is styled or planned: held at the origin + * (as a fresh row of the icon set was), always drawn over depth (receding + * toward the limb, as its set does), picked as `{layer, id}`. Its image comes with its style + * (`_applyIconPresentation`), before the item is first written. + */ +function baseContactItem(layerId, icao24, show) { + return { + id: icao24, + pos: { x: 0, y: 0, z: 0 }, + motion: { kind: 'hold', courseDeg: 0 }, + course: 0, + size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX], + rotationMode: 'course', + disableDepthTest: Infinity, + focus: 1, + show, + meta: { layer: layerId, id: icao24 }, + }; +} + +/** + * Test seams over an aircraft layer's icon rows, shared by the flights and + * military `testing` parts. + * @param {object} state The layer state holding `_icons`. + * @param {{icons: ReturnType}} parts Read at call time. + * @param {string} layerId + */ +export function aircraftIconTestSeams(state, parts, layerId) { + /** A hold at `position` on course 0, planned to hold. */ + const held = (position) => ({ + pos: clone(position), + motion: { kind: 'hold', courseDeg: 0 }, + course: 0, + courseGlide: undefined, + }); + + /** Give a test contact an icon row held at `icon.position`, shown as + * `icon.show` says (hidden by default while tracked). */ + function _seedIconForTest(icao24, icon, tracked) { + state._icons.put( + { + ...baseContactItem(layerId, icao24, icon?.show ?? !tracked), + ...(icon?.position ? held(icon.position) : null), + }, + { expiresAt: Infinity }, + ); + } + + /** Where a contact's icon is drawn now and whether the layer shows it. */ + function _iconForTest(icao24) { + const position = parts.icons._iconPosition(icao24); + return position + ? { + position, + shown: parts.icons._iconShown(icao24), + course: parts.icons._iconCourse(icao24), + } + : null; + } + + /** Show or hide a contact's icon as a handoff would, or hold it somewhere. */ + function _setIconForTest(icao24, { shown, position } = {}) { + const icons = state._icons; + if (!icons?.has(icao24)) return; + if (shown !== undefined) icons.setShown(icao24, shown); + if (position) icons.update(icao24, held(position), { expiresAt: Infinity }); + } + + return { _seedIconForTest, _iconForTest, _setIconForTest }; +} diff --git a/src/data/aircraftIconLayer.test.mjs b/src/data/aircraftIconLayer.test.mjs new file mode 100644 index 0000000000..73411d7f64 --- /dev/null +++ b/src/data/aircraftIconLayer.test.mjs @@ -0,0 +1,201 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + COAST_FLOOR_LOOKAHEAD_MS, + createAircraftIcons, + createContactIcons, + floorCoastArc, +} from './aircraftIconLayer.js'; +import { COAST_FLOOR_LIFT_M } from './motionModel.js'; +import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { createDisplayDelay } from './displayDelay.js'; + +const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0); + +test('following the world clock, contacts draw at the world’s time on the scene clock', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS + 86_400_000 }); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + let following = false; + const state = { + _viewer: viewer, + now: () => (following ? WORLD_MS : Date.now()), + }; + const icons = createAircraftIcons({ + state, + services: { focus: { focusPassIsNeeded: () => false } }, + parts: {}, + layerId: 'flights', + renderDelaySec: 30, + followsClock: () => following, + courseMaxDps: 3, + cockpitContactSizePx: 8, + }); + icons._createIcons(viewer); + const set = draw.find('flights-icons:'); + // Live: a poll interval behind real time, on the delayed live clock. + assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 }); + assert.equal(icons._displayMs(), Date.now() - 30_000); + following = true; + assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay'); + icons._syncMotionClock(); + assert.deepEqual(set.spec.motionClock, { kind: 'scene' }); + following = false; + icons._syncMotionClock(); + assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 }); + icons._disposeIcons(); +}); + +test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS }); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + let following = false; + const state = { _viewer: viewer, now: () => Date.now() }; + const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 }); + const icons = createAircraftIcons({ + state, + services: { focus: { focusPassIsNeeded: () => false } }, + parts: {}, + layerId: 'flights', + displayDelay: delay, + followsClock: () => following, + courseMaxDps: 3, + cockpitContactSizePx: 8, + }); + icons._createIcons(viewer); + const set = draw.find('flights-icons:'); + assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 }); + // Reports 90 s old every 30 s: the delay heads for about two minutes. + for (let i = 0; i < 20; i++) + delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000); + delay.settle(WORLD_MS); + t.mock.timers.setTime(WORLD_MS + 10_000); + icons._syncMotionClock(); + // 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's. + assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 }); + assert.equal(icons._displayMs(), Date.now() - 32_000); + // Following the world clock: no delay, and it is not moved on meanwhile. + following = true; + t.mock.timers.setTime(WORLD_MS + 20_000); + icons._syncMotionClock(); + assert.deepEqual(set.spec.motionClock, { kind: 'scene' }); + assert.equal(icons._displayMs(), Date.now()); + assert.equal(delay.currentMs, 32_000); + following = false; + icons._syncMotionClock(); + assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 }); + icons._disposeIcons(); +}); + +test('a coasting icon is kept above rising ground, as the CPU coast is', () => { + const T0 = WORLD_MS; + let now = T0; + const cosLat = Math.cos((30 * Math.PI) / 180); + const metresEast = (lonDeg) => lonDeg * 111_320 * cosLat; + // A slope rising east from 100 m out, half a metre per metre. + const ground = (_lat, lon) => Math.max(0, (metresEast(lon) - 100) * 0.5); + const fix = { epochMs: T0, position: fromDegrees(0, 30, 100) }; + const state = { + now: () => now, + _icons: createContactIcons(), + _positionHistory: new Map([['c', [fix]]]), + records: { data: new Map([['c', {}]]) }, + }; + const icons = createAircraftIcons({ + state, + services: { + focus: { focusPassIsNeeded: () => false }, + groundFloor: { cachedGroundFloor: ground }, + }, + parts: { + motion: { + _displayTimeAt: (ms) => ms, + _fixEpochMs: (f) => f.epochMs, + // Coasting east past its only fix at 100 m/s, for five minutes. + _motionRegime: () => ({ + kind: 'fix', + fix, + speed: 100, + heading: 90, + turnRateDps: 0, + minDt: -60, + maxDt: 300, + }), + }, + }, + layerId: 'flights', + renderDelaySec: 30, + followsClock: () => true, + courseMaxDps: 3, + cockpitContactSizePx: 8, + }); + state._icons.put( + { + id: 'c', + pos: fix.position, + motion: { kind: 'hold', courseDeg: 90 }, + course: 90, + size: [20, 20], + }, + { expiresAt: -Infinity }, + ); + icons._planIcon('c'); + // The fleet pass, every 80 ms for 12 s: the icon never sinks into the + // slope, and over open ground it coasts level. + let lowest = Infinity; + for (now = T0; now <= T0 + 12_000; now += 80) { + icons._replanExpired(now); + const p = icons._iconPosition('c'); + const carto = toCartographicRadians(p); + const floor = ground(0, (carto.lon * 180) / Math.PI) + COAST_FLOOR_LIFT_M; + lowest = Math.min(lowest, carto.height - floor); + if (now - T0 <= 2_000) + assert.ok(Math.abs(carto.height - 100) < 0.1, 'level over open ground'); + assert.ok(Math.abs(icons._iconCourse('c') - 90) < 1e-6, 'nose east'); + } + assert.ok(lowest > -0.05, `at most 5 cm under the floor (${lowest} m)`); + // 1.2 km east, the slope is at 550 m: it rode up the slope. + now = T0 + 12_000; + icons._replanExpired(now); + const end = toCartographicRadians(icons._iconPosition('c')); + const east = metresEast((end.lon * 180) / Math.PI); + assert.ok(Math.abs(east - 1_200) < 5, `1.2 km east (${east} m)`); + assert.ok(end.height > 550, `on the slope (${end.height} m)`); +}); + +test('a coast over known ground that never rises is planned once', () => { + const fix = { position: fromDegrees(0, 30, 100) }; + const arc = { + kind: 'arc', + fix: fix.position, + t0: 0, + minDtS: -60, + maxDtS: 5, + speedMps: 100, + trackDeg: 90, + turnRateDps: 0, + }; + assert.deepEqual( + floorCoastArc(arc, 0, () => 0), + { expiresAt: Infinity }, + ); + assert.deepEqual( + floorCoastArc(arc, 0, () => null), + { expiresAt: COAST_FLOOR_LOOKAHEAD_MS }, + 'unknown ground is read again', + ); + assert.equal( + floorCoastArc({ ...arc, fix: fromDegrees(0, 30, 10_000) }, 0, () => 0), + null, + 'a cruise above any terrain never reads it', + ); + // Stopped at the end of its coast, under ground that rose since. + const held = floorCoastArc(arc, 6_000, () => 200); + assert.equal(held.motion.kind, 'hold'); + assert.ok( + Math.abs(toCartographicRadians(held.pos).height - 201.5) < 1e-6, + 'held on the ground where the coast stopped', + ); +}); diff --git a/src/data/aircraftIcons.js b/src/data/aircraftIcons.js index f664c861ed..9948fa71b8 100644 --- a/src/data/aircraftIcons.js +++ b/src/data/aircraftIcons.js @@ -252,6 +252,8 @@ const _b64 = (s) => * NEAR the display size lets the browser's SVG AA do the work: crisp AND * smooth. 64 covers the 40–58 px fleet band with ≤1.6× minification. */ const FLEET_RASTER_PX = 64; +/** Raster size of the default fleet glyph. */ +export const FLEET_ICON_PX = FLEET_RASTER_PX; /** Tracked raster: the tracked billboard is the one SUSTAINED large 2D glyph * (close-zoom fleet flybys hand off to 3D models). Keep the 192 px texture so * it stays crisp at its biggest on-screen sizes. */ diff --git a/src/data/aircraftModelLayer.js b/src/data/aircraftModelLayer.js new file mode 100644 index 0000000000..b601b3179e --- /dev/null +++ b/src/data/aircraftModelLayer.js @@ -0,0 +1,1003 @@ +import { selectModelEligible } from './modelEligibility.js'; +import { + aircraftTreatmentAlpha, + DEFAULT_AIRCRAFT_RECESSION_PARAMS, +} from './aircraftRecession.js'; +import { + AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, + aircraftModelBlend, +} from './aircraftModelLighting.js'; +import { + createModelRecord, + modelIsRendering, + placeModel, + showModel, +} from './modelRecord.js'; +import { modelDrawnScale } from './modelVisualAnchor.js'; +import { fleetModelSet } from './fleetModels.js'; +import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { + distance, + distanceSquared, + dot, + RADIANS_PER_DEGREE, + sub, +} from '../geo/vector.js'; + +/** A white tint: what an IR-boosted model draws with. */ +const WHITE = Object.freeze([1, 1, 1, 1]); + +/** How long (ms) a fleet model whose load failed (`loadFailed`) waits + * before it is removed and added again, which loads it again. */ +const FLEET_MODEL_RETRY_MS = 5000; + +/** A colour as the draw contract's `[r, g, b, a]`, from `{red, green, blue, alpha}`. */ +function rgba(color) { + if (!color) return null; + if (typeof color === 'string' || Array.isArray(color)) return color; + return [color.red, color.green, color.blue, color.alpha ?? 1]; +} + +/** + * Whether `point` is inside the eye's view cone (`pose`), a metre's slack: + * the camera's culling volume against a one-metre sphere. + */ +function inView(pose, point) { + const v = sub(point, pose.position); + const depth = dot(v, pose.direction); + if (depth < -1) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * pose.aspectRatio; + return ( + Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 && + Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1 + ); +} + +/** + * An aircraft layer's 3D models: the fleet regime and its gap-proof handoff + * from the icon set (`createAircraftIcons`), the standalone tracked model, and + * the ~12 Hz fleet tick that drives both. Shared by the flights and military + * layers, which differ only in the options below. + * + * The models are two `models` sets of the renderer's draw port, made for each + * layer lifetime (`_createModelSets`): the fleet's, one item per modelled + * contact, and the tracked contact's (with a hidden item that keeps the + * tracked asset loaded). Each item is re-posed and restyled in place; the + * layer keeps its own record of each (`modelRecord.js`), a set's `ready` + * says when a model has loaded and its `loadFailed` when one failed to. A + * failed fleet model is loaded again every `FLEET_MODEL_RETRY_MS`; the + * tracked model has a per-selection budget (`TRACKED_MODEL_MAX_LOAD_FAILS` + * failures, `TRACKED_MODEL_RETRY_BACKOFF_MS` apart), after which the contact + * stays an icon until another is selected. Picks name the set and the + * contact's id. + * @param {object} options + * @param {object} options.state The layer state. + * @param {object} options.services + * @param {object} options.parts The layer's parts; `icons`, `motion` and + * `tracking` are read at call time. + * @param {(url: string) => string} options.resolveAsset + * @param {string} options.logLabel Console prefix, e.g. `Data:Flights`. + * @param {string} options.setPrefix The draw sets' id prefix, e.g. `flights`. + * @param {object} options.policy The layer's model budgets, radii, pixel + * bounds, heading offset, fleet tick interval and tracked-model load + * budget. + * @param {(meta: object|undefined) => object} options.modelSpec The fleet + * model an aircraft draws with, from its record (its type and emitter + * category): the model's url, scale, geometry, tint blend and spec `key`; + * `headingOffsetDeg` overrides the policy's. A spec without a `url` (the + * fleet set not loaded yet) keeps the aircraft an icon. A spec naming a + * `model` of the fleet set is drawn from the set's bytes (`gltf`). + * @param {(icao24: string) => object} options.modelColor Model tint + * (`{red, green, blue, alpha}`), including the tracked contact's. + * @param {(icao24: string) => void} [options.onModelEligible] Runs when a + * contact is about to render in 3D. + * @param {(renderTime: object, t: number, nowMs: number, eye: object|null) + * => void} [options.afterReplan] The layer's own pass in the fleet tick, + * after expired rows are re-planned: the display instant (as the layer's + * motion keeps it, and epoch ms), the focus clock and the eye (ECEF), or + * null without a camera. + */ +export function createAircraftModels({ + state, + services, + parts, + resolveAsset, + logLabel, + setPrefix, + policy, + modelSpec: _modelSpec, + modelColor: _modelColor, + onModelEligible = () => {}, + afterReplan = () => {}, +}) { + const { isTr3b } = services.aircraftPresentation; + const { focusNowMs, getFocusTarget } = services.focus; + const writeEpsilon = DEFAULT_AIRCRAFT_RECESSION_PARAMS.writeEpsilon; + let instances = 0; + /** The fleet items this tick wrote, sent together when it ends. */ + let pendingItems = []; + /** The ground sample's exclusions, kept while the sets they name live. */ + let exclusions = null; + + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + try { + return findCamera(state._viewer)?.pose() ?? null; + } catch { + return null; + } + } + + /** The renderer canvas's CSS size, and drawing-buffer pixels per CSS + * pixel; zero sizes without a renderer. */ + function _viewport() { + const renderer = rendererOf(state._viewer); + const canvas = renderer?.canvas; + return { + width: Number(canvas?.clientWidth) || 0, + height: Number(canvas?.clientHeight) || 0, + pixelRatio: renderer?.quality?.get?.()?.pixelRatio ?? 1, + }; + } + + /** A contact's record (its type and emitter category pick its model). */ + const _metaOf = (icao24) => state.records.data.get(icao24); + + /** The model heading offset an aircraft's model needs. */ + const _headingOffsetDeg = (meta) => + _modelSpec(meta).headingOffsetDeg ?? policy.MODEL_HEADING_OFFSET_DEG; + + /** A course (degrees) as the aircraft's model heading (radians). */ + const _modelHeading = (course, meta) => + ((course || 0) + _headingOffsetDeg(meta)) * RADIANS_PER_DEGREE; + + /** + * Make this lifetime's model sets on the viewer's draw port (none on a + * renderer that draws no models: the layer stays icons). `draw` stands in + * for the viewer's (tests). + * @param {object} viewer + * @param {{draw?: object}} [options] + */ + function _createModelSets(viewer, { draw } = {}) { + _disposeModelSets(); + const port = draw ?? findDraw(viewer); + if (typeof port?.models !== 'function') return; + const n = ++instances; + const fleet = port.models({ id: `${setPrefix}-models:${n}` }); + const tracked = port.models({ id: `${setPrefix}-tracked-model:${n}` }); + const offs = [ + fleet.on('ready', (id) => { + const record = state._models.get(id); + if (!record) return; + record.ready = true; + // Loaded after all (a renderer may retry on its own): no retry due. + record.failedAt = 0; + }), + fleet.on('loadFailed', (id) => { + const record = state._models.get(id); + if (record) record.failedAt = Date.now(); + }), + tracked.on('ready', (id) => { + if (id !== state._trackedIcao || !state._trackedModel) return; + state._trackedModel.ready = true; + // Loaded after all (a renderer may retry on its own): kept. + state._trackedModel.failedAt = 0; + // A good load retires this selection's failure budget: a contact + // that recovers after a transient blip is not one attempt from + // giving up. + state._trackedModelFailIcao = null; + state._trackedModelFailCount = 0; + state._trackedModelRetryAtMs = 0; + }), + tracked.on('loadFailed', (id, message) => { + const record = state._trackedModel; + if (id !== state._trackedIcao || !record || record.id !== id) return; + record.failedAt = Date.now(); + _noteTrackedModelLoadFailure(record.url, message); + }), + ]; + state._modelSets = { fleet, tracked, offs }; + } + + /** Let this lifetime's model sets go. */ + function _disposeModelSets() { + const sets = state._modelSets; + if (!sets) return; + state._modelSets = null; + for (const off of sets.offs) off(); + sets.fleet.dispose(); + sets.tracked.dispose(); + } + + /** Show or hide every model (the layer shown or hidden). */ + function _setModelsShown(show) { + const sets = state._modelSets; + if (!sets) return; + sets.fleet.show = show; + sets.tracked.show = show; + } + + /** The model sets' ids (picks, height samples); empty without sets. */ + function _modelSetIds() { + const sets = state._modelSets; + return sets ? [sets.fleet.id, sets.tracked.id] : []; + } + + /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude + * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the + * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in + * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms + * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED + * contact routes through here too (`_trackedModelRegimeActive`), with its place in the + * fleet's cap, so selecting a contact never changes its form. */ + + function _modelRegimeActive(pose = _pose()) { + if (!state._models3dEnabled) return false; + const h = pose?.height ?? Infinity; + return h < policy.MODEL_ALT_CEIL_M; + } + + /** Active model cap — the eligibility pre-pass AND _ensureModel's admission checks must use the + * SAME value, else 'all' (MODEL_MAX_ALL) would mark planes eligible that _ensureModel then refuses + * at the lower MODEL_MAX, silently degrading 'all' to 'proximity'. */ + + function _modelCap() { + const mapCap = + state._models3dMode === 'all' ? policy.MODEL_MAX_ALL : policy.MODEL_MAX; + // `Math.min` on purpose: cockpit may only ever LOWER the GLB budget. Cockpit is + // already the heaviest mode (20 Hz camera setView ahead of scene update, photoreal + // retraversal, the cloud pass) and every model is its own draw call. + return state._cockpitContactMode + ? Math.min(policy.COCKPIT_MODEL_MAX, mapCap) + : mapCap; + } + + /** Active ADD radius (m) — new planes inside this range get a model. Mode-aware: 'all' reaches far. */ + + function _modelAddDistM() { + return state._models3dMode === 'all' + ? policy.MODEL_ALL_ADD_M + : policy.MODEL_PROX_ADD_M; + } + + /** Active KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */ + + function _modelKeepDistM() { + return state._models3dMode === 'all' + ? policy.MODEL_ALL_KEEP_M + : policy.MODEL_PROX_KEEP_M; + } + + /** What a grounded model's ground sample sees through: the vertical sample + * at a plane's own lat/lon otherwise lands on its (or a parked neighbour's) + * icon or model instead of the tile skin. The query port sees through + * every draw set not drawn as ground; these are named for clarity. */ + + function _groundSampleExclusions() { + const modelSets = state._modelSets; + const iconSetId = state._icons?.setId ?? null; + if ( + exclusions?.modelSets !== modelSets || + exclusions.iconSetId !== iconSetId + ) { + const sets = [..._modelSetIds()]; + if (iconSetId) sets.push(iconSetId); + exclusions = { modelSets, iconSetId, value: { sets } }; + } + return exclusions.value; + } + + /** Position a 3D MODEL renders at. Airborne planes use their dead-reckoned position + * verbatim. GROUNDED planes' meta altitude is last-known baro or 0 m — nowhere near + * the photoreal tile skin in ellipsoid heights (buried ~100+ m at inland airports, + * hovering ~30 m at sea-level ones), and unlike the ground billboards a depth-tested + * model can't hide behind disableDepthTestDistance. So a modeled grounded plane rides + * a ONE-SHOT cached height sample of the skin at its lat/lon (groundSnap.js, + * CCTV-B9b discipline: never per-frame; taxiing >50 m retires the cached value to a + * bounded last-known and resamples), plus + * the belly offset so it sits on its gear rather than sinking to the model-origin + * fuselage centerline. Until the FIRST sample lands (tiles streaming / sample miss) + * there is no safe depth-tested placement at all: this returns null, the caller + * keeps the 2D billboard visible and the model hidden, and it retries later. Once + * a contact has resolved once, a later outage holds that measurement inside + * groundSnap's drift bound instead — a taxiing aircraft does not pop back to 2D + * because a resample is mid-backoff. */ + + function _modelDisplayPosition(icao24, pos) { + const meta = state.records.data.get(icao24); + if (!meta || !meta.onGround) return pos; + const h = state._groundSnap.heightFor( + state._viewer, + icao24, + pos, + _groundSampleExclusions(), + ); + if (h == null) return null; + const at = toLonLatH(pos); + if (!at) return null; + return fromDegrees(at.lon, at.lat, h + _modelSpec(meta).bellyM); + } + + /** How a contact's model draws now: the IR boost's flat white, or its tint. */ + function _shadingOf() { + return state._irBoost ? 'unlit' : 'pbr'; + } + + /** The tint a record sends: `base` at `alpha`, kept while within the + * write epsilon; a missing colour or alpha leaves it as it is. */ + function _treat(record, { base, alpha }) { + if (!base || !Number.isFinite(alpha)) return; + const tint = record.tint; + if ( + tint && + tint[0] === base[0] && + tint[1] === base[1] && + tint[2] === base[2] && + Math.abs(tint[3] - alpha) <= writeEpsilon + ) + return; + record.tint = [base[0], base[1], base[2], alpha]; + } + + /** The record's item, as its set draws it. */ + function _itemOf(id, record) { + return { + id, + pos: { x: record.position.x, y: record.position.y, z: record.position.z }, + url: record.url, + // Built from the bytes loaded up front: never fetched mid-session. + ...(record.gltf ? { gltf: record.gltf } : {}), + orientation: { heading: record.heading, pitch: 0, roll: 0 }, + scale: record.scale, + minPixelSize: record.minPixelSize, + shading: _shadingOf(), + tint: record.tint ?? WHITE, + // The mesh's own colours, tinted while tracked or in an emergency; + // the IR boost draws it flat white. + colorBlend: aircraftModelBlend(state._irBoost === true), + environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + show: record.show, + }; + } + + /** Send a record's item when anything it draws changed. */ + function _send(set, id, record, spec, out) { + if (!set) return; + const p = record.position; + const t = record.tint ?? WHITE; + const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}`; + if (key === record.sent) return; + record.sent = key; + const item = _itemOf(id, record); + if (out) out.push(item); + else set.upsert([item]); + } + + /** A fleet model whose load failed, removed from its set once + * `FLEET_MODEL_RETRY_MS` has passed; the write that follows adds it + * again, and the set loads it again. */ + function _retryFailedFleetModel(set, icao24, record) { + if ( + !set || + !record.failedAt || + Date.now() - record.failedAt < FLEET_MODEL_RETRY_MS + ) + return; + record.failedAt = 0; + record.sent = null; + // A fresh load: not ready until the set says so again. + record.ready = false; + set.remove([icao24]); + } + + /** Atomically hand one fleet contact from its icon to a safely placed, + * ready 3D model. Missing/loading models and unresolved terrain always leave + * the icon owning the visual, so no render frame can hide both. + * `beforeShow` runs only on the committing path — the per-tick model treatment + * belongs to a model that is about to draw, not to one still waiting. + * `out` collects the items to write (the tick writes them together). */ + + function _driveFleetModelHandoff( + icao24, + record, + pos, + course, + beforeShow, + out, + ) { + const icons = state._icons; + if (!record) { + icons.setShown(icao24, true); + return false; + } + const meta = _metaOf(icao24); + const spec = _modelSpec(meta); + const set = state._modelSets?.fleet ?? null; + _retryFailedFleetModel(set, icao24, record); + const displayPos = _modelDisplayPosition(icao24, pos); + if (!displayPos) { + showModel(record, false); // no ground evidence → nothing safe to place a depth-tested model at + _send(set, icao24, record, spec, out); + icons.setShown(icao24, true); + return false; + } + // Placed BEFORE the readiness test on purpose: a model can turn ready + // between ticks, and its first drawn frame must be at this placement. + placeModel(record, displayPos, _modelHeading(course, meta)); + if (!record.ready) { + showModel(record, false); // not loaded yet → keep the 2D icon, no half-model flash + _send(set, icao24, record, spec, out); + icons.setShown(icao24, true); + return false; + } + beforeShow?.(); + showModel(record, true); + _send(set, icao24, record, spec, out); + icons.setShown(icao24, false); // hand off ONLY once the model renders + return true; + } + + /** + * Whether a 3D model — not the billboard — is what the user actually SEES for + * this contact, and therefore whether the display floor should stand aside. + * + * Model EXISTENCE is not ownership. A fleet model that is still loading, or has + * no resolved ground to stand on, stays hidden while the icon stays shown + * (the gap-proof handoff: "hand off ONLY once the model renders"), and a tracked model + * is retained but hidden whenever the model regime is off — 3D disabled, camera + * zoomed past the ceiling, or cockpit mode. Gating on `has()`/existence therefore + * suppressed the clamp in exactly the states where the BILLBOARD is the visual, + * putting the burial straight back. + * + * Admission records a model hidden, so a fleet model admitted but not yet + * placed cannot claim ownership, and every site that shows one does so only + * after placing it. + * + * The two halves: + * - Fleet: the rendering test alone. Safe for the ground snap either way, + * because a fleet model is positioned from the RAW dead-reckon, not from + * the billboard. + * - Tracked: the rendering test AND `_trackedModelRegimeActive()`. The tracked + * model is fed from `_trackedDisplayPosition`, so once it is live the clamp + * must stand aside: two different chains would otherwise be deciding one + * contact's ground, and the billboard's is the one the operator is not + * looking at (T7). The regime check is what makes a regime + * flip take effect on the same frame rather than waiting for + * `_updateTrackedModel` to clear `show`; the rendering test is what keeps a + * null or still-loading tracked model from claiming a visual it is not + * drawing yet. Until the tracked model draws, the fleet model the contact + * had when it was selected still draws it, and owns the visual. + * @param {string} icao24 + * @param {import('./modelRecord.js').ModelRecord|null} [record] Resolved + * fleet model record; null means absent. + * @returns {boolean} + */ + + function _modelOwnsVisual(icao24, record) { + if (icao24 === state._trackedIcao) { + // Its fleet model draws it until the tracked model takes over. + return ( + parts.tracking._trackedModelRegimeActive() && + (modelIsRendering(state._trackedModel) || + modelIsRendering(state._models.get(icao24))) + ); + } + return modelIsRendering( + record === undefined ? state._models.get(icao24) : record, + ); + } + + // A model is the visual only once it actually draws, loaded AND shown + // (`modelIsRendering`). `show` is sufficient evidence of a safe placement + // because only ONE site ever sets it true for a fleet model + // (`_driveFleetModelHandoff`, after it is placed) and one for the + // tracked model (`_updateTrackedModel`, likewise); everything else — + // admission, an unresolved ground, a not-yet-ready glTF, the limb cull, a + // regime exit — only ever clears it. + + /** + * The scale a record's model is drawn at, by the draw contract's pixel + * rule (its `minPixelSize` at its distance from the eye). + * @param {import('./modelRecord.js').ModelRecord} record + * @param {object} spec The class spec (`nativeRadiusM`). + * @param {{pose: object|null, width: number, height: number, + * pixelRatio: number}} [view] + * One frame's camera and viewport, for a pass over many. + * @returns {number} + */ + function _modelDrawnScale(record, spec, view = _drawnScaleView()) { + return modelDrawnScale({ + scale: record.scale, + minPixelSize: record.minPixelSize, + radiusM: spec.nativeRadiusM, + center: record.position, + pose: view.pose, + viewportHeightPx: view.height, + viewportWidthPx: view.width, + pixelRatio: view.pixelRatio, + }); + } + + /** One frame's camera and viewport for `_modelDrawnScale`. */ + function _drawnScaleView() { + return { pose: _pose(), ..._viewport() }; + } + + /** Spec identity for an admitted model: the model and its scale together + * (one model draws several types, each at its own length). */ + + const _specKeyFor = (meta) => { + const spec = _modelSpec(meta); + return spec.key ?? `${spec.url}@${spec.scale}`; + }; + + /** A spec's bytes in the fleet model set loaded up front, if any. */ + const _gltfOf = (spec) => + spec.model ? (fleetModelSet()?.bytes?.get(spec.model) ?? null) : null; + + /** Type-change model sync (enrichment AND poll-path type/category updates): when the + * aircraft's model no longer matches its type's spec, drop it so the + * eligibility pass admits the right asset at the right scale. Gap-proof: the + * fleet icon is re-shown with the release, so the contact never goes + * invisible for the tick gap. The tracked standalone model gets the same + * rule (its billboard entity is always the fallback visual). */ + + function _syncModelToClass(icao24) { + const key = _specKeyFor(_metaOf(icao24)); + const current = state._models.get(icao24); + if (current && current.specKey !== key) _releaseModel(icao24); + if ( + icao24 === state._trackedIcao && + state._trackedModel && + state._trackedModel.specKey !== key + ) { + _releaseTrackedModel(); + } + } + + /** The IR boost flipped: every model restyles in place on its next write + * (shading and tint can change live). */ + function _reloadModelsForIrBoost() { + for (const record of state._models.values()) record.tint = null; + if (state._trackedModel) state._trackedModel.tint = null; + state._lastFleetTickMs = 0; + } + + /** Admit a fleet model for an aircraft; the icon shows until it is ready. */ + + function _ensureModel(icao24) { + // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet + // tick skips it, so a model here would be orphaned + double-rendered. + if (icao24 === state._trackedIcao) return; + onModelEligible(icao24); + if (state._models.has(icao24)) return; + // Without model sets (the renderer draws none) the icon stays. + if (!state._modelSets) return; + if (state._models.size >= _modelCap()) return; + if (!_modelRegimeActive() || !state.records.data.has(icao24)) return; + const meta = _metaOf(icao24); + const spec = _modelSpec(meta); + // Until the fleet model set has loaded the aircraft stays an icon. + if (!spec.url) return; + const record = createModelRecord({ + specKey: _specKeyFor(meta), // type-change sync compares against this + bellyM: spec.bellyM, + scale: spec.scale, + minPixelSize: policy.MODEL_MIN_PX, + }); + record.url = resolveAsset(spec.url); + record.gltf = _gltfOf(spec); + record.tint = state._irBoost ? WHITE : rgba(_modelColor(icao24)); + // Admitted, not yet the visual: the handoff places and shows it, and the + // set loads it from its first write. + state._models.set(icao24, record); + } + + /** Remove the 3D model for ONE aircraft (removal / military-suppression / track handoff). */ + + function _releaseModel(icao24) { + _releaseModelsOf([icao24]); + } + + /** Remove several aircraft's 3D models in one write (the eligibility pass). */ + + function _releaseModelsOf(ids) { + const gone = ids.filter((icao24) => state._models.delete(icao24)); + if (!gone.length) return; + state._modelSets?.fleet.remove(gone); + for (const icao24 of gone) _showReleasedIcon(icao24); + } + + /** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */ + + function _releaseModels() { + if (state._models.size) state._modelSets?.fleet.clear(); + for (const icao24 of state._models.keys()) _showReleasedIcon(icao24); + state._models.clear(); + } + + /** A released fleet model hands the visual straight back to its icon (the + * tracked contact's entity keeps its own). */ + + function _showReleasedIcon(icao24) { + const icons = state._icons; + if (icons?.has(icao24) && icao24 !== state._trackedIcao) + icons.setShown(icao24, true); + } + + /** Whether the driver may load the tracked model again: an untried + * selection, or one under its failure budget past its backoff. */ + function _trackedModelLoadAllowed(nowMs = Date.now()) { + if (state._trackedModelFailIcao !== state._trackedIcao) return true; + if (state._trackedModelFailCount >= policy.TRACKED_MODEL_MAX_LOAD_FAILS) + return false; + return nowMs >= state._trackedModelRetryAtMs; + } + + /** Count a failed tracked-model load against the selection's budget and + * arm the backoff, or the give-up latch. */ + function _noteTrackedModelLoadFailure(url, message) { + if (state._trackedModelFailIcao !== state._trackedIcao) { + state._trackedModelFailIcao = state._trackedIcao; + state._trackedModelFailCount = 0; + } + state._trackedModelFailCount += 1; + state._trackedModelRetryAtMs = + Date.now() + policy.TRACKED_MODEL_RETRY_BACKOFF_MS; + if (state._trackedModelFailCount >= policy.TRACKED_MODEL_MAX_LOAD_FAILS) + console.warn( + `[${logLabel}] tracked 3D model gave up after ${state._trackedModelFailCount} failed loads of ${url}; ` + + 'this contact stays 2D until another is selected', + message, + ); + } + + /** Drop the standalone tracked-aircraft model. */ + + function _releaseTrackedModel() { + const record = state._trackedModel; + if (!record) return; + state._trackedModel = null; + if (record.id) state._modelSets?.tracked.remove([record.id]); + } + + /** Hide the tracked model, writing it once. */ + function _hideTrackedModel() { + const record = state._trackedModel; + if (!record) return; + showModel(record, false); + _send( + state._modelSets?.tracked, + record.id, + record, + _modelSpec(_metaOf(record.id)), + ); + } + + /** A fleet model still drawing the tracked contact (it was a model when + * it was selected) lets go once the tracked model draws, or once the + * contact is no longer drawn as a model at all. */ + function _releaseTrackedFleetModel() { + if (state._trackedIcao && state._models.has(state._trackedIcao)) + _releaseModel(state._trackedIcao); + } + + /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet + * cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the + * follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed + * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). + * + * The model draws exactly as the fleet would draw this contact: the same + * asset at the same scale and `minPixelSize` (`MODEL_MIN_PX`), only its + * tint the tracked colour; whether it draws at all is the fleet's rule too + * (`_trackedModelRegimeActive`). Selecting a contact changes its colour, + * never its size or form. */ + + function _updateTrackedModel() { + // A failed load is let go (the icon carries the contact); the budget + // decides when, if ever, it is loaded again. + if (state._trackedModel?.failedAt) _releaseTrackedModel(); + const active = + state._trackedIcao && + parts.tracking._trackedModelRegimeActive() && + state._modelSets; + if (!active) { + _hideTrackedModel(); + _releaseTrackedFleetModel(); + return; + } + // Ask the frame-cached source directly. If the entity callback already ran, + // this is a no-op; if model loading completed between phases, it establishes + // this frame's single sample before the model renders. Camera, detection, and + // readout consumers then reuse that exact cached position. + const pos = + parts.motion._trackedDisplayPosition(state._trackedIcao) || + parts.icons._iconPosition(state._trackedIcao); + if (!pos) { + _hideTrackedModel(); + _releaseTrackedFleetModel(); + return; + } + const icao24 = state._trackedIcao; + const meta = _metaOf(icao24); + const spec = _modelSpec(meta); + if (state._trackedModel && state._trackedModel.id !== icao24) + _releaseTrackedModel(); + if (!state._trackedModel) { + // The icon carries it: after the load budget is spent, or until the + // fleet model set has loaded. + if (!_trackedModelLoadAllowed() || !spec.url) { + _releaseTrackedFleetModel(); + return; + } + const record = createModelRecord({ + specKey: _specKeyFor(meta), // type-change sync compares against this + bellyM: spec.bellyM, + scale: spec.scale, + minPixelSize: policy.MODEL_MIN_PX, + }); + record.id = icao24; + record.url = resolveAsset(spec.url); + record.gltf = _gltfOf(spec); + state._trackedModel = record; + } + const record = state._trackedModel; + // The tracked aircraft uses the same dominant light tint as the fleet; + // the IR boost removes the remaining diffuse hint with flat white. It + // fades like the tracked billboard while the plane is stale. + const base = state._irBoost ? WHITE : rgba(_modelColor(icao24)); + _treat(record, { + base, + alpha: parts.tracking._trackedStaleCue?.(icao24)?.dimmed + ? policy.STALE_ALPHA + : base[3], + }); + // Placed while it loads too: its first drawn frame is at this placement. + const displayPos = _modelDisplayPosition(icao24, pos); + if (!displayPos) { + _hideTrackedModel(); // no ground evidence → the icon carries it + _releaseTrackedFleetModel(); + return; + } + placeModel( + record, + displayPos, + _modelHeading(parts.motion._trackedDisplayCourse(), meta), + ); + showModel(record, record.ready); + _send(state._modelSets.tracked, icao24, record, spec); + if (record.ready) _releaseTrackedFleetModel(); + } + + /** + * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and + * the two-tier glyph swap all run on the GPU from each icon's motion, so this + * only re-plans icons whose regime ended, runs the layer's own pass after + * that (flights floors grounded contacts), advances focus de-emphasis while + * a target exists, and drives the 3D-model handoff inside the model regime. + * Driven before each frame draws: what it writes is flushed to the draw + * sets before the frame draws, as the 3D models it shows and hides are. + * @returns {void} + */ + + function _fleetTick() { + // Every frame, shown or not: the tracked label's stale cue follows the + // clock. (The tracked trail moves on in its own pass before each frame.) + if (state._viewer) parts.tracking._staleCueTick?.(); + try { + // Every frame too: the icons recede by the tuning as it is now, so a + // change shows on the next frame, shown or not. + parts.icons._syncRecede?.(); + _fleetPass(); + } finally { + // The models first, then the icons they take over from, so a pass + // that stopped part way never flushes an icon hidden for a model it + // did not write. + if (pendingItems.length) { + const items = pendingItems; + pendingItems = []; + try { + state._modelSets?.fleet.upsert(items); + } catch (error) { + // Nothing of these reached the set: send them again next tick, and + // let their icons carry the contacts meanwhile. + for (const item of items) { + const record = state._models.get(item.id); + if (record) { + record.sent = null; + showModel(record, false); + } + _showReleasedIcon(item.id); + } + console.warn(`[${logLabel}] fleet model write failed`, error); + } + } + state._icons?.flush(); + } + } + + function _fleetPass() { + const icons = state._icons; + if (!state._viewer || !icons || !icons.show) return; + // Following the world clock, the icons move on its time. + parts.icons._syncMotionClock?.(); + const nowMs = focusNowMs(Date.now()); + + if (nowMs - state._lastFleetTickMs < policy.FLEET_DR_INTERVAL_MS) return; + state._lastFleetTickMs = nowMs; + const pose = _pose(); + // Every contact in this pass shares the same delayed display instant. + const t = parts.icons._displayMs(); + + if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); + parts.icons._syncImageSwitch(); + parts.icons._replanExpired(t); + const renderTime = parts.motion._displayTimeAt( + t, + state._scratchFleetRenderTime, + ); + afterReplan(renderTime, t, nowMs, pose?.position ?? null); + const focusTarget = getFocusTarget(); + parts.icons._focusIcons(t, nowMs, focusTarget); + + // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. + // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. + const useModels = _modelRegimeActive(pose); + if (!useModels && state._models.size) _releaseModels(); + if (!useModels) { + state._trackedModelEligible = false; + return; + } + + // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the + // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen + // already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius, + // nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots + // (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint). + // Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an + // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap + // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum + // filtering dropped near off-screen planes entirely. This does both right. + const cap = _modelCap(); + const camPos = pose.position; + const addM = _modelAddDistM(); + const addDistSq = addM * addM; + const keepM = _modelKeepDistM(); + const keepDistSq = keepM * keepM; + // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. + const cand = []; + for (const icao of icons.ids()) { + // The tracked contact competes like any other (its model is drawn by + // `_updateTrackedModel`), so selecting it never changes its form; in + // cockpit it is the airframe you sit in, and takes no slot. + if (icao === state._trackedIcao && state._cockpitContactMode) continue; + // A converted TR-3B renders as an icon and can never take a model, so + // it must not occupy a CAP SLOT either — excluded here at selection time, + // not just at the handoff below, or accumulated conversions would starve + // ordinary contacts of 3D models. (The handoff guard stays as defence.) + if (isTr3b(icao)) continue; + // Ground planes compete for model slots like everyone else (owner decision + // 2026-07-03: "3D mode is respected regardless of whether a plane is on the + // ground or in the air — no distinction"). The cap + nearest-first ordering + // below already bound airport clusters; grounded placement is handled by the + // one-shot ground snap in _modelDisplayPosition. + const position = icons.position(icao, t); + const d2 = distanceSquared(camPos, position); + if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible + cand.push([icao, d2, inView(pose, position)]); + } + cand.sort((a, b) => a[1] - b[1]); // nearest first + if (cand.length > cap && nowMs - state._lastModelCapWarnMs > 5000) { + console.warn( + `[${logLabel}] ${cand.length} planes in 3D range; capped at ${cap} (${state._models3dMode}). On-screen planes are prioritized.`, + ); + state._lastModelCapWarnMs = nowMs; + } + const modelEligible = selectModelEligible(cand, { + cap, + addDistSq, + isModeled: (icao) => + state._models.has(icao) || + (icao === state._trackedIcao && state._trackedModelEligible), + }); + state._trackedModelEligible = + Boolean(state._trackedIcao) && modelEligible.has(state._trackedIcao); + const toRelease = []; + for (const icao of state._models.keys()) { + if (icao !== state._trackedIcao && !modelEligible.has(icao)) + toRelease.push(icao); + } + _releaseModelsOf(toRelease); + + // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown + // until the model is actually READY to render, so a plane is never both iconless AND + // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick + // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on + // purpose: the Easter egg IS the triangle, and there is no GLB for it. + const occluder = parts.icons._occluder(); + const items = pendingItems; + for (const icao24 of modelEligible) { + if (isTr3b(icao24)) continue; + // The tracked contact's model is `_updateTrackedModel`'s. + if (icao24 === state._trackedIcao) continue; + if (!icons.has(icao24)) continue; + const position = icons.position(icao24, t); + if ( + icons.unseen?.(icao24) || + !parts.icons._aboveHorizon(position, occluder) + ) { + // A model that crossed the limb would keep drawing through the + // hidden globe; the icon's own cull is on the GPU. A contact not + // there yet at the time drawn is hidden as one beyond it. + const hidden = state._models.get(icao24); + if (hidden?.show) { + showModel(hidden, false); + _send( + state._modelSets?.fleet, + icao24, + hidden, + _modelSpec(_metaOf(icao24)), + items, + ); + } + continue; + } + _ensureModel(icao24); + const record = state._models.get(icao24); + const cameraDistanceM = distance(camPos, position); + _driveFleetModelHandoff( + icao24, + record, + position, + icons.course(icao24, t), + () => { + _treat(record, { + // IR boost must survive the per-tick treatment write — otherwise + // any alpha change would repaint the ordinary tint over the hot + // white. Boosted models also skip the recession fade: hot targets + // stay full-strength at any range (icons keep their normal + // fade — full-opacity glyph walls read as overwhelming). + base: state._irBoost ? WHITE : rgba(_modelColor(icao24)), + alpha: state._irBoost + ? 1 + : aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(icao24), + focusFactor: icons.focus(icao24), + cameraDistanceM, + cameraHeightM: pose.height, + }), + }); + }, + items, + ); + } + } + return { + _createModelSets, + _disposeModelSets, + _setModelsShown, + _modelSetIds, + _modelRegimeActive, + _modelCap, + _modelAddDistM, + _modelKeepDistM, + _groundSampleExclusions, + _modelDisplayPosition, + _driveFleetModelHandoff, + _modelOwnsVisual, + _modelDrawnScale, + _drawnScaleView, + _specKeyFor, + _syncModelToClass, + _reloadModelsForIrBoost, + _ensureModel, + _releaseModel, + _releaseModels, + _showReleasedIcon, + _releaseTrackedModel, + _updateTrackedModel, + _fleetTick, + }; +} diff --git a/src/data/aircraftModelLayer.test.mjs b/src/data/aircraftModelLayer.test.mjs new file mode 100644 index 0000000000..5db4baa4ce --- /dev/null +++ b/src/data/aircraftModelLayer.test.mjs @@ -0,0 +1,391 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createAircraftModels } from './aircraftModelLayer.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; + +const POLICY = { + MODEL_ALT_CEIL_M: 800_000, + MODEL_MAX: 40, + MODEL_MAX_ALL: 350, + COCKPIT_MODEL_MAX: 60, + MODEL_PROX_ADD_M: 150_000, + MODEL_PROX_KEEP_M: 185_000, + MODEL_ALL_ADD_M: 400_000, + MODEL_ALL_KEEP_M: 450_000, + MODEL_MIN_PX: 24, + TRACKED_MODEL_MIN_PX: 48, + TRACKED_MODEL_MAX_PX: 600, + MODEL_HEADING_OFFSET_DEG: 0, + FLEET_DR_INTERVAL_MS: 80, + TRACKED_MODEL_MAX_LOAD_FAILS: 3, + TRACKED_MODEL_RETRY_BACKOFF_MS: 1500, +}; + +const SPEC = { + url: 'plane.glb', + scale: 1, + bellyM: 3, + nativeRadiusM: 20, + blendAmount: 0.9, +}; + +/** + * A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a + * models layer over a fake draw port whose fleet set can be told to fail a + * write. The eye sits above them at 30 km. + */ +function fleetFixture(positions) { + const base = fakeDrawPort(); + const removes = []; + let failNextUpsert = false; + const draw = { + ...base, + models(spec) { + const set = base.models(spec); + return { + ...set, + get show() { + return set.show; + }, + set show(value) { + set.show = value; + }, + id: set.id, + upsert(items) { + if (failNextUpsert && spec.id.includes('-models:')) { + failNextUpsert = false; + throw new Error('simulated write failure'); + } + return set.upsert(items); + }, + remove(ids) { + removes.push([...ids]); + return set.remove(ids); + }, + }; + }, + }; + const eye = fromDegrees(-97.71, 30.21, 30_000); + const viewer = {}; + bindRenderer(viewer, { + draw, + camera: { + pose: () => ({ + position: eye, + direction: { x: 0, y: 0, z: -1 }, + up: { x: 0, y: 1, z: 0 }, + right: { x: 1, y: 0, z: 0 }, + fovy: Math.PI / 3, + aspectRatio: 1, + height: 30_000, + }), + }, + }); + const shown = new Map([...positions.keys()].map((id) => [id, true])); + let alphaOf = 1; + let focusOf = 1; + const unseenIds = new Set(); + const icons = { + show: true, + setId: 'flights-icons:1', + ids: () => [...positions.keys()], + has: (id) => positions.has(id), + position: (id) => positions.get(id), + course: () => 90, + alpha: () => alphaOf, + focus: () => focusOf, + setShown: (id, value) => shown.set(id, value), + unseen: (id) => unseenIds.has(id), + flush() {}, + }; + const state = { + _viewer: viewer, + _icons: icons, + _models: new Map(), + _modelSets: null, + _trackedIcao: null, + _trackedModel: null, + _models3dEnabled: true, + _models3dMode: 'proximity', + _cockpitContactMode: false, + _irBoost: false, + _lastFleetTickMs: 0, + _lastModelCapWarnMs: 0, + records: { + data: new Map( + [...positions.keys()].map((id) => [id, { klass: 'airliner' }]), + ), + }, + }; + let now = 1_000_000; + let iconRecedeSyncs = 0; + const parts = { + icons: { + _displayMs: () => now, + _syncImageSwitch() {}, + _replanExpired() {}, + _focusIcons() {}, + _occluder: () => null, + _aboveHorizon: () => true, + _syncRecede() { + iconRecedeSyncs += 1; + }, + }, + motion: { _displayTimeAt: () => null }, + tracking: { + _refreshCockpitNearContacts() {}, + _trackedModelRegimeActive: () => false, + }, + }; + const models = createAircraftModels({ + state, + services: { + aircraftPresentation: { isTr3b: () => false }, + camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale }, + focus: { focusNowMs: () => now, getFocusTarget: () => null }, + }, + parts, + resolveAsset: (url) => url, + logLabel: 'Test', + setPrefix: 'flights', + policy: POLICY, + modelSpec: () => SPEC, + modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }), + }); + models._createModelSets(viewer); + const fleetId = models._modelSetIds()[0]; + return { + models, + state, + draw: base, + fleet: () => base.set(fleetId), + fleetId, + removes, + shown, + failNextUpsert: () => (failNextUpsert = true), + /** How often the icons were told to recede by the tuning as it is now. */ + iconRecedeSyncs: () => iconRecedeSyncs, + /** Mark a contact as not there yet at the time drawn, or there again. */ + setUnseen(id, value) { + if (value) unseenIds.add(id); + else unseenIds.delete(id); + }, + /** The icons' alpha and focus the fleet models take. */ + look(alpha, focus) { + alphaOf = alpha; + focusOf = focus; + }, + /** One fleet tick, past the tick interval. */ + tick() { + now += 1000; + models._fleetTick(); + }, + }; +} + +const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000); +const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000); + +test('the fleet tick hands contacts to ready models and back without a gap', () => { + const positions = new Map([ + ['a1', near(1)], + ['a2', near(2)], + ]); + const f = fleetFixture(positions); + f.tick(); + assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']); + assert.equal( + f.shown.get('a1'), + true, + 'icons carry contacts until models load', + ); + f.draw.ready(f.fleetId, 'a1'); + f.tick(); + assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over'); + assert.equal(f.fleet().items.get('a1').show, true); + assert.equal( + f.shown.get('a2'), + true, + 'a model still loading leaves its icon', + ); +}); + +test('contacts leaving the model band are released in one write', () => { + const positions = new Map([ + ['a1', near(1)], + ['a2', near(2)], + ['a3', near(3)], + ]); + const f = fleetFixture(positions); + f.tick(); + for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id); + f.tick(); + positions.set('a2', far(2)); + positions.set('a3', far(3)); + f.removes.length = 0; + f.tick(); + assert.deepEqual( + f.removes, + [['a2', 'a3']], + 'one remove for every evicted model', + ); + assert.deepEqual([...f.fleet().items.keys()], ['a1']); + assert.equal( + f.shown.get('a2'), + true, + 'a released model hands back to its icon', + ); + assert.equal(f.shown.get('a3'), true); +}); + +test('a failed fleet write leaves the icons in charge and is sent again', () => { + const positions = new Map([['a1', near(1)]]); + const f = fleetFixture(positions); + f.tick(); + f.draw.ready(f.fleetId, 'a1'); + const realWarn = console.warn; + console.warn = () => {}; + try { + f.failNextUpsert(); + f.tick(); + } finally { + console.warn = realWarn; + } + assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon'); + assert.equal( + f.fleet().items.get('a1').show, + false, + 'the set still has the hidden model', + ); + assert.equal(f.models._modelOwnsVisual('a1'), false); + f.tick(); + assert.equal( + f.fleet().items.get('a1').show, + true, + 'the next tick sends it again', + ); + assert.equal(f.shown.get('a1'), false); +}); + +test('a fleet model whose load failed is loaded again after a wait, not before', () => { + const positions = new Map([['a1', near(1)]]); + const f = fleetFixture(positions); + const realNow = Date.now; + let clock = 50_000_000; + Date.now = () => clock; + try { + f.tick(); + const writes = f.fleet().writes; + clock += 60_000; + f.tick(); + assert.equal( + f.fleet().writes, + writes, + 'a model still loading is not rewritten, however long it takes', + ); + f.draw.loadFailed(f.fleetId, 'a1'); + f.removes.length = 0; + clock += 4_999; + f.tick(); + assert.deepEqual(f.removes, [], 'not before the wait'); + assert.equal(f.shown.get('a1'), true, 'the icon carries the contact'); + clock += 1; + f.tick(); + assert.deepEqual(f.removes, [['a1']], 'removed once the wait is over'); + assert.ok(f.fleet().items.has('a1'), 'and added again in the same tick'); + assert.equal(f.state._models.get('a1').failedAt, 0); + assert.equal(f.state._models.get('a1').ready, false, 'a fresh load'); + f.removes.length = 0; + clock += 60_000; + f.tick(); + assert.deepEqual(f.removes, [], 'tried again only after another failure'); + // A renderer's own retry that loads before the layer's: nothing is due. + f.draw.loadFailed(f.fleetId, 'a1'); + f.draw.ready(f.fleetId, 'a1'); + clock += 60_000; + f.tick(); + assert.deepEqual(f.removes, [], 'a model that loaded is not tried again'); + assert.equal( + f.shown.get('a1'), + false, + 'the model takes over once it loads', + ); + } finally { + Date.now = realNow; + } +}); + +test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => { + const { + aircraftTreatmentAlpha, + setAircraftRecessionParams, + resetAircraftRecessionParams, + } = await import('./aircraftRecession.js'); + const position = near(1); + const f = fleetFixture(new Map([['a1', position]])); + assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede'); + const eye = fromDegrees(-97.71, 30.21, 30_000); + const expected = (focusFactor) => + aircraftTreatmentAlpha({ + baseAlpha: 0.8, + focusFactor, + cameraDistanceM: Math.hypot( + eye.x - position.x, + eye.y - position.y, + eye.z - position.z, + ), + cameraHeightM: 30_000, + }); + try { + // Recede from the eye on, so the haze is not 1 here. + setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 }); + f.look(0.8, 0.5); + f.tick(); + f.draw.ready(f.fleetId, 'a1'); + f.tick(); + const item = f.fleet().items.get('a1'); + assert.equal(item.tint[3], expected(0.5), 'the tint carries it all'); + assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose'); + // A frame inside the fleet interval writes nothing, whatever changed. + f.look(0.8, 0.25); + f.models._fleetTick(); + assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]); + f.tick(); + assert.equal( + f.fleet().items.get('a1').tint[3], + expected(0.25), + 'the next tick takes it', + ); + } finally { + resetAircraftRecessionParams(); + } + f.state._irBoost = true; + f.models._reloadModelsForIrBoost(); + f.tick(); + assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength'); +}); + +test('a tuning change reaches the icons on the next frame, icons shown or not', async () => { + const f = fleetFixture(new Map([['a1', near(1)]])); + f.state._icons.show = false; + const before = f.iconRecedeSyncs(); + f.models._fleetTick(); + assert.ok(f.iconRecedeSyncs() > before, 'the icons are told'); +}); + +test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => { + const f = fleetFixture(new Map([['a1', near(1)]])); + f.tick(); + f.draw.ready(f.fleetId, 'a1'); + f.tick(); + assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there'); + f.setUnseen('a1', true); + f.tick(); + assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen'); + f.setUnseen('a1', false); + f.tick(); + f.tick(); + assert.equal(f.fleet().items.get('a1').show, true, 'drawn again'); +}); diff --git a/src/data/aircraftModelLighting.js b/src/data/aircraftModelLighting.js index 38725be936..64d64aebeb 100644 --- a/src/data/aircraftModelLighting.js +++ b/src/data/aircraftModelLighting.js @@ -1,5 +1,3 @@ -import * as Cesium from 'cesium'; - /** * Lighting options shared by every aircraft 3D model (Flights, Military * Flights, Local ADS-B). @@ -16,16 +14,18 @@ export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({ enabled: false, }); +const HIGHLIGHT = Object.freeze({ mode: 'highlight' }); +const FLAT = Object.freeze({ mode: 'mix', amount: 1 }); + /** - * How an aircraft model's colour meets its mesh. HIGHLIGHT multiplies, so - * white draws the mesh's own colours as built, and the tracked or emergency - * colour tints the mesh without hiding its paint. The IR boost draws the - * model flat white instead (MIX at 1, with its unlit shader). + * How an aircraft model's colour meets its mesh, as a draw item's + * `colorBlend`. `highlight` multiplies, so white draws the mesh's own + * colours as built, and the tracked or emergency colour tints the mesh + * without hiding its paint. The IR boost draws the model flat white instead + * (`mix` at 1, unlit). * @param {boolean} irBoost - * @returns {{colorBlendMode: Cesium.ColorBlendMode, colorBlendAmount: number}} + * @returns {{mode: 'highlight'|'mix', amount?: number}} */ export function aircraftModelBlend(irBoost) { - return irBoost - ? { colorBlendMode: Cesium.ColorBlendMode.MIX, colorBlendAmount: 1 } - : { colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0 }; + return irBoost ? FLAT : HIGHLIGHT; } diff --git a/src/data/aircraftModelLighting.test.mjs b/src/data/aircraftModelLighting.test.mjs index 70be8e5d40..b20d3c6497 100644 --- a/src/data/aircraftModelLighting.test.mjs +++ b/src/data/aircraftModelLighting.test.mjs @@ -5,9 +5,8 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; /** - * Every aircraft model drawn in the scene skips Cesium's dynamic environment - * map (a sky render and GPU readback per model). Drawn models are the calls - * that set a minimum pixel size. + * Every aircraft model drawn in the scene skips the renderer's dynamic + * environment map (a sky render and GPU readback per model). */ const SOURCES = [ { @@ -18,13 +17,6 @@ const SOURCES = [ name: 'militaryFlights', source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)), }, - { - name: 'localAdsb', - source: readFileSync( - new URL('../layers/localAdsb/models.js', import.meta.url), - 'utf8', - ), - }, ]; test('the shared option turns the dynamic environment map off', () => { @@ -34,19 +26,25 @@ test('the shared option turns the dynamic environment map off', () => { for (const { name, source } of SOURCES) { test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => { - const calls = [ - ...source.matchAll( - /(?:fromGltfAsync\(|loadModel\(|(?:_createModel|createFleetModel)\(\s*\w+,\s*)\{([\s\S]*?)\n\s*\}[,)]/g, - ), - ] - .map((match) => match[1]) - .filter((options) => /\bminimumPixelSize:/.test(options)); - assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`); - for (const [index, options] of calls.entries()) - assert.match( - options, - /\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/, - `${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`, - ); + // Its models are draw-port items; every item it builds (fleet and + // tracked) carries the shared option. + assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/); + const items = [...source.matchAll(/\burl: record\.url,/g)]; + assert.ok(items.length >= 1, `expected model items in ${name}`); + const flags = [ + ...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g), + ]; + assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`); }); } + +test('localAdsb: its draw-port models skip the dynamic environment map', () => { + const source = readFileSync( + new URL('../layers/localAdsb/models.js', import.meta.url), + 'utf8', + ); + assert.match( + source, + /\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/, + ); +}); diff --git a/src/data/aircraftMotionRegime.js b/src/data/aircraftMotionRegime.js new file mode 100644 index 0000000000..5594ca20af --- /dev/null +++ b/src/data/aircraftMotionRegime.js @@ -0,0 +1,336 @@ +import { fromDegrees } from '../geo/ellipsoid.js'; +import { + julianFromEpochMs, + julianLessThan, + julianLessThanOrEquals, + julianToEpochMs, + secondsDifference, +} from '../geo/julian.js'; +import { clone, distance } from '../geo/vector.js'; +import { curvePieceAt, fixCurveCached } from './fixCurve.js'; +import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js'; +import { + COAST_MAX_SPEED_MPS, + courseBetweenCartesians, + speedRamp, + STALE_COAST_MAX_SEC, + staleCoastLimitSeconds, + staleHoldsForFix, +} from './motionModel.js'; + +/** + * Which record fields carry an aircraft layer's reported ground speed (m/s) + * and track (degrees clockwise from north). + * @typedef {{speed: string, track: string}} AircraftRecordFields + */ + +/** A fix's own ground speed, else the record's; never over COAST_MAX_SPEED_MPS. */ +export function fixSpeedMps(fix, info, fields) { + return Math.min( + Number.isFinite(fix.velocity) + ? fix.velocity + : (info && info[fields.speed]) || 0, + COAST_MAX_SPEED_MPS, + ); +} + +/** A fix's own track, else the record's. */ +export function fixTrackDeg(fix, info, fields) { + return Number.isFinite(fix.track) + ? fix.track + : (info && info[fields.track]) || 0; +} + +/** + * The instant `epochMs` as a Julian date (into `result` when given), for + * `aircraftMotionRegime`'s `renderTime`. + */ +export function julianAt(epochMs, result) { + return julianFromEpochMs(epochMs, result); +} + +/** A history fix's time in epoch ms: its `epochMs`, else its `time`'s. */ +export function fixEpochMs(fix) { + return Number.isFinite(fix.epochMs) ? fix.epochMs : julianToEpochMs(fix.time); +} + +/** A feed fix's ECEF position, from its degrees and render altitude. */ +export function fixPosition(lonDeg, latDeg, heightM) { + return fromDegrees(lonDeg, latDeg, heightM); +} + +/** A copy of a fix position, for a trail that keeps it. */ +export function copyPosition(position) { + return clone(position); +} + +/** + * A position-history entry for a feed fix at `epochMs`, carrying the fix's + * own speed and track; it keeps a copy of `position`. + */ +export function historyFix(epochMs, position, velocity, track) { + return { + time: julianAt(epochMs), + epochMs, + position: clone(position), + velocity, + track, + }; +} + +/** + * Whether a history fix is a forward synthetic fix (a motion aid built from + * a repeated report's new speed or course, `synthesizeForwardKinematicsFix`) + * rather than a report. + */ +export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs); + +/** + * Put a new report at the end of a contact's history: forward synthetic + * fixes after the previous report go (the report supersedes them), and past + * `limit` the oldest fixes go. + * @param {Array} history Oldest first; mutated. + * @param {object} fix The report's history fix. + * @param {number} limit + */ +export function pushReport(history, fix, limit) { + while (history.length && isSyntheticFix(history[history.length - 1])) + history.pop(); + history.push(fix); + while (history.length > limit) history.shift(); +} + +/** The newest report in a history (not a synthetic fix), or undefined. */ +export function newestReport(history) { + for (let i = history.length - 1; i >= 0; i--) + if (!isSyntheticFix(history[i])) return history[i]; + return undefined; +} + +/** The curve a contact is drawn along between two history fixes, or null. */ +export function historyCurve(a, b) { + return fixCurveCached( + a.position, + fixEpochMs(a), + a.track, + b.position, + fixEpochMs(b), + b.track, + ); +} + +/** A reusable result for `aircraftMotionRegime`. */ +export function createMotionRegime() { + return { + kind: 'fix', + a: null, + b: null, + piece: null, + span: 0, + speed: 0, + trackFrom: 0, + trackTo: 0, + chordCourse: null, + blend: 0, + fix: null, + heading: 0, + turnRateDps: 0, + minDt: 0, + maxDt: 0, + unseen: false, + }; +} + +/** + * Which motion an aircraft's history gives at `renderTime` — the one choice + * the CPU dead reckoning and the icon planner (GPU segment) both draw from. + * + * - `between`: between the bracketing pair `a`→`b`, no extrapolation + * error and no snap-back. Along their curve (`data/fixCurve`) when the + * pair describes one: `piece` is the curve's piece at `renderTime`, a + * contract `arc` segment with its times. Otherwise straight from `a` to + * `b` (`piece` null), and the course of the DISPLAYED motion blends the + * time-interpolated reported track toward the chord by `blend`: the chord + * is only trustworthy when the segment covers real ground (at hover its + * direction is GPS jitter; on a slow tight turn it STEPS the whole + * per-segment turn at each boundary), and helicopters never use it + * (rotorcraft chords are noise-dominated at their typical speeds). + * - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt]. + * Warm-up (renderTime predates ALL history: freshly seen or just tracked, + * before a poll interval of history exists) runs the OLDEST fix BACKWARD, + * preserving the behind-real-time invariant, so as history fills the icon + * glides FORWARD into interpolation with no freeze and no backward snap + * (holding the oldest fix froze the icon; extrapolating the newest to + * wall-clock made it jump back a poll interval when interpolation took + * over). Otherwise the newest fix coasts on its last speed and heading for + * five minutes past it, then stops (SIGNAL LOST). A contact last heard on + * or near the ground holds there instead (`staleHoldsForFix`, decided once + * per report), and a chain of synthetic fixes never coasts further than + * the real report they were built from would. Following the clock, a + * warm-up well before a contact's own first fix is `unseen`: it was not + * there yet, and is not drawn (`historyUnseenAt`). + * + * @param {Array} history Non-empty, oldest first. + * @param {object|undefined} info The contact's record. + * @param {{dayNumber: number, secondsOfDay: number}} renderTime A Julian date (geo/julian). + * @param {AircraftRecordFields} fields + * @param {object} result From `createMotionRegime`; returned filled in. + * @param {{cachedGroundFloor?: (latDeg: number, lonDeg: number) => number|null}} [options] + * The ground under a report, where known, for the hold decision. + */ +export function aircraftMotionRegime( + history, + info, + renderTime, + fields, + result, + { cachedGroundFloor } = {}, +) { + // A synthetic fix a later report superseded is not on the path: the + // contact is drawn report to report, as its trail is. + let report = history.length - 1; + while (report >= 0 && isSyntheticFix(history[report])) report--; + // The pairs are read back from the fix after the first one at or after + // the render time (so a fix at exactly that time takes the later pair, as + // it always did; past any superseded synthetic fix there), found by + // halving, and stop at the first pair wholly before it: a contact + // following the clock keeps a long history. + let start = Math.min( + historyBracketIndex(history, renderTime) + 1, + history.length - 1, + ); + while (start < report && isSyntheticFix(history[start])) start++; + let b = null; + for (let i = start; i >= 0; i--) { + const a = history[i]; + if (i < report && isSyntheticFix(a)) continue; + const pairB = b; + b = a; + if (!pairB) continue; + if (julianLessThan(pairB.time, renderTime)) break; + if ( + !julianLessThanOrEquals(a.time, renderTime) || + !julianLessThanOrEquals(renderTime, pairB.time) + ) + continue; + const span = secondsDifference(pairB.time, a.time); + const chordLenM = distance(a.position, pairB.position); + const speed = + span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0; + const fallbackTrack = (info && info[fields.track]) || 0; + const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; + const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed); + const curve = span > 0 ? historyCurve(a, pairB) : null; + result.kind = 'between'; + result.a = a; + result.b = pairB; + result.piece = curve + ? curvePieceAt(curve, julianToEpochMs(renderTime)) + : null; + result.span = span; + result.speed = speed; + result.trackFrom = trackFrom; + result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom; + result.chordCourse = + blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null; + result.blend = blend; + result.unseen = false; + return result; + } + const newest = history[history.length - 1]; + const warming = julianLessThan(renderTime, history[0].time); + result.kind = 'fix'; + result.piece = null; + result.fix = warming ? history[0] : newest; + result.unseen = warming && historyUnseenAt(history, renderTime); + result.speed = fixSpeedMps(result.fix, info, fields); + result.heading = fixTrackDeg(result.fix, info, fields); + // Past the newest report it flies straight on along its course: a turn + // rate averaged over earlier reports outlives the turn it measured, and + // coasting on it put contacts kilometres off a straight path. + result.turnRateDps = 0; + result.minDt = -60; + // A warm-up ends when real time reaches the oldest fix; a single fix keeps + // coasting forward on the same line. + result.maxDt = + warming && history.length > 1 + ? 0 + : staleCoastSeconds(newest, info, cachedGroundFloor); + return result; +} + +/** + * How long `newest` coasts at most: five minutes, less what a synthetic + * fix's chain already coasted since its real report (`reportEpochMs`); none + * for a report that holds (judged once per report, from its ground flag and + * the ground under it where `cachedGroundFloor` knows it). + * @param {object} newest + * @param {object|undefined} info + * @param {Function} [cachedGroundFloor] + * @returns {number} + */ +export function staleCoastSeconds(newest, info, cachedGroundFloor) { + const newestMs = fixEpochMs(newest); + const limitSec = staleCoastLimitSeconds({ + fixEpochMs: newestMs, + lastContactEpochMs: info?.lastContactEpochMs, + // A plane that stops reporting keeps flying for five minutes, whatever + // its contact time, then stops dimmed as SIGNAL LOST. A missed update + // shows STALE throughout. + minimumSec: 300, + maximumSec: 300, + }); + if (staleHoldsForFix(newest, { onGround: info?.onGround, cachedGroundFloor })) + return 0; + const alreadySec = Number.isFinite(newest.reportEpochMs) + ? Math.max(0, (newestMs - newest.reportEpochMs) / 1000) + : 0; + return Math.max(0, Math.min(limitSec, STALE_COAST_MAX_SEC - alreadySec)); +} + +/** A raw position this far (m) off its own path, plus half its step, is a jump. */ +const RAW_JUMP_SLACK_M = 5; + +/** + * Whether a tracked aircraft's raw position jumped this frame: a new report + * moved its path. Judged against the path itself, where its last frame's + * step carries it, not against a reported speed (which can be stale or 0 + * while the drawn motion, minutes behind the newest report, is fast). A + * frame with no step to go by (the first on a track, or the one after a + * jump) is never a jump. + * @param {{x: number, y: number, z: number}} raw This frame's raw position. + * @param {{x: number, y: number, z: number}} prevRaw Last frame's. + * @param {{x: number, y: number, z: number}} prevRawStep Last frame's step. + * @param {number} prevRawStepSec Last frame's length, s (0: no step). + * @param {number} dtSec This frame's length, s. + * @returns {boolean} + */ +export function rawPositionJumped( + raw, + prevRaw, + prevRawStep, + prevRawStepSec, + dtSec, +) { + if (!(prevRawStepSec > 0)) return false; + const k = dtSec / prevRawStepSec; + const dx = raw.x - (prevRaw.x + prevRawStep.x * k); + const dy = raw.y - (prevRaw.y + prevRawStep.y * k); + const dz = raw.z - (prevRaw.z + prevRawStep.z * k); + const stepM = + Math.hypot(prevRawStep.x, prevRawStep.y, prevRawStep.z) * Math.abs(k); + return Math.hypot(dx, dy, dz) > RAW_JUMP_SLACK_M + 0.5 * stepM; +} + +/** + * How fast the drawn path moves (m/s), from its last raw step; `fallback` + * (a reported speed) with no step to go by. + * @param {{x: number, y: number, z: number}} step + * @param {number} stepSec + * @param {number} fallback + * @returns {number} + */ +export function rawStepSpeedMps(step, stepSec, fallback) { + if (!(stepSec > 0)) return fallback; + return Math.hypot(step.x, step.y, step.z) / stepSec; +} diff --git a/src/data/aircraftRecession.js b/src/data/aircraftRecession.js index 0cc012e68d..9a72c3877b 100644 --- a/src/data/aircraftRecession.js +++ b/src/data/aircraftRecession.js @@ -1,35 +1,33 @@ /** - * Limb-relative recession for distant aircraft billboards. + * Limb-relative recession for distant aircraft: the tuning the aircraft icon + * and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha + * those sets draw with, for evidence and checks. * - * This multiplies the billboard's ordinary scale, which Cesium then composes - * with the locked NearFarScalar. It never edits that scalar, culls a contact, - * or allows alpha to reach zero. + * It multiplies an icon's ordinary scale, which composes with its locked + * NearFarScalar. It never edits that scalar, culls a contact, or allows alpha + * to reach zero. The maths is the Cesium-free `render/recession.js`, + * which the sets drawing aircraft recede by (`SetSpec.recede`). */ +import { + RECEDE_DEFAULTS, + limbDistanceM, + recedeFactors, + recedeFrame, + recedeParams, + recededAlpha, +} from '../render/recession.js'; export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({ - startLimbRatio: 0.5, - scaleFloor: 0.45, - alphaFloor: 0.35, - combinedAlphaFloor: 0.2, - globeViewBlendStartM: 3_500_000, - globeViewBlendEndM: 4_500_000, - earthRadiusM: 6_378_137, + ...RECEDE_DEFAULTS, writeEpsilon: 0.005, }); let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS }; const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null }; -const _treatmentResult = { - scale: 1, - alpha: 1, - scaleWrites: 0, - alphaWrites: 0, - factors: _scratchFactors, -}; - -function clamp(value, min, max) { - return Math.min(max, Math.max(min, value)); -} +const _scratchFrame = { active: false, limbM: 1, strength: 0 }; +// The tuning `_recede` was made from, and the set option made from it. +let _recedeFor = null; +let _recede = null; function resolvedParams(overrides) { if (!overrides || overrides === _params) return _params; @@ -42,47 +40,12 @@ function aircraftRecessionFactorsResolved( tuning, result, ) { - if ( - !Number.isFinite(cameraDistanceM) || - cameraDistanceM < 0 || - !Number.isFinite(cameraHeightM) || - cameraHeightM <= 0 || - cameraHeightM >= tuning.globeViewBlendEndM - ) { - result.scale = 1; - result.alpha = 1; - result.limbRatio = null; - return result; - } - const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM); - if (!Number.isFinite(limbDistance) || limbDistance <= 0) { - result.scale = 1; - result.alpha = 1; - result.limbRatio = null; - return result; - } - const limbRatio = cameraDistanceM / limbDistance; - if (limbRatio <= tuning.startLimbRatio) { - result.scale = 1; - result.alpha = 1; - result.limbRatio = limbRatio; - return result; - } - - const rawT = - (limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio); - const t = clamp(rawT, 0, 1); - const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges - const globeRawT = - (cameraHeightM - tuning.globeViewBlendStartM) / - (tuning.globeViewBlendEndM - tuning.globeViewBlendStartM); - const globeT = clamp(globeRawT, 0, 1); - const globeEase = globeT * globeT * (3 - 2 * globeT); - const strength = 1 - globeEase; - result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength; - result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength; - result.limbRatio = limbRatio; - return result; + return recedeFactors( + cameraDistanceM, + recedeFrame(cameraHeightM, tuning, _scratchFrame), + tuning, + result, + ); } /** @@ -91,45 +54,34 @@ function aircraftRecessionFactorsResolved( * @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} */ export function setAircraftRecessionParams(patch = {}) { - const next = { ..._params }; - if (Number.isFinite(patch.startLimbRatio)) { - next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99); - } - if (Number.isFinite(patch.scaleFloor)) - next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1); - if (Number.isFinite(patch.alphaFloor)) - next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1); - if (Number.isFinite(patch.combinedAlphaFloor)) { - next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1); - } - if (Number.isFinite(patch.globeViewBlendStartM)) { - next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM); - } - if (Number.isFinite(patch.globeViewBlendEndM)) { - next.globeViewBlendEndM = Math.max( - next.globeViewBlendStartM + 1, - patch.globeViewBlendEndM, - ); - } // Backward-compatible evidence override: the former hard threshold now // names the identity end of the blend band. - if (Number.isFinite(patch.globeViewHeightM)) { - next.globeViewBlendEndM = Math.max( - next.globeViewBlendStartM + 1, - patch.globeViewHeightM, - ); - } - if (next.globeViewBlendStartM >= next.globeViewBlendEndM) { - next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1); - } - if (Number.isFinite(patch.earthRadiusM)) - next.earthRadiusM = Math.max(1, patch.earthRadiusM); + const given = Number.isFinite(patch.globeViewHeightM) + ? { ...patch, globeViewBlendEndM: patch.globeViewHeightM } + : patch; + const next = { + ...recedeParams(given, _params), + writeEpsilon: _params.writeEpsilon, + }; if (Number.isFinite(patch.writeEpsilon)) next.writeEpsilon = Math.max(0, patch.writeEpsilon); _params = next; return { ..._params }; } +/** + * The tuning as the `recede` of the sets that draw aircraft: the same + * object until the tuning changes. + * @returns {import('../render/contract/index').RecedeSpec} + */ +export function aircraftRecedeSpec() { + if (_recedeFor !== _params) { + _recedeFor = _params; + _recede = Object.freeze(recedeParams(_params)); + } + return _recede; +} + /** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */ export function getAircraftRecessionParams() { return _params; @@ -148,13 +100,7 @@ export function resetAircraftRecessionParams() { * @param {number} [earthRadiusM] * @returns {number} */ -export function cameraLimbDistanceM( - cameraHeightM, - earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM, -) { - if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN; - return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM)); -} +export const cameraLimbDistanceM = limbDistanceM; /** * Pure recession factors for one aircraft. @@ -178,28 +124,18 @@ export function aircraftRecessionFactors( } /** - * Production wire helper: compose base scale/alpha, focus emphasis, and limb - * recession into one deadband-gated billboard write site. + * The alpha an aircraft draws with: base × max(combined floor, focus × limb + * haze). Icon sets compose the same thing in their shader; models need it here. * @param {object} input - * @param {object} input.billboard - * @param {number} input.baseScale * @param {number} input.baseAlpha - * @param {{withAlpha:(alpha:number)=>object}} input.baseColor * @param {number} input.focusFactor * @param {number} input.cameraDistanceM * @param {number} input.cameraHeightM * @param {Partial} [input.params] - * - * IMPORTANT: the returned object (including `factors`) is a module-owned - * mutable singleton. Consume every needed property before the next call; - * never retain it as a snapshot. - * @returns {{scale:number,alpha:number,scaleWrites:number,alphaWrites:number,factors:object}} + * @returns {number} */ -export function applyAircraftBillboardTreatment({ - billboard, - baseScale, +export function aircraftTreatmentAlpha({ baseAlpha, - baseColor, focusFactor, cameraDistanceM, cameraHeightM, @@ -212,33 +148,7 @@ export function applyAircraftBillboardTreatment({ tuning, _scratchFactors, ); - const scale = baseScale * factors.scale; - const composedTreatment = Math.max( - tuning.combinedAlphaFloor, - clamp(focusFactor, 0, 1) * factors.alpha, - ); - const alpha = baseAlpha * composedTreatment; - let scaleWrites = 0; - let alphaWrites = 0; - if ( - !Number.isFinite(billboard.scale) || - Math.abs(billboard.scale - scale) > tuning.writeEpsilon - ) { - billboard.scale = scale; - scaleWrites = 1; - } - if ( - !Number.isFinite(billboard.color?.alpha) || - Math.abs(billboard.color.alpha - alpha) > tuning.writeEpsilon - ) { - billboard.color = baseColor.withAlpha(alpha); - alphaWrites = 1; - } - _treatmentResult.scale = scale; - _treatmentResult.alpha = alpha; - _treatmentResult.scaleWrites = scaleWrites; - _treatmentResult.alphaWrites = alphaWrites; - return _treatmentResult; + return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning); } /** diff --git a/src/data/aircraftRecession.test.mjs b/src/data/aircraftRecession.test.mjs index 23b8ceffb0..bd45c32cf2 100644 --- a/src/data/aircraftRecession.test.mjs +++ b/src/data/aircraftRecession.test.mjs @@ -3,9 +3,9 @@ import assert from 'node:assert/strict'; import { DEFAULT_AIRCRAFT_RECESSION_PARAMS, aircraftRecessionFactors, - applyAircraftBillboardTreatment, applyAircraftModelTreatment, cameraLimbDistanceM, + aircraftTreatmentAlpha, } from './aircraftRecession.js'; const params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS }; @@ -66,72 +66,15 @@ test('globe-view transition eases to identity without a threshold pop', () => { assert.deepEqual(end, { scale: 1, alpha: 1, limbRatio: null }); }); -test('aircraft billboard wire writes scale and alpha only for the far treatment', () => { - const color = { withAlpha: (alpha) => ({ alpha }) }; - const near = { scale: 1.2, color: { alpha: 0.8 } }; - const nearResult = applyAircraftBillboardTreatment({ - billboard: near, - baseScale: 1.2, - baseAlpha: 0.8, - baseColor: color, - focusFactor: 1, - cameraDistanceM: limb * 0.4, - cameraHeightM, - params, - }); - assert.equal(nearResult.scaleWrites, 0); - assert.equal(nearResult.alphaWrites, 0); - - const far = { scale: 1.2, color: { alpha: 0.8 } }; - const farResult = applyAircraftBillboardTreatment({ - billboard: far, - baseScale: 1.2, - baseAlpha: 0.8, - baseColor: color, - focusFactor: 0.5, - cameraDistanceM: limb, - cameraHeightM, - params, - }); - assert.equal(farResult.scaleWrites, 1); - assert.equal(farResult.alphaWrites, 1); - assert.ok(Math.abs(far.scale - (1.2 * 0.45)) < 1e-12); - assert.ok(Math.abs(far.color.alpha - (0.8 * 0.20)) < 1e-12); -}); - test('combined focus and haze product is clamped at the composed alpha floor', () => { - const color = { withAlpha: (alpha) => ({ alpha }) }; - const billboard = { scale: 0.45, color: { alpha: 1 } }; - const result = applyAircraftBillboardTreatment({ - billboard, - baseScale: 1, + const alpha = aircraftTreatmentAlpha({ baseAlpha: 1, - baseColor: color, focusFactor: 0.25, cameraDistanceM: limb, cameraHeightM, params, }); - assert.equal(result.alpha, 0.20); - assert.equal(billboard.color.alpha, 0.20); -}); - -test('applyAircraftBillboardTreatment returns its documented module singleton', () => { - const color = { withAlpha: (alpha) => ({ alpha }) }; - const billboard = { scale: 1, color: { alpha: 1 } }; - const input = { - billboard, - baseAlpha: 1, - baseColor: color, - focusFactor: 1, - cameraDistanceM: 0, - cameraHeightM, - params, - }; - const first = applyAircraftBillboardTreatment({ ...input, baseScale: 1 }); - const second = applyAircraftBillboardTreatment({ ...input, baseScale: 0.5 }); - assert.strictEqual(first, second); - assert.equal(first.scale, 0.5, 'the prior reference reflects the next call'); + assert.equal(alpha, 0.2); }); test('ambient model presentation receives composed alpha without changing blend semantics', () => { @@ -154,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes' assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1); assert.equal(model.color.green,1); }); + +test('the aircraft sets recede by the tuning: one object until it changes', async () => { + const { + aircraftRecedeSpec, + setAircraftRecessionParams, + resetAircraftRecessionParams, + } = await import('./aircraftRecession.js'); + const { RECEDE_DEFAULTS } = await import('../render/recession.js'); + resetAircraftRecessionParams(); + const first = aircraftRecedeSpec(); + assert.deepEqual(first, { ...RECEDE_DEFAULTS }); + assert.equal(aircraftRecedeSpec(), first); + setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 }); + const tuned = aircraftRecedeSpec(); + assert.notEqual(tuned, first); + assert.equal(tuned.scaleFloor, 0.6); + assert.equal(tuned.globeViewBlendEndM, 4_000_000); + assert.equal('writeEpsilon' in tuned, false); + resetAircraftRecessionParams(); + assert.deepEqual(aircraftRecedeSpec(), first); +}); diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 6608eb0556..1b091ec4f7 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -34,14 +34,21 @@ import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js'; import { ensureGeoidReady, geoidHeight } from './geoid.js'; import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js'; import { applyVesselOverlayPolicy } from './vesselLabels.js'; +import { fakeInput } from '../input/testDoubles.mjs'; import { layerFeedState } from './manager.js'; import { presentSelectedVessel, subscribeSelectedVessel, } from '../hudReadouts.js'; +import { createVesselIconBook } from '../layers/vessels/iconBook.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { entityFollowTarget } from '../data/followed.js'; test('open feed with vessels is healthy (null)', () => { - assert.equal(deriveAisFeedError({ status: 'open', lastMessageAt: 1, error: null }, 42), null); + assert.equal( + deriveAisFeedError({ status: 'open', lastMessageAt: 1, error: null }, 42), + null, + ); }); test('open feed without a received message is not a fresh healthy update', () => { @@ -73,7 +80,10 @@ test('snapshot classification distinguishes raw rows from accepted vessel positi assert.equal(snapshot.lastMessageAt, 123); assert.equal(snapshot.rawRowCount, 3); assert.equal(snapshot.acceptedRowCount, 1); - assert.deepEqual(snapshot.acceptedRows.map((row) => row.mmsi), ['valid']); + assert.deepEqual( + snapshot.acceptedRows.map((row) => row.mmsi), + ['valid'], + ); assert.equal(snapshot.error, null); }); @@ -100,27 +110,45 @@ test('accepted cached rows remain usable while transport reconnects', () => { test('missing key with no rows surfaces a clean reason', () => { assert.equal( - deriveAisFeedError({ status: 'missing-key', error: 'AISSTREAM_API_KEY is not set' }, 0), + deriveAisFeedError( + { status: 'missing-key', error: 'AISSTREAM_API_KEY is not set' }, + 0, + ), 'AISSTREAM_API_KEY not set', ); }); test('socket error with no rows surfaces "feed down"', () => { - assert.equal(deriveAisFeedError({ status: 'error', error: 'AISStream websocket error' }, 0), 'feed down'); + assert.equal( + deriveAisFeedError( + { status: 'error', error: 'AISStream websocket error' }, + 0, + ), + 'feed down', + ); }); test('closed feed with no rows surfaces "feed disconnected"', () => { - assert.equal(deriveAisFeedError({ status: 'closed', error: null }, 0), 'feed disconnected'); + assert.equal( + deriveAisFeedError({ status: 'closed', error: null }, 0), + 'feed disconnected', + ); }); test('non-open status but rows still flowing is treated as stale, not down (null)', () => { // e.g. reconnecting/refreshing while a cached buffer still serves rows. - assert.equal(deriveAisFeedError({ status: 'connecting', error: null }, 30), null); + assert.equal( + deriveAisFeedError({ status: 'connecting', error: null }, 30), + null, + ); }); test('unknown status falls back to a generic reason and appends server detail', () => { assert.equal( - deriveAisFeedError({ status: 'weird-state', error: 'something specific' }, 0), + deriveAisFeedError( + { status: 'weird-state', error: 'something specific' }, + 0, + ), 'feed unavailable (something specific)', ); }); @@ -135,7 +163,10 @@ test('missing status treated as healthy (older/other payload shapes) (null)', () // degraded feed must stay visible even while cached vessels are still drawn. test("'live' is the healthy status and reads exactly like the older 'open'", () => { - assert.equal(deriveAisFeedError({ status: 'live', lastMessageAt: 1, error: null }, 42), null); + assert.equal( + deriveAisFeedError({ status: 'live', lastMessageAt: 1, error: null }, 42), + null, + ); assert.equal( deriveAisFeedError({ status: 'live', lastMessageAt: null, error: null }, 0), 'awaiting first AIS message…', @@ -148,7 +179,10 @@ test("'live' is the healthy status and reads exactly like the older 'open'", () test('a stale feed is surfaced even though cached vessels are still on screen', () => { assert.equal( - deriveAisFeedError({ status: 'stale', silentForMs: 184_000, lastMessageAt: 5 }, 4_812), + deriveAisFeedError( + { status: 'stale', silentForMs: 184_000, lastMessageAt: 5 }, + 4_812, + ), 'feed silent 184s — no AIS data', ); }); @@ -165,7 +199,10 @@ test('reconnecting reports which attempt is in flight, rows or no rows', () => { deriveAisFeedError({ status: 'reconnecting', reconnectAttempt: 2 }, 900), 'reconnecting to feed… (attempt 2)', ); - assert.equal(deriveAisFeedError({ status: 'reconnecting' }, 0), 'reconnecting to feed…'); + assert.equal( + deriveAisFeedError({ status: 'reconnecting' }, 0), + 'reconnecting to feed…', + ); }); test('DOWN is a visible terminal state, not a silent retry', () => { @@ -184,15 +221,19 @@ test('a rejected API key reads as actionable, not as a countdown', () => { const runtime = makeFakeAisRuntime(1_000_000); _setAisRuntimeForTest(runtime.runtime); try { - _applyAisFeedSnapshotForTest({}, { - status: 'auth-failed', - reconnectAttempt: 3, - nextAttemptAt: 1_000_000 + 3_600_000, - refreshing: true, - rows: [], - }); + _applyAisFeedSnapshotForTest( + {}, + { + status: 'auth-failed', + reconnectAttempt: 3, + nextAttemptAt: 1_000_000 + 3_600_000, + refreshing: true, + rows: [], + }, + ); assert.equal( - aisLiveVesselsLayer.getStats().retryInSec, 0, + aisLiveVesselsLayer.getStats().retryInSec, + 0, 'an hour-long countdown would imply waiting is the fix', ); } finally { @@ -204,17 +245,23 @@ test('a degraded feed reports its retry countdown to the chip', () => { const runtime = makeFakeAisRuntime(1_000_000); _setAisRuntimeForTest(runtime.runtime); try { - _applyAisFeedSnapshotForTest({}, { - status: 'reconnecting', - reconnectAttempt: 3, - nextAttemptAt: 1_060_000, // 60s past the fake clock - refreshing: true, - rows: [], - }); + _applyAisFeedSnapshotForTest( + {}, + { + status: 'reconnecting', + reconnectAttempt: 3, + nextAttemptAt: 1_060_000, // 60s past the fake clock + refreshing: true, + rows: [], + }, + ); assert.equal(aisLiveVesselsLayer.getStats().retryInSec, 60); // A feed with nothing scheduled must not invent a countdown. - _applyAisFeedSnapshotForTest({}, { status: 'live', lastMessageAt: 5, rows: [] }); + _applyAisFeedSnapshotForTest( + {}, + { status: 'live', lastMessageAt: 5, rows: [] }, + ); assert.equal(aisLiveVesselsLayer.getStats().retryInSec, 0); } finally { _setAisRuntimeForTest(null); @@ -228,7 +275,11 @@ test('a degraded feed keeps its reason through snapshot classification', () => { refreshing: true, rows: [{ mmsi: 'cached', lat: 29.7, lon: -95.1 }], }); - assert.equal(snapshot.acceptedRowCount, 1, 'the cached vessel is still drawable'); + assert.equal( + snapshot.acceptedRowCount, + 1, + 'the cached vessel is still drawable', + ); assert.equal(snapshot.error, 'feed down — retrying slowly (attempt 5)'); }); @@ -256,7 +307,9 @@ function makeFakeAisRuntime(startMs = 1000) { return { runtime, scheduled, - get nowMs() { return nowMs; }, + get nowMs() { + return nowMs; + }, advance(deltaMs) { nowMs += deltaMs; let fired; @@ -295,11 +348,14 @@ test('zero accepted rows preserve warm vessel selection, trail, and freshness ti lastMessageAt: 123, }); try { - const result = _applyAisFeedSnapshotForTest({}, { - status: 'open', - lastMessageAt: 789, - rows: [{ mmsi: 'invalid', lat: 'bad', lon: 4 }], - }); + const result = _applyAisFeedSnapshotForTest( + {}, + { + status: 'open', + lastMessageAt: 789, + rows: [{ mmsi: 'invalid', lat: 'bad', lon: 4 }], + }, + ); assert.equal(result.reconciled, false); assert.deepEqual(_getVesselFeedStateForTest(), { count: 1, @@ -334,11 +390,14 @@ test('open first load stays LOADING for one bounded first-connect grace period', _setVesselStateForTest({ viewer: {}, records: [] }); try { _beginAisSessionForTest(); - const result = _applyAisFeedSnapshotForTest({}, { - status: 'open', - lastMessageAt: null, - rows: [], - }); + const result = _applyAisFeedSnapshotForTest( + {}, + { + status: 'open', + lastMessageAt: null, + rows: [], + }, + ); assert.equal(result.reconciled, false); const feed = _getVesselFeedStateForTest(); assert.equal(feed.loaded, true); @@ -382,9 +441,15 @@ test('open and connecting polls do not restart the first-connect deadline', () = const initial = _getVesselFeedStateForTest(); clock.advance(12000); _applyAisFeedSnapshotForTest({}, { status: 'connecting', rows: [] }); - _applyAisFeedSnapshotForTest({}, { status: 'open', lastMessageAt: 9, rows: [] }); + _applyAisFeedSnapshotForTest( + {}, + { status: 'open', lastMessageAt: 9, rows: [] }, + ); const afterPolls = _getVesselFeedStateForTest(); - assert.equal(afterPolls.firstConnectStartedAt, initial.firstConnectStartedAt); + assert.equal( + afterPolls.firstConnectStartedAt, + initial.firstConnectStartedAt, + ); assert.equal(afterPolls.firstConnectDeadline, initial.firstConnectDeadline); assert.equal(clock.activeCount(), 1); assert.equal(afterPolls.loading, true); @@ -401,11 +466,14 @@ test('definitive AIS transport failures end grace immediately', () => { _setVesselStateForTest({ viewer: {}, records: [] }); try { _beginAisSessionForTest(); - _applyAisFeedSnapshotForTest({}, { - status: 'missing-key', - error: 'AISSTREAM_API_KEY is not set', - rows: [], - }); + _applyAisFeedSnapshotForTest( + {}, + { + status: 'missing-key', + error: 'AISSTREAM_API_KEY is not set', + rows: [], + }, + ); const feed = _getVesselFeedStateForTest(); assert.equal(feed.loading, false); assert.equal(feed.status, 'unavailable'); @@ -430,16 +498,21 @@ test('first accepted position ends grace and warm data survives later open silen _setVesselStateForTest({ viewer: {}, records: [record] }); try { _beginAisSessionForTest(); - const accepted = _applyAisFeedSnapshotForTest({}, { - status: 'open', - lastMessageAt: 12, - rows: [{ - mmsi: record.mmsi, - name: record.name, - lat: 51.93, - lon: 4.05, - }], - }); + const accepted = _applyAisFeedSnapshotForTest( + {}, + { + status: 'open', + lastMessageAt: 12, + rows: [ + { + mmsi: record.mmsi, + name: record.name, + lat: 51.93, + lon: 4.05, + }, + ], + }, + ); assert.equal(accepted.reconciled, true); let feed = _getVesselFeedStateForTest(); assert.equal(feed.loading, false); @@ -449,11 +522,14 @@ test('first accepted position ends grace and warm data survives later open silen assert.equal(clock.activeCount(), 0); clock.advance(5000); - const silent = _applyAisFeedSnapshotForTest({}, { - status: 'open', - lastMessageAt: 13, - rows: [], - }); + const silent = _applyAisFeedSnapshotForTest( + {}, + { + status: 'open', + lastMessageAt: 13, + rows: [], + }, + ); assert.equal(silent.reconciled, false); feed = _getVesselFeedStateForTest(); assert.equal(feed.count, 1); @@ -488,7 +564,10 @@ test('superseded first-connect timer cannot expire its replacement session', () const afterStaleTimer = _getVesselFeedStateForTest(); assert.equal(afterStaleTimer.sessionId, replacement.sessionId); assert.equal(afterStaleTimer.firstConnectPhase, 'loading'); - assert.equal(afterStaleTimer.firstConnectDeadline, replacement.firstConnectDeadline); + assert.equal( + afterStaleTimer.firstConnectDeadline, + replacement.firstConnectDeadline, + ); assert.equal(afterStaleTimer.error, null); } finally { _setVesselStateForTest({ enabled: false }); @@ -498,7 +577,9 @@ test('superseded first-connect timer cannot expire its replacement session', () function deferredFetchResponse() { let resolve; - const promise = new Promise((next) => { resolve = next; }); + const promise = new Promise((next) => { + resolve = next; + }); return { promise, resolve }; } @@ -556,7 +637,12 @@ test('superseded AIS response cannot mutate or finalize a replacement request', const replacement = makeRecord({ name: 'REPLACEMENT' }); const replacementTrail = makeTrailSpy(); try { - _setVesselStateForTest({ viewer: {}, records: [oldRecord], loaded: true, lastUpdate: 100 }); + _setVesselStateForTest({ + viewer: {}, + records: [oldRecord], + loaded: true, + lastUpdate: 100, + }); const oldLoad = _loadLivePositionsForTest({}); // Simulate destroy/re-init replacement. The old fetch intentionally ignores abort. @@ -572,18 +658,24 @@ test('superseded AIS response cannot mutate or finalize a replacement request', }); const replacementLoad = _loadLivePositionsForTest({}); - first.resolve(jsonResponse({ - status: 'open', - lastMessageAt: 1000, - rows: [{ mmsi: oldRecord.mmsi, name: 'STALE RESPONSE', lat: 1, lon: 2 }], - })); + first.resolve( + jsonResponse({ + status: 'open', + lastMessageAt: 1000, + rows: [ + { mmsi: oldRecord.mmsi, name: 'STALE RESPONSE', lat: 1, lon: 2 }, + ], + }), + ); await oldLoad; let feed = _getVesselFeedStateForTest(); assert.equal(feed.loading, true, 'old finally must not clear replacement loading ownership'); assert.equal(feed.lastUpdate, 200, 'old response must not advance replacement freshness'); assert.equal(feed.selectedId, replacement.mmsi); - second.resolve(jsonResponse({ status: 'open', lastMessageAt: null, rows: [] })); + second.resolve( + jsonResponse({ status: 'open', lastMessageAt: null, rows: [] }), + ); await replacementLoad; feed = _getVesselFeedStateForTest(); assert.equal(feed.loading, false); @@ -615,14 +707,21 @@ test('disable and destroy make abort-ignoring AIS responses inert', async () => const disableResponse = deferredFetchResponse(); globalThis.fetch = () => disableResponse.promise; const record = makeRecord(); - _setVesselStateForTest({ viewer: {}, records: [record], loaded: true, lastUpdate: 300 }); + _setVesselStateForTest({ + viewer: {}, + records: [record], + loaded: true, + lastUpdate: 300, + }); const disabledLoad = _loadLivePositionsForTest({}); aisLiveVesselsLayer.disable(); - disableResponse.resolve(jsonResponse({ - status: 'open', - lastMessageAt: 1000, - rows: [{ mmsi: record.mmsi, lat: 1, lon: 2 }], - })); + disableResponse.resolve( + jsonResponse({ + status: 'open', + lastMessageAt: 1000, + rows: [{ mmsi: record.mmsi, lat: 1, lon: 2 }], + }), + ); await disabledLoad; let feed = _getVesselFeedStateForTest(); assert.equal(feed.lastUpdate, 300); @@ -631,14 +730,21 @@ test('disable and destroy make abort-ignoring AIS responses inert', async () => const destroyResponse = deferredFetchResponse(); globalThis.fetch = () => destroyResponse.promise; const viewer = { scene: { primitives: { remove() {} } } }; - _setVesselStateForTest({ viewer, records: [record], loaded: true, lastUpdate: 400 }); + _setVesselStateForTest({ + viewer, + records: [record], + loaded: true, + lastUpdate: 400, + }); const destroyedLoad = _loadLivePositionsForTest(viewer); aisLiveVesselsLayer.destroy(viewer); - destroyResponse.resolve(jsonResponse({ - status: 'open', - lastMessageAt: 2000, - rows: [{ mmsi: record.mmsi, lat: 3, lon: 4 }], - })); + destroyResponse.resolve( + jsonResponse({ + status: 'open', + lastMessageAt: 2000, + rows: [{ mmsi: record.mmsi, lat: 3, lon: 4 }], + }), + ); await destroyedLoad; feed = _getVesselFeedStateForTest(); assert.equal(feed.count, 0); @@ -655,17 +761,30 @@ test('disable and destroy make abort-ignoring AIS responses inert', async () => } }); +/** One vessel row in a fresh set, as the layer adds it, plus its record. */ +function focusFixture() { + const icons = createVesselIconBook(); + icons.put({ + id: '353136000', + size: [32, 32], + meta: { layer: 'ais-live-vessels', id: '353136000' }, + }); + const record = { + iconId: '353136000', + position: { x: 1, y: 2, z: 3 }, + visible: true, + }; + return { + icons, + records: [record], + record, + focus: () => icons.focus('353136000'), + }; +} + test('vessel focus wire animates alpha with deadband and restores after tracking ends', () => { let writes = 0; - const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); - let color = makeColor(1); - const billboard = { - position: { x: 1, y: 2, z: 3 }, - show: true, - get color() { return color; }, - set color(next) { writes += 1; color = next; }, - }; - const records = [{ position: billboard.position, billboard }]; + const { icons, records, focus } = focusFixture(); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, paddingPx: 0, @@ -685,6 +804,7 @@ test('vessel focus wire animates alpha with deadband and restores after tracking const apply = (nowMs, focusTarget) => { const result = applyVesselFocusDeemphasis({ records, + icons, target: focusTarget, previousActiveCount: activeCount, nowMs, @@ -693,34 +813,42 @@ test('vessel focus wire animates alpha with deadband and restores after tracking params, }); activeCount = result.activeCount; + writes += result.writes; return result; }; assert.equal(apply(0, target).writes, 0); assert.equal(apply(150, target).writes, 1); - assert.ok(color.alpha > 0.25 && color.alpha < 1); - assert.equal(apply(150, target).writes, 0, 'same timestamp stays inside deadband'); + assert.ok(focus() > 0.25 && focus() < 1); + assert.equal( + apply(150, target).writes, + 0, + 'same timestamp stays inside deadband', + ); assert.equal(apply(300, target).writes, 1); - assert.equal(color.alpha, 0.25); - assert.equal(apply(300, null).writes, 0, 'release starts continuously from the floor'); + assert.equal(focus(), 0.25); + assert.equal( + apply(300, null).writes, + 0, + 'release starts continuously from the floor', + ); assert.equal(apply(600, null).writes, 1); - assert.ok(color.alpha > 0.25 && color.alpha < 1); + assert.ok(focus() > 0.25 && focus() < 1); assert.equal(apply(900, null).writes, 1); - assert.equal(color.alpha, 1); - assert.equal(apply(901, null).writes, 0, 'settled restoration causes no churn'); + assert.equal(focus(), 1); + assert.equal( + apply(901, null).writes, + 0, + 'settled restoration causes no churn', + ); assert.equal(writes, 4); }); test('vessel focus wire performs no alpha writes when nothing has been tracked', () => { - let writes = 0; - const billboard = { - position: { x: 0, y: 0, z: 0 }, - show: true, - get color() { return { alpha: 1 }; }, - set color(_next) { writes += 1; }, - }; + const { icons, records, focus } = focusFixture(); const result = applyVesselFocusDeemphasis({ - records: [{ position: billboard.position, billboard }], + records, + icons, target: null, nowMs: 100, screenPositionFor: () => ({ x: 50, y: 50 }), @@ -732,17 +860,11 @@ test('vessel focus wire performs no alpha writes when nothing has been tracked', activeCount: 0, ran: false, }); - assert.equal(writes, 0); + assert.equal(focus(), 1); }); test('vessel focus wire restores a hidden sprite before releasing the active pass', () => { - const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); - const billboard = { - position: { x: 1, y: 2, z: 3 }, - show: true, - color: makeColor(1), - }; - const records = [{ billboard }]; + const { icons, records, record, focus } = focusFixture(); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, paddingPx: 0, @@ -756,28 +878,34 @@ test('vessel focus wire restores a hidden sprite before releasing the active pas releaseMs: 600, writeEpsilon: 0.005, }; - const pass = (nowMs, focusTarget, previousActiveCount) => applyVesselFocusDeemphasis({ - records, - target: focusTarget, - previousActiveCount, - nowMs, - screenPositionFor: () => ({ x: 50, y: 50 }), - cameraDistanceFor: () => 1200, - params, - }); + const pass = (nowMs, focusTarget, previousActiveCount) => + applyVesselFocusDeemphasis({ + records, + icons, + target: focusTarget, + previousActiveCount, + nowMs, + screenPositionFor: () => ({ x: 50, y: 50 }), + cameraDistanceFor: () => 1200, + params, + }); pass(0, target, 0); const dimmed = pass(params.attackMs, target, 0); assert.equal(dimmed.activeCount, 1); - assert.equal(billboard.color.alpha, params.dimFloor); + assert.equal(focus(), params.dimFloor); - billboard.show = false; + record.visible = false; const releaseStart = pass(params.attackMs, null, dimmed.activeCount); - const restored = pass(params.attackMs + params.releaseMs, null, releaseStart.activeCount); + const restored = pass( + params.attackMs + params.releaseMs, + null, + releaseStart.activeCount, + ); assert.equal(restored.ran, true); assert.equal(restored.activeCount, 0); assert.equal(restored.writes, 1); - assert.equal(billboard.color.alpha, 1); + assert.equal(focus(), 1); }); // --- Selection gestures (FB-1) --------------------------------------------- @@ -801,10 +929,9 @@ test('vessel selection: Escape deselects only when this layer owns a selection', reduceVesselSelection({ selectedId: 353136000, gesture: 'escape' }), { action: 'deselect' }, ); - assert.deepEqual( - reduceVesselSelection({ gesture: 'escape' }), - { action: 'none' }, - ); + assert.deepEqual(reduceVesselSelection({ gesture: 'escape' }), { + action: 'none', + }); }); test('vessel selection: another vessel replaces selection; same vessel is a no-op', () => { @@ -847,7 +974,6 @@ function makeRecord(overrides = {}) { lastPositionUtc: '', missedRefreshes: 0, position: POS, - billboard: null, ...overrides, }; if (!Object.hasOwn(overrides, 'id')) record.id = record.mmsi; @@ -857,24 +983,14 @@ function makeRecord(overrides = {}) { function makeTrailSpy() { return { clearCalls: 0, - clear() { this.clearCalls += 1; }, + clear() { + this.clearCalls += 1; + }, setPositions() {}, destroy() {}, }; } -function makeInteractionHandler() { - return { - click: null, - destroyCalls: 0, - setInputAction(callback) { this.click = callback; }, - destroy() { - this.destroyCalls += 1; - this.click = null; - }, - }; -} - function makeCesiumEvent() { const listeners = new Set(); return { @@ -890,7 +1006,9 @@ function makeCesiumEvent() { raise() { for (const callback of [...listeners]) callback(); }, - get listenerCount() { return listeners.size; }, + get listenerCount() { + return listeners.size; + }, }; } @@ -915,21 +1033,36 @@ function installWireHarness(picked, stateOverrides = {}) { this.removed.push({ type, callback }); if (this.keydown === callback) this.keydown = null; }, - dispatch(event) { this.keydown?.(event); }, + dispatch(event) { + this.keydown?.(event); + }, }; - const handler = makeInteractionHandler(); - const reinstalledHandlers = []; - const interactionHandlerFactory = () => { - const next = makeInteractionHandler(); - reinstalledHandlers.push(next); - return next; - }; - const trackedEntityChanged = makeCesiumEvent(); const viewer = { scene: { pick: () => picked }, - trackedEntity: undefined, - trackedEntityChanged, }; + const input = fakeInput(viewer); + // The camera port other layers follow through, with no pose to read; its + // followChanged event counts who listens. + const followChanged = makeCesiumEvent(); + const camera = { + pose: () => null, + followed: null, + follow(target) { + this.followed = target; + followChanged.raise(); + }, + on: (name, callback) => + name === 'followChanged' + ? followChanged.addEventListener(callback) + : () => {}, + }; + const unbindRenderer = bindRenderer(viewer, { + camera, + get canvas() { + return viewer.scene?.canvas; + }, + }); + const handler = { click: (event) => input.click(event.position) }; const record = makeRecord(); const trail = makeTrailSpy(); presentSelectedVessel({ text: `AIS: ${record.name}` }); @@ -953,11 +1086,10 @@ function installWireHarness(picked, stateOverrides = {}) { trail, trailId: record.mmsi, trailPositions: [POS], - interactionHandlerFactory, interactionKeyTarget: keyTarget, ...stateOverrides, }); - _bindVesselInteractionForTest(viewer, handler, keyTarget); + _bindVesselInteractionForTest(viewer, keyTarget); return { handler, @@ -966,12 +1098,14 @@ function installWireHarness(picked, stateOverrides = {}) { trail, hud, viewer, + camera, + followChanged, windowTarget, - reinstalledHandlers, - interactionHandlerFactory, + input: input.input, cleanup() { stopReadout(); aisLiveVesselsLayer.destroy(); + unbindRenderer(); if (hadWindow) globalThis.window = priorWindow; else delete globalThis.window; if (hadDocument) globalThis.document = priorDocument; @@ -984,7 +1118,10 @@ test('vessel interaction wire: trail pick does not deselect', () => { const harness = installWireHarness({ id: 'gev-trail:71' }); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); assert.equal(_getVesselStateForTest().trailId, harness.record.mmsi); } finally { @@ -1024,7 +1161,10 @@ test('vessel interaction wire: flights-owned pick preserves vessel selection', ( const harness = installWireHarness({ id: 'a1b2c3' }); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); } finally { harness.cleanup(); @@ -1044,13 +1184,19 @@ test('vessel touch interaction yields to the first nearby flight behind map tile let drills = 0; harness.viewer.scene.drillPick = (_position, limit, width, height) => { drills++; - assert.deepEqual([limit, width, height], [8, 14, 14]); - return [tile, { id: 'a1b2c3' }]; + // The click's shared drill: the 14 px touch window, at least 8 deep. + assert.deepEqual([width, height], [14, 14]); + assert.ok(limit >= 8); + // The flight's icon: a draw-set item. + return [tile, { id: { set: 'flights:1', id: 'a1b2c3' } }]; }; try { harness.handler.click({ position: { x: 10, y: 20 } }); assert.equal(drills, 1); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); } finally { harness.cleanup(); @@ -1065,7 +1211,10 @@ test('vessel interaction wire: CCTV-owned pick preserves vessel selection', () = const harness = installWireHarness({ id: 'atx-cam-3' }); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); } finally { harness.cleanup(); @@ -1074,21 +1223,24 @@ test('vessel interaction wire: CCTV-owned pick preserves vessel selection', () = }); test('vessel interaction wire: own-layer unkeyed record pick does not deselect', () => { - const harness = installWireHarness({ id: makeRecord({ mmsi: undefined }) }); + // The layer's icon set, drawing the unkeyed row. + const icons = createVesselIconBook({ + id: 'ais-vessels:test', + upsert() {}, + remove() {}, + dispose() {}, + }); + icons.put({ id: 'ais-unkeyed:1', size: [32, 32], meta: {} }); + const harness = installWireHarness( + { id: { set: 'ais-vessels:test', id: 'ais-unkeyed:1' } }, + { icons }, + ); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); - assert.equal(harness.trail.clearCalls, 0); - } finally { - harness.cleanup(); - } -}); - -test('vessel interaction wire: own-shaped evicted record pick does not deselect', () => { - const harness = installWireHarness({ id: makeRecord({ mmsi: '999999999' }) }); - try { - harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); } finally { harness.cleanup(); @@ -1096,7 +1248,11 @@ test('vessel interaction wire: own-shaped evicted record pick does not deselect' }); test('vessel interaction wire: id-less 3D Tiles pick deselects and resets the HUD', () => { - const harness = installWireHarness({ primitive: {}, content: {}, featureId: 0 }); + const harness = installWireHarness({ + primitive: {}, + content: {}, + featureId: 0, + }); const cleared = []; try { registerEntityContext(harness.record, { @@ -1105,9 +1261,12 @@ test('vessel interaction wire: id-less 3D Tiles pick deselects and resets the HU label: harness.record.name, }); selectEntityContext(harness.record); - harness.windowTarget.addEventListener('gev:entity-selection-cleared', (event) => { - cleared.push(event.detail); - }); + harness.windowTarget.addEventListener( + 'gev:entity-selection-cleared', + (event) => { + cleared.push(event.detail); + }, + ); harness.handler.click({ position: { x: 10, y: 20 } }); @@ -1116,7 +1275,9 @@ test('vessel interaction wire: id-less 3D Tiles pick deselects and resets the HU // Clicking away is a deliberate deselect, not the vessel aging out of the // feed. Consumers that keep a readout on screen (the Cockpit Contact // panel) tear down on 'deliberate' and hold last-known on 'evicted'. - assert.deepEqual(cleared, [{ layerId: 'ais-live-vessels', reason: 'deliberate' }]); + assert.deepEqual(cleared, [ + { layerId: 'ais-live-vessels', reason: 'deliberate' }, + ]); } finally { harness.cleanup(); } @@ -1132,16 +1293,21 @@ test('vessel interaction wire: empty pick deselects and emits gev:entity-selecti label: harness.record.name, }); selectEntityContext(harness.record); - harness.windowTarget.addEventListener('gev:entity-selection-cleared', (event) => { - cleared.push(event.detail); - }); + harness.windowTarget.addEventListener( + 'gev:entity-selection-cleared', + (event) => { + cleared.push(event.detail); + }, + ); harness.handler.click({ position: { x: 10, y: 20 } }); assert.equal(aisLiveVesselsLayer.getSelectedInfo(), null); assert.equal(harness.hud.readout, null); // Empty pick is a deliberate deselect — see the note above. - assert.deepEqual(cleared, [{ layerId: 'ais-live-vessels', reason: 'deliberate' }]); + assert.deepEqual(cleared, [ + { layerId: 'ais-live-vessels', reason: 'deliberate' }, + ]); } finally { harness.cleanup(); } @@ -1161,16 +1327,18 @@ test('vessel interaction wire: Escape deselects the selected vessel', () => { test('vessel interaction wire: trackedEntityChanged clears only with tracking and a selection', () => { const harness = installWireHarness(undefined); try { - harness.viewer.trackedEntityChanged.raise(); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + harness.followChanged.raise(); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(harness.trail.clearCalls, 0); - harness.viewer.trackedEntity = { id: 'tracked-flight' }; - harness.viewer.trackedEntityChanged.raise(); + harness.camera.follow(entityFollowTarget({ id: 'tracked-flight' }, {})); assert.equal(aisLiveVesselsLayer.getSelectedInfo(), null); assert.equal(harness.trail.clearCalls, 1); - harness.viewer.trackedEntityChanged.raise(); + harness.followChanged.raise(); assert.equal(harness.trail.clearCalls, 1); } finally { harness.cleanup(); @@ -1183,13 +1351,13 @@ test('vessel interaction lifecycle: destroy removes the exact bound keydown list const added = harness.keyTarget.added[0]; aisLiveVesselsLayer.destroy(); - assert.equal(harness.handler.destroyCalls, 1); + assert.equal(harness.input.subscriberCount(), 0); assert.equal(harness.keyTarget.removed.length, 1); assert.equal(harness.keyTarget.removed[0].type, 'keydown'); assert.strictEqual(harness.keyTarget.removed[0].callback, added.callback); assert.equal(harness.keyTarget.keydown, null); - assert.equal(harness.viewer.trackedEntityChanged.removeCalls, 1); - assert.equal(harness.viewer.trackedEntityChanged.listenerCount, 0); + assert.equal(harness.followChanged.removeCalls, 1); + assert.equal(harness.followChanged.listenerCount, 0); } finally { harness.cleanup(); } @@ -1203,13 +1371,12 @@ test('vessel interaction lifecycle: disable detaches input and enable reinstalls const disabledKeydown = harness.keyTarget.keydown; aisLiveVesselsLayer.disable(); - assert.equal(harness.handler.destroyCalls, 1); - assert.equal(harness.handler.click, null); + assert.equal(harness.input.subscriberCount(), 0); assert.equal(harness.keyTarget.keydown, null); assert.equal(harness.keyTarget.removed.length, 1); assert.strictEqual(harness.keyTarget.removed[0].callback, disabledKeydown); - assert.equal(harness.viewer.trackedEntityChanged.removeCalls, 1); - assert.equal(harness.viewer.trackedEntityChanged.listenerCount, 0); + assert.equal(harness.followChanged.removeCalls, 1); + assert.equal(harness.followChanged.listenerCount, 0); _setVesselStateForTest({ records: [harness.record], @@ -1218,12 +1385,14 @@ test('vessel interaction lifecycle: disable detaches input and enable reinstalls trail: harness.trail, trailId: harness.record.mmsi, trailPositions: [POS], - interactionHandlerFactory: harness.interactionHandlerFactory, interactionKeyTarget: harness.keyTarget, }); disabledClick({ position: { x: 10, y: 20 } }); disabledKeydown({ key: 'Escape' }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); globalThis.fetch = async () => ({ ok: true, @@ -1231,12 +1400,11 @@ test('vessel interaction lifecycle: disable detaches input and enable reinstalls }); await aisLiveVesselsLayer.enable(harness.viewer); - assert.equal(harness.reinstalledHandlers.length, 1); + assert.equal(harness.input.subscriberCount(), 1); assert.equal(harness.keyTarget.added.length, 2); - assert.equal(harness.viewer.trackedEntityChanged.addCalls, 2); - assert.equal(harness.viewer.trackedEntityChanged.listenerCount, 1); - const reinstalled = harness.reinstalledHandlers[0]; - reinstalled.click({ position: { x: 10, y: 20 } }); + assert.equal(harness.followChanged.addCalls, 2); + assert.equal(harness.followChanged.listenerCount, 1); + harness.handler.click({ position: { x: 10, y: 20 } }); assert.equal(aisLiveVesselsLayer.getSelectedInfo(), null); assert.equal(aisLiveVesselsLayer.selectById(harness.record.mmsi), true); @@ -1264,8 +1432,14 @@ test('enable owns one grace timer and disable/re-enable starts a new session', a await aisLiveVesselsLayer.enable(harness.viewer); const duplicateEnable = _getVesselFeedStateForTest(); assert.equal(duplicateEnable.sessionId, first.sessionId); - assert.equal(duplicateEnable.firstConnectStartedAt, first.firstConnectStartedAt); - assert.equal(duplicateEnable.firstConnectDeadline, first.firstConnectDeadline); + assert.equal( + duplicateEnable.firstConnectStartedAt, + first.firstConnectStartedAt, + ); + assert.equal( + duplicateEnable.firstConnectDeadline, + first.firstConnectDeadline, + ); assert.equal(clock.activeCount(), 1); aisLiveVesselsLayer.disable(); @@ -1274,7 +1448,10 @@ test('enable owns one grace timer and disable/re-enable starts a new session', a const replacement = _getVesselFeedStateForTest(); assert.notEqual(replacement.sessionId, first.sessionId); assert.equal(replacement.firstConnectStartedAt, 25000); - assert.equal(replacement.firstConnectDeadline, 25000 + AIS_FIRST_CONNECT_GRACE_MS); + assert.equal( + replacement.firstConnectDeadline, + 25000 + AIS_FIRST_CONNECT_GRACE_MS, + ); assert.equal(replacement.firstConnectPhase, 'loading'); assert.equal(clock.activeCount(), 1); } finally { @@ -1334,18 +1511,24 @@ test('buildVesselCard: name title + type/speed/heading detail line', () => { }); test('buildVesselCard: heading falls back to course; missing parts are omitted', () => { - const card = buildVesselCard(makeRecord({ heading: null, type: '', speed: null })); + const card = buildVesselCard( + makeRecord({ heading: null, type: '', speed: null }), + ); assert.deepEqual(card.details, ['231°']); - const bare = buildVesselCard(makeRecord({ heading: null, course: null, type: '', speed: null })); + const bare = buildVesselCard( + makeRecord({ heading: null, course: null, type: '', speed: null }), + ); assert.deepEqual(bare.details, []); }); test('vessel cards read a course that rounds to north as 0°, not 360°', () => { - const card = (course) => buildVesselCard(makeRecord({ heading: null, course })).details[0]; + const card = (course) => + buildVesselCard(makeRecord({ heading: null, course })).details[0]; assert.equal(card(359.4), 'CONTAINER SHIP · 14.5KT · 359°'); assert.equal(card(359.7), 'CONTAINER SHIP · 14.5KT · 0°'); assert.equal( - buildSelectedVesselCard(makeRecord({ heading: null, course: 359.7 })).details[0], + buildSelectedVesselCard(makeRecord({ heading: null, course: 359.7 })) + .details[0], 'CONTAINER SHIP · 14.5KT · 0°', ); }); @@ -1368,10 +1551,10 @@ test('buildVesselCard: unnamed vessels title as MMSI; long names truncate', () = assert.ok(long.title.length <= 26, `title too long: ${long.title.length}`); }); -test('buildVesselCard: anchors to the billboard position when present', () => { - const rendered = { x: 9, y: 9, z: 9 }; - const card = buildVesselCard(makeRecord({ billboard: { position: rendered } })); - assert.equal(card.position, rendered); +test('buildVesselCard: anchors to the drawn position', () => { + const rendered = new Cesium.Cartesian3(9, 9, 9); + const card = buildVesselCard(makeRecord({ position: rendered })); + assert.deepEqual(card.position, rendered); }); test('buildVesselCard: tanker types carry the amber accent', () => { @@ -1387,16 +1570,27 @@ test('buildVesselCard: numeric AIS type codes read as family names, not digits', test('cardScreenSeparated: rejects candidates inside the min separation radius', () => { const accepted = [{ x: 400, y: 300 }]; - assert.equal(cardScreenSeparated(accepted, { x: 400 + 149, y: 300 }, 150), false); - assert.equal(cardScreenSeparated(accepted, { x: 400 + 151, y: 300 }, 150), true); - assert.equal(cardScreenSeparated(accepted, { x: 400, y: 300 + 100 }, 150), false); + assert.equal( + cardScreenSeparated(accepted, { x: 400 + 149, y: 300 }, 150), + false, + ); + assert.equal( + cardScreenSeparated(accepted, { x: 400 + 151, y: 300 }, 150), + true, + ); + assert.equal( + cardScreenSeparated(accepted, { x: 400, y: 300 + 100 }, 150), + false, + ); assert.equal(cardScreenSeparated([], { x: 0, y: 0 }, 150), true); }); test('buildSelectedVesselCard: full detail card with MMSI + position time', () => { - const card = buildSelectedVesselCard(makeRecord({ - lastPositionUtc: '2026-07-27T11:22:33Z', - })); + const card = buildSelectedVesselCard( + makeRecord({ + lastPositionUtc: '2026-07-27T11:22:33Z', + }), + ); assert.equal(card.selected, true); assert.equal(card.id, 'vessel:353136000'); assert.equal(card.priority, 100000); @@ -1409,24 +1603,48 @@ test('buildSelectedVesselCard: full detail card with MMSI + position time', () = test('vessel host publication preserves the shipped grid winner and separation selector', () => { const publications = []; - const originalProjection = Cesium.SceneTransforms.worldToWindowCoordinates; - const makeCandidate = (mmsi, name, x, y, speed = 1) => makeRecord({ - mmsi, - name, - speed, - position: { x: 1, y: 2, z: 3, screen: { x, y } }, - }); + // Where the query port projects each candidate, by its position's x. + const screens = new Map(); + const makeCandidate = (mmsi, name, x, y, speed = 1) => { + const key = screens.size + 1; + screens.set(key, { x, y }); + return makeRecord({ + mmsi, + name, + speed, + position: { x: key, y: 2, z: 3 }, + }); + }; const low = makeCandidate('100', 'VESSEL', 20, 20, 1); const winner = makeCandidate('200', 'NAMED WINNER', 40, 30, 16); const separated = makeCandidate('300', 'SEPARATED', 400, 300, 3); - Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => position.screen; + const viewer = { + get canvas() { + return this.scene?.canvas; + }, + scene: { canvas: { clientWidth: 1600, clientHeight: 900 } }, + }; + const unbind = bindRenderer(viewer, { + query: { + project: (p) => screens.get(p.x) ?? null, + projectMany(source, out) { + for (let i = 0; i * 3 < source.length; i++) { + const screen = screens.get(source[i * 3]); + out[i * 2] = screen ? screen.x : NaN; + out[i * 2 + 1] = screen ? screen.y : NaN; + } + }, + }, + }); _setVesselOverlayHostForTest({ - setEntries(sourceId, entries, options) { publications.push({ sourceId, entries, options }); }, + setEntries(sourceId, entries, options) { + publications.push({ sourceId, entries, options }); + }, setVisible() {}, clearSource() {}, }); _setVesselStateForTest({ - viewer: { scene: { canvas: { clientWidth: 1600, clientHeight: 900 } } }, + viewer, records: [low, winner, separated], }); try { @@ -1440,7 +1658,7 @@ test('vessel host publication preserves the shipped grid winner and separation s assert.equal(publications[0].options.cohortLimit, 112); assert.equal(publications[0].options.collisionCapacity, 112); } finally { - Cesium.SceneTransforms.worldToWindowCoordinates = originalProjection; + unbind(); _setVesselStateForTest({ enabled: false }); _setVesselOverlayHostForTest(); } @@ -1449,9 +1667,15 @@ test('vessel host publication preserves the shipped grid winner and separation s test('vessel real layer lifecycle publishes protected selection and leaves no stale host cards', () => { const calls = []; const host = { - setEntries(sourceId, entries, options) { calls.push({ op: 'set', sourceId, entries, options }); }, - setVisible(sourceId, visible) { calls.push({ op: 'visible', sourceId, visible }); }, - clearSource(sourceId) { calls.push({ op: 'clear', sourceId }); }, + setEntries(sourceId, entries, options) { + calls.push({ op: 'set', sourceId, entries, options }); + }, + setVisible(sourceId, visible) { + calls.push({ op: 'visible', sourceId, visible }); + }, + clearSource(sourceId) { + calls.push({ op: 'clear', sourceId }); + }, }; const hadWindow = Object.hasOwn(globalThis, 'window'); const priorWindow = globalThis.window; @@ -1465,10 +1689,14 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st }); _setVesselOverlayHostForTest(host); _setVesselStateForTest({ - viewer: { scene: { canvas: { clientWidth: 1600, clientHeight: 900 } } }, + viewer: { + get canvas() { + return this.scene?.canvas; + }, + scene: { canvas: { clientWidth: 1600, clientHeight: 900 } }, + }, records: [record], selectedRecord: record, - billboardCollection: { show: true, remove() {} }, }); try { _updateVesselCardsForTest([]); @@ -1481,16 +1709,26 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st assert.equal(publication.entries[0].variant, 'selected'); assert.equal(publication.entries[0].protected, true); assert.equal(publication.entries[0].collisionGroup, 'ambient-card'); - assert.match(publication.entries[0].accessibilityLabel, /Focus vessel EVER GIVEN, MMSI 353136000/); + assert.match( + publication.entries[0].accessibilityLabel, + /Focus vessel EVER GIVEN, MMSI 353136000/, + ); assert.equal(publication.entries[0].activate(), true); assert.equal(focusRequests.length, 1); assert.equal(focusRequests[0].id, '353136000'); aisLiveVesselsLayer.disable(); - assert.ok(calls.some((call) => call.op === 'clear'), 'disable clears host cards'); - assert.ok(calls.some((call) => call.op === 'visible' && call.visible === false)); + assert.ok( + calls.some((call) => call.op === 'clear'), + 'disable clears host cards', + ); + assert.ok( + calls.some((call) => call.op === 'visible' && call.visible === false), + ); - const clearsBeforeDestroy = calls.filter((call) => call.op === 'clear').length; + const clearsBeforeDestroy = calls.filter( + (call) => call.op === 'clear', + ).length; aisLiveVesselsLayer.destroy(); assert.ok( calls.filter((call) => call.op === 'clear').length > clearsBeforeDestroy, @@ -1506,14 +1744,16 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st }); test('buildSelectedVesselCard: destination line + STALE marker; placeholders for missing data', () => { - const card = buildSelectedVesselCard(makeRecord({ - type: 'Tanker', - speed: null, - heading: null, - course: null, - destination: 'ROTTERDAM', - missedRefreshes: 2, - })); + const card = buildSelectedVesselCard( + makeRecord({ + type: 'Tanker', + speed: null, + heading: null, + course: null, + destination: 'ROTTERDAM', + missedRefreshes: 2, + }), + ); assert.deepEqual(card.details, [ 'TANKER · --KT · --°', '→ ROTTERDAM', @@ -1543,23 +1783,34 @@ test('EGM96 N pins the field finding: Rotterdam sea sits ~45 m ABOVE the ellipso await ensureGeoidReady(); const rotterdam = geoidHeight(51.93, 4.05); const houston = geoidHeight(29.72, -95.08); - assert.ok(rotterdam > 40 && rotterdam < 50, `N(rotterdam) = ${rotterdam}, expected ≈ +45`); - assert.ok(houston > -32 && houston < -22, `N(houston) = ${houston}, expected ≈ −27`); + assert.ok( + rotterdam > 40 && rotterdam < 50, + `N(rotterdam) = ${rotterdam}, expected ≈ +45`, + ); + assert.ok( + houston > -32 && houston < -22, + `N(houston) = ${houston}, expected ≈ −27`, + ); }); // One-click transfer (pre-launch defect #4): clicking a vessel gives it the // camera, whether the camera was free or tracking something else. The layer // only announces the click — the UI owns the flight (src/worldFocus.js). test('vessel interaction wire: selecting a vessel by click requests a camera transfer', () => { - const harness = installWireHarness({ id: makeRecord() }, { selectedRecord: null }); + const harness = installWireHarness( + { id: makeRecord().mmsi }, + { selectedRecord: null }, + ); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), ); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, 1); assert.equal(requests[0].kind, 'vessel'); assert.equal(requests[0].id, harness.record.mmsi); @@ -1609,16 +1860,23 @@ function hostWithCardHit(entryId) { // on one picks the TERRAIN behind it — which read as empty space and cleared // the selection. A card hit must behave exactly like a sprite hit. test('vessel interaction wire: clicking a card selects and transfers, like the sprite', () => { - const harness = installWireHarness({ primitive: {}, content: {}, featureId: 0 }, { selectedRecord: null }); + const harness = installWireHarness( + { primitive: {}, content: {}, featureId: 0 }, + { selectedRecord: null }, + ); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`), ); - _setVesselOverlayHostForTest(hostWithCardHit(`vessel:${harness.record.mmsi}`)); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, 1); assert.equal(requests[0].kind, 'vessel'); assert.equal(requests[0].id, harness.record.mmsi); @@ -1629,16 +1887,24 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s }); test('vessel interaction wire: clicking the selected vessel card refocuses exactly once', () => { - const harness = installWireHarness({ primitive: {}, content: {}, featureId: 0 }); + const harness = installWireHarness({ + primitive: {}, + content: {}, + featureId: 0, + }); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`), ); - _setVesselOverlayHostForTest(hostWithCardHit(`vessel:${harness.record.mmsi}`)); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, 1); assert.equal(requests[0].id, harness.record.mmsi); assert.equal(harness.trail.clearCalls, 0); @@ -1649,17 +1915,23 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact }); test('vessel interaction wire: an unknown card id preserves selection and never flies', () => { - const harness = installWireHarness({ primitive: {}, content: {}, featureId: 0 }); + const harness = installWireHarness({ + primitive: {}, + content: {}, + featureId: 0, + }); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), ); // An evicted vessel's card id resolves to no live record. _setVesselOverlayHostForTest(hostWithCardHit('vessel:999999999')); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, 0); } finally { _setVesselOverlayHostForTest(null); @@ -1673,14 +1945,18 @@ test('vessel interaction wire: a sibling-owned pick wins without selection mutat registerPickOwner('flights', (pickedId) => pickedId === 'a1b2c3'); const harness = installWireHarness({ id: 'a1b2c3' }); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`), ); - _setVesselOverlayHostForTest(hostWithCardHit(`vessel:${harness.record.mmsi}`)); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, 0); } finally { _setVesselOverlayHostForTest(null); @@ -1695,16 +1971,32 @@ for (const card of ['live', 'stale', 'absent', 'covered']) { registerPickOwner('weather-cyclones', (pickedId) => pickedId === id); const harness = installWireHarness({ id }); const requests = []; - harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => requests.push(event.detail)); - const host = hostWithCardHit(card === 'live' ? `vessel:${harness.record.mmsi}` : card === 'stale' ? 'vessel:999999999' : null); - if (card === 'covered') host.hitTest = (_x, _y, options) => { - assert.equal(options?.sourceId, undefined, 'test topmost host hit, not a covered AIS card'); - return { sourceId: 'cctv', entryId: 'vessel:999999999' }; - }; + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + const host = hostWithCardHit( + card === 'live' + ? `vessel:${harness.record.mmsi}` + : card === 'stale' + ? 'vessel:999999999' + : null, + ); + if (card === 'covered') + host.hitTest = (_x, _y, options) => { + assert.equal( + options?.sourceId, + undefined, + 'test topmost host hit, not a covered AIS card', + ); + return { sourceId: 'cctv', entryId: 'vessel:999999999' }; + }; _setVesselOverlayHostForTest(host); try { harness.handler.click({ position: { x: 10, y: 20 } }); - assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi, + harness.record.mmsi, + ); assert.equal(requests.length, card === 'live' ? 1 : 0); } finally { _setVesselOverlayHostForTest(null); @@ -1740,9 +2032,8 @@ test('vessel cards are keyed by id and show the MMSI only when known', () => { test('vessel interaction wire: deselecting never moves the camera', () => { const harness = installWireHarness({ id: 'gev-empty-space' }); const requests = []; - harness.windowTarget.addEventListener( - WORLD_FOCUS_REQUEST_EVENT, - (event) => requests.push(event.detail), + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), ); try { harness.handler.click({ position: { x: 10, y: 20 } }); @@ -1760,14 +2051,24 @@ test('a vessel analyst record carries the MMSI the tracker keys on', () => { // selection keys on MMSI. The compact voice payload must carry both, or the // analyst → track_entity handoff hands over a name and nothing resolvable. const named = mapAnalystRecord({ - mmsi: '366999123', name: 'EVER GIVEN', lat: 37.8, lon: -122.4, speed: 12, type: 'Cargo', + mmsi: '366999123', + name: 'EVER GIVEN', + lat: 37.8, + lon: -122.4, + speed: 12, + type: 'Cargo', }); assert.equal(named.id, 'EVER GIVEN'); assert.equal(named.mmsi, '366999123', 'the key rides along with the label'); // A nameless vessel falls back to its MMSI for display; the key is still // present in its own field, so the payload never depends on that collapse. - const nameless = mapAnalystRecord({ mmsi: '366999124', name: null, lat: 37.9, lon: -122.5 }); + const nameless = mapAnalystRecord({ + mmsi: '366999124', + name: null, + lat: 37.9, + lon: -122.5, + }); assert.equal(nameless.id, '366999124'); assert.equal(nameless.mmsi, '366999124'); }); @@ -1779,13 +2080,19 @@ test('vessel selection passes the opaque source reference to optional history', aisLiveVesselsLayer.setSource({ label: 'Test vessel source', getSnapshot: async () => ({ records: [] }), - getTrack: async (reference, options) => { requests.push({ reference, options }); return { records: [] }; }, + getTrack: async (reference, options) => { + requests.push({ reference, options }); + return { records: [] }; + }, + }); + const harness = installWireHarness(undefined, { + selectedRecord: null, + trailId: null, }); - const harness = installWireHarness(undefined, { selectedRecord: null, trailId: null }); try { harness.record.reference = 'opaque:test-reference'; assert.equal(aisLiveVesselsLayer.selectById(harness.record.mmsi), true); - await new Promise(resolve => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); assert.equal(requests.length, 1); assert.equal(requests[0].reference, 'opaque:test-reference'); assert.ok(requests[0].options.signal instanceof AbortSignal); @@ -1798,18 +2105,13 @@ test('vessel selection passes the opaque source reference to optional history', }); test('vessel focus wire skips hidden sprites at rest while a target is tracked', () => { - const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); - const sprite = (show) => ({ - position: { x: 1, y: 2, z: 3 }, - show, - color: makeColor(1), + const icons = createVesselIconBook(); + const records = Array.from({ length: 51 }, (_, i) => { + const iconId = String(i); + icons.put({ id: iconId, size: [32, 32], meta: { id: iconId } }); + return { iconId, position: { x: 1, y: 2, z: 3 }, visible: i === 0 }; }); - const visible = sprite(true); - const hidden = Array.from({ length: 50 }, () => sprite(false)); - const records = [visible, ...hidden].map((billboard) => ({ - position: billboard.position, - billboard, - })); + const focus = (record) => icons.focus(record.iconId); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, paddingPx: 0, @@ -1820,6 +2122,7 @@ test('vessel focus wire skips hidden sprites at rest while a target is tracked', const apply = (nowMs) => applyVesselFocusDeemphasis({ records, + icons, target, nowMs, screenPositionFor: () => { @@ -1839,9 +2142,9 @@ test('vessel focus wire skips hidden sprites at rest while a target is tracked', // Only the on-screen sprite pays for projection and distance. assert.equal(projected, 2); assert.equal(measured, 2); - assert.equal(visible.color.alpha, 0.25); + assert.equal(focus(records[0]), 0.25); assert.equal(result.activeCount, 1); - for (const billboard of hidden) assert.equal(billboard.color.alpha, 1); + for (const record of records.slice(1)) assert.equal(focus(record), 1); }); test('detection objects name the vessel card their callout gives way to', () => { @@ -1856,14 +2159,14 @@ test('detection objects name the vessel card their callout gives way to', () => lastPositionUtc: '', missedRefreshes: 0, position: POS, - billboard: null, + // Drawn and on screen (a record with no visual of its own is its own). + visible: true, }); const keyed = vessel('200', 'GOLDEN BEAR'); const unkeyed = { ...vessel('', 'NO MMSI'), lat: 37.8, lon: -122.4 }; _setVesselStateForTest({ viewer: {}, records: [keyed, unkeyed], - billboardCollection: { show: true, remove() {} }, }); try { const objects = Object.fromEntries( @@ -1878,6 +2181,13 @@ test('detection objects name the vessel card their callout gives way to', () => 'vessel:unkeyed:NO MMSI:37.80000:-122.40000', 'the same identity the vessel card is published under', ); + // The ship the bridge camera rides is no object in view. + aisLiveVesselsLayer.setCockpitSubject('200'); + const ids = aisLiveVesselsLayer + .getDetectableObjects() + .map((object) => object.id); + assert.deepEqual(ids, ['NO MMSI']); + aisLiveVesselsLayer.setCockpitSubject(null); } finally { _setVesselStateForTest({ enabled: false }); } diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 4993e83458..d29780d554 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -3,6 +3,11 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { + bindFakeCesiumCamera, + followEntity, +} from '../testSupport/fakeCameraPort.mjs'; +import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import alprCamerasLayer, { createAlprCamerasLayer, configureAlprSource, @@ -31,6 +36,8 @@ import { isAlprSurveillanceType, normalizeAlprNode, } from './alprCameras.js'; +import { readEntityRecord } from './entityRecords.js'; +import { alprMarkers } from '../layers/alpr/markerState.js'; test('normalizeAlprNode: maps a full OSM node to a plain record', () => { const record = normalizeAlprNode({ @@ -308,7 +315,7 @@ function cameraHarness(layer = alprCamerasLayer) { }, }); let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 }; - let source, click, picked; + let click, picked; const credits = new Set(); const viewer = { creditDisplay: { @@ -333,20 +340,27 @@ function cameraHarness(layer = alprCamerasLayer) { postRender: new Cesium.Event(), pick: () => picked, }, - dataSources: { - add: (value) => { - source = value; - }, - remove() {}, - }, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. + trackedEntityChanged: new Cesium.Event(), + entities: {}, }; + const ports = fakeScenePorts(viewer); + bindFakeCesiumCamera(viewer, ports); + // The renderer's camera port relays moveEnd; the layer's own come on top. + const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners; const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction; Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function ( fn, type, modifier, ) { - if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) click = fn; + // The unmodified click: the input port binds one per modifier. + if ( + type === Cesium.ScreenSpaceEventType.LEFT_CLICK && + modifier === undefined + ) + click = fn; return setInput.call(this, fn, type, modifier); }; try { @@ -355,13 +369,22 @@ function cameraHarness(layer = alprCamerasLayer) { Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput; } layer.enable(); + const icons = () => { + const set = [...ports.draw.sets.values()].find( + (candidate) => candidate.kind === 'icons' && !candidate.disposed, + ); + return set && { ...set, id: set.spec.id }; + }; + const marker = (id) => + icons()?.items.has(id) + ? getContextStore().entities.get(id)?.entity + : undefined; return { viewer, + ports, + portMoveEndListeners, requests, credits, - get source() { - return source; - }, setFetch(fn) { response = fn; }, @@ -374,9 +397,16 @@ function cameraHarness(layer = alprCamerasLayer) { advance(ms) { now += ms; }, + /** The layer's icon set, as the fake draw port holds it. */ + icons, + /** The icon drawn for a camera, or undefined. */ + icon: (id) => icons()?.items.get(id), + /** The drawn markers' carriers (their context entities), in draw order. */ + markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)), + marker, click(id) { - const entity = typeof id === 'string' ? source.entities.getById(id) : id; - picked = entity ? { id: entity } : undefined; + const item = typeof id === 'string' ? icons()?.items.get(id) : null; + picked = item ? { id: { set: icons().id, id: item.id } } : undefined; click({ position: new Cesium.Cartesian2() }); }, restore() { @@ -440,28 +470,28 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a ]), ); await alprCamerasLayer.update(); - const entities = h.source.entities.values; + const entities = h.markers(); assert.equal(alprCamerasLayer.name, 'ALPR Cameras'); assert.deepEqual( - entities.map((entity) => entity.gevLabelModel.title), + entities.map((entity) => readEntityRecord(entity)?.labelModel.title), ['ALPR-0042', 'ALPR-0043', 'ALPR-0044'], ); assert.equal( - new Set(entities.map((entity) => entity.billboard.image.getValue())).size, + new Set(entities.map((entity) => h.icon(entity.id).image)).size, 1, ); - assert.deepEqual(entities[0].gevLabelModel.details, [ + assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [ 'OSM MAPPED', 'FLOCK SAFETY · CITY POLICE · FIXED', 'PUBLIC MAP DATA', ]); - assert.deepEqual(entities[1].gevLabelModel.details, [ + assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [ 'OSM MAPPED', 'MOTOROLA SOLUTIONS', 'PUBLIC MAP DATA', ]); assert.deepEqual( - entities[2].gevLabelModel.details, + readEntityRecord(entities[2])?.labelModel.details, ['OSM MAPPED', 'PUBLIC MAP DATA'], 'unknown metadata is not guessed, but the source is always named', ); @@ -486,7 +516,7 @@ test('the camera label stays English data in a translated interface', async () = ]), ); await alprCamerasLayer.update(); - h.click(h.source.entities.values[0].id); + h.click(h.markers()[0].id); assert.equal(getSelectedEntityContext().label, 'ALPR camera'); assert.equal( shownEntityLabel(getSelectedEntityContext().label), @@ -523,10 +553,7 @@ test('clicking the selected camera or empty map deselects, including after refre h.expire(); await alprCamerasLayer.update(); assert.equal(getSelectedEntityContext(), null); - assert.equal( - h.source.entities.getById('alpr:42').billboard.width.getValue(), - 38, - ); + assert.equal(h.icon('alpr:42').size[0], 38); } } finally { h.restore(); @@ -582,10 +609,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n alprCamerasLayer.enable(); await alprCamerasLayer.update(); assert.equal(getSelectedEntityContext(), null); - assert.equal( - h.source.entities.getById('alpr:42').billboard.width.getValue(), - 38, - ); + assert.equal(h.icon('alpr:42').size[0], 38); } finally { h.restore(); } @@ -674,7 +698,7 @@ test('duplicate nodes render once with a count that agrees with the entity set', await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'ready'); assert.equal(alprCamerasLayer.getStats().count, 1); - assert.equal(h.source.entities.values.length, 1); + assert.equal(h.icons().items.size, 1); } finally { h.restore(); } @@ -690,7 +714,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); assert.equal(alprCamerasLayer.getStats().count, 0); assert.equal(getSelectedEntityContext(), null); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); assert.equal(h.requests.length, 1); } finally { h.restore(); @@ -750,7 +774,7 @@ test('nearby camera moves reuse the snapped query but count and register only in await alprCamerasLayer.update(); assert.equal(h.requests.length, 1); assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']); @@ -797,9 +821,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di try { let samples = 0; h.viewer.scene.sampleHeightSupported = true; - h.viewer.scene.sampleHeight = (point, excluded) => { + h.viewer.scene.sampleHeight = () => { samples += 1; - assert.equal(excluded[0].id, 'alpr:42'); return 187; }; h.setFetch(async () => @@ -811,9 +834,9 @@ test('selected readout samples the rendered ground, not zero elevation or the di ); await alprCamerasLayer.update(); h.click('alpr:42'); - const entity = h.source.entities.getById('alpr:42'); + const entity = h.marker('alpr:42'); const anchor = Cesium.Cartographic.fromCartesian( - entity.gevDisplayPosition(), + readEntityRecord(entity)?.displayPosition(), ); assert.ok(Math.abs(anchor.height - 187) < 0.001); assert.ok( @@ -821,7 +844,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di ); for (let i = 0; i < 60; i++) { h.viewer.scene.postRender.raiseEvent(); - entity.gevDisplayPosition(); + readEntityRecord(entity)?.displayPosition(); } assert.equal(samples, 1, 'no per-frame raycasts'); h.advance(1000); @@ -859,6 +882,7 @@ test('a late network failure after disable cannot resurrect retries or an error }); test('two factories keep their requests, records and destruction independent', async () => { + const carriers = new Map(); const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, @@ -872,7 +896,9 @@ test('two factories keep their requests, records and destruction independent', a getSelectedEntityContext() { return null; }, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -918,14 +944,17 @@ test('two factories keep their requests, records and destruction independent', a await pending; assert.equal(first.getStats().count, 0); assert.equal(second.getStats().count, 1); - assert.equal(b.source.entities.values[0].id, 'directory:99'); + assert.deepEqual([...b.icons().items.keys()], ['directory:99']); assert.equal(second.source, 'Test camera directory'); assert.ok( - b.source.entities.values[0].gevLabelModel.details.includes( - 'Source: Test directory', - ), + readEntityRecord( + carriers.get('directory:99'), + )?.labelModel.details.includes('Source: Test directory'), + ); + assert.equal( + a.viewer.camera.moveEnd.numberOfListeners, + a.portMoveEndListeners, ); - assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0); assert.equal(a.viewer.scene.postRender.numberOfListeners, 0); } finally { b.restore(); @@ -937,6 +966,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso // Ground clamping re-samples every marker whenever a photoreal tile streams // in; a whole-city view (about 1,000 cameras) stuttered while zooming. const floors = new Map([['30.2672', 150]]); + const carriers = new Map(); let resolveCalls = 0; let releaseResolve; const services = { @@ -957,7 +987,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso getSelectedEntityContext() { return null; }, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -978,38 +1010,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso const h = cameraHarness(layer); try { await layer.update(); - const known = h.source.entities.getById('directory:1'); - const unknown = h.source.entities.getById('directory:2'); - assert.equal( - known.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, - ); + const known = h.icon('directory:1'); + const unknown = () => h.icon('directory:2'); + const unknownCarrier = carriers.get('directory:2'); + assert.equal(known.height, 'absolute'); assert.ok( - Math.abs( - Cesium.Cartographic.fromCartesian(known.position.getValue()).height - - 151.5, - ) < 0.01, - ); - assert.equal( - unknown.billboard.heightReference.getValue(), - Cesium.HeightReference.CLAMP_TO_GROUND, + Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) < + 0.01, ); + assert.equal(unknown().height, 'clampGround'); assert.equal(resolveCalls, 1); + const writes = h.icons().writes; releaseResolve(); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal( - unknown.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, - ); + assert.equal(unknown().height, 'absolute'); assert.ok( Math.abs( - Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height - - 161.5, + Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5, ) < 0.01, ); + assert.equal(h.icons().writes, writes + 1, 'one write for the move'); assert.equal( - h.source.entities.getById('directory:2'), - unknown, + carriers.get('directory:2'), + unknownCarrier, 'placed in place, not rebuilt', ); } finally { @@ -1061,23 +1084,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec ); await alprCamerasLayer.update(); h.click('alpr:42'); - const entity = h.source.entities.getById('alpr:42'); - const position = entity.position, - line = entity.polyline; + const entity = h.marker('alpr:42'); + const icon = h.icon('alpr:42'); // Ground-clamped native wedges cost ~40 ms per frame for a downtown view; // bearings are painted by the overlay for the nearest cameras instead. - assert.equal(line, undefined); - assert.equal(entity.polygon, undefined); + assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry'); let selections = 0, - clears = 0, - collectionChanges = 0; + clears = 0; window.addEventListener('gev:entity-selected', () => selections++); window.addEventListener('gev:entity-selection-cleared', () => clears++); - h.source.entities.collectionChanged.addEventListener( - (_collection, added, removed) => { - collectionChanges += added.length + removed.length; - }, - ); + const writes = h.icons().writes; h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 }); await alprCamerasLayer.update(); h.expire(); @@ -1093,30 +1109,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec ]), ); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); - assert.equal(entity.position, position); - assert.equal(entity.polyline, line); + assert.equal(h.marker('alpr:42'), entity); + assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again'); assert.equal( getSelectedEntityContext().properties.operator, 'Updated directory', ); assert.equal(selections, 0); assert.equal(clears, 0); - assert.equal(collectionChanges, 0); + assert.equal(h.icons().writes, writes, 'no icon added or removed'); assert.equal(h.requests.length, 2, 'only expiry needs another request'); h.expire(); h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })])); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); - assert.equal( - entity.polyline, - undefined, - 'removed direction must not persist', - ); + assert.equal(h.marker('alpr:42'), entity); assert.ok( - Cesium.Cartesian3.equals( - entity.position.getValue(), + Cesium.Cartesian3.equalsEpsilon( + h.icon('alpr:42').pos, Cesium.Cartesian3.fromDegrees(-97.742, 30.2672), + 0, + 1e-6, ), ); } finally { @@ -1156,7 +1168,7 @@ test('moves inside a pending query do not restart it; moving to another city can resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })])); await second; assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); } finally { @@ -1174,12 +1186,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200); try { await alprCamerasLayer.update(); - const entity = h.source.entities.getById('alpr:42'); + const entity = h.marker('alpr:42'); h.click('alpr:42'); for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) { h.setBox(box); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); + assert.equal(h.marker('alpr:42'), entity); assert.equal(getSelectedEntityContext().id, 'alpr:42'); assert.equal(h.requests.length, 1); } @@ -1190,7 +1202,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da ); await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); camera.pickEllipsoid = () => undefined; await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); @@ -1235,14 +1247,14 @@ test('nearby count and discovery control frame a real loaded camera without fetc ); assert.equal(flights[0].options.offset.range, 800); assert.equal(h.requests.length, 1); - h.viewer.trackedEntity = {}; + followEntity(h.viewer, {}); assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true); assert.equal( controls.chips[0].onClick(), false, 'a stale button cannot steal the follow camera', ); - h.viewer.trackedEntity = undefined; + followEntity(h.viewer, null); alprCamerasLayer.disable(); assert.equal(alprCamerasLayer.getStats().countLabel, ''); assert.equal(controls.chips[0].onClick(), false); @@ -1385,7 +1397,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an requests[1].release(); await new Promise((done) => setTimeout(done, 0)); assert.equal(requests.length, 2, 'queued final cells are discarded'); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); layer.enable(); await layer.update(); assert.equal( @@ -1404,10 +1416,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an } }); -test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => { +test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => { let floor = 180; let listener; let removed = 0; + const carriers = new Map(); const records = Array.from({ length: 70 }, (_, i) => ({ id: `surface:${i}`, latitude: 30.2672 + i * 0.00001, @@ -1433,7 +1446,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc context: { clearSelectedEntityContextForLayer() {}, getSelectedEntityContext() {}, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -1442,40 +1457,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc const h = cameraHarness(layer); try { await layer.update(); - const entities = [...h.source.entities.values]; + const entities = [...carriers.values()]; + // One marker under a canvas badge: its icon is the faint pick target. const saved = entities[1]; - saved.gevAlprNativeAppearance = { - position: saved.position, - heightReference: saved.billboard.heightReference, - }; - saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190); - saved.gevAlprPickPosition = saved.position; + Object.assign(alprMarkers.write(saved), { + canvasOwned: true, + canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190), + }); for (const next of [150, 120, null, 180]) { floor = next; - // Includes a provider switch with the same globe.show value. - h.viewer.scene.globe.show = next !== 180; listener({ detail: { status: 'ready' } }); for (const entity of entities) { - assert.equal(h.source.entities.getById(entity.id), entity); + const icon = h.icon(entity.id); assert.ok( Math.abs( - Cesium.Cartographic.fromCartesian(entity.position.getValue()) - .height - (next == null ? 0 : next + 1.5), + Cesium.Cartographic.fromCartesian(icon.pos).height - + (next == null ? 0 : next + 1.5), ) < 0.01, `${entity.id} refreshes at ${next}`, ); - assert.equal( - entity.billboard.heightReference.getValue(), - next == null - ? Cesium.HeightReference.CLAMP_TO_GROUND - : Cesium.HeightReference.NONE, - ); - assert.equal(entity.gevAlprCanvasPosition, null); + assert.equal(icon.height, next == null ? 'clampGround' : 'absolute'); + assert.equal(icon.color, undefined, 'drawn as a badge'); + assert.equal(alprMarkers.read(entity)?.canvasPosition, null); } assert.equal( - saved.gevAlprNativeAppearance, - null, - 'saved appearance restores at the new floor', + alprMarkers.read(saved)?.canvasOwned, + false, + 'the badge comes back at the new floor', ); } } finally { @@ -1488,7 +1496,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set const h = cameraHarness(); try { await alprCamerasLayer.update(); - const previous = h.source.entities.getById('alpr:42'); + const previous = h.marker('alpr:42'); const revision = alprCamerasLayer.getStats().renderRevision; let release; h.setFetch( @@ -1501,7 +1509,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set const pending = alprCamerasLayer.update(); await alprCamerasLayer.update(); assert.equal( - h.source.entities.getById('alpr:42'), + h.marker('alpr:42'), previous, 'do not show an intermediate filtered snapshot while the new query prepares', ); @@ -1511,7 +1519,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set await pending; assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1); assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); } finally { diff --git a/src/data/bhoteKoshiEmbeddedMedia.js b/src/data/bhoteKoshiEmbeddedMedia.js index fb2d4ca7cd..7e6be9bb63 100644 --- a/src/data/bhoteKoshiEmbeddedMedia.js +++ b/src/data/bhoteKoshiEmbeddedMedia.js @@ -1,4 +1,10 @@ -import * as Cesium from 'cesium'; +import { + canvasOf, + findCamera, + findFrame, + findQuery, +} from '../render/rendererOf.js'; +import { dot, sub } from '../geo/vector.js'; import { t, msg, onLocaleChange } from '../i18n/index.js'; const YOUTUBE_HOSTS = new Set([ @@ -538,23 +544,22 @@ function ensureProviderConnections(documentRef, provider) { } } +/** + * Where an anchor (ECEF) is in the card root, through the renderer's camera + * and query ports; null behind the eye, off the root, or with no renderer. + */ function anchorOnScreen(viewer, anchor, root) { - if (!viewer?.scene || !anchor || !root) return null; - const camera = viewer.camera; - if (camera?.positionWC && camera?.directionWC) { - const delta = Cesium.Cartesian3.subtract( - anchor, - camera.positionWC, - new Cesium.Cartesian3(), - ); - if (Cesium.Cartesian3.dot(delta, camera.directionWC) <= 0) return null; - } - const pixel = Cesium.SceneTransforms.worldToWindowCoordinates( - viewer.scene, - anchor, - ); + if (!anchor || !root) return null; + const camera = findCamera(viewer); + const query = findQuery(viewer); + if (!camera || !query) return null; + const pose = camera.pose(); + if (dot(sub(anchor, pose.position), pose.direction) <= 0) return null; + const pixel = query.project(anchor); if (!pixel) return null; - const canvasBounds = viewer.canvas?.getBoundingClientRect?.(); + // The renderer's canvas; a viewer with no renderer bound, its own. + const canvas = canvasOf(viewer); + const canvasBounds = canvas?.getBoundingClientRect?.(); const rootBounds = root.getBoundingClientRect?.(); if (!canvasBounds || !rootBounds) return null; const x = pixel.x + canvasBounds.left - rootBounds.left; @@ -865,7 +870,7 @@ export function createBhoteKoshiEmbeddedMedia({ } }; const removePostRender = - viewer.scene?.postRender?.addEventListener?.(position); + findFrame(viewer)?.on('postRender', () => position()) ?? null; function hide({ immediate = false, preserveWarm = false } = {}) { if (!preserveWarm) clearWarm(); diff --git a/src/data/bhoteKoshiEmbeddedMedia.test.mjs b/src/data/bhoteKoshiEmbeddedMedia.test.mjs index e55fb0d654..3d9bf1a983 100644 --- a/src/data/bhoteKoshiEmbeddedMedia.test.mjs +++ b/src/data/bhoteKoshiEmbeddedMedia.test.mjs @@ -10,6 +10,7 @@ import { publicEmbeddedMediaUrl, resolveEmbeddedMediaSource, } from './bhoteKoshiEmbeddedMedia.js'; +import { bindRenderer } from '../render/rendererOf.js'; test('Pinokio fallback never creates provider DOM or loads SDKs', async () => { const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); }; @@ -417,3 +418,55 @@ test('a media card stays between the panels when right-to-left swaps their sides assert.ok(left >= 340 + 18, `card at ${left}px lands on the context rail`); assert.ok(left + 392 <= 1040 - 18, `card at ${left}px lands on the scene panel`); }); + +test('a shown card follows its anchor through the renderer ports', () => { + class Element extends EventTarget { + constructor(tag) { + super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {}; + this.classList = { add() {}, remove() {}, contains() { return false; } }; + } + setAttribute() {} + removeAttribute() {} + querySelector() { return null; } + getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; } + append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } } + remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; } + } + const documentRef = { + body: new Element('body'), + createElement: (tag) => new Element(tag), + createElementNS: (_, tag) => new Element(tag), + }; + const listeners = new Set(); + const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } }; + let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } }; + const projected = []; + // The renderer's canvas, not the viewer's, places the card. + const unbind = bindRenderer(viewer, { + canvas: { getBoundingClientRect: () => ({ left: 10, top: 5 }) }, + camera: { pose: () => pose }, + query: { project: (p) => { projected.push(p); return { x: 300, y: 200 }; } }, + frame: { + on(phase, cb) { + const entry = [phase, cb]; + listeners.add(entry); + return () => listeners.delete(entry); + }, + }, + }); + const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} }); + assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']); + const anchor = { x: 10, y: 0, z: 0 }; + assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true); + const card = documentRef.body.children[0].children.find((node) => node.tag === 'section'); + assert.equal(card.hidden, false); + assert.equal(projected.at(-1), anchor); + assert.equal(card.style.left, `${300 + 10 + 42}px`); + // Behind the eye: hidden on the next drawn frame. + pose = { ...pose, direction: { x: -1, y: 0, z: 0 } }; + for (const [, cb] of listeners) cb(); + assert.equal(card.hidden, true); + media.destroy(); + assert.equal(listeners.size, 0); + unbind(); +}); diff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.js index 8211cebb57..e0fa8ee041 100644 --- a/src/data/bhoteKoshiEvent.js +++ b/src/data/bhoteKoshiEvent.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { isPointerFree } from './inputOwnership.js'; import { clearOverlaySource, @@ -24,10 +23,21 @@ import { resolveEmbeddedMediaSource, } from './bhoteKoshiEmbeddedMedia.js'; import { acquireImageryComparison } from '../maps/imageryComparison.js'; -import { createImagerySplit } from '../ui/imagerySplit.js'; +import { createImagerySplit, globeSplitTarget } from '../ui/imagerySplit.js'; import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js'; import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js'; import { applicationPinia } from '../ui/vueRuntime.js'; +import { heightsOf } from '../queries/heights.js'; +import { + cameraOf, + canvasOf, + drawOf, + findCamera, + findGlobe, +} from '../render/rendererOf.js'; +import { hexColor } from '../render/color.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { clone, lerp, lerpInto, toRadians, vec } from '../geo/vector.js'; export const BHOTE_KOSHI_LAYER_ID = 'bhote-koshi-2026'; export const BHOTE_KOSHI_OVERLAY_SOURCE_ID = 'bhote-koshi-witnesses'; @@ -46,8 +56,24 @@ const SCENE_PATH_RENDER_HOLD = 'bhote-koshi-scene-path-travel'; const SCENE_MEDIA_MIN_PLAYBACK_SECONDS = 6; const SCENE_MEDIA_EXIT_SECONDS = 0.65; const BHOTE_EVENT_ACCENT = WORLD_OVERLAY_STYLE.accent; -const FLOOD_COLOR = Cesium.Color.fromCssColorString('#d8954e').withAlpha(0.68); -const SURGE_COLOR = Cesium.Color.fromCssColorString('#e8b47c'); +const FLOOD_ACCENT = '#d8954e'; +const FLOOD_HALO_COLOR = hexColor(FLOOD_ACCENT, 0.38); +const FLOOD_CORE_COLOR = hexColor(FLOOD_ACCENT, 0.96); +const SURGE_COLOR = hexColor('#e8b47c'); +const SURGE_OUTLINE_COLOR = [0, 0, 0, 0.85]; +const FLOOD_HALO_ID = 'bhote-koshi-flood-halo'; +const FLOOD_CORE_ID = 'bhote-koshi-flood-core'; +const SURGE_FRONT_ID = 'bhote-koshi-surge-front'; +const IMAGERY_CREDIT = Object.freeze({ + text: 'Vantor WorldView Open Data · CC BY-NC 4.0', +}); + +// Each layer's draw sets have ids of their own. +let layerSerial = 0; + +/** Whether two positions are the same point; either may be null. */ +const samePoint = (a, b) => + a === b || (Boolean(a && b) && a.x === b.x && a.y === b.y && a.z === b.z); const CINEMATIC_INPUT_EVENTS = Object.freeze(['pointerdown', 'wheel']); const CINEMATIC_VIEW_SPECS = Object.freeze([ { @@ -119,23 +145,25 @@ const DEFAULT_EVENT_LOADER = async () => { throw new Error(`Bhote Koshi event pack unavailable (${response.status})`); return response.json(); }; -const DEFAULT_IMAGERY_PROVIDER_FACTORY = (url, options) => - Cesium.SingleTileImageryProvider.fromUrl(url, options); +/** The globe port's spec for one of the event's images, over `rectangle`. */ +const DEFAULT_IMAGERY_SPEC_FACTORY = (url, { rectangle, credit }) => ({ + kind: 'single-image', + url, + rectangle, + credit, +}); +/** + * Terrain heights under the observations, once the most detailed terrain + * has loaded. The bare ellipsoid answers no height, as there is no terrain + * to sample then. + */ const DEFAULT_TERRAIN_SAMPLER = async (viewer, observations) => { - if ( - !viewer?.terrainProvider || - !viewer.terrainProvider.availability || - typeof Cesium.sampleTerrainMostDetailed !== 'function' - ) { - return null; - } - const cartographics = observations.map((observation) => - Cesium.Cartographic.fromDegrees(observation.lon, observation.lat), - ); - return Cesium.sampleTerrainMostDetailed( - viewer.terrainProvider, - cartographics, - ); + if (!viewer) return null; + const heights = await heightsOf(viewer).batch(observations, { + against: 'terrain', + ellipsoidMisses: true, + }); + return heights.map((height) => ({ height })); }; const DEFAULT_MEDIA_LOADER = async (url, { signal } = {}) => { if (typeof createImageBitmap !== 'function') { @@ -187,7 +215,7 @@ export function visibleSegmentCount(progress, segmentCount) { /** * Build a corridor whose final vertex is the exact animated surge position. - * Returns true only when the Cesium polyline assignments need refreshing. + * Returns true only when the drawn corridor needs refreshing. */ export function updateCorridorPositionCache(progress, terrainPositions, cache) { const positions = Array.isArray(terrainPositions) ? terrainPositions : []; @@ -210,15 +238,15 @@ export function updateCorridorPositionCache(progress, terrainPositions, cache) { const startIndex = Math.min(segmentCount - 1, Math.floor(scaledProgress)); const segmentProgress = normalizedProgress >= 1 ? 1 : scaledProgress - startIndex; - cache.headPosition = Cesium.Cartesian3.lerp( + cache.headPosition = lerpInto( positions[startIndex], positions[startIndex + 1], segmentProgress, - cache.headPosition || new Cesium.Cartesian3(), + cache.headPosition || vec(), ); cache.positions = positions.slice(0, startIndex + 1); if (segmentProgress > 0) { - cache.positions.push(Cesium.Cartesian3.clone(cache.headPosition)); + cache.positions.push(clone(cache.headPosition)); } return true; } @@ -525,19 +553,19 @@ export function sampleCinematicPose(progress, keyframes, result = {}) { : (linearAmount - BHOTE_KOSHI_CAMERA_HOLD_RATIO) / (1 - BHOTE_KOSHI_CAMERA_HOLD_RATIO); const amount = travelAmount * travelAmount * (3 - 2 * travelAmount); - result.target = Cesium.Cartesian3.lerp( + result.target = lerpInto( from.target, to.target, amount, - result.target || new Cesium.Cartesian3(), + result.target || vec(), ); result.headingDeg = interpolateHeadingDegrees( from.headingDeg, to.headingDeg, amount, ); - result.pitchDeg = Cesium.Math.lerp(from.pitchDeg, to.pitchDeg, amount); - result.rangeM = Cesium.Math.lerp(from.rangeM, to.rangeM, amount); + result.pitchDeg = lerp(from.pitchDeg, to.pitchDeg, amount); + result.rangeM = lerp(from.rangeM, to.rangeM, amount); result.fromId = from.id; result.toId = to.id; return result; @@ -891,25 +919,29 @@ function openExternal(url) { function focusView(viewer, viewpoint) { announceNavigationAuthority('bhote-koshi-event-focus'); - const target = Cesium.Cartesian3.fromDegrees( + const target = fromDegrees( viewpoint.lon, viewpoint.lat, viewpoint.targetElevationM, ); - const offset = new Cesium.HeadingPitchRange( - Cesium.Math.toRadians(viewpoint.headingDeg), - Cesium.Math.toRadians(viewpoint.pitchDeg), - viewpoint.rangeM, - ); - viewer.camera.cancelFlight?.(); - viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(target, 80), { - offset, - duration: 2.2, - complete: () => { - viewer.camera.lookAt(target, offset); - viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); + const offset = { + heading: toRadians(viewpoint.headingDeg), + pitch: toRadians(viewpoint.pitchDeg), + range: viewpoint.rangeM, + }; + const camera = cameraOf(viewer); + camera.cancelFlight(); + camera.flyToBounds( + { center: target, radius: 80 }, + { + offset, + durationS: 2.2, + onComplete: () => { + camera.lookAt(target, offset); + camera.release(); + }, }, - }); + ); } function setElementProperty(element, property, value) { @@ -987,7 +1019,7 @@ export function createBhoteKoshiEventLayer({ overlayHost = DEFAULT_OVERLAY_HOST, renderHost = DEFAULT_RENDER_HOST, eventLoader = DEFAULT_EVENT_LOADER, - imageryProviderFactory = DEFAULT_IMAGERY_PROVIDER_FACTORY, + imagerySpecFactory = DEFAULT_IMAGERY_SPEC_FACTORY, terrainSampler = DEFAULT_TERRAIN_SAMPLER, mediaLoader = DEFAULT_MEDIA_LOADER, evidenceFrameFactory = createEvidenceFrame, @@ -1013,12 +1045,19 @@ export function createBhoteKoshiEventLayer({ let _splitControl = null; let _beforeLayer = null; let _afterLayer = null; - let _imageryLayerCollection = null; - let _floodDataSource = null; + // An event image failed to load this enable: no comparison is shown. + let _imageryFailed = false; + const _serial = ++layerSerial; + // The flood's draw sets: the corridor's halo and core lines, and the + // surge front. Null while the layer is off. + let _floodSets = null; let _floodSurfaceMode = null; - let _floodHalo = null; - let _floodCore = null; - let _surgePoint = null; + // What the flood shows, set as the event plays, and what was last drawn + // of it (`drawFlood`). + let _floodShow = false; + let _surgeShow = false; + let _surgePosition = null; + let _floodDrawn = null; let _terrainPositions = []; let _sourceShotPaths = new Map(); let _scenePathPositionCache = new Map(); @@ -1052,8 +1091,8 @@ export function createBhoteKoshiEventLayer({ let _cinematicKeyframes = []; let _cinematicActive = false; let _cinematicReplayArmed = false; - let _cinematicPose = { target: new Cesium.Cartesian3() }; - let _cinematicOffset = new Cesium.HeadingPitchRange(); + let _cinematicPose = { target: vec() }; + const _cinematicOffset = { heading: 0, pitch: 0, range: 0 }; let _lastCinematicProgress = null; let _cameraInputTarget = null; let _evidenceClickTarget = null; @@ -1068,7 +1107,6 @@ export function createBhoteKoshiEventLayer({ let _comparisonLease = null; let _introTimer = null; let _introGeneration = 0; - let _lastSurgePosition = null; let _lastSurgeVisible = null; let _presentation = 'standalone'; let _sceneBeatId = null; @@ -1154,33 +1192,52 @@ export function createBhoteKoshiEventLayer({ } async function createImagery(event) { - const rectangle = Cesium.Rectangle.fromDegrees( - event.imagery.rectangle.west, - event.imagery.rectangle.south, - event.imagery.rectangle.east, - event.imagery.rectangle.north, - ); - const [beforeProvider, afterProvider] = await Promise.all([ - imageryProviderFactory(eventAsset(event.imagery.before.path), { - rectangle, - credit: 'Vantor WorldView Open Data · CC BY-NC 4.0', - }), - imageryProviderFactory(eventAsset(event.imagery.after.path), { - rectangle, - credit: 'Vantor WorldView Open Data · CC BY-NC 4.0', - }), + _imageryFailed = false; + const { west, south, east, north } = event.imagery.rectangle; + const options = { + rectangle: { west, south, east, north }, + credit: IMAGERY_CREDIT, + }; + const [beforeSpec, afterSpec] = await Promise.all([ + imagerySpecFactory(eventAsset(event.imagery.before.path), options), + imagerySpecFactory(eventAsset(event.imagery.after.path), options), ]); if (!_enabled) return; - _imageryLayerCollection = _viewer.imageryLayers; - _beforeLayer = _imageryLayerCollection.addImageryProvider(beforeProvider); - _afterLayer = _imageryLayerCollection.addImageryProvider(afterProvider); - _beforeLayer.splitDirection = Cesium.SplitDirection.LEFT; - _afterLayer.splitDirection = Cesium.SplitDirection.RIGHT; - _beforeLayer.alpha = 0.96; - _afterLayer.alpha = 0.96; + const globe = findGlobe(_viewer); + if (!globe) + throw new Error('Bhote Koshi imagery needs a globe to drape on'); + _beforeLayer = addEventImagery(globe, beforeSpec, 'left'); + _afterLayer = addEventImagery(globe, afterSpec, 'right'); setSplit(_split); } + /** + * One of the before/after images, on its side of the split, over every + * layer drawn so far. It drapes on the globe's surface only, as the + * comparison is drawn on terrain. + */ + function addEventImagery(globe, spec, split) { + const layer = globe.imagery.add(spec, globe.imagery.list().length); + layer.split = split; + layer.alpha = 0.96; + layer.drapeOn = 'surface'; + layer.on('tileError', (error) => imageryFailed(error)); + return layer; + } + + /** + * An image that did not load: without both images there is nothing to + * compare, so the pair and the comparison's divider and labels go. + */ + function imageryFailed(error) { + if (_imageryFailed) return; + _imageryFailed = true; + console.warn('[Data:BhoteKoshi] Event imagery unavailable:', error); + removeImagery(); + syncPresentationMode(); + renderHost.request('bhote-koshi-imagery-failed'); + } + async function resolveEvidenceAnchors(event, signal) { const observations = Array.isArray(event.evidenceSpine) ? event.evidenceSpine @@ -1197,9 +1254,10 @@ export function createBhoteKoshiEventLayer({ } throwIfEnableCancelled(signal, _enabled); return observations.map((observation, index) => { - const sampledHeight = Number(sampled?.[index]?.height); + // A miss is null or undefined, never sea level. + const sampledHeight = Number(sampled?.[index]?.height ?? Number.NaN); const fallbackHeight = Number(observation.fallbackElevationM) || 0; - return Cesium.Cartesian3.fromDegrees( + return fromDegrees( observation.lon, observation.lat, (Number.isFinite(sampledHeight) ? sampledHeight : fallbackHeight) + 18, @@ -1240,7 +1298,7 @@ export function createBhoteKoshiEventLayer({ function showWitnessEmbed() { const witness = _event?.witnessAnchors?.[0]; if (!witness?.sourceUrl) return false; - const anchor = Cesium.Cartesian3.fromDegrees( + const anchor = fromDegrees( witness.lon, witness.lat, (Number(witness.elevationM) || 0) + 18, @@ -1566,24 +1624,21 @@ export function createBhoteKoshiEventLayer({ const cached = _scenePathPositionCache.get(cacheKey); if (cached) return cached; const positions = (_sourceShotPaths.get(beatId) || []).map((point) => { - const position = Cesium.Cartographic.fromDegrees(point.lon, point.lat); + const position = { lon: point.lon, lat: point.lat }; let height; // Some schematic reaches have a source elevation profile. Do not replace // it with coarse mesh heights on entry/exit from the comparison surface: // a single high sample can make the front dive backward in screen space. if (_sceneControls.evidencePathElevation !== 'source') { // Sample once while preparing the shot, never from an animation frame. - try { - height = _viewer?.scene?.sampleHeight?.( - position, - [_floodCore, _floodHalo, _surgePoint].filter(Boolean), - ); - } catch {} + // The flood's own sets are not ground: queries see through them. + const heights = _viewer ? heightsOf(_viewer) : null; + height = heights?.now(position); if (!Number.isFinite(height)) - height = _viewer?.scene?.globe?.getHeight?.(position); + height = heights?.now(position, { against: 'terrain' }); } if (!Number.isFinite(height)) height = point.fallbackElevationM; - return Cesium.Cartesian3.fromDegrees(point.lon, point.lat, height + 8); + return fromDegrees(point.lon, point.lat, height + 8); }); _scenePathPositionCache.set(cacheKey, positions); return positions; @@ -2480,11 +2535,7 @@ export function createBhoteKoshiEventLayer({ const elevationOffsetM = _presentation === BHOTE_KOSHI_SCENE_PRESENTATION ? 55 : 8; _terrainPositions = event.reconstruction.corridor.map((point) => - Cesium.Cartesian3.fromDegrees( - point.lon, - point.lat, - point.elevationM + elevationOffsetM, - ), + fromDegrees(point.lon, point.lat, point.elevationM + elevationOffsetM), ); prepareScenePath(); _evidenceTimeline = buildEvidenceTimeline( @@ -2522,86 +2573,144 @@ export function createBhoteKoshiEventLayer({ updateProgress(_progress); } - function createFloodDataSource() { - const tileSafe = usesPhotorealFloodSurface(); - _floodSurfaceMode = tileSafe ? 'tiles' : 'terrain'; - const haloMaterial = new Cesium.PolylineDashMaterialProperty({ - color: FLOOD_COLOR.withAlpha(0.38), - dashLength: 18, - }); - const coreMaterial = new Cesium.PolylineGlowMaterialProperty({ - color: FLOOD_COLOR.withAlpha(0.96), - glowPower: 0.24, - taperPower: 0.7, - }); - _floodDataSource = new Cesium.CustomDataSource('bhote-koshi-flood'); - _floodHalo = _floodDataSource.entities.add({ - id: 'bhote-koshi-flood-halo', + /** The flood's draw sets, drawing nothing until the event shows it. */ + function createFloodSets() { + _floodSurfaceMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain'; + const draw = drawOf(_viewer); + const prefix = `${BHOTE_KOSHI_LAYER_ID}:${_serial}`; + // Presentation only: clicks go through to what is under them. + _floodSets = { + lines: draw.lines({ id: `${prefix}:flood`, pickable: false }), + surge: draw.points({ + id: `${prefix}:surge-front`, + pickable: false, + clampTo: 'both', + }), + }; + resetFloodDrawn(); + } + + function resetFloodDrawn() { + _floodShow = false; + _surgeShow = false; + _surgePosition = null; + _lastSurgeVisible = null; + _floodDrawn = { + positions: null, show: false, - polyline: { - positions: new Cesium.CallbackProperty( - () => _corridorPositionCache.positions, - false, - ), - width: 18, - // Dynamic non-ground Cesium lines do not support depthFailMaterial. - // Classify the active surface so later-refined mesh tiles cannot bury it. - clampToGround: true, - material: haloMaterial, - classificationType: tileSafe - ? Cesium.ClassificationType.BOTH - : Cesium.ClassificationType.TERRAIN, + surge: null, + surgeShow: false, + }; + } + + function removeFloodSets() { + _floodSets?.lines.dispose(); + _floodSets?.surge.dispose(); + _floodSets = null; + _floodSurfaceMode = null; + resetFloodDrawn(); + } + + /** + * The corridor's lines along `positions`: a dashed halo under a glowing + * core, draped on the surface the flood is drawn on (tiles too under + * photoreal, so later-refined tiles cannot bury it). + */ + function floodLines(positions, show) { + const clampTo = _floodSurfaceMode === 'tiles' ? 'both' : 'terrain'; + return [ + { + id: FLOOD_HALO_ID, + positions, + widthPx: 18, + mode: 'draped', + clampTo, + style: { kind: 'dash', color: FLOOD_HALO_COLOR, length: 18 }, + show, }, - }); - _floodCore = _floodDataSource.entities.add({ - id: 'bhote-koshi-flood-core', - show: false, - polyline: { - positions: new Cesium.CallbackProperty( - () => _corridorPositionCache.positions, - false, - ), - width: 5, - clampToGround: true, - material: coreMaterial, - classificationType: tileSafe - ? Cesium.ClassificationType.BOTH - : Cesium.ClassificationType.TERRAIN, + { + id: FLOOD_CORE_ID, + positions, + widthPx: 5, + mode: 'draped', + clampTo, + style: { + kind: 'glow', + color: FLOOD_CORE_COLOR, + power: 0.24, + taper: 0.7, + }, + show, }, - }); - _surgePoint = _floodDataSource.entities.add({ - id: 'bhote-koshi-surge-front', - show: false, - position: Cesium.Cartesian3.ZERO, - point: { - pixelSize: 11, - color: SURGE_COLOR, - outlineColor: Cesium.Color.BLACK.withAlpha(0.85), - outlineWidth: 3, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - disableDepthTestDistance: tileSafe ? Number.POSITIVE_INFINITY : 0, - }, - }); - _viewer.dataSources.add(_floodDataSource); + ]; + } + + function surgeItem(position, show) { + return { + id: SURGE_FRONT_ID, + pos: position, + height: 'clampGround', + pixelSize: 11, + color: SURGE_COLOR, + outlineColor: SURGE_OUTLINE_COLOR, + outlineWidth: 3, + disableDepthTest: + _floodSurfaceMode === 'tiles' ? Number.POSITIVE_INFINITY : 0, + show, + }; + } + + /** + * Draw the flood as it now stands, changing only what changed: the + * corridor where it has grown to and whether it shows, and the surge + * front's place and whether it shows. + */ + function drawFlood() { + if (!_floodSets) return; + const drawn = _floodDrawn; + const positions = _corridorPositionCache.positions; + if (positions.length > 1) { + if (positions !== drawn.positions || _floodShow !== drawn.show) { + _floodSets.lines.upsert(floodLines(positions, _floodShow)); + drawn.positions = positions; + drawn.show = _floodShow; + } + } else if (drawn.show) { + // Too short to be a line: the last one drawn hides, kept so the next + // can still be drawn where it moves in the same frame. + _floodSets.lines.upsert(floodLines(drawn.positions, false)); + drawn.show = false; + } + if ( + _surgePosition && + (!samePoint(_surgePosition, drawn.surge) || + _surgeShow !== drawn.surgeShow) + ) { + drawn.surge = _surgePosition; + drawn.surgeShow = _surgeShow; + _floodSets.surge.upsert([surgeItem(drawn.surge, _surgeShow)]); + } } function syncFloodSurfaceMode() { const nextMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain'; - if (!_viewer || !_floodDataSource || _floodSurfaceMode === nextMode) return; - _viewer.dataSources.remove(_floodDataSource, true); - _floodDataSource = null; - _floodHalo = null; - _floodCore = null; - _surgePoint = null; - _lastSurgePosition = null; - _lastSurgeVisible = null; + if (!_viewer || !_floodSets || _floodSurfaceMode === nextMode) return; + // Drawn anew on the other surface as the event next moves on. + removeFloodSets(); _corridorPositionCache = { visibleCount: -1, positions: [] }; - createFloodDataSource(); + createFloodSets(); + } + + /** The canvas the scene is drawn on, for its pointer events. */ + function sceneCanvas() { + if (!_viewer) return null; + return canvasOf(_viewer); } function createSplitControl(event) { _splitControl = createImagerySplit({ - scene: _viewer.scene, + // The split as the divider moves it: the globe's, through its port. + scene: globeSplitTarget(findGlobe(_viewer)), initialValue: _split, id: 'bhote-koshi-split-line', handleClass: 'bhote-koshi-split-handle', @@ -2621,7 +2730,7 @@ export function createBhoteKoshiEventLayer({ function applyCinematicCamera() { if ( !_cinematicActive || - !_viewer?.camera || + !findCamera(_viewer) || _cinematicKeyframes.length === 0 ) return; @@ -2632,10 +2741,10 @@ export function createBhoteKoshiEventLayer({ _cinematicPose, ); if (!pose) return; - _cinematicOffset.heading = Cesium.Math.toRadians(pose.headingDeg); - _cinematicOffset.pitch = Cesium.Math.toRadians(pose.pitchDeg); + _cinematicOffset.heading = toRadians(pose.headingDeg); + _cinematicOffset.pitch = toRadians(pose.pitchDeg); _cinematicOffset.range = pose.rangeM; - _viewer.camera.lookAt(pose.target, _cinematicOffset); + findCamera(_viewer)?.lookAt(pose.target, _cinematicOffset); _lastCinematicProgress = _progress; } @@ -2705,7 +2814,7 @@ export function createBhoteKoshiEventLayer({ _cinematicActive = true; _lastCinematicProgress = null; announceNavigationAuthority('bhote-koshi-cinematic'); - _viewer?.camera?.cancelFlight?.(); + findCamera(_viewer)?.cancelFlight(); } syncCinematicButton(); return true; @@ -2722,8 +2831,7 @@ export function createBhoteKoshiEventLayer({ } _cinematicActive = false; _lastCinematicProgress = null; - if (releaseCamera) - _viewer?.camera?.lookAtTransform?.(Cesium.Matrix4.IDENTITY); + if (releaseCamera) findCamera(_viewer)?.release(); syncCinematicButton(); renderHost.request('bhote-koshi-cinematic-stop'); } @@ -2757,7 +2865,7 @@ export function createBhoteKoshiEventLayer({ } function attachCameraInputRelease() { - _cameraInputTarget = _viewer?.scene?.canvas || null; + _cameraInputTarget = sceneCanvas(); for (const type of CINEMATIC_INPUT_EVENTS) { _cameraInputTarget?.addEventListener?.(type, handleManualCameraInput); } @@ -2803,7 +2911,7 @@ export function createBhoteKoshiEventLayer({ } function attachEvidenceCardActivation() { - _evidenceClickTarget = _viewer?.scene?.canvas || null; + _evidenceClickTarget = sceneCanvas(); _evidenceClickTarget?.addEventListener?.('click', handleEvidenceCardClick); } @@ -3252,7 +3360,8 @@ export function createBhoteKoshiEventLayer({ function syncPresentationMode() { const sceneDirected = _presentation === BHOTE_KOSHI_SCENE_PRESENTATION; const imageryAvailable = - !sceneDirected || _sceneControls.imageryComparison === true; + !_imageryFailed && + (!sceneDirected || _sceneControls.imageryComparison === true); const scrubberAvailable = !sceneDirected || Boolean(_sceneController?.seekScene); const knownSceneBeat = @@ -3302,13 +3411,13 @@ export function createBhoteKoshiEventLayer({ } function updateFloodTrace(progress) { - if (!_floodHalo || !_floodCore) return; + if (!_floodSets) return; if ( _presentation === BHOTE_KOSHI_SCENE_PRESENTATION && _sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT ) { - _floodHalo.show = false; - _floodCore.show = false; + _floodShow = false; + drawFlood(); return; } if ( @@ -3319,31 +3428,24 @@ export function createBhoteKoshiEventLayer({ ) ) return; - const positions = _corridorPositionCache.positions; - _floodHalo.show = positions.length > 1; - _floodCore.show = positions.length > 1; + _floodShow = _corridorPositionCache.positions.length > 1; + drawFlood(); } function updateSurgeFront(progress) { - if (!_surgePoint) return; + if (!_floodSets) return; if ( _presentation === BHOTE_KOSHI_SCENE_PRESENTATION && _sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT ) { - _surgePoint.show = false; + _surgeShow = false; + drawFlood(); return; } const headPosition = _corridorPositionCache.headPosition; - if ( - headPosition && - !Cesium.Cartesian3.equals(_lastSurgePosition, headPosition) - ) { - _surgePoint.position = headPosition; - _lastSurgePosition = Cesium.Cartesian3.clone( - headPosition, - _lastSurgePosition || new Cesium.Cartesian3(), - ); - } + // A copy, as the cache's head is written in place as the flood moves. + if (headPosition && !samePoint(_surgePosition, headPosition)) + _surgePosition = clone(headPosition); const visible = Boolean(headPosition) && progress > 0 && @@ -3352,9 +3454,10 @@ export function createBhoteKoshiEventLayer({ sceneKeepsFloodVisible() || progress < 1); if (_lastSurgeVisible !== visible) { - _surgePoint.show = visible; + _surgeShow = visible; _lastSurgeVisible = visible; } + drawFlood(); } function updateProgress(progress) { @@ -3455,11 +3558,10 @@ export function createBhoteKoshiEventLayer({ } function removeImagery() { - if (_beforeLayer) _imageryLayerCollection?.remove(_beforeLayer, true); - if (_afterLayer) _imageryLayerCollection?.remove(_afterLayer, true); + _beforeLayer?.remove(); + _afterLayer?.remove(); _beforeLayer = null; _afterLayer = null; - _imageryLayerCollection = null; } async function init(viewer) { @@ -3493,7 +3595,7 @@ export function createBhoteKoshiEventLayer({ throwIfEnableCancelled(signal, _enabled); await syncTerrainComparison(); throwIfEnableCancelled(signal, _enabled); - createFloodDataSource(); + createFloodSets(); createSplitControl(event); _panelRefs = createPanelRecords(event); _panelOwner = {}; @@ -3618,14 +3720,7 @@ export function createBhoteKoshiEventLayer({ closeFrame(slot.poster); } _evidenceFrameSlots = []; - if (_floodDataSource) _viewer.dataSources.remove(_floodDataSource, true); - _floodDataSource = null; - _floodSurfaceMode = null; - _floodHalo = null; - _floodCore = null; - _surgePoint = null; - _lastSurgePosition = null; - _lastSurgeVisible = null; + removeFloodSets(); if (_panelOwner && panelStore.panel?.owner === _panelOwner) { panelStore.connect(null); panelStore.publish(null); diff --git a/src/data/bhoteKoshiEvent.test.mjs b/src/data/bhoteKoshiEvent.test.mjs index 51e5f11f58..509147e152 100644 --- a/src/data/bhoteKoshiEvent.test.mjs +++ b/src/data/bhoteKoshiEvent.test.mjs @@ -1,3 +1,6 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs'; import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import test from 'node:test'; @@ -231,16 +234,27 @@ function installEventDom() { return { body, removedProperties }; } -function eventViewer(splitPosition = 0.37) { - const imagery = []; - const removedImagery = []; - const dataSources = []; - const removedDataSources = []; +/** + * A viewer with fake draw and globe ports bound, under the Cesium camera + * port over a fake camera. `_test` reads what the event draws: its imagery + * layers (`imagery`, `removedImagery`), its flood sets (`floodSets`, live + * or not) and a flood item by id (`flood`); `scene.splitPosition` is the + * globe's split. + */ +function eventViewer(splitPosition = 0.37, ports = {}) { + const draw = fakeDrawPort(); + const globe = fakeGlobePort(); + globe.imagery.setSplit(splitPosition); const canvas = new FakeElement('canvas'); const cameraLooks = []; const cameraTransforms = []; - return { - scene: { splitPosition, canvas }, + const floodSets = () => [...draw.sets.values()].filter(({ spec }) => spec.id.startsWith(`${BHOTE_KOSHI_LAYER_ID}:`)); + const liveFloodSets = () => floodSets().filter((set) => !set.disposed); + const viewer = { + scene: { + get splitPosition() { return globe.imagery.getSplit(); }, + canvas, + }, camera: { cancelFlight() {}, lookAt(target, offset) { @@ -251,28 +265,38 @@ function eventViewer(splitPosition = 0.37) { }, lookAtTransform(transform) { cameraTransforms.push(transform); }, }, - imageryLayers: { - addImageryProvider(provider) { - const layer = { provider }; - imagery.push(layer); - return layer; - }, - remove(layer) { removedImagery.push(layer); }, - }, - dataSources: { - add(source) { dataSources.push(source); }, - remove(source) { removedDataSources.push(source); }, - }, _test: { - imagery, - removedImagery, - dataSources, - removedDataSources, + draw, + globe, + imagery: globe.added, + get removedImagery() { return globe.added.filter((layer) => layer.removed); }, + floodSets, + liveFloodSets, + /** The live flood item with this id, or undefined. */ + flood(id) { + for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id); + return undefined; + }, + /** Reads the flood item with this id as it is drawn now: whether it shows, its positions or position. */ + floodView(id) { + const view = viewer._test; + return { + get show() { return view.floodShows(id); }, + get positions() { return view.flood(id)?.positions; }, + get position() { return view.flood(id)?.pos; }, + }; + }, + /** Whether the flood item with this id is drawn showing. */ + floodShows(id) { + for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id).show !== false; + return false; + }, canvas, cameraLooks, cameraTransforms, }, }; + return bindFakeCesiumCamera(viewer, { draw, globe, ...ports }); } test('public lifecycle restores Nepal scene ownership without forwarding origin to enable', async () => { @@ -293,7 +317,7 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin const mapCalls = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })), mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -316,16 +340,11 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin assert.equal(layer.getPlaybackState().enabled, true); assert.deepEqual(mapCalls, [], `${initialMap}/${origin}: preserve the shot map`); assert.equal(activeMap, initialMap); - const floodSource = viewer._test.dataSources.at(-1); - for (const id of ['bhote-koshi-flood-halo', 'bhote-koshi-flood-core']) { - const line = floodSource.entities.getById(id).polyline; - assert.equal(line.clampToGround.getValue(), true, 'dynamic trail follows the rendered surface'); - assert.equal(line.classificationType.getValue(), initialMap === 'photoreal' - ? Cesium.ClassificationType.BOTH : Cesium.ClassificationType.TERRAIN); - assert.equal(line.depthFailMaterial, undefined, 'do not rely on unsupported dynamic depth-fail rendering'); - } - assert.equal(floodSource.entities.getById('bhote-koshi-surge-front').point.heightReference.getValue(), - Cesium.HeightReference.CLAMP_TO_GROUND); + const floodSets = viewer._test.liveFloodSets(); + assert.deepEqual(floodSets.map(({ kind }) => kind), ['lines', 'points']); + assert.ok(floodSets.every(({ spec }) => spec.pickable === false)); + assert.equal(floodSets[1].spec.clampTo, 'both', 'the surge front clamps to the ground'); + assert.ok(floodSets.every(({ items }) => items.size === 0), 'a panel-only shot draws no flood'); assert.deepEqual(viewer._test.cameraLooks, [], 'enable must not focus the corridor'); assert.deepEqual(timers, [], 'enable must not schedule independent playback'); assert.equal(layer.getPlaybackState().playing, false); @@ -355,7 +374,7 @@ test('trimmed scene media holds through provider startup, playback and fade, the const event = JSON.parse(await readFile(eventUrl, 'utf8')); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })), mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -403,7 +422,7 @@ test('Pinokio source-card fallback selects authored Director dwell, not an impos const event = JSON.parse(await readFile(eventUrl, 'utf8')); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async url => ({ url }), + imagerySpecFactory: async url => ({ url }), terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })), mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -448,7 +467,7 @@ test('saved autoplay controls cannot authorize media; live shot ownership is can const event = JSON.parse(await readFile(eventUrl, 'utf8')); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async url => ({ url }), + imagerySpecFactory: async url => ({ url }), terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })), mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -838,12 +857,10 @@ test('Bhote Koshi failed direct enable restores the prior map and shared split', let generation = 7; const viewer = { scene: { splitPosition: 0.37 }, - imageryLayers: { remove() {} }, - dataSources: { remove() {} }, }; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async () => { throw new Error('fixture image failure'); }, + imagerySpecFactory: async () => { throw new Error('fixture image failure'); }, overlayHost: { setEntries() {}, setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); }, @@ -946,7 +963,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever const renderCalls = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), overlayHost: { setEntries() {}, setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); }, @@ -971,7 +988,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever try { assert.equal(await layer.enable(viewer, { origin: 'scene' }), true); assert.equal(viewer._test.imagery.length, 2); - assert.equal(viewer._test.dataSources.length, 1); + assert.equal(viewer._test.floodSets().length, 2); assert.ok(eventPanel()); assert.ok(eventSplit()); @@ -981,7 +998,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever assert.deepEqual(mapCalls, ['esri-imagery']); assert.equal(viewer._test.removedImagery.length, 2); - assert.equal(viewer._test.removedDataSources.length, 1); + assert.equal(viewer._test.liveFloodSets().length, 0, 'its flood sets let go'); assert.equal(eventPanel(), undefined); assert.equal(eventSplit(), undefined); assert.equal(viewer.scene.splitPosition, 0.37); @@ -1013,7 +1030,7 @@ test('Bhote Koshi disable stops active playback and releases its global render h const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, renderHost: { request() {}, @@ -1071,7 +1088,7 @@ test('Bhote Koshi passive restores do not start off-screen playback', async () = const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }), overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, renderHost: { request() {}, hold() {}, release() {} }, @@ -1120,7 +1137,7 @@ test('Bhote Koshi standalone Scene keeps its Esri cinematic contract', async () const mapCalls = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1195,7 +1212,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership const overlayVisibility = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1375,7 +1392,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership 'bhote-koshi-flood-core', 'bhote-koshi-surge-front', ]) { - assert.equal(viewer._test.dataSources[0].entities.getById(id).show, false); + assert.equal(viewer._test.floodShows(id), false); } panel.querySelector('[data-action="play"]').dispatch('click'); await Promise.resolve(); @@ -1464,9 +1481,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership assert.ok(entries .filter((entry) => entry.id.startsWith('evidence-breadcrumb-')) .every((entry) => entry.position() == null)); - assert.equal(viewer._test.dataSources.filter((source) => ( - !viewer._test.removedDataSources.includes(source) - )).length, 1, 'surface transitions leave exactly one active event surface'); + assert.equal(viewer._test.liveFloodSets().length, 2, 'surface transitions leave exactly one active event surface'); assert.equal(viewer._test.cameraLooks.length, 0, 'consecutive beats never write the camera'); } panel.querySelector('[data-action="open-source"]').dispatch('click'); @@ -1485,7 +1500,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership 'disable revokes the pending real-time scene-clock scrub frame', ); assert.deepEqual(mapCalls, []); - assert.equal(viewer._test.removedDataSources.length, viewer._test.dataSources.length); + assert.equal(viewer._test.liveFloodSets().length, 0); } finally { globalThis.document = originalDocument; globalThis.window = originalWindow; @@ -1506,7 +1521,7 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t const comparisonCalls = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1540,17 +1555,17 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t assert.equal(viewer._test.imagery.length, 2); assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === true)); assert.equal(viewer.scene.splitPosition, 0.5); - assert.equal(viewer._test.imagery[0].splitDirection, Cesium.SplitDirection.LEFT); - assert.equal(viewer._test.imagery[1].splitDirection, Cesium.SplitDirection.RIGHT); + assert.equal(viewer._test.imagery[0].split, 'left'); + assert.equal(viewer._test.imagery[1].split, 'right'); + assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.alpha === 0.96 && imageryLayer.drapeOn === 'surface')); layer.setParams({ split: 0.25 }); assert.equal(viewer.scene.splitPosition, 0.25); - const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core'); - const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front'); - assert.equal(flood.polyline.clampToGround.getValue(), true); - assert.equal( - surge.point.heightReference.getValue(), - Cesium.HeightReference.CLAMP_TO_GROUND, - ); + const flood = viewer._test.flood('bhote-koshi-flood-core'); + const surge = viewer._test.flood('bhote-koshi-surge-front'); + assert.equal(flood.mode, 'draped'); + assert.equal(flood.clampTo, 'terrain', 'the comparison surface is terrain'); + assert.equal(surge.height, 'clampGround'); + assert.equal(surge.disableDepthTest, 0); layer.setParams({ presentation: 'scene-beat', @@ -1561,9 +1576,12 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === false)); assert.equal(comparisonCalls.at(-1), null); - const tileFlood = viewer._test.dataSources.at(-1).entities.getById('bhote-koshi-flood-core'); - assert.equal(tileFlood.polyline.clampToGround.getValue(), true); - assert.equal(tileFlood.polyline.classificationType.getValue(), Cesium.ClassificationType.BOTH); + assert.equal(viewer._test.flood('bhote-koshi-flood-core'), undefined, 'drawn anew on the tiles as the event plays'); + layer.setParams({ progress: 0.6 }, { origin: 'scene' }); + const tileFlood = viewer._test.flood('bhote-koshi-flood-core'); + assert.equal(tileFlood.mode, 'draped'); + assert.equal(tileFlood.clampTo, 'both', 'photoreal drapes it on tiles too'); + assert.equal(viewer._test.flood('bhote-koshi-surge-front').disableDepthTest, Number.POSITIVE_INFINITY); await layer.disable(); assert.equal(viewer._test.removedImagery.length, 2); @@ -1650,7 +1668,7 @@ test('Bhote Koshi publishes the evidence spine once and scrubs through cards and const publications = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1747,7 +1765,7 @@ test('Bhote Koshi keeps one local fallback video active and unloads it on beat c }; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1848,7 +1866,7 @@ test('Upper Valley Collapse autoplays its muted local fallback without starting }; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -1924,7 +1942,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v let activeCard = null; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2015,7 +2033,7 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from const releases = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2073,8 +2091,8 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from layer.setSceneMediaPlayback({ sceneId: 'scene', shotId: 'shot', token: { cancelled: false } }); await layer.enable(viewer, { origin: 'scene' }); const card = entries.find(({ id }) => id === 'evidence-card-gyirong-border-gate'); - const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core'); - const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front'); + const flood = viewer._test.floodView('bhote-koshi-flood-core'); + const surge = viewer._test.floodView('bhote-koshi-surge-front'); assert.equal(card.position(), null, 'the evidence card is absent during the camera flight'); assert.equal(flood.show, false); assert.equal(surge.show, false); @@ -2186,7 +2204,7 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one const publications = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2239,8 +2257,8 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one panel.querySelector('[data-role="beat-meta"]').textContent, 'PROPAGATION / TIME UNVERIFIED / 5 SOURCES', ); - const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core'); - assert.ok(flood.polyline.positions.getValue().length > 1); + const flood = viewer._test.floodView('bhote-koshi-flood-core'); + assert.ok(flood.positions.length > 1); assert.equal( body.children.some((element) => element.id === 'bhote-koshi-story-strap'), false, @@ -2306,7 +2324,7 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera', const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2336,7 +2354,10 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera', const panelStore = useBhoteKoshiPanelStore(applicationPinia()); const published = panelStore.panel; const cameraLookCount = viewer._test.cameraLooks.length; + const floodWrites = () => viewer._test.liveFloodSets().map(({ writes }) => writes); + const drawnWrites = floodWrites(); for (let index = 0; index < 20; index += 1) progress.dispatch('input'); + assert.deepEqual(floodWrites(), drawnWrites, 'unchanged frames draw no flood again'); assert.ok(panelStore.panel === published, 'unchanged frames do not republish the panel'); assert.equal( @@ -2389,7 +2410,7 @@ test('Bhote Koshi cinematic camera stays synchronized through pause and determin const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2470,7 +2491,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async (_viewer, observations) => ( observations.map((observation) => ({ height: observation.fallbackElevationM })) ), @@ -2552,7 +2573,7 @@ test('Bhote Koshi closes a poster that resolves after disable', async () => { const poster = { closed: false, close() { this.closed = true; } }; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async () => [{ height: 2800 }], mediaLoader: async (url) => { assert.equal(url, '/events/bhote-koshi-2026/evidence-09.jpg'); @@ -2592,13 +2613,15 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c globalThis.performance = { now: () => now }; globalThis.requestAnimationFrame = (callback) => { frames.set(++nextFrame, callback); return nextFrame; }; globalThis.cancelAnimationFrame = (id) => frames.delete(id); - const viewer = eventViewer(); let heightSamples = 0; - viewer.scene.sampleHeight = () => { heightSamples++; return 1500; }; + let surfaceHeight = 1500; + const viewer = eventViewer(0.37, { + query: { sampleHeightNow: () => { heightSamples++; return surfaceHeight; } }, + }); let entries = []; const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async () => null, mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); }, overlayHost: { setEntries(_id, value) { entries = value; }, setVisible() {}, clearSource() {} }, @@ -2618,23 +2641,23 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c try { layer.setParams(params(SOURCE_PATH_BEAT_IDS[0], false)); await layer.enable(viewer, { origin: 'scene' }); - const source = viewer._test.dataSources.at(-1); - const flood = source.entities.getById('bhote-koshi-flood-core'); - const surge = source.entities.getById('bhote-koshi-surge-front'); + const flood = viewer._test.floodView('bhote-koshi-flood-core'); + const surge = viewer._test.floodView('bhote-koshi-surge-front'); for (const id of SOURCE_PATH_BEAT_IDS) { layer.setParams(params(id, false)); assert.equal(flood.show, false, `${id}: hide the previous route during flight`); assert.equal(surge.show, false); layer.setParams(params(id, true)); const sampleCount = heightSamples; + assert.ok(sampleCount > 0, 'surface heights are sampled while preparing the shot'); let previousLength = 0; for (const elapsed of [400, 1800, 4000]) { advance(elapsed); - const points = flood.polyline.positions.getValue(); + const points = flood.positions; assert.ok(points.length >= previousLength); assert.equal(flood.show, true); assert.equal(surge.show, true); - assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue()), `${id}: tail must reach head in every frame`); + assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position), `${id}: tail must reach head in every frame`); previousLength = points.length; } assert.equal(heightSamples, sampleCount, 'do not resample geometry during motion'); @@ -2649,28 +2672,27 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c assert.equal(flood.show, false, 'new shot clears its tail before the first animation frame'); assert.equal(surge.show, false); advance(1800); - const headBeforeSync = Cesium.Cartesian3.clone(surge.position.getValue()); + const headBeforeSync = Cesium.Cartesian3.clone(surge.position); const frameBeforeSync = nextFrame; layer.setParams(params('dhunche', true)); assert.equal(nextFrame, frameBeforeSync, 'repeated settled notification does not restart the reveal'); - assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue())); + assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position)); advance(2200); - assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue())); + assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position)); // The comparison exit can expose coarse photogrammetry samples a kilometre // above the river. Dhunche's schematic profile must not dive through them. - viewer.scene.sampleHeight = () => { heightSamples++; return 2703; }; - viewer.scene.globe = { getHeight: () => 0 }; + surfaceHeight = 2703; layer.setParams(params('dhunche', false, 'source', 'source')); const samplesBeforeProfile = heightSamples; layer.setParams(params('dhunche', true, 'source', 'source')); for (const elapsed of [40, 400, 1800, 4000]) { advance(elapsed); - const points = flood.polyline.positions.getValue(); + const points = flood.positions; for (const position of points) { const height = Cesium.Cartographic.fromCartesian(position).height; assert.ok(height >= 1307 && height <= 1332, `source profile stays near river elevation, got ${height}`); } - assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue())); + assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position)); } assert.equal(heightSamples, samplesBeforeProfile, 'source elevation does not sample the changing mesh'); layer.setParams(params('charaudi', false, 'none')); @@ -2700,7 +2722,7 @@ test('media-led upper-valley shots retain only their upstream prefix during came const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async url => ({ url }), + imagerySpecFactory: async url => ({ url }), terrainSampler: async () => null, mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -2725,12 +2747,11 @@ test('media-led upper-valley shots retain only their upstream prefix during came try { layer.setParams(params('debris-dammed-lake', false)); await layer.enable(viewer, { origin: 'scene' }); - const source = viewer._test.dataSources.at(-1); - const flood = source.entities.getById('bhote-koshi-flood-core'); - const surge = source.entities.getById('bhote-koshi-surge-front'); + const flood = viewer._test.floodView('bhote-koshi-flood-core'); + const surge = viewer._test.floodView('bhote-koshi-surge-front'); layer.setParams(params('debris-dammed-lake', true)); finishReveal(); - const lakeTail = flood.polyline.positions.getValue().map(point => Cesium.Cartesian3.clone(point)); + const lakeTail = flood.positions.map(({ x, y, z }) => ({ x, y, z })); assert.ok(lakeTail.length > 1); const origin = Cesium.Cartographic.fromCartesian(lakeTail[0]); assert.ok(Math.abs(Cesium.Math.toDegrees(origin.longitude) - 85.48476) < 1e-6); @@ -2738,16 +2759,16 @@ test('media-led upper-valley shots retain only their upstream prefix during came 'the rendered trail starts at the lake reach, not the earlier trigger reach'); layer.setParams(params('second-landslide', false)); assert.equal(flood.show, true, 'lake trail survives departure before the next camera settles'); - assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'retain the prefix without revealing the next segment'); - assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), lakeTail.at(-1))); + assert.deepEqual(flood.positions, lakeTail, 'retain the prefix without revealing the next segment'); + assert.ok(Cesium.Cartesian3.equals(surge.position, lakeTail.at(-1))); layer.setParams(params('second-landslide', true)); - assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'arrival does not clear the prefix'); + assert.deepEqual(flood.positions, lakeTail, 'arrival does not clear the prefix'); finishReveal(); - assert.ok(flood.polyline.positions.getValue().length > lakeTail.length); + assert.ok(flood.positions.length > lakeTail.length); layer.setParams(params('debris-dammed-lake', false)); assert.equal(flood.show, false, 'backward replay trims future segments instead of retaining stale history'); layer.setParams(params('second-landslide', false)); - assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'direct load reconstructs the same prefix'); + assert.deepEqual(flood.positions, lakeTail, 'direct load reconstructs the same prefix'); layer.setParams(params('second-landslide', false, { evidencePathPersistent: false })); assert.equal(flood.show, false, 'nonpersistent shots retain their arrival gate'); for (const beatId of ['devighat-taadi-khola-bridge', 'charaudi', 'final-view']) { @@ -2756,13 +2777,13 @@ test('media-led upper-valley shots retain only their upstream prefix during came evidencePathDuringMedia: false, evidenceMediaAutoplay: beatId !== 'final-view', }; layer.setParams(params(beatId, false, historyControls)); - const completedTail = [...flood.polyline.positions.getValue()]; + const completedTail = [...flood.positions]; assert.ok(completedTail.length > 100, `${beatId}: direct load reconstructs full sourced history`); layer.setParams(params(beatId, true, historyControls)); - assert.deepEqual(flood.polyline.positions.getValue(), completedTail, + assert.deepEqual(flood.positions, completedTail, `${beatId}: arrival must not reset the completed history`); finishReveal(); - assert.deepEqual(flood.polyline.positions.getValue(), completedTail, + assert.deepEqual(flood.positions, completedTail, `${beatId}: media/card reveal must not erase or regrow completed history`); } await layer.disable(); @@ -2798,7 +2819,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot const viewer = eventViewer(); const layer = createBhoteKoshiEventLayer({ eventLoader: async () => event, - imageryProviderFactory: async (url) => ({ url }), + imagerySpecFactory: async (url) => ({ url }), terrainSampler: async () => null, mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, @@ -2840,44 +2861,42 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot evidenceSequence: true, })); await layer.enable(viewer, { origin: 'scene' }); - let source = viewer._test.dataSources.at(-1); - let flood = source.entities.getById('bhote-koshi-flood-core'); - let surge = source.entities.getById('bhote-koshi-surge-front'); - const timureStart = flood.polyline.positions.getValue().length; + let flood = viewer._test.floodView('bhote-koshi-flood-core'); + let surge = viewer._test.floodView('bhote-koshi-surge-front'); + const timureStart = flood.positions.length; assert.ok(timureStart > 1, 'the completed Border Gate prefix is already visible during travel'); assert.equal(surge.show, true); advance(420); - const earlyTimureLength = flood.polyline.positions.getValue().length; + const earlyTimureLength = flood.positions.length; assert.ok(earlyTimureLength > timureStart, 'the trail leads during the opening tenth of camera travel instead of waiting for arrival'); advance(2880); - const timureEnd = flood.polyline.positions.getValue().length; + const timureEnd = flood.positions.length; assert.ok(timureEnd > timureStart); assert.equal(flood.show, true, 'the completed tail remains visible at the next point'); - assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue())); + assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position)); layer.setParams(params('syabru-besi', 'comparison', travel(2), { evidenceSequence: true, })); - assert.ok(flood.polyline.positions.getValue().length >= timureEnd, + assert.ok(flood.positions.length >= timureEnd, 'the Timure segment remains painted when Syabru travel starts'); advance(3300); assert.equal(surge.show, true, 'the amber head remains visible at comparison completion'); - assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue())); + assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position)); layer.setParams(params('dhunche', 'source', travel(3), { evidencePathHistory: true, evidencePathElevation: 'source', evidenceHoldCard: true, })); - source = viewer._test.dataSources.at(-1); - flood = source.entities.getById('bhote-koshi-flood-core'); - surge = source.entities.getById('bhote-koshi-surge-front'); - const dhuncheStart = flood.polyline.positions.getValue().length; + flood = viewer._test.floodView('bhote-koshi-flood-core'); + surge = viewer._test.floodView('bhote-koshi-surge-front'); + const dhuncheStart = flood.positions.length; assert.ok(dhuncheStart >= event.reconstruction.corridor.length, 'the comparison corridor survives the transition onto Google photogrammetry'); advance(3300); - const dhuncheEnd = flood.polyline.positions.getValue().length; + const dhuncheEnd = flood.positions.length; assert.ok(dhuncheEnd > dhuncheStart); assert.equal(surge.show, true); @@ -2886,11 +2905,11 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot evidencePathElevation: 'source', evidenceHoldCard: true, })); - assert.ok(flood.polyline.positions.getValue().length >= dhuncheEnd, + assert.ok(flood.positions.length >= dhuncheEnd, 'the completed Dhunche segment never disappears'); advance(900); - const frozenHead = Cesium.Cartesian3.clone(surge.position.getValue()); - const frozenLength = flood.polyline.positions.getValue().length; + const frozenHead = Cesium.Cartesian3.clone(surge.position); + const frozenLength = flood.positions.length; layer.setParams(params('mailung-upper-trishuli', 'source', travel(4, 4.2, { active: false, cancelled: true, }), { @@ -2899,8 +2918,8 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot evidenceHoldCard: true, })); assert.equal(frames.size, 0, 'cancelling camera travel revokes the path animation frame'); - assert.equal(flood.polyline.positions.getValue().length, frozenLength); - assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), frozenHead)); + assert.equal(flood.positions.length, frozenLength); + assert.ok(Cesium.Cartesian3.equals(surge.position, frozenHead)); assert.ok(holds.includes('bhote-koshi-scene-path-travel')); assert.ok(releases.includes('bhote-koshi-scene-path-travel')); @@ -2912,16 +2931,16 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot evidencePathElevation: 'source', evidenceHoldCard: true, })); - const startLength = flood.polyline.positions.getValue().length; + const startLength = flood.positions.length; assert.ok(startLength >= previousCompleteLength, `${beatId} retains every completed upstream segment while travel begins`); advance(3300); - const completeLength = flood.polyline.positions.getValue().length; + const completeLength = flood.positions.length; assert.ok(completeLength > startLength, `${beatId} grows its own segment during travel`); assert.equal(flood.show, true); assert.equal(surge.show, true); assert.ok(Cesium.Cartesian3.equals( - flood.polyline.positions.getValue().at(-1), surge.position.getValue(), + flood.positions.at(-1), surge.position, )); previousCompleteLength = completeLength; } @@ -2940,20 +2959,20 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot evidencePathElevation: 'source', evidenceHoldCard: true, })); - assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd, + assert.ok(flood.positions.length > dhuncheEnd, 'a direct Bidur load reconstructs its complete upstream prefix'); advance(3300); - assert.equal(flood.polyline.positions.getValue().length, bidurCompleteLength); + assert.equal(flood.positions.length, bidurCompleteLength); layer.setParams(params('dhunche', 'source', travel(travelId++), { evidencePathHistory: true, evidencePathElevation: 'source', evidenceHoldCard: true, })); - assert.ok(flood.polyline.positions.getValue().length < bidurCompleteLength, + assert.ok(flood.positions.length < bidurCompleteLength, 'backward navigation trims unsupported downstream history immediately'); advance(3300); - assert.equal(flood.polyline.positions.getValue().length, dhuncheEnd); + assert.equal(flood.positions.length, dhuncheEnd); // The deadline is independent of RAF, so a throttled render loop still // completes the active segment before the camera's longer flight ends. @@ -2967,7 +2986,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot now += deadlineEntry[1].delay; deadlineEntry[1].callback(); assert.equal(frames.size, 0, 'the deadline cancels a stalled animation frame'); - assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd); + assert.ok(flood.positions.length > dhuncheEnd); layer.setParams({ presentation: 'scene-beat', sceneSurface: 'evidence-beat', beatId: 'charaudi', @@ -2992,3 +3011,140 @@ test('Bhote Koshi corridor remains ordered downstream and inside the imagery rec priorChainage = point.chainageM; } }); + +test('an evidence point whose terrain sample misses sits at its fallback elevation, not sea level', async () => { + const event = JSON.parse(await readFile(eventUrl, 'utf8')); + const originalDocument = globalThis.document; + const originalWindow = globalThis.window; + installEventDom(); + globalThis.window = { setTimeout: () => 71, clearTimeout() {} }; + const viewer = eventViewer(); + const publications = []; + const layer = createBhoteKoshiEventLayer({ + eventLoader: async () => event, + imagerySpecFactory: async (url) => ({ url }), + terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: null })), + mediaLoader: async () => { + const error = new Error('fixture media intentionally unavailable'); + error.name = 'AbortError'; + throw error; + }, + overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} }, + renderHost: { request() {}, hold() {}, release() {} }, + }); + try { + layer.setParams({ + presentation: 'scene-beat', + sceneSurface: 'evidence-beat', + beatId: 'gyirong-border-gate', + }, { origin: 'scene' }); + await layer.enable(viewer, { origin: 'scene' }); + const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate'); + const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM; + assert.ok(fallback > 100, 'the fixture has a real fallback elevation'); + const height = Cesium.Cartographic.fromCartesian(card.position()).height; + assert.ok(Math.abs(height - (fallback + 18)) < 1, `card at ${height} m`); + await layer.disable(); + } finally { + await layer.destroy(); + globalThis.document = originalDocument; + globalThis.window = originalWindow; + } +}); + +for (const [source, expected] of [['terrain', 'sampled'], ['ellipsoid', 'fallback']]) { + test(`the default terrain sampler places an evidence point at a ${source} answer's ${expected} height`, async () => { + const event = JSON.parse(await readFile(eventUrl, 'utf8')); + const originalDocument = globalThis.document; + const originalWindow = globalThis.window; + installEventDom(); + globalThis.window = { setTimeout: () => 71, clearTimeout() {} }; + const asked = []; + const query = { + async sampleHeight(points, options) { + asked.push(options); + return points.map(() => ({ height: 1234, source, confidence: 1, lod: 'finest' })); + }, + }; + const viewer = eventViewer(0.37, { query }); + const publications = []; + const layer = createBhoteKoshiEventLayer({ + eventLoader: async () => event, + imagerySpecFactory: async (url) => ({ url }), + mediaLoader: async () => { + const error = new Error('fixture media intentionally unavailable'); + error.name = 'AbortError'; + throw error; + }, + overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} }, + renderHost: { request() {}, hold() {}, release() {} }, + }); + try { + layer.setParams({ + presentation: 'scene-beat', + sceneSurface: 'evidence-beat', + beatId: 'gyirong-border-gate', + }, { origin: 'scene' }); + await layer.enable(viewer, { origin: 'scene' }); + assert.deepEqual(asked, [{ against: 'terrain', mostDetailed: true }]); + const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate'); + const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM; + const height = Cesium.Cartographic.fromCartesian(card.position()).height; + const want = (expected === 'sampled' ? 1234 : fallback) + 18; + assert.ok(Math.abs(height - want) < 1, `card at ${height} m, not ${want} m`); + await layer.disable(); + } finally { + await layer.destroy(); + globalThis.document = originalDocument; + globalThis.window = originalWindow; + } + }); +} + +test('an event image that fails to load takes the comparison down, not the event', async (t) => { + const event = JSON.parse(await readFile(eventUrl, 'utf8')); + const originalDocument = globalThis.document; + const originalWindow = globalThis.window; + installEventDom(); + globalThis.window = { setTimeout: () => 71, clearTimeout() {} }; + const warn = t.mock.method(console, 'warn', () => {}); + const viewer = eventViewer(); + const renders = []; + const layer = createBhoteKoshiEventLayer({ + eventLoader: async () => event, + embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }), + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + renderHost: { request(reason) { renders.push(reason); }, hold() {}, release() {} }, + }); + try { + layer.setParams({ progress: 0.4 }, { origin: 'local-restore' }); + assert.equal(await layer.enable(viewer), true); + const [before, after] = viewer._test.imagery; + assert.equal(before.spec.kind, 'single-image', 'the default spec is one image'); + assert.deepEqual(Object.keys(before.spec.rectangle).sort(), ['east', 'north', 'south', 'west']); + assert.equal(before.spec.credit.text, 'Vantor WorldView Open Data · CC BY-NC 4.0'); + assert.deepEqual(viewer._test.globe.layers, [before, after], 'the pair goes on top, before under after'); + assert.equal(eventSplit().view.hidden, false); + assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, false); + + after.fail({ tile: { x: 0, y: 0, level: 0 }, status: 404 }); + assert.ok(before.removed && after.removed, 'neither image is left to compare'); + assert.equal(eventSplit().view.hidden, true); + assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, true); + assert.equal(layer.getPlaybackState().enabled, true, 'the event itself stays on'); + assert.ok(renders.includes('bhote-koshi-imagery-failed')); + assert.equal(warn.mock.callCount(), 1); + before.fail({ tile: { x: 0, y: 0, level: 0 } }); + assert.equal(warn.mock.callCount(), 1, 'a removed layer reports nothing more'); + + await layer.disable(); + assert.equal(await layer.enable(viewer), true); + assert.equal(viewer._test.globe.layers.length, 2, 'the next enable tries the images again'); + assert.equal(eventSplit().view.hidden, false); + await layer.disable(); + } finally { + await layer.destroy(); + globalThis.document = originalDocument; + globalThis.window = originalWindow; + } +}); diff --git a/src/data/bhoteKoshiLocator.js b/src/data/bhoteKoshiLocator.js index 43b685a543..81c3e3a196 100644 --- a/src/data/bhoteKoshiLocator.js +++ b/src/data/bhoteKoshiLocator.js @@ -1,9 +1,13 @@ -import * as Cesium from 'cesium'; import { clearOverlaySource, setOverlayEntries, } from '../overlays/worldOverlay.js'; import { governorRequestRender } from '../renderGovernor.js'; +import { drawOf, findCamera } from '../render/rendererOf.js'; +import { hexColor } from '../render/color.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { toRadians } from '../geo/vector.js'; +import { lengthFraction } from '../geo/polyline.js'; import { BHOTE_KOSHI_LOCATOR_CREDIT, registerDynamicCredit, @@ -144,10 +148,11 @@ const NEARBY_CITIES = Object.freeze([ placement: 'right-lower', }), ]); -const BORDER_COLOR = Cesium.Color.fromCssColorString('#20e7f2'); const BORDER_ACCENT = '#20e7f2'; const INCIDENT_ACCENT = '#ffad55'; -const INCIDENT_COLOR = Cesium.Color.fromCssColorString(INCIDENT_ACCENT); + +// Each layer's draw sets have ids of their own. +let layerSerial = 0; const DEFAULT_OVERLAY_HOST = Object.freeze({ setEntries: setOverlayEntries, @@ -194,10 +199,6 @@ function presentationUsesBoundary(value) { ); } -function presentationAnimatesBoundary(value) { - return value === BHOTE_KOSHI_REGIONAL_PRESENTATION; -} - function smoothstep(from, to, value) { if (to <= from) return value >= to ? 1 : 0; const amount = Math.max(0, Math.min(1, (value - from) / (to - from))); @@ -219,26 +220,21 @@ export function anchoredCalloutPresentation(elapsedMs) { }; } -/** Return the progressive prefix used by the animated Nepal border. */ -export function revealPolylinePositions(positions, progress) { - if (!Array.isArray(positions) || positions.length < 2) return []; +/** + * How much of a line's length is drawn when it is revealed vertex by + * vertex: `progress` of its vertices (the head between two of them), as a + * fraction of its length, for the draw port's `revealFraction`. + * @param {Array<{x: number, y: number, z: number}>} positions + * @param {number} progress 0..1 + */ +export function revealLengthFraction(positions, progress) { + if (!Array.isArray(positions) || positions.length < 2) return 0; const clamped = Math.max(0, Math.min(1, Number(progress) || 0)); - if (clamped >= 1) return positions; + if (clamped >= 1) return 1; + if (clamped <= 0) return 0; const scaled = clamped * (positions.length - 1); - const completed = Math.floor(scaled); - const revealed = positions.slice(0, completed + 1); - const next = Math.min(completed + 1, positions.length - 1); - if (next > completed) { - revealed.push( - Cesium.Cartesian3.lerp( - positions[completed], - positions[next], - scaled - completed, - new Cesium.Cartesian3(), - ), - ); - } - return revealed.length >= 2 ? revealed : [positions[0], positions[0]]; + const index = Math.floor(scaled); + return lengthFraction(positions, index, scaled - index); } /** Close a region ring without duplicating an already-closed final vertex. */ @@ -285,14 +281,27 @@ export function createBhoteKoshiLocatorLayer({ cancelDelay = (handle) => clearTimeout(handle), } = {}) { let _viewer = null; - let _dataSource = null; + const _serial = ++layerSerial; + // Whether the layer draws: from enable until it is let go. + let _drawing = false; + let _sets = null; + // What the presentation draws, each item worked out for the time now: + // pulsing halos, lines revealed as they grow, and the country fill, drawn + // once it is due. + let _halos = []; + let _lines = []; + let _fill = null; + let _fillShown = false; + // Each line's reveal and show as last drawn. + const _drawnLines = new Map(); + // Each halo's look as last drawn. + const _drawnHalos = new Map(); let _enabled = false; let _boundaryReady = false; let _boundaryResolved = false; let _boundaryRing = null; let _generation = 0; let _presentation = BHOTE_KOSHI_REGIONAL_PRESENTATION; - let _borderAnimationFrame = null; let _calloutPulseFrame = null; let _triggerApproachTimer = null; let _removeTriggerMoveStart = null; @@ -332,30 +341,164 @@ export function createBhoteKoshiLocatorLayer({ _removeTriggerMoveEnd = null; const wasInFlight = _triggerApproachInFlight; _triggerApproachInFlight = false; - if (wasInFlight) _viewer?.camera?.cancelFlight?.(); + if (wasInFlight) findCamera(_viewer)?.cancelFlight(); if (!preserveCallout) _triggerCalloutStartedAt = Number.POSITIVE_INFINITY; } function stopAnimations() { - if (_borderAnimationFrame !== null) cancelFrame(_borderAnimationFrame); if (_calloutPulseFrame !== null) cancelFrame(_calloutPulseFrame); - _borderAnimationFrame = null; _calloutPulseFrame = null; _placeRevealMoving = false; _placeRevealSettledAt = Number.POSITIVE_INFINITY; clearTriggerApproach(); } - function removeDataSource() { + function removeDrawn() { stopAnimations(); overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); - if (_dataSource && _viewer?.dataSources) - _viewer.dataSources.remove(_dataSource, true); - _dataSource = null; + if (_sets) for (const set of Object.values(_sets)) set.dispose(); + _sets = null; + _drawing = false; + resetDrawn(); + } + + function resetDrawn() { + _halos = []; + _lines = []; + _fill = null; + _fillShown = false; + _drawnLines.clear(); + _drawnHalos.clear(); + } + + /** The layer's draw sets, made on first use: fill under lines under halos. */ + function drawSets() { + if (_sets) return _sets; + const draw = drawOf(_viewer); + const prefix = `${BHOTE_KOSHI_LOCATOR_LAYER_ID}:${_serial}`; + // Presentation only: clicks go through to what is under them. + _sets = { + fill: draw.shapes({ id: `${prefix}:fill`, pickable: false }), + lines: draw.lines({ id: `${prefix}:lines`, pickable: false }), + halos: draw.points({ id: `${prefix}:halos`, pickable: false }), + }; + return _sets; + } + + /** Draw the presentation as it now stands, in place of what was drawn. */ + function commitDrawn() { + const sets = drawSets(); + _drawnLines.clear(); + _fillShown = Boolean(_fill?.visible()); + sets.fill.set(_fillShown ? [_fill.item] : []); + sets.lines.set( + _lines.map((line) => { + const item = line(); + _drawnLines.set(item.id, lineKey(item)); + return item; + }), + ); + _drawnHalos.clear(); + sets.halos.set( + _halos.map((halo) => { + const item = halo(); + _drawnHalos.set(item.id, haloKey(item)); + return item; + }), + ); + } + + const haloKey = (item) => + `${item.pixelSize}:${item.color}:${item.outlineColor}:${item.show}`; + + const lineKey = (item) => `${item.revealFraction}:${item.show !== false}`; + + /** + * Bring what is drawn to the time now: halos pulse, lines that grew or + * showed are changed in place, and the fill shows once it is due. + */ + function syncDrawn() { + if (!_drawing || !_sets) return; + if (!_fillShown && _fill?.visible()) { + _fillShown = true; + _sets.fill.set([_fill.item]); + } + const changed = []; + for (const line of _lines) { + const item = line(); + const key = lineKey(item); + if (_drawnLines.get(item.id) === key) continue; + _drawnLines.set(item.id, key); + changed.push(item); + } + if (changed.length) _sets.lines.upsert(changed); + const pulsed = []; + for (const halo of _halos) { + const item = halo(); + const key = haloKey(item); + if (_drawnHalos.get(item.id) === key) continue; + _drawnHalos.set(item.id, key); + pulsed.push(item); + } + if (pulsed.length) _sets.halos.upsert(pulsed); + } + + /** + * A pulsing halo point: `progress()` (0..1) sizes it and fades its fill + * and ring (`fillAlpha`, `ringAlpha`), shown while `visible()`. + */ + function addHalo({ + id, + subject, + color, + visible, + progress, + fillAlpha, + ringAlpha, + scaleByDistance, + }) { + const pos = { lon: subject.lon, lat: subject.lat, height: subject.heightM }; + _halos.push(() => { + const p = progress(); + return { + id, + pos, + pixelSize: CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * p, + color: hexColor(color, fillAlpha(p)), + outlineColor: hexColor(color, ringAlpha(p)), + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + scaleByDistance, + show: visible(), + }; + }); + } + + /** + * A draped line revealed vertex by vertex as `progress()` runs 0..1, + * shown while `visible()`. + */ + function addRevealedLine({ + id, + positions, + widthPx, + color, + progress, + visible, + }) { + _lines.push(() => ({ + id, + positions, + widthPx, + mode: 'draped', + clampTo: 'both', + style: { kind: 'solid', color }, + revealFraction: revealLengthFraction(positions, progress()), + show: visible(), + })); } function addCallout( - dataSource, subject, color, { @@ -365,51 +508,27 @@ export function createBhoteKoshiLocatorLayer({ showAnchor = true, } = {}, ) { - const position = Cesium.Cartesian3.fromDegrees( - subject.lon, - subject.lat, - subject.heightM, - ); + const position = fromDegrees(subject.lon, subject.lat, subject.heightM); const visibleAt = sequenceStartedAt + visibleAfterMs; const isVisible = () => now() >= visibleAt; const pulseProgress = () => { const elapsed = Math.max(0, now() - visibleAt); return (elapsed % CALLOUT_PULSE_DURATION_MS) / CALLOUT_PULSE_DURATION_MS; }; - const ringSize = new Cesium.CallbackProperty(() => { - return ( - CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * pulseProgress() - ); - }, false); - const ringColor = new Cesium.CallbackProperty((_time, result) => { - const dynamicColor = Cesium.Color.clone(color, result); - dynamicColor.alpha = isVisible() ? 0.14 * (1 - pulseProgress()) : 0; - return dynamicColor; - }, false); - const ringOutlineColor = new Cesium.CallbackProperty((_time, result) => { - const dynamicColor = Cesium.Color.clone(color, result); - dynamicColor.alpha = isVisible() - ? 0.08 + 0.72 * (1 - pulseProgress()) - : 0; - return dynamicColor; - }, false); if (showAnchor) { - dataSource.entities.add({ + addHalo({ id: `${subject === INCIDENT ? 'bhote-koshi-incident' : 'nepal-context'}-halo`, - position, - show: new Cesium.CallbackProperty(isVisible, false), - point: { - pixelSize: ringSize, - color: ringColor, - outlineColor: ringOutlineColor, - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar( - 250000, - 0.8, - 25000000, - 1.35, - ), + subject, + color, + visible: isVisible, + progress: pulseProgress, + fillAlpha: (p) => (isVisible() ? 0.14 * (1 - p) : 0), + ringAlpha: (p) => (isVisible() ? 0.08 + 0.72 * (1 - p) : 0), + scaleByDistance: { + near: 250000, + nearValue: 0.8, + far: 25000000, + farValue: 1.35, }, }); } @@ -498,25 +617,22 @@ export function createBhoteKoshiLocatorLayer({ _placeRevealSettledAt = Number.POSITIVE_INFINITY; publishOverlayEntries(); } + syncDrawn(); requestRender('bhote-koshi-locator-callout-pulse'); _calloutPulseFrame = scheduleFrame(pulseFrame); }; _calloutPulseFrame = scheduleFrame(pulseFrame); } - function addIncidentCallout( - dataSource, - sequenceStartedAt, - visibleAfterMs = 0, - ) { - addCallout(dataSource, INCIDENT, INCIDENT_COLOR, { + function addIncidentCallout(sequenceStartedAt, visibleAfterMs = 0) { + addCallout(INCIDENT, INCIDENT_ACCENT, { sequenceStartedAt, visibleAfterMs, }); } - function addTriggerRecordCallout(dataSource) { - const position = Cesium.Cartesian3.fromDegrees( + function addTriggerRecordCallout() { + const position = fromDegrees( TRIGGER_RECORD.lon, TRIGGER_RECORD.lat, TRIGGER_RECORD.heightM, @@ -531,30 +647,19 @@ export function createBhoteKoshiLocatorLayer({ CALLOUT_PULSE_DURATION_MS ); }; - dataSource.entities.add({ + addHalo({ id: 'bhote-koshi-trigger-record-halo', - position, - show: new Cesium.CallbackProperty(isVisible, false), - point: { - pixelSize: new Cesium.CallbackProperty( - () => - CALLOUT_RING_MIN_SIZE_PX + - CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(), - false, - ), - color: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.16 * (1 - pulseProgress()); - return color; - }, false), - outlineColor: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = isVisible() ? 0.08 + 0.78 * (1 - pulseProgress()) : 0; - return color; - }, false), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(3000, 1, 250000, 0.82), + subject: TRIGGER_RECORD, + color: INCIDENT_ACCENT, + visible: isVisible, + progress: pulseProgress, + fillAlpha: (p) => 0.16 * (1 - p), + ringAlpha: (p) => (isVisible() ? 0.08 + 0.78 * (1 - p) : 0), + scaleByDistance: { + near: 3000, + nearValue: 1, + far: 250000, + farValue: 0.82, }, }); queueOverlayEntry({ @@ -618,8 +723,8 @@ export function createBhoteKoshiLocatorLayer({ _removeTriggerMoveEnd = null; _triggerCalloutStartedAt = now(); requestRender('bhote-koshi-trigger-record-reveal'); - const camera = _viewer?.camera; - if (!camera?.flyTo) return; + const port = findCamera(_viewer); + if (!port) return; const generation = _generation; _triggerApproachInFlight = true; const finish = () => { @@ -627,50 +732,54 @@ export function createBhoteKoshiLocatorLayer({ attempt.phase = 'finished'; _triggerApproachInFlight = false; }; - camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees( - TRIGGER_APPROACH_CAMERA.lon, - TRIGGER_APPROACH_CAMERA.lat, - TRIGGER_APPROACH_CAMERA.alt, - ), - orientation: { - heading: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.heading), - pitch: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.pitch), - roll: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.roll), + port.flyTo( + { + lon: TRIGGER_APPROACH_CAMERA.lon, + lat: TRIGGER_APPROACH_CAMERA.lat, + height: TRIGGER_APPROACH_CAMERA.alt, }, - duration: TRIGGER_APPROACH_DURATION_SEC, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - complete: () => { - if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying') - return; - if ( - !_enabled || - generation !== _generation || - _presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION - ) { - finish(); - return; - } - attempt.phase = 'orbiting'; - camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees( - TRIGGER_ORBIT_CAMERA.lon, - TRIGGER_ORBIT_CAMERA.lat, - TRIGGER_ORBIT_CAMERA.alt, - ), - orientation: { - heading: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.heading), - pitch: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.pitch), - roll: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.roll), - }, - duration: TRIGGER_ORBIT_DURATION_SEC, - easingFunction: Cesium.EasingFunction.SINUSOIDAL_IN_OUT, - complete: finish, - cancel: finish, - }); + { + orientation: { + heading: toRadians(TRIGGER_APPROACH_CAMERA.heading), + pitch: toRadians(TRIGGER_APPROACH_CAMERA.pitch), + roll: toRadians(TRIGGER_APPROACH_CAMERA.roll), + }, + durationS: TRIGGER_APPROACH_DURATION_SEC, + easing: 'cubicInOut', + onComplete: () => { + if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying') + return; + if ( + !_enabled || + generation !== _generation || + _presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION + ) { + finish(); + return; + } + attempt.phase = 'orbiting'; + port.flyTo( + { + lon: TRIGGER_ORBIT_CAMERA.lon, + lat: TRIGGER_ORBIT_CAMERA.lat, + height: TRIGGER_ORBIT_CAMERA.alt, + }, + { + orientation: { + heading: toRadians(TRIGGER_ORBIT_CAMERA.heading), + pitch: toRadians(TRIGGER_ORBIT_CAMERA.pitch), + roll: toRadians(TRIGGER_ORBIT_CAMERA.roll), + }, + durationS: TRIGGER_ORBIT_DURATION_SEC, + easing: 'sineInOut', + onComplete: finish, + onCancel: finish, + }, + ); + }, + onCancel: finish, }, - cancel: finish, - }); + ); } function armTriggerApproach() { @@ -681,40 +790,36 @@ export function createBhoteKoshiLocatorLayer({ const attempt = { phase: 'armed' }; _triggerApproachAttempt = attempt; const start = () => startTriggerApproach(attempt); - const camera = _viewer?.camera; - if ( - !camera?.moveStart?.addEventListener || - !camera?.moveEnd?.addEventListener - ) { + const camera = findCamera(_viewer); + if (!camera) { start(); return; } - _removeTriggerMoveStart = camera.moveStart.addEventListener(() => { + _removeTriggerMoveStart = camera.on('moveStart', () => { if (_triggerApproachAttempt !== attempt || attempt.phase !== 'armed') return; if (_triggerApproachTimer !== null) cancelDelay(_triggerApproachTimer); _triggerApproachTimer = null; _removeTriggerMoveStart?.(); _removeTriggerMoveStart = null; - _removeTriggerMoveEnd = camera.moveEnd.addEventListener(start); + _removeTriggerMoveEnd = camera.on('moveEnd', start); }); _triggerApproachTimer = scheduleDelay(start, TRIGGER_APPROACH_ARM_MS); } function addNepalCallout( - dataSource, sequenceStartedAt = now(), labelPlacement = 'right', { showAnchor = true } = {}, ) { - addCallout(dataSource, NEPAL, BORDER_COLOR, { + addCallout(NEPAL, BORDER_ACCENT, { labelPlacement, sequenceStartedAt, showAnchor, }); } - function addNearbyCityCallouts(dataSource, sequenceStartedAt) { + function addNearbyCityCallouts(sequenceStartedAt) { NEARBY_CITIES.forEach((city, index) => { const visibleAt = sequenceStartedAt + @@ -724,11 +829,7 @@ export function createBhoteKoshiLocatorLayer({ smoothstep(0, 1, (now() - visibleAt) / CITY_CALLOUT_REVEAL_MS); const labelOnLeft = city.placement === 'left'; const labelLower = city.placement === 'right-lower'; - const position = Cesium.Cartesian3.fromDegrees( - city.lon, - city.lat, - city.heightM, - ); + const position = fromDegrees(city.lon, city.lat, city.heightM); queueOverlayEntry({ id: `bhote-koshi-city-${city.id}`, position, @@ -765,7 +866,6 @@ export function createBhoteKoshiLocatorLayer({ } function addIncidentPlaceCallouts( - dataSource, sequenceStartedAt, { pulseHalos = false, places = INCIDENT_OVERVIEW_PLACES } = {}, ) { @@ -778,11 +878,7 @@ export function createBhoteKoshiLocatorLayer({ smoothstep(0, 1, (now() - visibleAt) / PLACE_CALLOUT_REVEAL_MS); const labelOnLeft = place.placement === 'left'; const labelLower = place.placement === 'right-lower'; - const position = Cesium.Cartesian3.fromDegrees( - place.lon, - place.lat, - place.heightM, - ); + const position = fromDegrees(place.lon, place.lat, place.heightM); if (pulseHalos) { const pulseSequenceDurationMs = PLACE_CALLOUT_STAGGER_MS * places.length; @@ -810,30 +906,19 @@ export function createBhoteKoshiLocatorLayer({ Math.min(1, pulseWindowElapsed() / PLACE_CALLOUT_STAGGER_MS), ); }; - dataSource.entities.add({ + addHalo({ id: `bhote-koshi-place-${place.id}-halo`, - position, - show: new Cesium.CallbackProperty(pulseIsActive, false), - point: { - pixelSize: new Cesium.CallbackProperty( - () => - CALLOUT_RING_MIN_SIZE_PX + - CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(), - false, - ), - color: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.16 * (1 - pulseProgress()); - return color; - }, false), - outlineColor: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.08 + 0.78 * (1 - pulseProgress()); - return color; - }, false), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(5000, 1, 500000, 0.82), + subject: place, + color: INCIDENT_ACCENT, + visible: pulseIsActive, + progress: pulseProgress, + fillAlpha: (p) => 0.16 * (1 - p), + ringAlpha: (p) => 0.08 + 0.78 * (1 - p), + scaleByDistance: { + near: 5000, + nearValue: 1, + far: 500000, + farValue: 0.82, }, }); } @@ -872,105 +957,67 @@ export function createBhoteKoshiLocatorLayer({ }); } - function addIncidentFloodPath(dataSource, sequenceStartedAt) { + function addIncidentFloodPath(sequenceStartedAt) { const positions = BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => - Cesium.Cartesian3.fromDegrees(lon, lat), + fromDegrees(lon, lat), ); const drawStartedAt = sequenceStartedAt + FLOOD_PATH_START_DELAY_MS; - const animatedPositions = new Cesium.CallbackProperty( - () => - revealPolylinePositions( - positions, - (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS, - ), - false, - ); - dataSource.entities.add({ + addRevealedLine({ id: 'bhote-koshi-flood-path', - show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false), - polyline: { - positions: animatedPositions, - width: 3.5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.96), - classificationType: Cesium.ClassificationType.BOTH, - }, + positions, + widthPx: 3.5, + color: hexColor(BORDER_ACCENT, 0.96), + progress: () => (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS, + visible: () => now() >= drawStartedAt, }); } - function addNepalBoundary(dataSource, ring, sequenceStartedAt) { + function addNepalBoundary(ring, sequenceStartedAt) { const closed = closeRegionRing(ring); if (closed.length < 4) return false; - const positions = Cesium.Cartesian3.fromDegreesArray(closed.flat()); - const hierarchy = new Cesium.PolygonHierarchy(positions.slice(0, -1)); + const positions = closed.map(([lon, lat]) => fromDegrees(lon, lat)); const drawStartedAt = sequenceStartedAt + BORDER_START_DELAY_MS; - const animatedPositions = new Cesium.CallbackProperty( - () => - revealPolylinePositions( - positions, - (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS, - ), - false, - ); - dataSource.entities.add({ - id: 'nepal-border-fill', - show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false), - polygon: { - hierarchy, - material: BORDER_COLOR.withAlpha(0.055), - classificationType: Cesium.ClassificationType.BOTH, + const progress = () => (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS; + _fill = { + visible: () => now() >= drawStartedAt, + item: { + id: 'nepal-border-fill', + geometry: { + kind: 'polygon', + rings: [closed.slice(0, -1).map(([lon, lat]) => ({ lon, lat }))], + }, + fill: hexColor(BORDER_ACCENT, 0.055), + height: 'clampGround', + clampTo: 'both', }, - }); - dataSource.entities.add({ - id: 'nepal-border-halo', - polyline: { - positions: animatedPositions, - width: 5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.12), - classificationType: Cesium.ClassificationType.BOTH, - }, - }); - dataSource.entities.add({ - id: 'nepal-border-highlight', - polyline: { - positions: animatedPositions, - width: 2.5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.96), - classificationType: Cesium.ClassificationType.BOTH, - }, - }); - const generation = _generation; - const drawFrame = () => { - if ( - !_enabled || - generation !== _generation || - !presentationAnimatesBoundary(_presentation) - ) - return; - requestRender('bhote-koshi-locator-border-draw'); - if (now() - drawStartedAt < BORDER_DRAW_DURATION_MS) { - _borderAnimationFrame = scheduleFrame(drawFrame); - } else { - _borderAnimationFrame = null; - } }; - _borderAnimationFrame = scheduleFrame(drawFrame); + for (const [id, widthPx, alpha] of [ + ['nepal-border-halo', 5, 0.12], + ['nepal-border-highlight', 2.5, 0.96], + ]) + addRevealedLine({ + id, + positions, + widthPx, + color: hexColor(BORDER_ACCENT, alpha), + progress, + visible: () => true, + }); + // The callout pulse draws each step of the reveal (`syncDrawn`). return true; } function renderPresentation() { - if (!_dataSource) return; + if (!_drawing) return; stopAnimations(); overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); _overlayEntries = []; - _dataSource.entities.removeAll(); + resetDrawn(); if (_presentation === NEPAL_CONTEXT_PRESENTATION) { - addNepalCallout(_dataSource); + addNepalCallout(); } else if (_presentation === BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION) { const sequenceStartedAt = now(); - addIncidentPlaceCallouts(_dataSource, sequenceStartedAt, { + addIncidentPlaceCallouts(sequenceStartedAt, { pulseHalos: true, places: INCIDENT_OVERVIEW_PLACES, }); @@ -987,8 +1034,8 @@ export function createBhoteKoshiLocatorLayer({ PLACE_CALLOUT_START_DELAY_MS - (INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS - PLACE_CALLOUT_REVEAL_MS; - addIncidentFloodPath(_dataSource, sequenceStartedAt); - addIncidentPlaceCallouts(_dataSource, settledPlacesAt); + addIncidentFloodPath(sequenceStartedAt); + addIncidentPlaceCallouts(settledPlacesAt); } else if (_presentation === BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION) { const sequenceStartedAt = now(); const settledPathAt = @@ -1000,21 +1047,22 @@ export function createBhoteKoshiLocatorLayer({ PLACE_CALLOUT_START_DELAY_MS - (INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS - PLACE_CALLOUT_REVEAL_MS; - addIncidentFloodPath(_dataSource, settledPathAt); - addIncidentPlaceCallouts(_dataSource, settledPlacesAt); + addIncidentFloodPath(settledPathAt); + addIncidentPlaceCallouts(settledPlacesAt); } else if (_presentation === BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION) { const sequenceStartedAt = now(); const settledPathAt = sequenceStartedAt - FLOOD_PATH_START_DELAY_MS - FLOOD_PATH_DRAW_DURATION_MS; - addIncidentFloodPath(_dataSource, settledPathAt); - addTriggerRecordCallout(_dataSource); + addIncidentFloodPath(settledPathAt); + addTriggerRecordCallout(); armTriggerApproach(); } else { const sequenceStartedAt = now(); - addNepalCallout(_dataSource, sequenceStartedAt, 'left'); + addNepalCallout(sequenceStartedAt, 'left'); if (!_boundaryResolved) { + commitDrawn(); publishOverlayEntries(); startCalloutAnimation(); requestRender('bhote-koshi-locator-presentation'); @@ -1023,24 +1071,20 @@ export function createBhoteKoshiLocatorLayer({ if (_presentation === BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION) { const settledAt = sequenceStartedAt - BORDER_START_DELAY_MS - BORDER_DRAW_DURATION_MS; - if (_boundaryRing) - addNepalBoundary(_dataSource, _boundaryRing, settledAt); - addIncidentCallout( - _dataSource, - sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS, - ); - addNearbyCityCallouts(_dataSource, sequenceStartedAt); + if (_boundaryRing) addNepalBoundary(_boundaryRing, settledAt); + addIncidentCallout(sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS); + addNearbyCityCallouts(sequenceStartedAt); } else { - if (_boundaryRing) - addNepalBoundary(_dataSource, _boundaryRing, sequenceStartedAt); + if (_boundaryRing) addNepalBoundary(_boundaryRing, sequenceStartedAt); const incidentDelayMs = _boundaryRing ? BORDER_START_DELAY_MS + BORDER_DRAW_DURATION_MS + INCIDENT_CALLOUT_GAP_MS : BORDER_START_DELAY_MS; - addIncidentCallout(_dataSource, sequenceStartedAt, incidentDelayMs); + addIncidentCallout(sequenceStartedAt, incidentDelayMs); } } + commitDrawn(); publishOverlayEntries({ moving: _placeRevealMoving }); startCalloutAnimation(); requestRender('bhote-koshi-locator-presentation'); @@ -1058,11 +1102,9 @@ export function createBhoteKoshiLocatorLayer({ _boundaryResolved = false; _boundaryRing = null; const generation = ++_generation; - removeDataSource(); - const dataSource = new Cesium.CustomDataSource('bhote-koshi-locator'); - _dataSource = dataSource; + removeDrawn(); + _drawing = true; renderPresentation(); - viewer.dataSources.add(dataSource); registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT); showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID); requestRender('bhote-koshi-locator-callout'); @@ -1084,7 +1126,7 @@ export function createBhoteKoshiLocatorLayer({ return true; } catch (error) { if (error?.name === 'AbortError') { - if (generation === _generation) removeDataSource(); + if (generation === _generation) removeDrawn(); throw error; } console.warn( @@ -1106,7 +1148,7 @@ export function createBhoteKoshiLocatorLayer({ _boundaryResolved = false; _boundaryRing = null; _generation += 1; - removeDataSource(); + removeDrawn(); requestRender('bhote-koshi-locator-disable'); return true; } diff --git a/src/data/bhoteKoshiLocator.test.mjs b/src/data/bhoteKoshiLocator.test.mjs index 605f8eaab3..a24afefee6 100644 --- a/src/data/bhoteKoshiLocator.test.mjs +++ b/src/data/bhoteKoshiLocator.test.mjs @@ -1,3 +1,6 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; import assert from 'node:assert/strict'; import test from 'node:test'; import { readFile } from 'node:fs/promises'; @@ -24,32 +27,58 @@ import { createBhoteKoshiLocatorLayer, largestGeoJsonRing, NEPAL_CONTEXT_PRESENTATION, - revealPolylinePositions, + revealLengthFraction, } from './bhoteKoshiLocator.js'; -function viewerFixture() { - const added = []; - const removed = []; - return { +/** + * A viewer with a fake draw port bound; with `camera`, the Cesium camera + * port over that fake camera too. `_test` reads what is drawn: every live + * item by id (`drawn`), and `sets` of the layer. + */ +function viewerFixture({ camera } = {}) { + const draw = fakeDrawPort(); + const viewer = { creditDisplay: { addStaticCredit() {}, removeStaticCredit() {} }, - dataSources: { - add(source) { - added.push(source); - }, - remove(source) { - removed.push(source); - }, - }, - _test: { added, removed }, }; + if (camera) { + viewer.camera = camera; + bindFakeCesiumCamera(viewer, { draw }); + } else bindRenderer(viewer, { draw }); + const live = () => + [...draw.sets.values()].filter( + (set) => !set.disposed && set.spec.id.startsWith('bhote-koshi-locator:'), + ); + viewer._test = { + draw, + live, + /** Every live item, by id. */ + drawn() { + const items = new Map(); + for (const set of live()) + for (const [id, item] of set.items) items.set(id, item); + return items; + }, + ids: () => [...viewer._test.drawn().keys()], + item: (id) => viewer._test.drawn().get(id), + }; + return viewer; } +/** Frames that run only when a test ticks them. */ function nonRunningAnimation() { + let queued = []; return { - scheduleFrame() { - return 1; + scheduleFrame(callback) { + queued.push(callback); + return queued.length; }, cancelFrame() {}, + /** Run the frames asked for so far (each asks for its next). */ + tick() { + const run = queued; + queued = []; + for (const callback of run) callback(); + }, }; } @@ -132,21 +161,18 @@ test('Bhote Koshi locator selects the largest GeoJSON country exterior', () => { ); }); -test('Bhote Koshi locator reveals a border progressively', () => { +test('Bhote Koshi locator reveals a border progressively, vertex by vertex', () => { const positions = [ - new Cesium.Cartesian3(0, 0, 0), - new Cesium.Cartesian3(10, 0, 0), - new Cesium.Cartesian3(20, 0, 0), + { x: 0, y: 0, z: 0 }, + { x: 10, y: 0, z: 0 }, + { x: 40, y: 0, z: 0 }, ]; - assert.deepEqual(revealPolylinePositions(positions, 0), [ - positions[0], - positions[0], - ]); - assert.deepEqual(revealPolylinePositions(positions, 0.25), [ - positions[0], - new Cesium.Cartesian3(5, 0, 0), - ]); - assert.equal(revealPolylinePositions(positions, 1), positions); + assert.equal(revealLengthFraction(positions, 0), 0); + // A quarter of the vertices: halfway along the first, shorter segment. + assert.equal(revealLengthFraction(positions, 0.25), 5 / 40); + assert.equal(revealLengthFraction(positions, 0.75), 25 / 40); + assert.equal(revealLengthFraction(positions, 1), 1); + assert.equal(revealLengthFraction(positions.slice(0, 1), 0.5), 0); }); test('Bhote Koshi locator stages its anchored callout from dot to leader to text', () => { @@ -169,6 +195,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', const overlayHost = overlayHostFixture(); const renders = []; let nowMs = 0; + const frames = nonRunningAnimation(); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => ({ name: 'Nepal', @@ -182,24 +209,29 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', requestRender: (reason) => renders.push(reason), overlayHost, now: () => nowMs, - ...nonRunningAnimation(), + ...frames, }); assert.equal(await layer.init(viewer), true); assert.equal(await layer.enable(viewer, { origin: 'scene' }), true); - assert.equal(viewer._test.added.length, 1); - const source = viewer._test.added[0]; - const ids = source.entities.values.map((entity) => entity.id); + const sets = viewer._test.live(); + assert.deepEqual( + sets.map(({ kind }) => kind), + ['shapes', 'lines', 'points'], + 'the fill under the lines under the halos', + ); + assert.ok(sets.every(({ spec }) => spec.pickable === false)); + // The fill is drawn once it is due, below. + const ids = viewer._test.ids(); for (const id of [ 'nepal-context-halo', - 'nepal-border-fill', 'nepal-border-highlight', 'bhote-koshi-incident-halo', ]) { assert.ok(ids.includes(id), `${id} belongs to the regional sequence`); } - const incidentHalo = source.entities.getById('bhote-koshi-incident-halo'); - const border = source.entities.getById('nepal-border-highlight'); + const incidentHalo = () => viewer._test.item('bhote-koshi-incident-halo'); + const border = () => viewer._test.item('nepal-border-highlight'); const publication = overlayHost._test.publications.at(-1); assert.equal(publication.sourceId, BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); assert.equal(publication.entries.length, 2); @@ -225,15 +257,31 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', assert.equal(incident.contentAlpha(), 0); assert.equal(incident.presentationScale(), 0.96); assert.equal(nepal.sourceAlpha(), 0); - assert.ok(border.polyline.positions.getValue().length < 5); - assert.equal(incidentHalo.show.getValue(), false); - assert.equal(incidentHalo.point.pixelSize.getValue(), 16); + assert.equal(border().revealFraction, 0); + assert.equal(border().mode, 'draped'); + assert.equal(border().positions.length, 5); + assert.equal(viewer._test.item('nepal-border-fill'), undefined); + assert.equal(incidentHalo().show, false); + assert.equal(incidentHalo().pixelSize, 16); + nowMs = 800; + frames.tick(); + const fill = viewer._test.item('nepal-border-fill'); + assert.equal(fill.height, 'clampGround', 'the fill, due, drapes'); + assert.equal(fill.geometry.rings[0].length, 4); + assert.ok(border().revealFraction > 0 && border().revealFraction < 0.1); nowMs = 3100; + frames.tick(); assert.equal(nepal.sourceAlpha(), 1); - assert.equal(border.polyline.positions.getValue().length, 5); - assert.equal(incidentHalo.show.getValue(), false); + assert.equal(border().revealFraction, 1); + assert.equal(incidentHalo().show, false); + const lines = sets.find(({ kind }) => kind === 'lines'); + const lineWrites = lines.writes; nowMs = 3300; - assert.equal(incidentHalo.show.getValue(), true); + frames.tick(); + frames.tick(); + assert.equal(lines.writes, lineWrites, 'settled lines are not drawn again'); + assert.equal(incidentHalo().show, true); + assert.equal(incidentHalo().disableDepthTest, Number.POSITIVE_INFINITY); assert.equal(incident.sourceAlpha(), 0); nowMs = 4500; assert.equal(incident.sourceAlpha(), 1); @@ -247,7 +295,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', assert.ok(renders.includes('bhote-koshi-locator-boundary')); assert.equal(await layer.disable(), true); - assert.equal(viewer._test.removed.length, 1); + assert.equal(viewer._test.live().length, 0, 'its sets let go'); assert.equal( overlayHost._test.clears.at(-1), BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID, @@ -275,10 +323,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION }); await layer.enable(viewer); - assert.deepEqual( - viewer._test.added[0].entities.values.map((entity) => entity.id), - ['nepal-context-halo'], - ); + assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']); const nepalLabel = overlayHost._test.publications.at(-1).entries[0]; assert.equal(nepalLabel.variant, 'label'); assert.equal(nepalLabel.placement, 'right'); @@ -298,11 +343,8 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide ); layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION }); - assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight')); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), - undefined, - ); + assert.ok(viewer._test.item('nepal-border-highlight')); + assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined); assert.equal( overlayHost._test.publications .at(-1) @@ -311,10 +353,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide ); layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION }); - assert.deepEqual( - viewer._test.added[0].entities.values.map((entity) => entity.id), - ['nepal-context-halo'], - ); + assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']); await layer.destroy(); }); @@ -336,7 +375,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ }); layer.setParams({ presentation: BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; + const tick = () => { + const frame = pulseFrame; + frame?.(); + }; const event = JSON.parse( await readFile( new URL( @@ -348,7 +390,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ ); assert.equal(event.evidenceSpine.length, 16); assert.equal(event.evidenceSpine.at(-1).id, 'charaudi'); - assert.equal(source.entities.values.length, 15); + assert.equal(viewer._test.ids().length, 15); const labels = overlayHost._test.publications.at(-1).entries; assert.equal(labels.length, 15); assert.equal(overlayHost._test.publications.at(-1).options.moving, true); @@ -371,10 +413,11 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ nowMs = 349 + index * 650; assert.equal(pin.sourceAlpha(), 0); nowMs += 1; + tick(); assert.equal(pin.sourceAlpha(), 0); assert.equal( - source.entities.values.filter( - (entity) => entity.id.endsWith('-halo') && entity.show.getValue(), + [...viewer._test.drawn().values()].filter( + (item) => item.id.endsWith('-halo') && item.show, ).length, 1, ); @@ -384,10 +427,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ assert.ok(nowMs < INCIDENT_OVERVIEW_HOLD_SEC * 1000); // A repeat halo cycle must not erase already revealed labels. nowMs = 350 + 15 * 650; + tick(); assert.equal( - source.entities - .getById('bhote-koshi-place-immediate-collapse-viewpoint-halo') - .show.getValue(), + viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo') + .show, true, ); assert.equal( @@ -405,9 +448,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ assert.equal(overlayHost._test.publications.at(-1).options.moving, false); layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION }); assert.equal( - source.entities.values.some((entity) => - entity.id.startsWith('bhote-koshi-place-'), - ), + viewer._test.ids().some((id) => id.startsWith('bhote-koshi-place-')), false, ); await layer.destroy(); @@ -457,18 +498,18 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh const viewer = viewerFixture(); const overlayHost = overlayHostFixture(); let nowMs = 0; + const frames = nonRunningAnimation(); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => null, requestRender() {}, overlayHost, now: () => nowMs, - ...nonRunningAnimation(), + ...frames, }); layer.setParams({ presentation: BHOTE_KOSHI_FLOOD_PATH_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const path = source.entities.getById('bhote-koshi-flood-path'); + const path = () => viewer._test.item('bhote-koshi-flood-path'); const labels = overlayHost._test.publications.at(-1).entries; const trigger = labels.find( ({ id }) => id === 'bhote-koshi-place-immediate-collapse-viewpoint', @@ -477,46 +518,56 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh ({ id }) => id === 'bhote-koshi-place-bidur-trishuli-bridge', ); - assert.equal(source.entities.values.length, 1); + assert.equal(viewer._test.ids().length, 1); assert.equal(labels.length, 15); assert.equal(bidur.title, '14 · BIDUR BRIDGE'); for (const place of INCIDENT_OVERVIEW_PLACES) { const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`); assert.equal(pin.sourceAlpha(), 1, place.id); } - assert.equal(path.polyline.clampToGround.getValue(), true); - assert.ok(path.polyline.material instanceof Cesium.ColorMaterialProperty); + assert.equal(path().mode, 'draped'); + assert.equal(path().clampTo, 'both'); + assert.equal(path().widthPx, 3.5); + assert.equal(path().style.kind, 'solid'); + const color = Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96); assert.ok( - path.polyline.material.color - .getValue() - .equalsEpsilon( - Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96), + path().style.color.every( + (value, i) => + Math.abs(value - Cesium.Color.pack(color, [])[i]) < Cesium.Math.EPSILON7, - ), + ), ); - assert.equal(path.show.getValue(), false); + assert.equal(path().show, false); assert.equal(trigger.sourceAlpha(), 1); assert.equal(bidur.sourceAlpha(), 1); nowMs = 250; - assert.equal(path.show.getValue(), true); - assert.equal(path.polyline.positions.getValue().length, 2); + frames.tick(); + assert.equal(path().show, true); + assert.equal(path().revealFraction, 0); nowMs = 2250; - const halfwayCount = path.polyline.positions.getValue().length; - assert.ok(Math.abs(halfwayCount - BHOTE_KOSHI_FLOOD_PATH.length / 2) <= 2); + frames.tick(); + // Halfway through its vertices. + const positions = path().positions; + assert.equal(path().revealFraction, revealLengthFraction(positions, 0.5)); + assert.ok(path().revealFraction > 0.2 && path().revealFraction < 0.8); nowMs = 4250; - assert.equal( - path.polyline.positions.getValue().length, - BHOTE_KOSHI_FLOOD_PATH.length, - ); + frames.tick(); + assert.equal(path().revealFraction, 1); assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH[0], [85.48476, 28.33255]); // More observation pins must not extend or straighten the sourced route. - assert.deepEqual( - path.polyline.positions.getValue(), - BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => - Cesium.Cartesian3.fromDegrees(lon, lat), - ), - ); + assert.equal(positions.length, BHOTE_KOSHI_FLOOD_PATH.length); + positions.forEach((position, i) => { + const [lon, lat] = BHOTE_KOSHI_FLOOD_PATH[i]; + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + position, + Cesium.Cartesian3.fromDegrees(lon, lat), + 0, + 1e-6, + ), + ); + }); assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH.at(-1), [85.14943, 27.92177]); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Flood path'); assert.deepEqual(layer.getParams(), { @@ -547,11 +598,10 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep layer.setParams({ presentation: BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const path = source.entities.getById('bhote-koshi-flood-path'); + const path = viewer._test.item('bhote-koshi-flood-path'); const labels = overlayHost._test.publications.at(-1).entries; - assert.equal(source.entities.values.length, 1); + assert.equal(viewer._test.ids().length, 1); assert.equal(labels.length, 15); for (const [index, place] of INCIDENT_OVERVIEW_PLACES.entries()) { const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`); @@ -561,23 +611,21 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep ); assert.equal(pin.sourceAlpha(), 1); } - assert.equal(path.show.getValue(), true); - assert.equal( - path.polyline.positions.getValue().length, - BHOTE_KOSHI_FLOOD_PATH.length, - ); + assert.equal(path.show, true); + assert.equal(path.revealFraction, 1); + assert.equal(path.positions.length, BHOTE_KOSHI_FLOOD_PATH.length); assert.ok( - Cesium.Cartesian3.equals( - path.polyline.positions.getValue()[0], + Cesium.Cartesian3.equalsEpsilon( + path.positions[0], Cesium.Cartesian3.fromDegrees(85.48476, 28.33255), + 0, + 1e-6, ), ); - assert.equal(source.entities.getById('nepal-border-fill'), undefined); - assert.equal(source.entities.getById('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('nepal-border-fill'), undefined); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); assert.equal( - source.entities.getById( - 'bhote-koshi-place-immediate-collapse-viewpoint-halo', - ), + viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo'), undefined, ); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Path overview'); @@ -604,14 +652,13 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', preview: true, }); await layer.enable(viewer); - const source = viewer._test.added[0]; const publication = overlayHost._test.publications.at(-1); const record = publication.entries[0]; - assert.deepEqual( - source.entities.values.map(({ id }) => id), - ['bhote-koshi-flood-path', 'bhote-koshi-trigger-record-halo'], - ); + assert.deepEqual(viewer._test.ids(), [ + 'bhote-koshi-flood-path', + 'bhote-koshi-trigger-record-halo', + ]); assert.equal(record.title, 'USGS INITIAL REPORT'); assert.deepEqual(record.details, [ '26 AUG 2026 · 08:37 NPT', @@ -624,7 +671,7 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', assert.equal(record.sourceAlpha(), 0); nowMs = 1200; assert.equal(record.sourceAlpha(), 1); - assert.equal(source.entities.getById('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Trigger record'); assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION, @@ -633,20 +680,21 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', }); test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits', async () => { - const viewer = viewerFixture(); const overlayHost = overlayHostFixture(); const moveStart = new Cesium.Event(); const moveEnd = new Cesium.Event(); const flights = []; let armedCallback = null; - viewer.camera = { - moveStart, - moveEnd, - flyTo(options) { - flights.push(options); + const viewer = viewerFixture({ + camera: { + moveStart, + moveEnd, + flyTo(options) { + flights.push(options); + }, + cancelFlight() {}, }, - cancelFlight() {}, - }; + }); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => null, requestRender() {}, @@ -688,21 +736,24 @@ test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits' for (const phase of ['timer', 'move-end', 'approach', 'orbit']) { test(`Scene Stop revokes locator ${phase} and stale callbacks cannot own a successor`, async () => { - const viewer = viewerFixture(); const timers = new Map(); const callbacks = []; const flights = []; let nextTimer = 0; const moveStart = new Cesium.Event(); const moveEnd = new Cesium.Event(); - viewer.camera = { - moveStart, - moveEnd, - flyTo(options) { - flights.push(options); + const viewer = viewerFixture({ + camera: { + moveStart, + moveEnd, + flyTo(options) { + flights.push(options); + }, + cancelFlight() {}, }, - cancelFlight() {}, - }; + }); + // The renderer's camera port relays these; the layer's own come on top. + const portListeners = [moveStart, moveEnd].map((e) => e.numberOfListeners); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => null, overlayHost: overlayHostFixture(), @@ -745,8 +796,10 @@ for (const phase of ['timer', 'move-end', 'approach', 'orbit']) { const oldFlights = [...flights]; SceneDirector.prototype.stopScene.call(director); assert.equal(timers.size, 0, 'Stop cancels the actual delayed work'); - assert.equal(moveStart.numberOfListeners, 0); - assert.equal(moveEnd.numberOfListeners, 0); + assert.deepEqual( + [moveStart, moveEnd].map((e) => e.numberOfListeners), + portListeners, + ); callbacks[0](); moveEnd.raiseEvent(); for (const flight of oldFlights) flight.complete(); @@ -807,8 +860,7 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities layer.setParams({ presentation: BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const borderFill = source.entities.getById('nepal-border-fill'); + const borderFill = viewer._test.item('nepal-border-fill'); const entries = overlayHost._test.publications.at(-1).entries; const incident = entries.find( ({ id }) => id === 'bhote-koshi-incident-callout', @@ -823,7 +875,8 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities ({ id }) => id === 'bhote-koshi-city-dhulikhel', ); - assert.equal(borderFill.show.getValue(), true); + assert.ok(borderFill, 'the settled fill is drawn at once'); + assert.equal(viewer._test.item('nepal-border-highlight').revealFraction, 1); assert.equal(incident.contentAlpha(), 1); assert.equal(kathmandu.title, 'KATHMANDU'); assert.equal(bhaktapur.title, 'BHAKTAPUR'); @@ -866,9 +919,7 @@ test('Bhote Koshi locator degrades to labels when the regional boundary is unava }); try { await layer.enable(viewer); - const ids = viewer._test.added[0].entities.values.map( - (entity) => entity.id, - ); + const ids = viewer._test.ids(); assert.ok(ids.includes('nepal-context-halo')); assert.ok(ids.includes('bhote-koshi-incident-halo')); assert.equal(ids.includes('bhote-koshi-city-kathmandu'), false); @@ -899,15 +950,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu }); const enabling = layer.enable(viewer); - assert.ok(viewer._test.added[0].entities.getById('nepal-context-halo')); - assert.equal( - viewer._test.added[0].entities.getById('nepal-border-highlight'), - undefined, - ); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'), - undefined, - ); + assert.ok(viewer._test.item('nepal-context-halo')); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('bhote-koshi-incident-halo'), undefined); assert.equal(overlayHost._test.publications.length, 1); assert.deepEqual( overlayHost._test.publications[0].entries.map(({ id }) => id), @@ -923,14 +968,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu ], }); await enabling; - assert.ok( - viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'), - ); - assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight')); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), - undefined, - ); + assert.ok(viewer._test.item('bhote-koshi-incident-halo')); + assert.ok(viewer._test.item('nepal-border-highlight')); + assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined); assert.equal(overlayHost._test.publications.length, 2); assert.deepEqual( overlayHost._test.publications.at(-1).entries.map(({ id }) => id), @@ -960,6 +1000,52 @@ test('Bhote Koshi locator cancels a stale boundary resolution and removes its su [88, 30], ], }); + assert.ok(viewer._test.live().length > 0, 'drawn while it resolves'); await assert.rejects(enabling, (error) => error?.name === 'AbortError'); - assert.equal(viewer._test.removed.length, 1); + assert.equal(viewer._test.live().length, 0, 'let go'); +}); + +test('Bhote Koshi locator layers draw sets of their own, and halos only as they change', async () => { + const viewer = viewerFixture(); + const ring = [ + [80, 26], + [88, 26], + [88, 30], + [80, 30], + ]; + let nowMs = 0; + const frames = nonRunningAnimation(); + const make = () => + createBhoteKoshiLocatorLayer({ + boundaryResolver: async () => ({ name: 'Nepal', ring }), + requestRender() {}, + overlayHost: overlayHostFixture(), + now: () => nowMs, + ...frames, + }); + const first = make(); + const second = make(); + assert.equal(await first.enable(viewer, { origin: 'scene' }), true); + assert.equal(await second.enable(viewer, { origin: 'scene' }), true); + const ids = viewer._test.live().map(({ spec }) => spec.id); + assert.equal(ids.length, 6); + assert.equal(new Set(ids).size, 6, 'no two layers share a set'); + + // Before the incident halo is due, nothing about any halo changes. + const halos = viewer._test.live().filter(({ kind }) => kind === 'points'); + nowMs = 100; + frames.tick(); + const writes = halos.map((set) => set.writes); + frames.tick(); + frames.tick(); + assert.deepEqual( + halos.map((set) => set.writes), + writes, + 'unchanged halos are not drawn again', + ); + + assert.equal(await first.disable(), true); + assert.equal(viewer._test.live().length, 3, 'the other layer keeps its sets'); + assert.equal(await second.disable(), true); + assert.equal(viewer._test.live().length, 0); }); diff --git a/src/data/bikeshare.test.mjs b/src/data/bikeshare.test.mjs index 308135d4a3..8bf3de554b 100644 --- a/src/data/bikeshare.test.mjs +++ b/src/data/bikeshare.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS, _clearBikeshareSelectionForTest, @@ -19,17 +20,17 @@ function makeRecord() { isInstalled: true, isRenting: false, isReturning: true, - point: { - position: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 2), - show: true, - }, + key: 'austin-capmetro:3790', + position: fromDegrees(-97.7431, 30.2672, 2), + pixelSize: 8, + color: [0, 1, 0, 1], }; } test('selected bikeshare entry preserves source copy and protected-lane policy', () => { const record = makeRecord(); const entry = createBikeshareSelectedOverlayEntry('austin-capmetro:3790', record); - assert.equal(entry.position, record.point.position); + assert.equal(entry.position, record.position); assert.equal(entry.title, 'Congress & 6th'); assert.deepEqual(entry.details, [ '🚲 7 avail · 4 docks · 11 cap', @@ -44,7 +45,7 @@ test('selected bikeshare entry preserves source copy and protected-lane policy', assert.equal(entry.horizonCull, true); }); -test('real station select/clear path publishes one card and creates no native label graphic', () => { +test('real station select/clear path publishes one card and draws no native label', () => { const calls = []; const overlayHost = { setEntries: (...args) => calls.push(['entries', ...args]), @@ -53,27 +54,36 @@ test('real station select/clear path publishes one card and creates no native la }; const key = 'austin-capmetro:3790'; const record = makeRecord(); - const viewer = { entities: new Cesium.EntityCollection() }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); _setBikeshareSelectionStateForTest({ viewer, key, record, overlayHost }); + const live = (suffix) => + [...draw.sets.values()].find((set) => !set.disposed && set.spec.id.endsWith(suffix)); + const stations = live(':stations'); + const selected = live(':selected'); try { _selectBikeshareStationForTest(key); - assert.equal(record.point.show, false); - assert.equal(viewer.entities.values.length, 1, 'runtime guard requires a real selected entity'); - assert.equal(viewer.entities.values[0].label, undefined); - assert.ok(viewer.entities.values[0].point, 'selected point highlight remains native'); + assert.equal(stations.items.get(key).show, false, 'the station’s own dot is hidden'); + assert.equal(selected.items.size, 1, 'one highlight dot replaces it'); + const [highlight] = selected.items.values(); + assert.equal(highlight.pos, record.position); + assert.deepEqual(highlight.color, [0, 1, 1, 1], 'cyan'); + assert.equal(highlight.pixelSize, 14); + assert.equal(highlight.disableDepthTest, Infinity); const publication = calls.find(([type]) => type === 'entries'); assert.ok(publication); assert.equal(publication[1], 'bikeshare-selected'); assert.equal(publication[2].length, 1); - assert.equal(publication[2][0].position, record.point.position); + assert.equal(publication[2][0].position, record.position); assert.deepEqual(publication[3], BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS); _clearBikeshareSelectionForTest(); - assert.equal(record.point.show, true); - assert.equal(viewer.entities.values.length, 0); + assert.equal(stations.items.get(key).show, true); + assert.equal(selected.items.size, 0); assert.deepEqual(calls.at(-1), ['clear', 'bikeshare-selected']); } finally { _clearBikeshareSelectionForTest(); + unbind(); } }); diff --git a/src/data/boundaryLabels.test.mjs b/src/data/boundaryLabels.test.mjs index a46a0aed5c..44d80a092f 100644 --- a/src/data/boundaryLabels.test.mjs +++ b/src/data/boundaryLabels.test.mjs @@ -8,6 +8,8 @@ import { readFileSync } from 'node:fs'; import * as Cesium from 'cesium'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from '../annotations/resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js'; const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8'); @@ -21,7 +23,7 @@ const DATA_MODULES = [ './local_data/wof_neighborhoods/files.js', ]; -/** Modules that use Cesium for outlines but must not draw text with it. */ +/** Modules that draw outlines but must not draw text with Cesium. */ const CESIUM_MODULES = [ '../annotations/resolver.js', '../annotations/worldAnnotationRenderer.js', @@ -109,21 +111,22 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label', featureSource, }); const primitives = []; - const dataSources = []; - const viewer = { - camera: { - positionCartographic: Cesium.Cartographic.fromDegrees( - -97.7431, - 30.2672, - 3000, - ), + const draw = fakeDrawPort(); + // The resolver reads the camera through the renderer's camera port; the + // world renderer draws through its draw port. + const viewer = bindFakeCesiumCamera( + { + camera: { + positionCartographic: Cesium.Cartographic.fromDegrees( + -97.7431, + 30.2672, + 3000, + ), + }, + scene: { primitives: { add: (p) => primitives.push(p) } }, }, - scene: { primitives: { add: (p) => primitives.push(p) } }, - dataSources: { - add: (ds) => dataSources.push(ds), - remove() {}, - }, - }; + { draw }, + ); const renderer = createWorldAnnotationRenderer(viewer); for (const [target, lon, lat] of [ ['Austin', -97.7431, 30.2672], @@ -135,8 +138,8 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label', 3000, ); const resolved = await resolveAnnotationTarget({ - // The resolver reads only the camera (no scene to pick from). - viewer: { camera: viewer.camera }, + // The resolver reads only the camera (no query port to pick with). + viewer, target, footprint: true, deferFootprint: true, @@ -155,8 +158,14 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label', }); } assert.equal(primitives.length, 0, 'no primitive collections'); - const entities = dataSources.flatMap((ds) => ds.entities.values); - assert.ok(entities.length >= 2, 'the outlines were drawn'); - for (const entity of entities) assert.equal(entity.label, undefined); + const live = [...draw.sets.values()].filter((record) => !record.disposed); + const items = live.flatMap((record) => [...record.items.values()]); + assert.ok(items.length >= 2, 'the outlines were drawn'); + // Fills and lines only: no point, text or label is drawn for a name. + assert.deepEqual([...new Set(live.map((record) => record.kind))].sort(), [ + 'lines', + 'shapes', + ]); + for (const item of items) assert.equal(item.label, undefined); renderer.destroy(); }); diff --git a/src/data/cameraFraming.js b/src/data/cameraFraming.js index a2d38b5ecd..af2ee7fc5f 100644 --- a/src/data/cameraFraming.js +++ b/src/data/cameraFraming.js @@ -1,10 +1,29 @@ -import * as Cesium from 'cesium'; +import { toRadians } from '../geo/index.js'; +import { findCamera } from '../render/rendererOf.js'; + +/** The camera port's pose, or null when there is none to read. */ +function poseOf(viewer) { + try { + return findCamera(viewer)?.pose() ?? null; + } catch { + return null; + } +} /** Camera range with breathing room in both viewport dimensions. */ export function rangeForBoundingSphere(viewer, radius) { - const frustum = viewer.camera?.frustum; - const verticalFov = Number(frustum?.fov) || Cesium.Math.toRadians(60); - const aspectRatio = Math.max(0.5, Number(frustum?.aspectRatio) || 1); + const pose = poseOf(viewer); + const fovy = Number(pose?.fovy); + const aspect = Number(pose?.aspectRatio); + // The frustum's field of view: along its wider side. + const fov = + fovy > 0 && aspect > 1 + ? 2 * Math.atan(Math.tan(fovy / 2) * aspect) + : fovy > 0 + ? fovy + : NaN; + const verticalFov = fov || toRadians(60); + const aspectRatio = Math.max(0.5, aspect || 1); const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio); const limitingFov = Math.min(verticalFov, horizontalFov); // Target 57% sphere occupancy so perspective still leaves at least 40% diff --git a/src/data/cameraFraming.test.mjs b/src/data/cameraFraming.test.mjs new file mode 100644 index 0000000000..55da2fa803 --- /dev/null +++ b/src/data/cameraFraming.test.mjs @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { rangeForBoundingSphere } from './cameraFraming.js'; + +/** The range as it was read from Cesium's frustum before the camera port. */ +function rangeFromFrustum(frustum, radius) { + const verticalFov = frustum.fov; + const aspectRatio = Math.max(0.5, frustum.aspectRatio); + const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio); + const limitingFov = Math.min(verticalFov, horizontalFov); + return (radius / Math.sin((limitingFov * 0.57) / 2)) * 1.05; +} + +for (const aspectRatio of [16 / 9, 390 / 844, 1]) { + test(`framing reads the frustum's field of view through the camera port (aspect ${aspectRatio.toFixed(2)})`, () => { + const frustum = new Cesium.PerspectiveFrustum({ + fov: Math.PI / 3, + aspectRatio, + near: 1, + far: 1e8, + }); + const viewer = bindFakeCesiumCamera({ camera: { frustum } }); + const range = rangeForBoundingSphere(viewer, 250); + assert.ok( + Math.abs(range - rangeFromFrustum(frustum, 250)) < 1e-6, + `${range} vs ${rangeFromFrustum(frustum, 250)}`, + ); + }); +} + +test('framing without a camera assumes a 60 degree square view', () => { + const expected = rangeFromFrustum({ fov: Math.PI / 3, aspectRatio: 1 }, 100); + assert.ok(Math.abs(rangeForBoundingSphere({}, 100) - expected) < 1e-9); +}); diff --git a/src/data/cameraSensitivity.js b/src/data/cameraSensitivity.js deleted file mode 100644 index 87933dc9e1..0000000000 --- a/src/data/cameraSensitivity.js +++ /dev/null @@ -1,93 +0,0 @@ -// src/data/cameraSensitivity.js -/** - * Shared claims on `camera.percentageChanged`. - * - * `camera.changed` fires once the view has moved by this fraction, and it is a - * single number on the camera that every listener in the app shares. Several - * layers want it finer than the default — traffic, bikeshare and transit all - * ask for 0.05 so they notice they have entered a coverage area — and each of - * them used to write the number directly and hand back whatever it remembered. - * - * That cannot work, because a number is not an owner. Two layers asking for the - * same 0.05 write the same value, so when the first one leaves it sees its own - * number still in place, concludes nothing else has claimed it, and restores - * the coarse default out from under a layer that is still running. The symptom - * is a camera-driven layer that quietly stops noticing the camera: Transit is - * turned off and Bikeshare stops loading new cities until something else nudges - * it. - * - * So ownership is tracked explicitly. Claims are named, the camera gets the - * finest value anyone has asked for, and the original value returns only when - * the last claim is gone. Claiming twice under one name replaces that claim. - * - * This is bookkeeping, not policy: it never decides what a layer should ask - * for, only that nobody's answer is taken away while they still need it. - */ - -/** @type {WeakMap}>} */ -const _cameras = new WeakMap(); - -/** The value Cesium starts a camera at, used when the camera reports nothing. */ -const DEFAULT_PERCENTAGE_CHANGED = 0.5; - -function ledgerFor(camera) { - let ledger = _cameras.get(camera); - if (!ledger) { - const base = Number.isFinite(camera.percentageChanged) - ? camera.percentageChanged - : DEFAULT_PERCENTAGE_CHANGED; - ledger = { base, claims: new Map() }; - _cameras.set(camera, ledger); - } - return ledger; -} - -function applyLedger(camera, ledger) { - let value = ledger.base; - for (const claimed of ledger.claims.values()) { - if (claimed < value) value = claimed; - } - camera.percentageChanged = value; - return value; -} - -/** - * Ask for a camera-change sensitivity at least as fine as `value`. - * @param {object|null|undefined} camera A Cesium camera (or anything with `percentageChanged`). - * @param {string} owner Stable claim name, usually the layer id. - * @param {number} value Requested `percentageChanged`. - * @returns {number|null} The value now in force, or null when there is no camera. - */ -export function claimCameraSensitivity(camera, owner, value) { - if (!camera || !owner || !Number.isFinite(value)) return null; - const ledger = ledgerFor(camera); - ledger.claims.set(owner, value); - return applyLedger(camera, ledger); -} - -/** - * Give up one claim. The camera keeps the finest value still claimed by - * somebody else, and returns to its original only when none are left. - * @param {object|null|undefined} camera - * @param {string} owner - * @returns {number|null} The value now in force, or null when there is no camera. - */ -export function releaseCameraSensitivity(camera, owner) { - if (!camera || !owner) return null; - const ledger = _cameras.get(camera); - if (!ledger) return null; - if (!ledger.claims.delete(owner)) return camera.percentageChanged; - const applied = applyLedger(camera, ledger); - if (ledger.claims.size === 0) _cameras.delete(camera); - return applied; -} - -/** - * Who currently holds a claim. For tests and diagnostics only. - * @param {object|null|undefined} camera - * @returns {Array} - */ -export function cameraSensitivityClaims(camera) { - const ledger = camera ? _cameras.get(camera) : null; - return ledger ? [...ledger.claims.keys()] : []; -} diff --git a/src/data/cctv.js b/src/data/cctv.js index 884638a964..58fe30c9e2 100644 --- a/src/data/cctv.js +++ b/src/data/cctv.js @@ -66,6 +66,7 @@ export const materializeCctvVisibleCoverageEntities = export const _extractPickedCameraIdForTest = layer._extractPickedCameraIdForTest; export const _setCctvCoverageStateForTest = layer._setCctvCoverageStateForTest; +export const _cctvIconsForTest = layer._cctvIconsForTest; export const focusCctvRecord = layer.focusCctvRecord; export const maybeAutoHop = layer.maybeAutoHop; export const openingCameraId = layer.openingCameraId; diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index 087422584c..35a634c6cf 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -13,6 +13,11 @@ // // computeFrustumGeometry is PURE (no viewer, no scene queries) so it runs under // plain node:test. +import { + bindFakeCesiumCamera, + followEntity, +} from '../testSupport/fakeCameraPort.mjs'; +import { entityFollowTarget, followedOf } from './followed.js'; import { test } from 'node:test'; // Preserve structural pins across component qualification and formatter wrapping. function componentFunctionSource(fn) { @@ -32,6 +37,7 @@ import cctvLayer, { _extractPickedCameraIdForTest, _updateCctvProjectionPlaneForTest, _setCctvCoverageStateForTest, + _cctvIconsForTest, _pushAmbientCardEntriesForTest, _setCctvOverlayHostForTest, activationProbeClampRange, @@ -82,27 +88,12 @@ import { IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; const ASPECT = 16 / 9; const toRad = (deg) => (deg * Math.PI) / 180; -const GESTURE_TYPES = { - LEFT_DOWN: 'left-down', - MOUSE_MOVE: 'mouse-move', - LEFT_UP: 'left-up', - LEFT_CLICK: 'left-click', -}; - -function makeGestureHandler() { - const actions = new Map(); - return { - setInputAction(callback, type) { - actions.set(type, callback); - }, - fire(type, event) { - actions.get(type)?.(event); - }, - }; -} +const GESTURE_TYPES = FAKE_EVENT_TYPES; // Same spherical earth radius projectPoint uses (R = 6371 km) so the // lat/lon→metres conversion in the assertions matches the module's math. const M_PER_DEG = (Math.PI / 180) * 6371000; @@ -293,15 +284,9 @@ test('default COVERAGE refresh materializes the active and visible camera frustu coverageEntities: [], projection: null, })); - const inserted = []; - const viewer = { - entities: { - add(entity) { - inserted.push(entity); - return entity; - }, - }, - }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + const inserted = () => draw.find('cctv:')?.items ?? new Map(); const activeRecord = records.at(-1); try { @@ -316,10 +301,16 @@ test('default COVERAGE refresh materializes the active and visible camera frustu (record) => record.coverageEntities.length > 0, ); assert.equal( - inserted.length, + inserted().size, 14 * 5, 'default COVERAGE ON builds the 14-camera visible cohort', ); + assert.ok( + [...inserted().keys()].every((id) => + /^cctv-cam-\d+-(ray-..|cap)$/.test(id), + ), + 'coverage lines keep the cctv-- ids', + ); assert.equal(materialized.length, 14); assert.equal( activeRecord.coverageEntities.length, @@ -335,7 +326,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu ...records[0], camera: { ...records[0].camera, id: 'projection-only' }, coverageEntities: [], - projection: { planeEntity: { show: false } }, + projection: { plane: { show: false } }, }; _setCctvCoverageStateForTest({ viewer, @@ -350,22 +341,31 @@ test('default COVERAGE refresh materializes the active and visible camera frustu projectionOnly.coverageEntities.every((entity) => entity.show), 'COVERAGE OFF keeps the active projection frustum materialized and visible', ); + assert.ok( + projectionOnly.coverageEntities.every( + (entity) => inserted().get(entity.id)?.show === true, + ), + 'and draws it', + ); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { const record = (id, feedType) => ({ camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, - billboard: {}, + // Every catalog record is placed as it is made, and drawn there. + position: { x: 6378137, y: 0, z: 0 }, coverageEntities: [], projection: null, }); const idleVideo = record('idle-hls', 'hls'); const idleStill = record('idle-image', 'image'); const activeVideo = record('active-hls', 'hls'); - const viewer = { entities: { add: (entity) => entity } }; + const viewer = {}; + const { unbind } = bindFakeDraw(viewer); try { // Disabled keeps the active video camera from opening a real projection; @@ -378,18 +378,23 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ coverageMode: 'off', }); refreshCoverageStyles(); - assert.equal(idleVideo.billboard.color, LIVE_CAMERA_COLOR); - assert.equal(idleStill.billboard.color, IDLE_CAMERA_COLOR); - assert.equal(activeVideo.billboard.color, ACTIVE_CAMERA_COLOR); + const icons = _cctvIconsForTest(); + const color = (record) => icons.item(record.camera.id).color; + assert.deepEqual(color(idleVideo), LIVE_CAMERA_COLOR); + assert.deepEqual(color(idleStill), IDLE_CAMERA_COLOR); + assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR); + assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); + assert.equal(icons.item(idleVideo.camera.id).scale, 1); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); test('geometry drain pacing yields to tracked and cockpit camera ownership', () => { assert.deepEqual(cctvGeometryDrainPacing(), { batchSize: 4, delayMs: 120 }); assert.deepEqual( - cctvGeometryDrainPacing({ trackedEntity: { id: 'flight-1' } }), + cctvGeometryDrainPacing({ followed: { key: 'flights:1' } }), { batchSize: 2, delayMs: 250 }, ); assert.deepEqual(cctvGeometryDrainPacing({ cockpitActive: true }), { @@ -404,13 +409,13 @@ test('geometry drain pacing yields to tracked and cockpit camera ownership', () }); test('geometry drain rechecks pacing when tracking releases between batches', () => { - let trackedEntity = { id: 'flight-1' }; + let followed = { key: 'flights:1' }; const queue = Array.from({ length: 10 }, (_, index) => index + 1); const visited = []; const runBatch = () => processCctvGeometryDrainBatch({ queue, - readOwnership: () => ({ trackedEntity, cockpitActive: false }), + readOwnership: () => ({ followed, cockpitActive: false }), visit: (record) => visited.push(record), progress: () => {}, complete: () => {}, @@ -420,7 +425,7 @@ test('geometry drain rechecks pacing when tracking releases between batches', () assert.deepEqual(trackedBatch, { hasMore: true, batchSize: 2, delayMs: 250 }); assert.deepEqual(visited, [1, 2]); - trackedEntity = null; + followed = null; const untrackedBatch = runBatch(); assert.deepEqual(untrackedBatch, { hasMore: true, @@ -696,18 +701,16 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou camera: { id: 'a' }, activationDone: true, probeClampRangeM: 105, - billboard: { color: 'keep-color', scale: 1.25 }, coverageEntities: [{ show: true }, { show: true }], - projection: { planeEntity: { show: true } }, - viewshedPrimitive: viewshedA, + projection: { plane: { show: true } }, + viewshedVolume: viewshedA, }, { camera: { id: 'b' }, activationDone: true, probeClampRangeM: 146, - billboard: { color: 'keep-color', scale: 1 }, projection: null, - viewshedPrimitive: viewshedB, + viewshedVolume: viewshedB, }, ]; const destroyed = []; @@ -716,7 +719,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou records, (record) => { destroyed.push(record.camera.id); - record.viewshedPrimitive = null; + record.viewshedVolume = null; }, 'a', ); @@ -727,10 +730,10 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou ), [false, false], ); - assert.equal(records[0].projection.planeEntity.show, false); + assert.equal(records[0].projection.plane.show, false); assert.deepEqual(destroyed, ['a', 'b']); - assert.equal(records[0].viewshedPrimitive, null); - assert.equal(records[1].viewshedPrimitive, null); + assert.equal(records[0].viewshedVolume, null); + assert.equal(records[1].viewshedVolume, null); assert.deepEqual( records.map((record) => record.probeClampRangeM), [null, null], @@ -739,13 +742,6 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou records.map((record) => record.activationDone), [false, true], ); - assert.deepEqual( - records.map((record) => record.billboard), - [ - { color: 'keep-color', scale: 1.25 }, - { color: 'keep-color', scale: 1 }, - ], - ); }); test('real active monitor plane owns one protected host label and no native label entity', () => { @@ -755,7 +751,8 @@ test('real active monitor plane owns one protected host label and no native labe setVisible: (...args) => calls.push(['visible', ...args]), clearSource: (...args) => calls.push(['clear', ...args]), }; - const viewer = { entities: new Cesium.EntityCollection() }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); const record = { camera: { ...UNCLAMPED_CAMERA, @@ -779,17 +776,23 @@ test('real active monitor plane owns one protected host label and no native labe }); refreshCoverageStyles(); + assert.ok(runtime.plane, 'runtime guard requires a real monitor plane'); + const planes = draw.find('cctv:') + ? [...draw.sets.values()].filter((set) => set.kind === 'quads') + : []; + assert.equal(planes.length, 1, 'the plane draws as a quad'); + const quad = planes[0].items.get(`cctv-${record.camera.id}-plane`); + assert.ok(quad, 'under its cctv--plane id'); + assert.equal(quad.alpha, 0.95); + assert.deepEqual(quad.size, [ + record.frustumGeometry.halfW * 2, + record.frustumGeometry.halfH * 2, + ]); + assert.ok(quad.outline, 'with its outline'); + assert.equal(quad.meta.cameraId, record.camera.id); assert.ok( - runtime.planeEntity, - 'runtime guard requires a real monitor-plane entity', - ); - assert.equal(runtime.planeEntity.label, undefined); - assert.ok( - runtime.planeEntity.plane, - 'monitor plane geometry remains native', - ); - assert.ok( - viewer.entities.values.every((entity) => entity.label === undefined), + [...draw.sets.values()].every((set) => set.kind !== 'labels'), + 'and no native label', ); const publication = calls.find( ([type, sourceId]) => @@ -805,7 +808,8 @@ test('real active monitor plane owns one protected host label and no native labe assert.equal(entry.position(), runtime.labelPosition); assert.equal(entry.protected, true); assert.equal(entry.paintLane, 'selected'); - assert.equal(runtime.planeEntity.show, true); + assert.equal(runtime.plane.show, true); + assert.equal(quad.show, true, 'shown once projected'); const cachedPosition = runtime.labelPosition; record.frustumPositions.label = Cesium.Cartesian3.add( @@ -833,7 +837,8 @@ test('real active monitor plane owns one protected host label and no native labe showProjection: false, }); refreshCoverageStyles(); - assert.equal(runtime.planeEntity.show, false); + assert.equal(runtime.plane.show, false); + assert.equal(planes[0].items.get(quad.id).show, false); assert.deepEqual(calls.slice(-2), [ ['clear', 'cctv-projection'], ['visible', 'cctv-projection', false], @@ -841,6 +846,7 @@ test('real active monitor plane owns one protected host label and no native labe } finally { _setCctvCoverageStateForTest({ enabled: false }); _setCctvOverlayHostForTest(); + unbind(); } }); @@ -893,13 +899,18 @@ test('CCTV disable→enable defers the active-camera re-probe until its next act test('CCTV focus distinguishes tracking ownership from a missing active camera', () => { let flyCalls = 0; const viewer = { - trackedEntity: { id: 'tracked-flight' }, camera: { flyToBoundingSphere() { flyCalls += 1; }, }, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. + trackedEntityChanged: new Cesium.Event(), + entities: {}, }; + bindFakeCesiumCamera(viewer); + followEntity(viewer, { id: 'tracked-flight' }); const record = { camera: { rangeM: 210, headingDeg: 41 }, position: { x: 1, y: 2, z: 3 }, @@ -931,6 +942,7 @@ test('CCTV focus reports when the camera flight starts', () => { }, }, }; + bindFakeCesiumCamera(viewer); const record = { camera: { rangeM: 210, headingDeg: 41 }, position: { x: 1, y: 2, z: 3 }, @@ -951,6 +963,7 @@ test('CCTV focus refuses camera flights while cockpit owns the view', () => { }, }, }; + bindFakeCesiumCamera(viewer); const record = { camera: { rangeM: 210, headingDeg: 41 }, position: { x: 1, y: 2, z: 3 }, @@ -1003,7 +1016,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat assert.deepEqual(requests, [{ cameraId: 'atx-cam-3' }]); assert.match( componentFunctionSource(cctvLayer.init), - /bindCctvWorldClickGesture\(_clickHandler/, + /bindCctvWorldClickGesture\(\s*input,/, ); assert.match( componentFunctionSource(cctvLayer.init), @@ -1026,10 +1039,8 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat // ─── Empty-space deselection and stable null-active state ────────────────── function makeDeselectViewer() { - return { - entities: new Cesium.EntityCollection(), + const viewer = { isDestroyed: () => false, - trackedEntity: { id: 'sibling-track-owner' }, camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 4_000), positionCartographic: Cesium.Cartographic.fromDegrees( @@ -1052,6 +1063,20 @@ function makeDeselectViewer() { requestRender() {}, }, }; + // The layer's lines and plane draw through this. The eye has a pose only + // once a test places it (`viewer.eye`, degrees and metres). + viewer.draw = bindFakeDraw(viewer, { + camera: { + pose: () => (viewer.eye ? { ...viewer.eye } : undefined), + on: () => () => {}, + // A sibling layer's follow owns the camera. + followed: entityFollowTarget({ id: 'sibling-track-owner' }, {}), + follow(target) { + this.followed = target; + }, + }, + }).draw; + return viewer; } function makeDeselectRecord(id, index = 0) { @@ -1085,7 +1110,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and assert.equal(cctvEmptyClickDeselects(null, { activeCameraId: null }), false); assert.equal( cctvEmptyClickDeselects( - { id: 'registered-sibling' }, + { set: 'flights:1', id: 'registered-sibling', surface: false }, { activeCameraId: 'cam-1', }, @@ -1094,7 +1119,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and ); assert.equal( cctvEmptyClickDeselects( - { id: { id: 'unregistered-local-entity' } }, + { set: '', id: 'unregistered-local-entity', surface: false }, { activeCameraId: 'cam-1', }, @@ -1103,7 +1128,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and ); assert.equal( cctvEmptyClickDeselects( - { primitive: { id: 'unregistered-primitive' } }, + { set: '', id: 'unregistered-primitive', surface: false }, { activeCameraId: 'cam-1', }, @@ -1112,7 +1137,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and ); assert.equal( cctvEmptyClickDeselects( - { id: '' }, + { set: '', id: '', surface: false }, { activeCameraId: 'cam-1', }, @@ -1122,13 +1147,13 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and ); assert.equal( cctvEmptyClickDeselects( - { primitive: {} }, + { set: '', id: null, surface: false }, { activeCameraId: 'cam-1', }, ), true, - 'an ID-less surface pick remains true empty space', + 'something with no id remains true empty space', ); const initSource = componentFunctionSource(cctvLayer.init); @@ -1142,55 +1167,86 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and }); test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => { - const billboard = { id: 'shared-id' }; - const ownedCoverageEntity = { - id: 'cctv-shared-id-cap', - properties: { cctvCameraId: 'shared-id' }, - }; - const record = { - ...makeDeselectRecord('shared-id'), - billboard, - coverageEntities: [ownedCoverageEntity], - }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + const record = makeDeselectRecord('shared-id'); _setCctvCoverageStateForTest({ + viewer, records: [record], activeCameraId: 'shared-id', }); try { + refreshCoverageStyles(); + const coverage = [...draw.sets.values()].find( + (set) => set.kind === 'lines' && set.spec.id.startsWith('cctv:'), + ); + assert.ok(coverage.items.has('cctv-shared-id-cap')); + const lineHit = (set, id) => ({ + set, + id, + meta: { cameraId: 'shared-id' }, + surface: false, + }); assert.equal( - _extractPickedCameraIdForTest({ id: 'shared-id', primitive: billboard }), + _extractPickedCameraIdForTest({ + set: _cctvIconsForTest().setId, + id: 'shared-id', + surface: false, + }), 'shared-id', ); assert.equal( _extractPickedCameraIdForTest({ + set: 'sibling:1:icons', id: 'shared-id', - primitive: { id: 'shared-id' }, + surface: false, }), null, - 'a sibling primitive with the same canonical ID cannot activate CCTV', - ); - assert.equal( - _extractPickedCameraIdForTest({ id: { id: 'shared-id' } }), - null, - 'a sibling Entity with the same canonical ID cannot activate CCTV', - ); - assert.equal( - _extractPickedCameraIdForTest({ id: ownedCoverageEntity }), - 'shared-id', - 'an exact stored CCTV coverage Entity retains activation ownership', + "a sibling set's icon with the same canonical ID cannot activate CCTV", ); assert.equal( _extractPickedCameraIdForTest({ - id: { - id: 'sibling-entity', - properties: { cctvCameraId: 'shared-id' }, - }, + set: _cctvIconsForTest().setId, + id: 'not-a-camera', + surface: false, + }), + null, + 'an id the icon book does not draw is not a camera', + ); + assert.equal( + _extractPickedCameraIdForTest( + lineHit(coverage.spec.id, 'cctv-shared-id-cap'), + ), + 'shared-id', + 'a coverage line the record draws retains activation ownership', + ); + assert.equal( + _extractPickedCameraIdForTest( + lineHit('sibling:1:lines', 'cctv-shared-id-cap'), + ), + null, + "a sibling set's item with a CCTV id and meta cannot activate CCTV", + ); + assert.equal( + _extractPickedCameraIdForTest({ + set: 'sibling:1:entities', + id: 'sibling-entity', + meta: { cctvCameraId: 'shared-id', cameraId: 'shared-id' }, + surface: false, }), null, 'a sibling cannot impersonate CCTV by copying its property shape', ); + assert.equal( + _extractPickedCameraIdForTest( + lineHit(coverage.spec.id, 'cctv-shared-id-stray'), + ), + null, + 'a camera id alone is not ownership: the record must draw the item', + ); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); @@ -1231,7 +1287,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose pitch: viewer.camera.pitch, roll: viewer.camera.roll, transform: Cesium.Matrix4.clone(viewer.camera.transform), - trackedEntity: viewer.trackedEntity, + followed: followedOf(viewer), }; assert.equal(deactivateActiveCamera(), true); @@ -1244,7 +1300,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose assert.equal(publications.at(-1).activeCameraId, null); assert.equal(publications.at(-1).activeCamera, null); assert.equal(publications.at(-1).enabled, true); - assert.equal(runtime.planeEntity.show, false); + assert.equal(runtime.plane.show, false); assert.equal(record.probeClampRangeM, null); assert.equal(record.activationDone, false); assert.deepEqual(viewer.camera.positionWC, pose.positionWC); @@ -1256,7 +1312,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose assert.equal(viewer.camera.pitch, pose.pitch); assert.equal(viewer.camera.roll, pose.roll); assert.deepEqual(viewer.camera.transform, pose.transform); - assert.equal(viewer.trackedEntity, pose.trackedEntity); + assert.equal(followedOf(viewer), pose.followed); assert.equal(viewer.camera.flyCalls || 0, 0); unsubscribe(); } finally { @@ -1314,16 +1370,7 @@ test('CCTV opens on the camera nearest the viewer, not the first in the catalog' // QA 2026-11-05: at King's Cross, turning CCTV on showed a Sydney camera, // the first catalog record, instead of the TfL camera 0.3 km away. const viewer = makeDeselectViewer(); - viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees( - -0.1209, - 51.5295, - 187, - ); - viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees( - -0.1209, - 51.5295, - 187, - ); + viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 }; const sydney = makeDeselectRecord('au-sydney'); sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 }; const london = makeDeselectRecord('gb-kings-cross'); @@ -1358,11 +1405,7 @@ test('the opening camera follows a shared view that lands after CCTV turned on, // A share link turns CCTV on before its flight lands, so enable() picks // from the startup view; the flight's settled move re-picks near London. const viewer = makeDeselectViewer(); - viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees( - -0.1209, - 51.5295, - 187, - ); + viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 }; const sydney = makeDeselectRecord('au-sydney'); sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 }; const london = makeDeselectRecord('gb-kings-cross'); @@ -1529,29 +1572,22 @@ test('active CCTV camera is absent from host by default and protected only when test('CCTV drag-then-release over a camera is inert, while a clean tap activates and dispatches', () => { let timeMs = 0; let activationCalls = 0; - const handler = makeGestureHandler(); + const { input, handler } = fakeInput({ scene: {} }, { now: () => timeMs }); const target = new EventTarget(); const requests = []; target.addEventListener(CCTV_FOCUS_REQUEST_EVENT, (event) => requests.push(event.detail), ); - bindCctvWorldClickGesture( - handler, - () => { - activateCctvCameraFromWorldClick( - 'atx-cam-3', - () => { - activationCalls += 1; - return CCTV_ACTIVATION_RESULT.ACTIVATED; - }, - target, - ); - }, - { - now: () => timeMs, - eventTypes: GESTURE_TYPES, - }, - ); + bindCctvWorldClickGesture(input, () => { + activateCctvCameraFromWorldClick( + 'atx-cam-3', + () => { + activationCalls += 1; + return CCTV_ACTIVATION_RESULT.ACTIVATED; + }, + target, + ); + }); handler.fire(GESTURE_TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } }); timeMs = 20; diff --git a/src/data/cctvGizmo.js b/src/data/cctvGizmo.js index fa15c55320..1a865c8736 100644 --- a/src/data/cctvGizmo.js +++ b/src/data/cctvGizmo.js @@ -8,7 +8,7 @@ * - Pure drag math (this top section): ray↔axis closest-point, ray↔plane * intersection with a grazing-angle guard, ring angles. All unit-tested * under node:test with zero scene dependencies. - * - createCalibrationGizmo (below): the entity + ScreenSpaceEventHandler + * - createCalibrationGizmo (below): the draw-set + pointer-input * controller that renders grab-able handles on the ACTIVE camera and turns * drags into calibration patches through a narrow callback interface. It * never touches the layer's records/stores directly. @@ -23,8 +23,10 @@ * throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query * invariant is untouched. */ -import * as Cesium from 'cesium'; -import { isPointerFree } from './inputOwnership.js'; +import { inputFor } from '../input/dispatcher.js'; +import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js'; +import { eastNorthUp } from '../geo/frames.js'; +import { add, dot, scale, sub } from '../geo/vector.js'; // Grazing guard (spec §5): reject plane intersections when the view ray is // nearly parallel to the constraint plane — the hit point races to infinity @@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08; // Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²). const PARALLEL_EPS = 1e-6; -const scratchW = new Cesium.Cartesian3(); - /** * Parameter t (metres) along an axis line of the point on that axis closest * to a mouse ray. Both directions must be normalized. @@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3(); * t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin, * d = rayDir·w, e = axisDir·w. * - * @param {Cesium.Cartesian3} rayOrigin - * @param {Cesium.Cartesian3} rayDir - Unit. - * @param {Cesium.Cartesian3} axisOrigin - * @param {Cesium.Cartesian3} axisDir - Unit. + * Vectors are ECEF `{x, y, z}`. + * @param {{x: number, y: number, z: number}} rayOrigin + * @param {{x: number, y: number, z: number}} rayDir - Unit. + * @param {{x: number, y: number, z: number}} axisOrigin + * @param {{x: number, y: number, z: number}} axisDir - Unit. * @returns {number|null} Axis parameter in metres, or null when near-parallel. */ export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) { - const b = Cesium.Cartesian3.dot(rayDir, axisDir); + const b = dot(rayDir, axisDir); const denom = 1 - b * b; if (Math.abs(denom) < PARALLEL_EPS) return null; - const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW); - const d = Cesium.Cartesian3.dot(rayDir, w); - const e = Cesium.Cartesian3.dot(axisDir, w); + const w = sub(rayOrigin, axisOrigin); + const d = dot(rayDir, w); + const e = dot(axisDir, w); return (e - b * d) / denom; } /** * Intersects a mouse ray with a plane, refusing grazing configurations * (|rayDir·normal| < 0.08) and hits behind the ray origin. - * @param {Cesium.Cartesian3} rayOrigin - * @param {Cesium.Cartesian3} rayDir - Unit. - * @param {Cesium.Cartesian3} planeOrigin - * @param {Cesium.Cartesian3} planeNormal - Unit. - * @returns {Cesium.Cartesian3|null} Hit point (new instance), or null. + * @param {{x: number, y: number, z: number}} rayOrigin + * @param {{x: number, y: number, z: number}} rayDir - Unit. + * @param {{x: number, y: number, z: number}} planeOrigin + * @param {{x: number, y: number, z: number}} planeNormal - Unit. + * @returns {{x: number, y: number, z: number}|null} Hit point (new), or null. */ export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) { - const denom = Cesium.Cartesian3.dot(rayDir, planeNormal); + const denom = dot(rayDir, planeNormal); if (Math.abs(denom) < GRAZING_DOT_MIN) return null; - const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW); - const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom; + const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom; if (s < 0) return null; - const hit = Cesium.Cartesian3.multiplyByScalar( - rayDir, - s, - new Cesium.Cartesian3(), - ); - return Cesium.Cartesian3.add(rayOrigin, hit, hit); + return add(rayOrigin, scale(rayDir, s)); } /** * Angle (radians, atan2 convention) of a point around a ring center in the * plane spanned by two orthonormal basis vectors. - * @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane. - * @param {Cesium.Cartesian3} center - Ring center. - * @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0). - * @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°). + * @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane. + * @param {{x: number, y: number, z: number}} center - Ring center. + * @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0). + * @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°). * @returns {number} Angle in (−π, π]. */ export function ringAngle(hitPoint, center, basisA, basisB) { - const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW); - return Math.atan2( - Cesium.Cartesian3.dot(v, basisB), - Cesium.Cartesian3.dot(v, basisA), - ); + const v = sub(hitPoint, center); + return Math.atan2(dot(v, basisB), dot(v, basisA)); } /** @@ -117,9 +109,9 @@ export function signedAngleDelta(fromRad, toRad) { // Gizmo controller // --------------------------------------------------------------------------- -/** Entity id prefix for every gizmo part — the layer's pick-owner regex and - * click-to-select guard key off this. Gizmo entities NEVER carry a - * `cctvCameraId` property, so the layer's selection path ignores them. */ +/** Item id prefix for every gizmo part — the layer's pick-owner regex and + * click-to-select guard key off this. Gizmo parts NEVER get a camera id in + * the layer's pick store, so the layer's selection path ignores them. */ export const GIZMO_ID_PREFIX = 'cctv-gizmo-'; const RING_SEGMENTS = 96; @@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6; const DRAG_THROTTLE_MS = 16; const HOVER_THROTTLE_MS = 120; -const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff'); -const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0'); -const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252'); -const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a'); -const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff'); -const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a'); +/** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */ +function rgba(hex, alpha = 1) { + const n = Number.parseInt(hex.slice(1), 16); + return [ + ((n >> 16) & 255) / 255, + ((n >> 8) & 255) / 255, + (n & 255) / 255, + alpha, + ]; +} + +const COLOR_RING_HEADING = '#35d8ff'; +const COLOR_RING_PITCH = '#ff5fd0'; +const COLOR_MOVE_EAST = '#ff5252'; +const COLOR_MOVE_NORTH = '#52ff7a'; +const COLOR_MOVE_UP = '#5b8cff'; +const COLOR_HANDLE = '#ffd97a'; +const HANDLE_OUTLINE = [0, 0, 0, 0.7]; const toRadians = (deg) => (deg * Math.PI) / 180; const toDeg = (rad) => (rad * 180) / Math.PI; /** * Local ENU unit axes at an ECEF position. - * @param {Cesium.Cartesian3} position - * @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}} + * @param {{x: number, y: number, z: number}} position + * @returns {{east: object, north: object, up: object}} */ function enuAxes(position) { - const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position); - const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3()); - return { - east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()), - north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()), - up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()), - }; + const frame = eastNorthUp(position); + return { east: frame.x, north: frame.y, up: frame.z }; } -/** a*sa + b*sb (fresh Cartesian3). */ +/** a*sa + b*sb. */ function combine2(a, sa, b, sb) { - const out = Cesium.Cartesian3.multiplyByScalar( - a, - sa, - new Cesium.Cartesian3(), - ); - const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3()); - return Cesium.Cartesian3.add(out, t, out); + return add(scale(a, sa), scale(b, sb)); } +/** The midpoint of two points. */ +const midpoint = (a, b) => scale(add(a, b), 0.5); + /** * View-frame unit vectors for a pose within a local ENU frame: horizontal * forward, viewer-right, and the full pitched view axis. @@ -192,25 +188,57 @@ function ringPositions(center, radius, basisA, basisB) { const positions = []; for (let i = 0; i <= RING_SEGMENTS; i++) { const angle = (i / RING_SEGMENTS) * 2 * Math.PI; - const offset = combine2( - basisA, - Math.cos(angle) * radius, - basisB, - Math.sin(angle) * radius, + positions.push( + add( + center, + combine2( + basisA, + Math.cos(angle) * radius, + basisB, + Math.sin(angle) * radius, + ), + ), ); - positions.push(Cesium.Cartesian3.add(center, offset, offset)); } return positions; } +/** The ring and arrow parts: their colour, width and whether an arrow. */ +const LINE_PARTS = Object.freeze([ + ['ring-heading', COLOR_RING_HEADING, 3, false], + ['ring-pitch', COLOR_RING_PITCH, 3, false], + ['move-east', COLOR_MOVE_EAST, 12, true], + ['move-north', COLOR_MOVE_NORTH, 12, true], + ['move-up', COLOR_MOVE_UP, 12, true], +]); +/** The point parts (an arrow's tip included): colour and first size. */ +const POINT_PARTS = Object.freeze([ + ['move-east', COLOR_MOVE_EAST, 14], + ['move-north', COLOR_MOVE_NORTH, 14], + ['move-up', COLOR_MOVE_UP, 14], + ['handle-range', COLOR_HANDLE, 13], + ['handle-fov-l', COLOR_HANDLE, 10], + ['handle-fov-r', COLOR_HANDLE, 10], +]); +/** Every part a pick can grab. */ +const PARTS = new Set([ + ...LINE_PARTS.map(([part]) => part), + ...POINT_PARTS.map(([part]) => part), +]); + +let gizmoInstances = 0; + /** * Creates the calibration gizmo controller (design §3c). Renders grab-able * handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags * into calibration patches through a narrow callback interface — the gizmo - * never touches layer records/stores directly. + * never touches layer records/stores directly. It draws through the + * renderer's draw port (a line set for the rings and arrows, a point set + * for the handles and arrow tips, each item `cctv-gizmo-`) and picks + * and casts rays through its query port. * * @param {Object} deps - * @param {Cesium.Viewer} deps.viewer + * @param {object} deps.viewer - The viewer whose renderer draws it. * @param {function(): Object|null} deps.getActiveRecord - Returns the record * the gizmo should attach to, or null to hide (layer decides: enabled + * calibration mode + active camera). @@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) { * end, for the PINNED drag record. * @returns {{setEnabled: function(boolean): void, refresh: function(): void, * destroy: function(): void, isDragging: function(): boolean, - * isEnabled: function(): boolean}} + * isEnabled: function(): boolean, partsForTest: function(): Object}} */ export function createCalibrationGizmo({ viewer, @@ -234,73 +262,70 @@ export function createCalibrationGizmo({ let hoveredId = null; let lastDragAt = 0; let lastHoverAt = 0; - const entities = new Map(); // part -> Entity + // Whether the parts are drawn now, and each point part's pixel size. + let shown = false; + const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size])); + // The parts' geometry as last drawn: ECEF line positions and point spots. + const linePositions = new Map(); + const pointPositions = new Map(); - const scene = viewer.scene; - const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas); + const input = inputFor(viewer); + let releaseCamera = null; - /** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */ - function addEntity(part, options) { - const id = `${GIZMO_ID_PREFIX}${part}`; - const stale = viewer.entities.getById(id); - if (stale) viewer.entities.remove(stale); - const entity = viewer.entities.add({ id, show: false, ...options }); - entities.set(part, entity); - return entity; - } + const instance = ++gizmoInstances; + const draw = drawOf(viewer); + const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` }); + const points = draw.points({ id: `cctv-gizmo:${instance}:points` }); - function polylinePart(part, color, width, arrow = false) { - addEntity(part, { - ...(arrow - ? { - position: Cesium.Cartesian3.ZERO, - point: { - pixelSize: 14, - color, - outlineColor: Cesium.Color.BLACK.withAlpha(0.7), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - } - : {}), - polyline: { - positions: [], - width, - material: arrow - ? new Cesium.PolylineArrowMaterialProperty(color) - : color.withAlpha(0.9), + /** The rings and arrows as they now are. */ + function lineItems() { + const items = []; + for (const [part, color, widthPx, arrow] of LINE_PARTS) { + const positions = linePositions.get(part); + if (!positions) continue; + items.push({ + id: `${GIZMO_ID_PREFIX}${part}`, + positions, + widthPx, + mode: '3d', + style: arrow + ? { kind: 'arrow', color: rgba(color) } + : { kind: 'solid', color: rgba(color, 0.9) }, // Standard gizmo convention: parts behind geometry stay clearly // visible, just dimmed (a street-level mount buries half the heading // ring in sloped photogrammetry tiles — smoke-tested 2026-07-05). - depthFailMaterial: color.withAlpha(0.45), - }, - }); + depthFail: { kind: 'solid', color: rgba(color, 0.45) }, + show: shown, + }); + } + return items; } - function pointPart(part, color, pixelSize) { - addEntity(part, { - position: Cesium.Cartesian3.ZERO, - point: { - pixelSize, - color, - outlineColor: Cesium.Color.BLACK.withAlpha(0.7), + /** The handles and arrow tips as they now are. */ + function pointItems() { + const items = []; + for (const [part, color] of POINT_PARTS) { + const pos = pointPositions.get(part); + if (!pos) continue; + items.push({ + id: `${GIZMO_ID_PREFIX}${part}`, + pos, + pixelSize: pointSizes.get(part), + color: rgba(color), + outlineColor: HANDLE_OUTLINE, outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + disableDepthTest: Number.POSITIVE_INFINITY, + show: shown, + }); + } + return items; } - polylinePart('ring-heading', COLOR_RING_HEADING, 3); - polylinePart('ring-pitch', COLOR_RING_PITCH, 3); - polylinePart('move-east', COLOR_MOVE_EAST, 12, true); - polylinePart('move-north', COLOR_MOVE_NORTH, 12, true); - polylinePart('move-up', COLOR_MOVE_UP, 12, true); - pointPart('handle-range', COLOR_HANDLE, 13); - pointPart('handle-fov-l', COLOR_HANDLE, 10); - pointPart('handle-fov-r', COLOR_HANDLE, 10); - function hideAll() { - for (const entity of entities.values()) entity.show = false; + if (!shown) return; + shown = false; + lines.upsert(lineItems()); + points.upsert(pointItems()); } /** Recomputes every handle's geometry from the active record's CURRENT pose @@ -328,69 +353,52 @@ export function createCalibrationGizmo({ ); const arrowLen = radius * ARROW_LENGTH_FACTOR; - entities.get('ring-heading').polyline.positions = ringPositions( - mount, - radius, - axes.north, - axes.east, + linePositions.set( + 'ring-heading', + ringPositions(mount, radius, axes.north, axes.east), ); - entities.get('ring-pitch').polyline.positions = ringPositions( - mount, - radius, - forwardHoriz, - axes.up, + linePositions.set( + 'ring-pitch', + ringPositions(mount, radius, forwardHoriz, axes.up), ); - const arrowTo = (dir) => [ - mount, - Cesium.Cartesian3.add( - mount, - Cesium.Cartesian3.multiplyByScalar( - dir, - arrowLen, - new Cesium.Cartesian3(), - ), - new Cesium.Cartesian3(), - ), - ]; - const eastArrow = arrowTo(axes.east); - const northArrow = arrowTo(axes.north); - const upArrow = arrowTo(axes.up); - entities.get('move-east').polyline.positions = eastArrow; - entities.get('move-east').position = eastArrow[1]; - entities.get('move-north').polyline.positions = northArrow; - entities.get('move-north').position = northArrow[1]; - entities.get('move-up').polyline.positions = upArrow; - entities.get('move-up').position = upArrow[1]; - entities.get('handle-range').position = positions.capCenter; - entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint( - positions.tl, - positions.bl, - new Cesium.Cartesian3(), - ); - entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint( - positions.tr, - positions.br, - new Cesium.Cartesian3(), - ); - for (const entity of entities.values()) entity.show = true; + const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))]; + for (const [part, dir] of [ + ['move-east', axes.east], + ['move-north', axes.north], + ['move-up', axes.up], + ]) { + const arrow = arrowTo(dir); + linePositions.set(part, arrow); + pointPositions.set(part, arrow[1]); + } + pointPositions.set('handle-range', positions.capCenter); + pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl)); + pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br)); + shown = true; + lines.upsert(lineItems()); + points.upsert(pointItems()); } - /** Extracts a gizmo part name from a pick result, or null. */ - function gizmoPartFrom(picked) { - const id = picked?.id?.id ?? picked?.id; + /** The gizmo part a pick hit is, or null. */ + function gizmoPartFrom(hit) { + if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null; + const id = hit.id; if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null; - return id.slice(GIZMO_ID_PREFIX.length); + const part = id.slice(GIZMO_ID_PREFIX.length); + return PARTS.has(part) ? part : null; } function pickGizmoPart(windowPosition) { + const query = findQuery(viewer); + if (!query || !windowPosition) return null; + const { x, y } = windowPosition; // Gizmo primitives render depth-test-free and should be the topmost pick. // Take the cheap single-result path first: a full drillPick can stall for // tens of seconds under software GL even when its first result is already // the gizmo. Retain drillPick for uncommon overlap/fallback cases. try { - const picked = scene.pick(windowPosition, 14, 14); - const part = gizmoPartFrom(picked); - if (part && entities.get(part)?.show) return part; + const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 })); + if (part && shown) return part; } catch (err) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug('[CCTV:gizmo] pick threw:', err?.message || err); @@ -399,7 +407,8 @@ export function createCalibrationGizmo({ let results = []; try { - results = scene.drillPick(windowPosition, 6, 14, 14) || []; + results = + query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || []; } catch (err) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err); @@ -409,52 +418,54 @@ export function createCalibrationGizmo({ if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug( '[CCTV:gizmo] drillPick @', - windowPosition?.x, - windowPosition?.y, + x, + y, '→', JSON.stringify( - results.map((r) => - String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name), + results.map((hit) => + hit.surface ? '(surface)' : `${hit.set}/${hit.id}`, ), ), ); } - for (const picked of results) { - const part = gizmoPartFrom(picked); - if (part && entities.get(part)?.show) return part; + for (const hit of results) { + const part = gizmoPartFrom(hit); + if (part && shown) return part; } return null; } function pickRay(windowPosition) { try { - return viewer.camera.getPickRay(windowPosition) || null; + return ( + findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null + ); } catch { return null; } } function setCursor(value) { - if (scene.canvas?.style) scene.canvas.style.cursor = value; + const style = canvasOf(viewer)?.style; + if (style) style.cursor = value; } function setHovered(part) { const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null; if (nextId === hoveredId) return; hoveredId = nextId; - // Hover feedback must NEVER touch polyline geometry: a width change makes - // Cesium rebuild the batched polyline primitive, and until the next render - // the part vanishes from the pick buffer — so the very hover that finds a - // ring makes the following LEFT_DOWN miss it (root-caused via the QA - // harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback - // only; point handles are PointPrimitives (live-updatable, no rebuild), so - // they keep the size bump. - for (const [name, entity] of entities.entries()) { - if (!entity.point) continue; + // Hover feedback must NEVER touch line geometry: a width change rebuilds + // the line, and until the next render the part vanishes from the pick + // buffer — so the very hover that finds a ring makes the following + // LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag, + // 2026-07-05). Rings/arrows get cursor feedback only; point handles + // (an arrow's tip included) change size in place, so they keep the size + // bump. + for (const [name] of POINT_PARTS) { const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`; - entity.point.pixelSize = - (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0); + pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0)); } + points.upsert(pointItems()); setCursor(hoveredId ? 'grab' : ''); } @@ -468,8 +479,8 @@ export function createCalibrationGizmo({ const ray = pickRay(windowPosition); if (!ray) return false; - const mount = Cesium.Cartesian3.clone(positions.mount); - const capCenter = Cesium.Cartesian3.clone(positions.capCenter); + const mount = { ...positions.mount }; + const capCenter = { ...positions.capCenter }; const axes = enuAxes(mount); const { forwardHoriz, right, view } = viewAxesFor( camera.headingDeg, @@ -533,9 +544,7 @@ export function createCalibrationGizmo({ drag = state; setCursor('grabbing'); - if (scene.screenSpaceCameraController) { - scene.screenSpaceCameraController.enableInputs = false; - } + releaseCamera = input.suspendCamera('cctv-gizmo-drag'); return true; } @@ -596,12 +605,7 @@ export function createCalibrationGizmo({ if (part === 'handle-fov-l' || part === 'handle-fov-r') { const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view); if (!hit) return null; - const lateral = Math.abs( - Cesium.Cartesian3.dot( - Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()), - right, - ), - ); + const lateral = Math.abs(dot(sub(hit, capCenter), right)); const halfW = Math.max(0.5, lateral); const fovDeg = toDeg( 2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)), @@ -615,9 +619,8 @@ export function createCalibrationGizmo({ if (!drag) return; const record = drag.record; drag = null; - if (scene.screenSpaceCameraController) { - scene.screenSpaceCameraController.enableInputs = true; - } + releaseCamera?.(); + releaseCamera = null; setCursor(hoveredId ? 'grab' : ''); endPatch(record); } @@ -629,18 +632,21 @@ export function createCalibrationGizmo({ } } - handler.setInputAction((event) => { - // A tool owns the pointer (src/data/inputOwnership.js): yield the press. - if (!isPointerFree()) return; + // An ambient press: the dispatcher withholds it while a tool owns the pointer + // (src/data/inputOwnership.js). + const offDown = input.onPointer('down', (event) => { if (!enabled) return; + // A release Cesium never reported (one with a modifier key held) leaves + // the last drag open; a new press ends it, hold and patch included. + if (drag) endDrag(); const part = pickGizmoPart(event.position); debugLog('LEFT_DOWN', event.position, 'part:', part); if (!part) return; const started = beginDrag(part, event.position); debugLog('beginDrag', part, '→', started); - }, Cesium.ScreenSpaceEventType.LEFT_DOWN); + }); - handler.setInputAction((event) => { + const offMove = input.onPointer('move', (event) => { if (!enabled) return; const now = Date.now(); if (drag) { @@ -667,12 +673,12 @@ export function createCalibrationGizmo({ if (now - lastHoverAt < HOVER_THROTTLE_MS) return; lastHoverAt = now; setHovered(pickGizmoPart(event.endPosition)); - }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); + }); - handler.setInputAction(() => { + const offUp = input.onPointer('up', () => { if (!enabled) return; endDrag(); - }, Cesium.ScreenSpaceEventType.LEFT_UP); + }); return { setEnabled(value) { @@ -688,14 +694,25 @@ export function createCalibrationGizmo({ refresh, destroy() { if (drag) endDrag(); - handler.destroy(); - for (const entity of entities.values()) { - viewer.entities.remove(entity); - } - entities.clear(); + offDown(); + offMove(); + offUp(); + lines.dispose(); + points.dispose(); setCursor(''); }, isDragging: () => !!drag, isEnabled: () => enabled, + /** + * The parts as last drawn, by item id, for the QA harness: whether each + * shows, a line's `positions` and a point's `pos` (an arrow has both). + */ + partsForTest() { + const parts = {}; + for (const item of [...lineItems(), ...pointItems()]) + parts[item.id] = { ...parts[item.id], ...item }; + for (const item of lineItems()) parts[item.id].show = item.show; + return parts; + }, }; } diff --git a/src/data/cctvGizmo.test.mjs b/src/data/cctvGizmo.test.mjs index 850e7708e9..8ea8976efc 100644 --- a/src/data/cctvGizmo.test.mjs +++ b/src/data/cctvGizmo.test.mjs @@ -8,66 +8,99 @@ // - rayPlaneIntersect refuses grazing rays (|dir·normal| < 0.08 — spec §5 // precision guard) and behind-origin hits; // - ringAngle/signedAngleDelta give quadrant-correct, wrap-safe angles for -// the heading/pitch ring drags. +// the heading/pitch ring drags; +// - the controller ends an open drag, and its camera hold, on the next press. import { test } from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import { + GIZMO_ID_PREFIX, closestParamOnAxis, + createCalibrationGizmo, rayPlaneIntersect, ringAngle, signedAngleDelta, } from './cctvGizmo.js'; +import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { add, distance, negate, normalize, scale } from '../geo/vector.js'; -const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z); +const c3 = (x, y, z) => ({ x, y, z }); test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => { // Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5): // nearest axis point is x=10 → t=10. - const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(0, 0, 0), c3(1, 0, 0)); + const t = closestParamOnAxis( + c3(10, 0, 5), + c3(0, 0, -1), + c3(0, 0, 0), + c3(1, 0, 0), + ); assert.ok(Math.abs(t - 10) < 1e-9, `expected 10, got ${t}`); }); test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => { // Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the // axis around x=10 (it reaches y=0 at x=10). - const dir = Cesium.Cartesian3.normalize(c3(1, -1, 0), new Cesium.Cartesian3()); + const dir = normalize(c3(1, -1, 0)); const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0)); assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`); }); test('closestParamOnAxis: axis origin offset shifts the parameter', () => { - const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(4, 0, 0), c3(1, 0, 0)); + const t = closestParamOnAxis( + c3(10, 0, 5), + c3(0, 0, -1), + c3(4, 0, 0), + c3(1, 0, 0), + ); assert.ok(Math.abs(t - 6) < 1e-9, `expected 6, got ${t}`); }); test('closestParamOnAxis: near-parallel ray/axis returns null', () => { - assert.equal(closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), null); - const nearly = Cesium.Cartesian3.normalize(c3(1, 1e-9, 0), new Cesium.Cartesian3()); - assert.equal(closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), null); + assert.equal( + closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), + null, + ); + const nearly = normalize(c3(1, 1e-9, 0)); + assert.equal( + closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), + null, + ); }); test('rayPlaneIntersect: straight-on hit lands at the expected point', () => { - const hit = rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, -1), c3(0, 0, 0), c3(0, 0, 1)); + const hit = rayPlaneIntersect( + c3(0, 0, 10), + c3(0, 0, -1), + c3(0, 0, 0), + c3(0, 0, 1), + ); assert.ok(hit, 'expected a hit'); - assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9); + assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9); }); test('rayPlaneIntersect: oblique hit resolves correctly', () => { - const dir = Cesium.Cartesian3.normalize(c3(1, 0, -1), new Cesium.Cartesian3()); + const dir = normalize(c3(1, 0, -1)); const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)); assert.ok(hit); - assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`); + assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`); }); test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => { // dir almost in-plane: z component 0.05 < 0.08 threshold. - const dir = Cesium.Cartesian3.normalize(c3(1, 0, -0.05), new Cesium.Cartesian3()); - assert.equal(rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), null); + const dir = normalize(c3(1, 0, -0.05)); + assert.equal( + rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), + null, + ); }); test('rayPlaneIntersect: plane behind the ray origin returns null', () => { - assert.equal(rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)), null); + assert.equal( + rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)), + null, + ); }); test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => { @@ -75,9 +108,15 @@ test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => { const a = c3(1, 0, 0); const b = c3(0, 1, 0); assert.ok(Math.abs(ringAngle(c3(5, 0, 0), center, a, b) - 0) < 1e-9); - assert.ok(Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9); - assert.ok(Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9); - assert.ok(Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9); + assert.ok( + Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9, + ); + assert.ok( + Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9, + ); + assert.ok( + Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9, + ); }); test('signedAngleDelta: shortest-path wrap', () => { @@ -86,3 +125,296 @@ test('signedAngleDelta: shortest-path wrap', () => { assert.ok(Math.abs(signedAngleDelta(d2r(-170), d2r(170)) - d2r(-20)) < 1e-9); assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9); }); + +/** + * A viewer double drawing through a fake draw port, whose query port picks + * `picked` and casts the ray `ray` (a ray, + * or a function of the window position). + */ +function gizmoViewer(t, { picked, ray }) { + const viewer = { + scene: { + canvas: { style: {} }, + screenSpaceCameraController: { enableInputs: true }, + }, + }; + const queries = []; + const { draw, unbind } = bindFakeDraw(viewer, { + query: { + pick: (x, y, window) => (queries.push(['pick', window]), picked()), + drillPick: (x, y, options) => (queries.push(['drill', options]), []), + pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray), + }, + }); + t.after(unbind); + return { viewer, draw, queries }; +} + +const mount = fromDegrees(0, 0, 10); +const east = c3(0, 1, 0); // east at lon 0, lat 0 +const gizmoRecord = () => ({ + frustumPositions: { + mount, + capCenter: mount, + tl: mount, + tr: mount, + bl: mount, + br: mount, + }, + frustumGeometry: { rangeM: 50 }, + camera: { + headingDeg: 0, + pitchDeg: 0, + rangeM: 50, + calibration: {}, + basePose: {}, + }, +}); + +test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => { + const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null }); + const { input } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + const lines = draw.find('cctv-gizmo:'); + const points = [...draw.sets.values()].find( + (set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'), + ); + assert.equal(lines.kind, 'lines'); + assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST'); + gizmo.setEnabled(true); + assert.deepEqual( + [...lines.items.keys()], + ['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map( + (part) => GIZMO_ID_PREFIX + part, + ), + ); + assert.deepEqual( + [...points.items.keys()], + [ + 'move-east', + 'move-north', + 'move-up', + 'handle-range', + 'handle-fov-l', + 'handle-fov-r', + ].map((part) => GIZMO_ID_PREFIX + part), + ); + const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`); + assert.equal(ring.mode, '3d'); + assert.equal(ring.widthPx, 3); + assert.equal(ring.positions.length, 97, 'a closed 96-segment ring'); + assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12); + assert.ok(Math.abs(ring.depthFail.color[3] - 0.45) < 1e-12); + const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`); + assert.equal(arrow.style.kind, 'arrow'); + assert.equal(arrow.widthPx, 12); + // The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up. + assert.ok( + distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6, + ); + const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`); + assert.deepEqual(tip.pos, arrow.positions[1]); + assert.equal(tip.pixelSize, 14); + assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY); + assert.ok( + [...lines.items.values(), ...points.items.values()].every( + (item) => item.show, + ), + ); + gizmo.setEnabled(false); + assert.ok( + [...lines.items.values(), ...points.items.values()].every( + (item) => !item.show, + ), + 'hidden off ADJUST', + ); + gizmo.destroy(); + assert.equal(lines.disposed, true); + assert.equal(points.disposed, true); +}); + +test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => { + let lineSet = null; + const { viewer, draw, queries } = gizmoViewer(t, { + picked: () => ({ + set: lineSet, + id: `${GIZMO_ID_PREFIX}move-up`, + surface: false, + }), + ray: { origin: add(mount, scale(east, 100)), direction: negate(east) }, + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const ended = []; + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch: (r) => ended.push(r), + }); + t.after(() => gizmo.destroy()); + lineSet = draw.find('cctv-gizmo:').spec.id; + gizmo.setEnabled(true); + const controller = viewer.scene.screenSpaceCameraController; + + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), true); + assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]); + assert.equal(controller.enableInputs, false); + // The release came with a modifier key held: Cesium raised no LEFT_UP. + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.deepEqual(ended, [record], 'the open drag was committed'); + handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), false); + assert.equal(controller.enableInputs, true, 'no hold was stranded'); +}); + +test('a pick of another set or a stray id is no gizmo part', (t) => { + let picked = null; + const { viewer, draw } = gizmoViewer(t, { + picked: () => picked, + ray: { origin: add(mount, scale(east, 100)), direction: negate(east) }, + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + gizmo.setEnabled(true); + picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false }; + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), false, 'another set'); + handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } }); + picked = { + set: draw.find('cctv-gizmo:').spec.id, + id: `${GIZMO_ID_PREFIX}nothing`, + surface: false, + }; + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), false, 'no such part'); +}); + +test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => { + const up = c3(1, 0, 0); // up at lon 0, lat 0 + let lineSet = null; + const { viewer, draw } = gizmoViewer(t, { + picked: () => ({ + set: lineSet, + id: `${GIZMO_ID_PREFIX}move-east`, + surface: false, + }), + // Straight down onto the east axis, `x` metres east of the mount. + ray: (x) => ({ + origin: add(add(mount, scale(east, x)), scale(up, 100)), + direction: negate(up), + }), + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + record.camera.calibration = { offsetEastM: 2 }; + const patches = []; + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch: (patch, pinned) => patches.push([patch, pinned]), + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + lineSet = draw.find('cctv-gizmo:').spec.id; + gizmo.setEnabled(true); + + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), true); + assert.equal(viewer.scene.canvas.style.cursor, 'grabbing'); + handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, { + startPosition: { x: 5, y: 5 }, + endPosition: { x: 12, y: 5 }, + }); + assert.equal(patches.length, 1); + const [patch, pinned] = patches[0]; + assert.equal(pinned, record, 'patched on the record dragged'); + assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`); + handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } }); + assert.equal(gizmo.isDragging(), false); +}); + +test('hovering a handle grows it and shows the grab cursor', (t) => { + let pointSet = null; + let over = true; + const { viewer, draw } = gizmoViewer(t, { + picked: () => + over + ? { + set: pointSet, + id: `${GIZMO_ID_PREFIX}handle-range`, + surface: false, + } + : null, + ray: null, + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + const points = [...draw.sets.values()].find( + (set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'), + ); + pointSet = points.spec.id; + gizmo.setEnabled(true); + const size = () => + points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize; + assert.equal(size(), 13); + handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, { + startPosition: { x: 5, y: 5 }, + endPosition: { x: 6, y: 5 }, + }); + assert.equal(size(), 17); + assert.equal(viewer.scene.canvas.style.cursor, 'grab'); +}); + +test('the harness reads each part as drawn, an arrow with its line and tip', (t) => { + const { viewer } = gizmoViewer(t, { picked: () => null, ray: null }); + const { input } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST'); + gizmo.setEnabled(true); + const parts = gizmo.partsForTest(); + const arrow = parts[`${GIZMO_ID_PREFIX}move-east`]; + assert.equal(arrow.positions.length, 2, 'its line'); + assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip'); + assert.equal(arrow.show, true); + assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true); + assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos); + gizmo.setEnabled(false); + assert.ok( + Object.values(gizmo.partsForTest()).every((part) => part.show === false), + ); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 1bc94eed8a..bf5a3edf5b 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -2,10 +2,13 @@ // near the screen show, a zoomed-out view keeps one camera per world-anchored // cell, and the layer's UI state never rebuilds every camera for a listener // that does not read the list. -import { test } from 'node:test'; +import { afterEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { + _cctvIconsForTest, _setCctvCoverageStateForTest, _viewRecordIdsForTest, refreshHorizonCulling, @@ -14,18 +17,10 @@ import cctvLayer, { const WIDTH = 800; const HEIGHT = 600; -/** - * Records at the given [lon, lat] degrees near the origin, each drawn at the - * screen point `screenAt` gives it (default: the middle of the screen). - */ -function recordsAt( - lonLats, - screenAt = () => ({ x: WIDTH / 2, y: HEIGHT / 2 }), -) { - const screenByPosition = new Map(); +/** Records at the given [lon, lat] degrees near the origin. */ +function recordsAt(lonLats) { const records = lonLats.map(([lon, lat], index) => { const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10); - screenByPosition.set(position, screenAt(index)); return { camera: { id: `cam-${index}`, @@ -39,36 +34,62 @@ function recordsAt( rangeM: 145, mountHeightM: 8, }, - position, - billboard: { position, show: true }, + position: { x: position.x, y: position.y, z: position.z }, coverageEntities: [], projection: null, }; }); - return { records, screenByPosition }; + return { records }; } -function viewerAt(heightM, screenByPosition, shiftX = 0) { - return { - isDestroyed: () => false, - camera: { - positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM), - positionCartographic: { latitude: 0, longitude: 0, height: heightM }, - frustum: { fovy: Math.PI / 3 }, +/** + * A viewer looking straight down from `heightM` over `lonDeg` on the + * equator, north up, through a camera port: the view pass projects the + * cameras from its pose. + */ +function viewerAt(heightM, lonDeg = 0) { + const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); + const down = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const north = { x: 0, y: 0, z: 1 }; + const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3()); + const { port } = fakeCameraPort({ + pose: { + lon: lonDeg, + lat: 0, + height: heightM, + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: { x: down.x, y: down.y, z: down.z }, + up: north, + right: { x: right.x, y: right.y, z: right.z }, + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, }, - scene: { + }); + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, - cartesianToCanvasCoordinates: (position) => { - const screen = screenByPosition.get(position); - return screen && { x: screen.x + shiftX, y: screen.y }; - }, - }, - }; + }), + ); + return viewer; } +/** The renderers bound for the running test, let go when it ends. */ +const bindings = []; +afterEach(() => { + for (const unbind of bindings.splice(0)) unbind(); +}); + function shownIds(records) { + const icons = _cctvIconsForTest(); return records - .filter((record) => record.billboard.show) + .filter((record) => icons.item(record.camera.id)?.show === true) .map((record) => record.camera.id) .sort(); } @@ -82,9 +103,9 @@ const CLUSTER = [ ]; test('zoomed out, cameras sharing a ground cell show one icon', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, }); assert.equal( @@ -99,34 +120,34 @@ test('zoomed out, cameras sharing a ground cell show one icon', () => { }); test('a pan keeps the same winners, and an unchanged view keeps its list', () => { - const { records, screenByPosition } = recordsAt(CLUSTER, (index) => ({ - x: 100 + index * 7, - y: 300, - })); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, }); refreshHorizonCulling(); const before = shownIds(records); const list = _viewRecordIdsForTest(); - for (const shiftX of [3, 11, 20, 37]) { + // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up). + for (const shiftM of [90, 330, 600, 1110]) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition, shiftX), + viewer: viewerAt(20_000, shiftM / 111_320), records, }); refreshHorizonCulling(); - assert.deepEqual(shownIds(records), before, `pan by ${shiftX} px`); + assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`); } + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); }); test('a small zoom within one cell size keeps the same winners', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); const shownAt = (heightM) => { _setCctvCoverageStateForTest({ - viewer: viewerAt(heightM, screenByPosition), + viewer: viewerAt(heightM), records, }); refreshHorizonCulling(); @@ -138,11 +159,11 @@ test('a small zoom within one cell size keeps the same winners', () => { }); test('a healthy camera wins its cell over an unknown one', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); + const { records } = recordsAt(CLUSTER.slice(0, 2)); // Whichever camera the id order would pick, the healthy one must win. for (const id of ['cam-0', 'cam-1']) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, healthById: new Map([[id, { status: 'ok' }]]), }); @@ -152,30 +173,31 @@ test('a healthy camera wins its cell over an unknown one', () => { }); test('the active camera always shows, even in a crowded cell', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3)); + const { records } = recordsAt(CLUSTER.slice(0, 3)); for (const active of records) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, activeCameraId: active.camera.id, }); refreshHorizonCulling(); - assert.ok(active.billboard.show, `${active.camera.id} shows while active`); + const icons = _cctvIconsForTest(); + assert.ok( + icons.item(active.camera.id).show, + `${active.camera.id} shows while active`, + ); } }); test('close up, every camera near the screen shows and far-off ones hide', () => { - const { records, screenByPosition } = recordsAt( - [ - [0, 0], - [0.0001, 0], - [0.0002, 0], - ], - (index) => - index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 }, - ); + // From 300 m up the screen spans some 460 m: the third camera is 1.1 km off. + const { records } = recordsAt([ + [0, 0], + [0.0001, 0], + [0.01, 0], + ]); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, }); refreshHorizonCulling(); @@ -183,9 +205,9 @@ test('close up, every camera near the screen shows and far-off ones hide', () => }); test('a disabled layer skips the view pass', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, enabled: false, }); @@ -194,9 +216,9 @@ test('a disabled layer skips the view pass', () => { }); test('UI state builds the full camera list only when it is read', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); + const { records } = recordsAt(CLUSTER.slice(0, 2)); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, }); refreshHorizonCulling(); @@ -227,16 +249,13 @@ test('UI state builds the full camera list only when it is read', () => { }); test('the camera picker lists the view, with the active camera first', () => { - const { records, screenByPosition } = recordsAt( - [ - [0, 0], - [0.0001, 0], - [0.0002, 0], - ], - (index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }), - ); + const { records } = recordsAt([ + [0, 0], + [0.01, 0], + [0.0002, 0], + ]); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, activeCameraId: 'cam-1', }); diff --git a/src/data/cctvViewshed.js b/src/data/cctvViewshed.js index 6654b599c8..9a8fc2fe57 100644 --- a/src/data/cctvViewshed.js +++ b/src/data/cctvViewshed.js @@ -6,17 +6,17 @@ * * Two responsibilities, both pure of layer state: * - Color identity: a stable per-camera hue (golden-angle spaced over the - * id-sorted catalog index) and the derived fill/line Cesium colors. - * - Volume geometry: a translucent frustum pyramid primitive built FROM the - * exact frustumCartesians positions the wireframe uses — welded by - * construction, never recomputed independently. 5 vertices, 6 triangles, - * synchronous build (trivially small), no picking. + * id-sorted catalog index) and the derived fill/line renderer colors. + * - Volume geometry: the vertex and index buffers of a translucent frustum + * pyramid built FROM the exact frustumCartesians positions the wireframe + * uses — welded by construction, never recomputed independently. 5 + * vertices, 6 triangles; the layer's rendering part draws them. * * Nothing here queries the scene or persists anything: colors are * presentation-only and volumes are rebuilt only at the moments the frustum * wireframe already rewrites (pose edits / visible-set changes). */ -import * as Cesium from 'cesium'; +import { hslColor } from '../render/color.js'; /** Golden angle in degrees — maximally spreads consecutive indices around the hue wheel. */ const GOLDEN_ANGLE_DEG = 137.50776405003785; @@ -43,15 +43,16 @@ export function cameraHue(index) { * Derived viewshed colors for a hue: translucent volume fills (idle/active) * and wireframe line tints (idle/active), all in the same hue family. * @param {number} hueDeg - Hue in degrees. - * @returns {{fill: Cesium.Color, fillActive: Cesium.Color, line: Cesium.Color, lineActive: Cesium.Color}} + * @returns {{fill: number[], fillActive: number[], line: number[], lineActive: number[]}} + * Renderer colours, [r, g, b, a] in 0..1. */ export function viewshedColors(hueDeg) { const hue = (((Number(hueDeg) % 360) + 360) % 360) / 360; return { - fill: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_IDLE), - fillActive: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE), - line: Cesium.Color.fromHsl(hue, 0.9, 0.65, LINE_ALPHA_IDLE), - lineActive: Cesium.Color.fromHsl(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE), + fill: hslColor(hue, 0.85, 0.6, FILL_ALPHA_IDLE), + fillActive: hslColor(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE), + line: hslColor(hue, 0.9, 0.65, LINE_ALPHA_IDLE), + lineActive: hslColor(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE), }; } @@ -61,8 +62,8 @@ export function viewshedColors(hueDeg) { * the apex + the far cap split into 2 triangles. Pure — this is the ONLY * geometry definition (weld-by-construction with the wireframe, which draws * its rays/cap from the same 5 Cartesians). - * @param {{mount: Cesium.Cartesian3, tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, - * br: Cesium.Cartesian3, bl: Cesium.Cartesian3}} positions - frustumCartesians shape. + * @param {{mount: object, tl: object, tr: object, br: object, bl: object}} + * positions - frustumCartesians shape: ECEF points with x, y and z. * @returns {{positions: Float64Array, indices: Uint16Array}} */ export function frustumVolumeGeometryData(positions) { @@ -85,46 +86,3 @@ export function frustumVolumeGeometryData(positions) { ]); return { positions: flat, indices }; } - -/** - * Builds the translucent frustum-volume primitive for one camera. - * Synchronous (6 triangles — cheaper than the async geometry pipeline's - * bookkeeping), unlit flat color, both faces visible (the viewer is routinely - * inside or behind a cone), never pickable (clicks fall through to the - * billboard/wireframe/plane, whose pick semantics are established). - * @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData). - * @param {Cesium.Color} color - Per-camera fill color (already alpha'd). - * @returns {Cesium.Primitive} - */ -export function createFrustumVolumePrimitive(positions, color) { - const { positions: flat, indices } = frustumVolumeGeometryData(positions); - const geometry = new Cesium.Geometry({ - attributes: { - position: new Cesium.GeometryAttribute({ - componentDatatype: Cesium.ComponentDatatype.DOUBLE, - componentsPerAttribute: 3, - values: flat, - }), - }, - indices, - primitiveType: Cesium.PrimitiveType.TRIANGLES, - boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)), - }); - return new Cesium.Primitive({ - geometryInstances: new Cesium.GeometryInstance({ - geometry, - attributes: { - color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), - }, - }), - appearance: new Cesium.PerInstanceColorAppearance({ - flat: true, - translucent: true, - renderState: { - cull: { enabled: false }, - }, - }), - asynchronous: false, - allowPicking: false, - }); -} diff --git a/src/data/cctvViewshed.test.mjs b/src/data/cctvViewshed.test.mjs index c2359ceea8..2a43044aea 100644 --- a/src/data/cctvViewshed.test.mjs +++ b/src/data/cctvViewshed.test.mjs @@ -62,14 +62,26 @@ test('cameraHue: consecutive indices separated by >= 80 degrees', () => { test('viewshedColors: fill/line pairs with the designed alphas', () => { const colors = viewshedColors(210); for (const key of ['fill', 'fillActive', 'line', 'lineActive']) { - assert.ok(colors[key] instanceof Cesium.Color, `${key} must be a Cesium.Color`); + assert.ok(Array.isArray(colors[key]) && colors[key].length === 4, `${key} must be a renderer colour`); } - assert.ok(Math.abs(colors.fill.alpha - 0.12) < 1e-6); - assert.ok(Math.abs(colors.fillActive.alpha - 0.22) < 1e-6); - assert.ok(Math.abs(colors.line.alpha - 0.85) < 1e-6); - assert.ok(Math.abs(colors.lineActive.alpha - 1.0) < 1e-6); + assert.ok(Math.abs(colors.fill[3] - 0.12) < 1e-6); + assert.ok(Math.abs(colors.fillActive[3] - 0.22) < 1e-6); + assert.ok(Math.abs(colors.line[3] - 0.85) < 1e-6); + assert.ok(Math.abs(colors.lineActive[3] - 1.0) < 1e-6); // Same hue family: fill and line of the same hue must not be gray. - assert.ok(colors.line.red !== colors.line.green || colors.line.green !== colors.line.blue); + assert.ok(colors.line[0] !== colors.line[1] || colors.line[1] !== colors.line[2]); +}); + +test('viewshedColors: the same colours the renderer derived from the hue', () => { + const asArray = (c) => [c.red, c.green, c.blue, c.alpha]; + for (const hueDeg of [0, 137.5, 210, 359.9, -30]) { + const hue = (((hueDeg % 360) + 360) % 360) / 360; + const colors = viewshedColors(hueDeg); + assert.deepEqual(colors.fill, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.12))); + assert.deepEqual(colors.fillActive, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.22))); + assert.deepEqual(colors.line, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.65, 0.85))); + assert.deepEqual(colors.lineActive, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.7, 1.0))); + } }); /** Minimal frustumCartesians-shaped fixture. */ diff --git a/src/data/cockpitDetectionSubjects.test.mjs b/src/data/cockpitDetectionSubjects.test.mjs index 8421267fcf..79a95cb1b0 100644 --- a/src/data/cockpitDetectionSubjects.test.mjs +++ b/src/data/cockpitDetectionSubjects.test.mjs @@ -27,8 +27,8 @@ const LAYERS = [ _setTrackedFlightRefreshStateForTest({ icao24, entity: null, - billboard: candidateBillboard(icao24), - billboardCollection: { show: true, remove() {} }, + icon: candidateBillboard(icao24), + iconLayer: { show: true, remove() {} }, viewer: candidateViewer(), tracked: false, meta: { @@ -48,8 +48,8 @@ const LAYERS = [ _setTrackedMilitaryRefreshStateForTest({ icao24, entity: null, - billboard: candidateBillboard(icao24), - billboardCollection: { show: true, remove() {} }, + icon: candidateBillboard(icao24), + iconLayer: { show: true, remove() {} }, viewer: candidateViewer(), tracked: false, meta: { diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 0488a6d1e5..0d71584fa7 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -1,4 +1,5 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs'; +import { readFileSync } from 'node:fs'; import test from 'node:test'; import assert from 'node:assert/strict'; @@ -12,6 +13,11 @@ import assert from 'node:assert/strict'; * regression would silently revert. These assertions pin the decisions. */ +const DRAW_MODELS_SOURCE = readFileSync( + new URL('../render/cesium/drawModels.js', import.meta.url), + 'utf8', +); + const LAYERS = [ { name: 'flights', path: new URL('./flights.js', import.meta.url) }, { name: 'militaryFlights', path: new URL('./militaryFlights.js', import.meta.url) }, @@ -28,10 +34,11 @@ for (const layer of LAYERS) { const source = readLayerSource(layer.path); test(`${layer.name}: every GLB creation bypasses the tile-contended frame-spread queue`, () => { - const calls = [...source.matchAll(/_createModel\(\s*\w+,\s*\{([\s\S]*?)\n\s*\}\)/g)]; - assert.ok(calls.length >= 2, `expected fleet and tracked model calls; found ${calls.length}`); - assert.doesNotMatch(source, /Cesium\.Model\.fromGltfAsync\(/, - 'every model is built from the loaded fleet set through _createModel'); + // The fleet and tracked models are draw-port models sets; the Cesium + // draw port creates every model off the frame-spread queue. + assert.match(source, /\.models\(\{\s*id:/, 'the layer draws its models as draw-port models sets'); + const calls = [...DRAW_MODELS_SOURCE.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)]; + assert.ok(calls.length >= 1, 'the draw port creates models'); for (const [index, call] of calls.entries()) { assert.match(call[1], /\basynchronous:\s*false\b/, `_createModel call ${index + 1} must keep bounded GLB readiness independent of tile jobs`); @@ -41,9 +48,9 @@ for (const layer of LAYERS) { test(`${layer.name}: Cockpit 3D obeys the shared Display toggle`, () => { const regime = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(regime, '_modelRegimeActive is defined'); - assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, + assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, 'OFF must keep Cockpit AIR contacts in 2D'); - assert.doesNotMatch(regime, /!(?:flightState\.)?_models3dEnabled\s*&&\s*!(?:flightState\.)?_cockpitContactMode/, + assert.doesNotMatch(regime, /!(?:(?:flightState|state)\.)?_models3dEnabled\s*&&\s*!(?:(?:flightState|state)\.)?_cockpitContactMode/, 'Cockpit must not bypass the owner-visible Display toggle'); }); @@ -55,7 +62,7 @@ for (const layer of LAYERS) { // suppression is now an explicit early return. const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(regime, '_trackedModelRegimeActive is defined'); - assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/, + assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_trackedIcao\s*\|\|\s*(?:(?:flightState|state)\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/, '_trackedModelRegimeActive excludes cockpit'); const tracked = /^([ \t]*)function _updateTrackedModel\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(tracked, '_updateTrackedModel is defined'); @@ -72,37 +79,59 @@ for (const layer of LAYERS) { const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(add, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_ADD_M\s*:\s*MODEL_PROX_ADD_M/); - assert.match(keep, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_KEEP_M\s*:\s*MODEL_PROX_KEEP_M/); + assert.match(add, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_ADD_M\s*:\s*(?:policy\.)?MODEL_PROX_ADD_M/); + assert.match(keep, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_KEEP_M\s*:\s*(?:policy\.)?MODEL_PROX_KEEP_M/); assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/); assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/); const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(cap, /Math\.min\(\s*COCKPIT_MODEL_MAX/, + assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/, 'Cockpit keeps its 60-model performance ceiling'); }); test(`${layer.name}: near AIR state is independent from model admission`, () => { assert.match(source, /nextCockpitNearContacts\(/, 'Cockpit derives a separate near-contact hysteresis set'); - assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)/, + assert.match(source, /!state\._cockpitNearContacts\.has\(icao24\);\s*const look = cockpitDot\s*\?\s*\{\s*image: cockpitDotImage\(\)/, 'only out-of-range Cockpit contacts become dots'); // `_iconKind` is identity for every unconverted contact (see // tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the // operator explicitly converted into a TR-3B. - assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*bb\._gevIconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/, + assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); - assert.match(source, /bb\.rotation\s*=\s*0;/, + assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/, 'far dots are reset to a rotation-free presentation'); - assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)/, + assert.match(source, /color: rgba\(rendering\._fleetBillboardColor\(icao24, info\)\),\s*rotationMode: 'course',/, 'near 2D silhouettes continue to receive projected course'); - assert.match(source, /if\s*\(\s*bb\.show,?\s*\)\s*bb\.show\s*=\s*false;\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, - 'the gap-proof billboard-to-model handoff remains intact'); + assert.match(source, /icons\.setShown\(icao24, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, + 'the gap-proof icon-to-model handoff remains intact'); }); test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => { const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); - assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);/); + assert.match(setMode, /else\s*(?:(?:flightState|state)\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); + assert.match(setMode, /for \(const icao24 of (?:flightState\._)?icons\?\.ids\(\) \?\? \[\]\)\s*parts\.icons\._applyIconPresentation\(icao24\);/); }); } + +// The source reads above include the shared model module, so they pass from it +// alone. These pin that each layer actually builds its models from it, and that +// flights keeps its own hooks. +const RENDERING = { + flights: new URL('../layers/flights/rendering.js', import.meta.url), + militaryFlights: new URL('../layers/military/rendering.js', import.meta.url), +}; + +for (const [name, url] of Object.entries(RENDERING)) { + test(`${name}: 3D models come from the shared aircraft model module`, () => { + const source = readFileSync(url, 'utf8'); + assert.match(source, /createAircraftModels\(\{/); + assert.match(source, /\.\.\.models\b/); + }); +} + +test('flights: model eligibility nudges enrichment and the tick floors grounded icons', () => { + const source = readFileSync(RENDERING.flights, 'utf8'); + assert.match(source, /onModelEligible:[\s\S]*?_requestTypeEnrichment\(icao24, true\)/); + assert.match(source, /afterReplan:[\s\S]*?_floorGroundedIcons\(/); +}); diff --git a/src/data/contactTrailRenderer.js b/src/data/contactTrailRenderer.js index 1f82f3b9c7..0d14fc59fe 100644 --- a/src/data/contactTrailRenderer.js +++ b/src/data/contactTrailRenderer.js @@ -1,4 +1,19 @@ -import * as Cesium from 'cesium'; +/** + * @module contactTrailRenderer + * @description The selected transit vehicle's trail, drawn through the + * renderer's draw port as draped lines: a history body and a moving head. + * + * The body is every subdivision of the vehicle's history, each a segment of + * a draped line in two lanes (a dark 5 px backing under a 3 px line in the + * mode colour). A segment shows once the vehicle has passed it and fades + * with its age; both change in place (`segmentShow`, `segmentColors`), so + * the body is rebuilt only when the history changes. The head is the + * subdivision the vehicle is on, revealed up to the vehicle + * (`revealFraction`): it moves only where the vehicle crosses into the + * next subdivision, and a frame writes how far it is revealed. + */ +import { cssColor } from '../render/color.js'; +import { findDraw } from '../render/rendererOf.js'; const ALPHA_STOPS = [ [0, 0.8], @@ -19,95 +34,141 @@ export function trailAlpha(ageMs) { return 0.08; } -/** One static history batch and one frequently updated head. Never entities. */ -export function createContactTrailRenderer(scene) { - const ground = - !!scene.frameState?.context && - Cesium.GroundPolylinePrimitive.isSupported(scene); - const collection = ground ? scene.groundPrimitives : scene.primitives; - // One 25 m corridor is clipped in material coordinates. Only subdivision - // crossings build geometry; frame updates write a scalar, never vertex buffers. - const headMaterial = (alpha) => - new Cesium.Material({ - fabric: { - type: 'TransitTrailHead', - uniforms: { - color: new Cesium.Color(0.37, 0.94, 0.54, alpha), - fraction: 0, - backing: true, - }, - source: `czm_material czm_getMaterial(czm_materialInput materialInput) { - if (materialInput.st.s > fraction) discard; - czm_material m = czm_getDefaultMaterial(materialInput); - bool edge = abs(materialInput.st.t - 0.5) > 0.3; - m.diffuse = czm_gammaCorrect(vec4(edge && backing ? vec3(0.02, 0.03, 0.05) : color.rgb, 1.0)).rgb; - m.alpha = color.a; - return m; - }`, - }, - translucent: true, - }); - const material = headMaterial(0.8), - depthMaterial = headMaterial(0.55); - depthMaterial.uniforms.backing = false; - const head = { positions: [], show: false, width: 3, material }; +/** The backing lane's colour, under the mode colour. */ +const BACKING = [0.02, 0.03, 0.05]; +/** Alpha of the head, and of a body segment the vehicle has just passed. */ +const HEAD_ALPHA = 0.8; +const WHITE = [1, 1, 1, 1]; +/** The two lanes, drawn in this order: the backing, then the line. */ +const LANES = [ + { name: 'backing', widthPx: 5, dark: true }, + { name: 'line', widthPx: 3, dark: false }, +]; + +/** Uniquifier for each renderer's set ids. */ +let trailSeq = 0; + +const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z; + +/** + * The history as runs of joined segments (each segment starting where the + * one before it ends), so each lane is a few lines rather than one a + * segment. `first` is the index of the run's first segment; a segment with + * no length ends a run. + */ +function runsOf(segments) { + const runs = []; + let run = null; + for (let i = 0; i < segments.length; i++) { + const [from, to] = segments[i].positions; + if (!from || !to) run = null; + else if (run && samePoint(run.positions.at(-1), from)) + run.positions.push(to); + else runs.push((run = { first: i, positions: [from, to] })); + } + return runs; +} + +/** + * The trail renderer of one selection, over `viewer`'s draw port. Never + * entities; nothing it draws takes part in picks. + * @param {object} viewer + */ +export function createContactTrailRenderer(viewer) { + const draw = findDraw(viewer); + const prefix = `transit-trail:${++trailSeq}`; + const body = draw?.lines({ id: `${prefix}:body`, pickable: false }) ?? null; + const headLines = + draw?.lines({ id: `${prefix}:head`, pickable: false, show: false }) ?? null; + /** What the head draws now, for diagnostics: its start to the vehicle. */ + const endpoint = { x: 0, y: 0, z: 0 }; + const headPositions = [null, endpoint]; + const head = { positions: [], show: false, width: 3 }; const backing = { positions: [], show: false, width: 5 }; - let headPrimitive = null, - headRebuilds = 0; - function geometry(positions, width, material = false) { - return ground - ? new Cesium.GroundPolylineGeometry({ positions, width, granularity: 0 }) - : new Cesium.PolylineGeometry({ - positions, - width, - arcType: Cesium.ArcType.NONE, - vertexFormat: material - ? Cesium.PolylineMaterialAppearance.VERTEX_FORMAT - : Cesium.PolylineColorAppearance.VERTEX_FORMAT, - }); - } - function primitive(instances, appearance, depthFailAppearance) { - return ground - ? new Cesium.GroundPolylinePrimitive({ - geometryInstances: instances, - appearance, - classificationType: Cesium.ClassificationType.BOTH, - allowPicking: false, - asynchronous: true, - show: visible, - }) - : new Cesium.Primitive({ - geometryInstances: instances, - appearance, - depthFailAppearance, - allowPicking: false, - asynchronous: false, - show: visible, - }); - } - let body = null, - segments = [], + let segments = [], + runs = [], revision = -1, visible = true, - style = '#5EF08A'; + style = '#5EF08A', + styleColor = cssColor(style).slice(0, 3); let lastSecond = -1, completed = -1, - active = null; - const styleColor = Cesium.Color.fromCssColorString(style); - const attributeIds = []; - const color = new Cesium.Color(), - endpoint = new Cesium.Cartesian3(); - const headPositions = [new Cesium.Cartesian3(), endpoint]; - let rebuilds = 0; - function tint(alpha, dark = false) { - if (dark) { - color.red = 0.02; - color.green = 0.03; - color.blue = 0.05; - } else Cesium.Color.clone(styleColor, color); - color.alpha = alpha; - return color; + active = null, + revealed = -1, + restyled = false; + let rebuilds = 0, + headRebuilds = 0; + + const tint = (alpha, dark) => [...(dark ? BACKING : styleColor), alpha]; + + /** The body's lines: each lane's runs, segments shown up to `done`. */ + function bodyLines(displayT, done) { + const lines = []; + for (const lane of LANES) + for (let r = 0; r < runs.length; r++) { + const run = runs[r]; + const count = run.positions.length - 1; + const segmentColors = new Array(count); + const segmentShow = new Array(count); + for (let k = 0; k < count; k++) { + const i = run.first + k; + const alpha = + displayT === null + ? HEAD_ALPHA + : trailAlpha(displayT - segments[i].toT); + segmentColors[k] = tint(alpha, lane.dark); + segmentShow[k] = i <= done; + } + lines.push({ + id: `${lane.name}:${r}`, + positions: run.positions, + widthPx: lane.widthPx, + mode: 'draped', + clampTo: 'both', + // Every segment has its own colour: the line's own never + // changes, so a new mode colour is written in place. + style: { kind: 'solid', color: lane.dark ? [...BACKING, 1] : WHITE }, + segmentColors, + segmentShow, + }); + } + return lines; } + + /** + * The head over `segment`, revealed to `fraction`: one line the backing's + * width, its edge the backing's colour and its centre the line's width, + * in one pass. Two lanes stacked would darken the centre where their + * translucent passes overlap. + */ + function headItems(segment, fraction) { + const [backingLane, lineLane] = LANES; + return [ + { + id: 'head', + positions: segment.positions, + widthPx: backingLane.widthPx, + mode: 'draped', + clampTo: 'both', + style: { + kind: 'solid', + color: tint(HEAD_ALPHA, false), + outline: { + color: tint(HEAD_ALPHA, true), + widthPx: backingLane.widthPx - lineLane.widthPx, + }, + }, + revealFraction: fraction, + }, + ]; + } + + // Written only when it changes: a renderer may redraw for each write. + function showHead(show) { + head.show = backing.show = show; + if (headLines && headLines.show !== show) headLines.show = show; + } + function replaceHistory(next) { if (next.revision === revision) return; revision = next.revision; @@ -115,51 +176,22 @@ export function createContactTrailRenderer(scene) { completed = -1; lastSecond = -1; active = null; - if (headPrimitive) collection.remove(headPrimitive); - headPrimitive = null; - head.show = backing.show = false; - if (body) collection.remove(body); - body = null; - const instances = []; - attributeIds.length = 0; - for (let i = 0; i < segments.length; i++) { - const segment = segments[i]; - attributeIds.push([`${i}:0`, `${i}:1`]); - if (segment.positions.length < 2) continue; - for (let lane = 0; lane < 2; lane++) { - instances.push( - new Cesium.GeometryInstance({ - id: `${i}:${lane}`, - geometry: geometry(segment.positions, lane ? 3 : 5), - attributes: { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - tint(0.8, !lane), - ), - depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor( - tint(0.55), - ), - show: new Cesium.ShowGeometryInstanceAttribute(false), - }, - }), - ); - } - } - if (instances.length) { - body = collection.add( - primitive( - instances, - new Cesium.PolylineColorAppearance({ translucent: true }), - new Cesium.PolylineColorAppearance({ translucent: true }), - ), - ); - rebuilds++; + revealed = -1; + showHead(false); + headLines?.clear(); + runs = runsOf(segments); + if (!body) return; + if (!runs.length) { + body.clear(); + return; } + body.set(bodyLines(null, -1)); + rebuilds++; } + function setDisplaySample(sample, renderedPosition) { if (!sample || !renderedPosition) { - head.show = false; - backing.show = false; - if (headPrimitive) headPrimitive.show = false; + showHead(false); return; } const second = Math.floor(sample.displayT / 1000); @@ -179,114 +211,69 @@ export function createContactTrailRenderer(scene) { candidate.toSeq === sample.toSeq ? candidate : null; - if (body?.ready && done !== completed) { - for ( - let i = Math.min(done, completed) + 1; - i <= Math.max(done, completed); - i++ - ) { - for (let lane = 0; lane < 2; lane++) { - const attributes = body.getGeometryInstanceAttributes( - attributeIds[i][lane], - ); - if (!attributes) continue; - // Cesium getters return copies. Write back the array we changed. - const show = attributes.show; - show[0] = i <= done ? 1 : 0; - attributes.show = show; - } - } + // Passed segments show, and every segment fades with its age, once a + // second; the port writes only the segments that change. + if (body && runs.length && (done !== completed || second !== lastSecond)) { + body.upsert(bodyLines(sample.displayT, done)); completed = done; - } - if (body?.ready && second !== lastSecond) { - for (let i = 0; i < segments.length; i++) { - const alpha = trailAlpha(sample.displayT - segments[i].toT); - for (let lane = 0; lane < 2; lane++) { - const attributes = body.getGeometryInstanceAttributes( - attributeIds[i][lane], - ); - if (!attributes) continue; - const rgba = attributes.color; - Cesium.ColorGeometryInstanceAttribute.toValue( - tint(alpha, !lane), - rgba, - ); - attributes.color = rgba; - if (!ground) { - const depthRgba = attributes.depthFailColor; - Cesium.ColorGeometryInstanceAttribute.toValue( - tint(0.55), - depthRgba, - ); - attributes.depthFailColor = depthRgba; - } - } - } lastSecond = second; } - const show = visible && !!segment && sample.fraction < 1; - head.show = show; - backing.show = show; - if (headPrimitive) headPrimitive.show = show; + const show = + visible && + !!segment?.positions[0] && + !!segment.positions[1] && + sample.fraction < 1; + showHead(show); if (!show) return; - if (active !== segment) { - active = segment; - if (headPrimitive) collection.remove(headPrimitive); - headPrimitive = collection.add( - primitive( - new Cesium.GeometryInstance({ - geometry: geometry(segment.positions, 5, true), - }), - new Cesium.PolylineMaterialAppearance({ - material, - translucent: true, - }), - new Cesium.PolylineMaterialAppearance({ - material: depthMaterial, - translucent: true, - }), - ), - ); - headRebuilds++; - headPositions[0] = segment.positions[0]; - headPositions[1] = endpoint; - } - Cesium.Cartesian3.clone(renderedPosition, endpoint); - head.positions = headPositions; - backing.positions = headPositions; - material.uniforms.fraction = Math.max( + const fraction = Math.max( 0, Math.min( 1, (sample.displayT - segment.fromT) / (segment.toT - segment.fromT), ), ); - depthMaterial.uniforms.fraction = material.uniforms.fraction; - Cesium.Color.clone(tint(0.8), material.uniforms.color); - Cesium.Color.clone(tint(0.55), depthMaterial.uniforms.color); + if (active !== segment || restyled) { + if (active !== segment) headRebuilds++; + active = segment; + restyled = false; + revealed = fraction; + // Upserted, not set: a renderer can move a draped line to where it + // now runs in the same frame, instead of building it anew. + headLines?.upsert(headItems(segment, fraction)); + } else if (fraction !== revealed) { + revealed = fraction; + headLines?.upsert(headItems(segment, fraction)); + } + headPositions[0] = segment.positions[0]; + endpoint.x = renderedPosition.x; + endpoint.y = renderedPosition.y; + endpoint.z = renderedPosition.z; + head.positions = backing.positions = headPositions; } + return { replaceHistory, setDisplaySample, setStyle(next) { if (next === style) return; style = next; - Cesium.Color.fromCssColorString(style, styleColor); + styleColor = cssColor(style)?.slice(0, 3) ?? styleColor; + // Faded again in the new colour on the next sample, and the head + // drawn in it. lastSecond = -1; + restyled = true; }, setVisible(next) { visible = next; - if (headPrimitive) headPrimitive.show = next && head.show; - if (body) body.show = next; + if (body && body.show !== next) body.show = next; + if (!next) showHead(false); }, destroy() { - if (body) collection.remove(body); - if (headPrimitive) collection.remove(headPrimitive); - headPrimitive = null; - material.destroy(); - depthMaterial.destroy(); - body = null; + body?.dispose(); + headLines?.dispose(); segments = []; + runs = []; + active = null; }, diagnostics() { return { @@ -294,13 +281,11 @@ export function createContactTrailRenderer(scene) { rebuilds, segments: segments.length, body, + headLines, head, backing, - headPrimitive, - headStrategy: ground - ? 'draped corridor with material clip' - : 'depth-fail corridor with material clip', - ground, + headStrategy: 'draped lines revealed to the vehicle', + ground: !!draw, headRebuilds, entitiesAdded: 0, }; diff --git a/src/data/contactTrailRenderer.test.mjs b/src/data/contactTrailRenderer.test.mjs index f5204c6eff..3d02d1aae6 100644 --- a/src/data/contactTrailRenderer.test.mjs +++ b/src/data/contactTrailRenderer.test.mjs @@ -1,153 +1,289 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; -import { readFileSync } from 'node:fs'; -import { TRAIL_VERTEX_LIMIT } from '../layers/transit/trails.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { createContactTrailRenderer, trailAlpha, } from './contactTrailRenderer.js'; -function fixture(t, ground = false) { - for (const key of [ - 'HTMLCanvasElement', - 'HTMLImageElement', - 'ImageBitmap', - 'OffscreenCanvas', - ]) { - const prior = globalThis[key]; - globalThis[key] = class {}; - t.after(() => { - if (prior === undefined) delete globalThis[key]; - else globalThis[key] = prior; - }); - } - const width = Cesium.ContextLimits._maximumAliasedLineWidth; - Cesium.ContextLimits._maximumAliasedLineWidth = 1; - t.after(() => { - Cesium.ContextLimits._maximumAliasedLineWidth = width; - }); - const primitives = new Cesium.PrimitiveCollection(); - t.after(() => primitives.destroy()); - const groundPrimitives = new Cesium.PrimitiveCollection(); - t.after(() => groundPrimitives.destroy()); - return { - primitives, - groundPrimitives, - frameState: { context: { depthTexture: ground } }, - globe: { show: false }, - }; +const GREEN = [0x5e / 255, 0xf0 / 255, 0x8a / 255]; +const DARK = [0.02, 0.03, 0.05]; + +function viewerWithDraw(t) { + const viewer = { isDestroyed: () => false }; + const { draw, unbind } = bindFakeDraw(viewer); + t.after(unbind); + return { viewer, draw }; } -test('body clips future subdivisions, head ends at exact marker, and frames retain geometry', (t) => { - const scene = fixture(t), - renderer = createContactTrailRenderer(scene); - const positions = [0, 1, 2].map((i) => - Cesium.Cartesian3.fromDegrees(-71, 42 + i * 0.001, 11.5), - ); - renderer.replaceHistory({ - revision: 1, + +const point = (i) => ({ x: 1000 * i, y: 2000, z: 3000 }); +function history(revision = 1) { + return { + revision, segments: [ { fromSeq: 0, toSeq: 1, fromT: 0, toT: 10000, - positions: positions.slice(0, 2), + positions: [point(0), point(1)], }, { fromSeq: 0, toSeq: 1, fromT: 10000, toT: 20000, - positions: positions.slice(1, 3), + positions: [point(1), point(2)], }, ], - }); - const { body } = renderer.diagnostics(); - assert.equal(body.allowPicking, false); - // The constructor defers this check until shader preparation. Run the real - // Cesium validator without WebGL, including a missing-attribute control. - const source = body.depthFailAppearance.vertexShaderSource; - body._batchTableAttributeIndices = { color: 0 }; - assert.throws( - () => Cesium.Primitive._updateColorAttribute(body, source, true), - /depthFailColor/, - ); - for (const instance of body.geometryInstances) { - assert.deepEqual( - instance.attributes.depthFailColor.value, - Cesium.ColorGeometryInstanceAttribute.toValue( - Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55), - ), - ); - } - body._batchTableAttributeIndices = { color: 0, depthFailColor: 1 }; - assert.doesNotThrow(() => - Cesium.Primitive._updateColorAttribute(body, source, true), - ); - const attributes = new Map( - body.geometryInstances.map((instance) => [ - instance.id, - { - show: new Uint8Array([0]), - color: new Uint8Array(4), - depthFailColor: new Uint8Array(4), - }, - ]), - ); - // Simulate Cesium's completed upload; exercise public attribute writes. - body._ready = true; - body.getGeometryInstanceAttributes = (id) => { - const stored = attributes.get(id), - accessor = {}; - for (const name of ['show', 'color', 'depthFailColor']) - Object.defineProperty(accessor, name, { - get: () => stored[name].slice(), - set: (value) => { - stored[name] = value.slice(); - }, - }); - return accessor; }; - const marker = Cesium.Cartesian3.lerp( - positions[1], - positions[2], - 0.5, - new Cesium.Cartesian3(), +} + +/** The trail's live set whose id ends with `suffix`. */ +const setOf = (draw, suffix) => + [...draw.sets.values()].find( + (set) => !set.disposed && set.spec.id.endsWith(suffix), ); - const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; - for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker); + +const close = (actual, expected) => + actual.every((value, i) => Math.abs(value - expected[i]) < 1e-9); + +test('the body is two draped lanes whose passed segments show, faded by age', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory(history()); + const body = setOf(draw, ':body'); + assert.equal(body.spec.pickable, false); + const lines = [...body.items.values()]; + // One run (the segments join): a backing lane under the mode colour. assert.deepEqual( - [...attributes.values()].map((a) => a.show[0]), - [1, 1, 0, 0], + lines.map((line) => [line.id, line.widthPx, line.mode, line.clampTo]), + [ + ['backing:0', 5, 'draped', 'both'], + ['line:0', 3, 'draped', 'both'], + ], ); - for (const a of attributes.values()) - assert.deepEqual( - a.depthFailColor, - Cesium.ColorGeometryInstanceAttribute.toValue( - Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55), - ), - ); - const result = renderer.diagnostics(); - assert.equal(result.body, body); - assert.equal(result.rebuilds, 1); - assert.equal(result.headRebuilds, 1, '120 frames retain head geometry'); - assert.equal(result.head.material.uniforms.fraction, 0.5); - assert.equal(result.head.width, 3); - assert.equal(result.backing.width, 5); - assert.ok(Cesium.Cartesian3.equals(result.head.positions.at(-1), marker)); - assert.equal(result.head.positions.length, 2); + assert.deepEqual(lines[0].positions, [point(0), point(1), point(2)]); + assert.deepEqual(lines[0].segmentShow, [false, false], 'none passed yet'); + + const marker = { x: 1500, y: 2000, z: 3000 }; + const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; + renderer.setDisplaySample(sample, marker); + const [backing, line] = body.items.values(); + assert.deepEqual(line.segmentShow, [true, false], 'the future is clipped'); + assert.deepEqual(backing.segmentShow, [true, false]); + assert.ok(close(line.segmentColors[0], [...GREEN, trailAlpha(5000)])); + assert.ok(close(backing.segmentColors[0], [...DARK, trailAlpha(5000)])); + + // Within the second, nothing is written again; a rewind hides again. + const writes = body.writes; + for (let i = 0; i < 60; i++) renderer.setDisplaySample(sample, marker); + assert.equal(body.writes, writes); renderer.setDisplaySample( { ...sample, displayT: 5000, fraction: 0.25 }, - positions[0], + point(0), ); - assert.ok( - [...attributes.values()].every((a) => a.show[0] === 0), + assert.deepEqual( + body.items.get('line:0').segmentShow, + [false, false], 'rewind hides future geometry again', ); + assert.equal(renderer.diagnostics().rebuilds, 1); renderer.destroy(); - assert.equal(scene.primitives.length, 0); + assert.equal(body.disposed, true); }); + +test('the head is revealed to the vehicle and drawn anew only at a crossing', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory(history()); + const head = renderer.diagnostics().headLines; + const record = setOf(draw, ':head'); + assert.equal(record.spec.pickable, false); + const marker = { x: 1500, y: 2000, z: 3000 }; + const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; + for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker); + assert.equal(head.show, true); + // One line, its dark edge in the same pass: lanes stacked would darken + // its centre where their translucent passes overlap. + const lines = [...record.items.values()]; + assert.deepEqual( + lines.map((line) => [line.id, line.widthPx, line.revealFraction]), + [['head', 5, 0.5]], + ); + assert.deepEqual(lines[0].positions, [point(1), point(2)]); + assert.ok(close(lines[0].style.color, [...GREEN, 0.8])); + assert.ok(close(lines[0].style.outline.color, [...DARK, 0.8])); + assert.equal(lines[0].style.outline.widthPx, 2); + const result = renderer.diagnostics(); + assert.equal(result.headRebuilds, 1, '120 frames retain head geometry'); + assert.equal(result.entitiesAdded, 0); + assert.equal(result.ground, true); + assert.deepEqual(result.head.positions, [point(1), marker]); + assert.equal(result.head.width, 3); + assert.equal(result.backing.width, 5); + + // A frame further along writes only how far it is revealed. + renderer.setDisplaySample({ ...sample, displayT: 17500 }, marker); + assert.equal(record.items.get('head').revealFraction, 0.75); + assert.equal(renderer.diagnostics().headRebuilds, 1); + // The next subdivision, or the end of the leg, hides it. + renderer.setDisplaySample({ ...sample, fraction: 1 }, marker); + assert.equal(head.show, false); + renderer.setVisible(false); + renderer.setDisplaySample(sample, marker); + assert.equal(head.show, false, 'hidden with the trail'); + assert.equal(result.body.show, false); +}); + +test('a new mode colour is written into the segments, never rebuilding the body', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory(history()); + const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; + renderer.setDisplaySample(sample, point(1)); + const body = setOf(draw, ':body'); + const look = body.items.get('line:0').style; + renderer.setStyle('#FFFFFF'); + renderer.setDisplaySample(sample, point(1)); + const line = body.items.get('line:0'); + assert.deepEqual(line.style, look, 'the line itself is unchanged'); + assert.ok(close(line.segmentColors[0], [1, 1, 1, trailAlpha(5000)])); + assert.equal(renderer.diagnostics().rebuilds, 1); + assert.equal(renderer.diagnostics().headRebuilds, 1, 'no crossing'); + const headLine = setOf(draw, ':head').items.get('head'); + assert.ok(close(headLine.style.color, [1, 1, 1, 0.8]), 'and the head'); +}); + +test('separate runs of the history are separate lines', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + const { segments } = history(); + segments[1] = { ...segments[1], positions: [point(5), point(6)] }; + renderer.replaceHistory({ revision: 2, segments }); + assert.deepEqual( + [...setOf(draw, ':body').items.keys()], + ['backing:0', 'backing:1', 'line:0', 'line:1'], + ); + renderer.replaceHistory({ revision: 3, segments: [] }); + assert.equal(setOf(draw, ':body').items.size, 0); +}); + +test('a viewer with nothing to draw with draws no trail', () => { + const renderer = createContactTrailRenderer({ isDestroyed: () => false }); + assert.doesNotThrow(() => { + renderer.replaceHistory(history()); + renderer.setDisplaySample( + { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }, + point(1), + ); + }); + assert.equal(renderer.diagnostics().ground, false); + renderer.destroy(); +}); + +test('playback across a crossing redraws the head once and shows the passed segment', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory({ + revision: 1, + segments: history().segments.map((segment) => ({ ...segment, toSeq: 2 })), + }); + const body = setOf(draw, ':body'), + head = setOf(draw, ':head'); + // 60 fps through both subdivisions of one leg. + for (let t = 0; t < 20000; t += 16) + renderer.setDisplaySample( + { displayT: t, fromSeq: 0, toSeq: 2, fraction: t / 20000 }, + point(t / 10000), + ); + assert.equal(renderer.diagnostics().headRebuilds, 2, 'one per subdivision'); + assert.deepEqual(body.items.get('line:0').segmentShow, [true, false]); + assert.deepEqual(head.items.get('head').positions, [point(1), point(2)]); + assert.ok(head.items.get('head').revealFraction > 0.99); + // Body writes: one a second, and one at the crossing at most. + assert.ok(body.writes <= 1 + 20 + 1, `${body.writes} body writes`); +}); + +test('the head hides off its leg and with no sample, and shows again', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory(history()); + const head = renderer.diagnostics().headLines; + const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; + renderer.setDisplaySample({ ...sample, toSeq: 9 }, point(1)); + assert.equal(head.show, false, 'another leg'); + renderer.setDisplaySample(sample, point(1)); + assert.equal(head.show, true); + renderer.setDisplaySample(null, null); + assert.equal(head.show, false, 'no sample'); + renderer.setVisible(false); + renderer.setVisible(true); + renderer.setDisplaySample(sample, point(1)); + assert.equal(head.show, true, 'shown again with the trail'); + assert.equal(renderer.diagnostics().body.show, true); + const sets = [setOf(draw, ':body'), setOf(draw, ':head')]; + renderer.destroy(); + assert.ok( + sets.every((set) => set.disposed), + 'both sets disposed', + ); +}); + +test('a segment with no length ends a run and later ones keep their times', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + const { segments } = history(); + segments.splice(1, 0, { + fromSeq: 0, + toSeq: 1, + fromT: 10000, + toT: 10000, + positions: [], + }); + segments[2] = { ...segments[2], fromT: 10000, toT: 20000 }; + renderer.replaceHistory({ revision: 1, segments }); + renderer.setDisplaySample( + { displayT: 25000, fromSeq: 0, toSeq: 1, fraction: 1 }, + point(2), + ); + const body = setOf(draw, ':body'); + assert.deepEqual( + [...body.items.keys()], + ['backing:0', 'backing:1', 'line:0', 'line:1'], + ); + const later = body.items.get('line:1'); + assert.deepEqual(later.positions, [point(1), point(2)]); + assert.deepEqual(later.segmentShow, [true]); + assert.ok(close(later.segmentColors[0], [...GREEN, trailAlpha(5000)])); +}); + +test('frames that change nothing write no show', (t) => { + const { viewer } = viewerWithDraw(t); + const renderer = createContactTrailRenderer(viewer); + renderer.replaceHistory(history()); + const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 }; + renderer.setVisible(true); + renderer.setDisplaySample(sample, point(1)); + const { body, headLines } = renderer.diagnostics(); + let writes = 0; + for (const set of [body, headLines]) { + let show = set.show; + Object.defineProperty(set, 'show', { + get: () => show, + set(value) { + writes++; + show = value; + }, + }); + } + for (let i = 0; i < 30; i++) { + renderer.setVisible(true); + renderer.setDisplaySample(sample, point(1)); + } + assert.equal(writes, 0, 'a renderer may redraw for each show written'); +}); + test('trail age curve uses the specified four alpha anchors', () => { assert.equal(trailAlpha(0), 0.8); assert.equal(trailAlpha(120000), 0.45); @@ -155,203 +291,3 @@ test('trail age curve uses the specified four alpha anchors', () => { assert.equal(trailAlpha(900000), 0.08); assert.ok(Math.abs(trailAlpha(60000) - 0.625) < 1e-10); }); - -test('ground body and clipped head stay inside rebuild and frame geometry budgets', async () => { - Cesium.ApproximateTerrainHeights._terrainHeights = JSON.parse( - readFileSync( - new URL( - import.meta - .resolve('@cesium/engine/Source/Assets/approximateTerrainHeights.json'), - ), - ), - ); - const positions = [ - Cesium.Cartesian3.fromDegrees(-97.7431, 30.267), - Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672), - ]; - const start = performance.now(); - const instances = async (count) => - Promise.all( - Array.from( - { length: count }, - async (_, i) => - new Cesium.GeometryInstance({ - id: i, - geometry: await Cesium.GroundPolylineGeometry.createGeometry( - new Cesium.GroundPolylineGeometry({ - positions, - width: i % 2 ? 3 : 5, - granularity: 0, - }), - ), - }), - ), - ); - const pipelineBytes = async (count) => { - // Match GroundPolylinePrimitive's internal Primitive options and the - // application's morph-capable scene, including batch IDs and encoding. - const result = Cesium.PrimitivePipeline.combineGeometry({ - instances: await instances(count), - projection: new Cesium.GeographicProjection(), - ellipsoid: Cesium.Ellipsoid.WGS84, - modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY), - elementIndexUintSupported: true, - scene3DOnly: false, - vertexCacheOptimize: false, - compressVertices: false, - createPickOffsets: false, - }); - return result.geometries.reduce( - (sum, geometry) => - sum + - Object.values(geometry.attributes).reduce( - (n, a) => n + (a?.values?.byteLength || 0), - 0, - ) + - geometry.indices.byteLength, - 0, - ); - }; - const bytes = await pipelineBytes(1); - const bodyInstances = 2 * (TRAIL_VERTEX_LIMIT - 1); - const bodyBytes = await pipelineBytes(bodyInstances); - assert.equal(bytes, 1576, 'measure final encoded and batched geometry'); - assert.equal(bodyBytes, 2014128); - const instanceReserve = 64 * bodyInstances; - assert.ok(bodyBytes + instanceReserve <= 2 * 1024 * 1024); - assert.ok( - bytes <= 2048, - 'subdivision crossings stay below 2 KiB of head geometry', - ); - console.log( - `trail final pipeline: ${bytes} bytes/head crossing, 0 bytes/ordinary head frame, ${bodyBytes} bytes/body (${bodyInstances} instances), ${instanceReserve} bytes instance reserve; geometry CPU ${(performance.now() - start).toFixed(3)} ms`, - ); -}); - -test('supported scenes drape body and clipped head on 3D tiles and retain head geometry', (t) => { - const scene = fixture(t, true), - renderer = createContactTrailRenderer(scene); - const positions = [ - Cesium.Cartesian3.fromDegrees(-97.7431, 30.267), - Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672), - ]; - renderer.replaceHistory({ - revision: 1, - segments: [{ fromSeq: 0, toSeq: 1, fromT: 0, toT: 20000, positions }], - }); - const first = renderer.diagnostics(); - assert.ok(first.body instanceof Cesium.GroundPolylinePrimitive); - assert.equal(first.body.classificationType, Cesium.ClassificationType.BOTH); - assert.ok(scene.groundPrimitives.contains(first.body)); - for (const instance of first.body.geometryInstances) - assert.ok(instance.geometry instanceof Cesium.GroundPolylineGeometry); - for (let i = 1; i <= 120; i++) - renderer.setDisplaySample( - { displayT: i * 100, fromSeq: 0, toSeq: 1, fraction: i / 200 }, - positions[1], - ); - const result = renderer.diagnostics(); - assert.equal(result.body, first.body); - assert.equal(result.headRebuilds, 1); - assert.ok(result.headPrimitive instanceof Cesium.GroundPolylinePrimitive); - assert.equal(result.head.material.uniforms.fraction, 0.6); - assert.match(result.head.material.shaderSource, /discard/); - for (const stack of ['Google', 'OSM', 'Bing', 'Google']) { - scene.globe.show = stack !== 'Google'; - renderer.setDisplaySample( - { displayT: 12000, fromSeq: 0, toSeq: 1, fraction: 0.6 }, - positions[1], - ); - const retained = renderer.diagnostics(); - assert.equal(retained.body, result.body, `${stack}: retained history`); - assert.equal(retained.headPrimitive, result.headPrimitive); - for (const primitive of [retained.body, retained.headPrimitive]) { - assert.equal( - primitive.classificationType, - Cesium.ClassificationType.BOTH, - stack, - ); - assert.equal(primitive.show, true, stack); - } - } - renderer.setVisible(false); - assert.equal(result.body.show, false); - assert.equal(result.headPrimitive.show, false); - renderer.destroy(); - assert.equal(scene.groundPrimitives.length, 0); - assert.equal(scene.primitives.length, 0); -}); - -test('subdivision crossings only write the changed show range and age colors once per second', (t) => { - const renderer = createContactTrailRenderer(fixture(t)); - const positions = [ - Cesium.Cartesian3.fromDegrees(-71, 42), - Cesium.Cartesian3.fromDegrees(-71, 42.001), - ]; - renderer.replaceHistory({ - revision: 1, - segments: Array.from({ length: 100 }, (_, i) => ({ - fromSeq: 0, - toSeq: 1, - fromT: i * 500, - toT: (i + 1) * 500, - positions, - })), - }); - const { body } = renderer.diagnostics(); - const counts = { show: 0, color: 0, depthFailColor: 0 }; - const attributes = new Map( - body.geometryInstances.map((instance) => { - const result = {}; - for (const name of Object.keys(counts)) { - let value = instance.attributes[name].value; - Object.defineProperty(result, name, { - get: () => value, - set(next) { - value = next; - counts[name]++; - }, - }); - } - return [instance.id, result]; - }), - ); - body._ready = true; - body.getGeometryInstanceAttributes = (id) => attributes.get(id); - const display = (displayT) => - renderer.setDisplaySample( - { displayT, fromSeq: 0, toSeq: 1, fraction: 0.1 }, - positions[0], - ); - const reset = () => { - for (const name of Object.keys(counts)) counts[name] = 0; - }; - display(100); - assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 }); - reset(); - display(600); - assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 }); - reset(); - display(100); - assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 }); - assert.ok( - [...attributes.values()].every((a) => a.show[0] === 0), - 'backward seek hides the completed range', - ); - reset(); - display(1100); - assert.deepEqual(counts, { show: 4, color: 200, depthFailColor: 200 }); - reset(); - display(1200); - assert.deepEqual(counts, { show: 0, color: 0, depthFailColor: 0 }); - renderer.setStyle('#FF4538'); - display(1200); - assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 }); - for (const a of attributes.values()) - assert.deepEqual( - a.depthFailColor, - Cesium.ColorGeometryInstanceAttribute.toValue( - Cesium.Color.fromCssColorString('#FF4538').withAlpha(0.55), - ), - ); -}); diff --git a/src/data/contextStore.js b/src/data/contextStore.js index e0b14b2ba9..2f2847b245 100644 --- a/src/data/contextStore.js +++ b/src/data/contextStore.js @@ -1,3 +1,5 @@ +import { entityRecord, readEntityRecord } from './entityRecords.js'; + const STORE_KEY = '__gevContextStore'; function createStore() { @@ -36,14 +38,14 @@ export function registerEntityContext(entity, metadata) { entity, updatedAt: Date.now(), }; - entity.__gevContextId = metadata.id; + entityRecord(entity).contextId = metadata.id; store.entities.set(metadata.id, record); return record; } export function selectEntityContext(entity) { const store = getContextStore(); - const contextId = entity?.__gevContextId; + const contextId = readEntityRecord(entity)?.contextId; if (!contextId || !store.entities.has(contextId)) return null; store.selectedEntityId = contextId; store.selectedAt = Date.now(); @@ -84,7 +86,7 @@ export function selectTrackedSubjectContext(metadata) { store.entities.delete(key); } // Reuse the existing carrier so a per-poll refresh does not churn identity. - const carrier = store.entities.get(id)?.entity || { __gevContextId: id }; + const carrier = store.entities.get(id)?.entity || {}; const record = registerEntityContext(carrier, { ...metadata, id }); if (!record) return null; store.selectedEntityId = id; diff --git a/src/data/contextStore.test.mjs b/src/data/contextStore.test.mjs index e9631133d4..cb9f75eeda 100644 --- a/src/data/contextStore.test.mjs +++ b/src/data/contextStore.test.mjs @@ -96,7 +96,7 @@ test('a sibling tracking layer keeps its own subject slot', () => { test('the per-poll refresh updates values without stealing the selection', () => { withWindow(() => { selectTrackedSubjectContext(flightSubject('aaa001')); - const other = registerEntityContext({ __gevContextId: 'dc-7' }, { + const other = registerEntityContext({}, { id: 'dc-7', layerId: 'local-datacenters', label: 'Datacenter 7', }); selectEntityContext(other.entity); @@ -130,7 +130,7 @@ test('deselecting a contact releases the shared slot', () => { test('clearing one tracking layer leaves another layer selection alone', () => { withWindow(() => { - const other = registerEntityContext({ __gevContextId: 'dam-3' }, { + const other = registerEntityContext({}, { id: 'dam-3', layerId: 'local-dams', label: 'Dam 3', }); selectEntityContext(other.entity); diff --git a/src/data/dataCredits.js b/src/data/dataCredits.js index 3dad278e71..da5e576fc3 100644 --- a/src/data/dataCredits.js +++ b/src/data/dataCredits.js @@ -1,4 +1,5 @@ -import * as Cesium from 'cesium'; +import { creditFromMarkup } from '../render/creditMarkup.js'; +import { findCredits } from '../render/rendererOf.js'; /** * Per-layer data attribution registered into Cesium's credit display. @@ -44,6 +45,20 @@ export const ACARTIA_CREDIT = Object.freeze({ const osmDisplays = new WeakMap(); +/** The short inline OSM credits, as the renderer's credits port takes them. */ +const OSM_INLINE_CREDITS = Object.freeze({ + osm: Object.freeze({ + text: '© OpenStreetMap', + href: 'https://www.openstreetmap.org/copyright', + inline: true, + }), + tiles: Object.freeze({ + text: '© OpenMapTiles', + href: 'https://openmaptiles.org', + inline: true, + }), +}); + function updateOsmDisplay(viewer, state) { const osm = state.owners.size > 0; let tiles = false; @@ -52,37 +67,27 @@ function updateOsmDisplay(viewer, state) { ['osm', osm], ['tiles', tiles], ]) { - if (state[key].visible === visible) continue; - state[key].visible = visible; - viewer.creditDisplay[visible ? 'addStaticCredit' : 'removeStaticCredit']( - state[key].credit, - ); - viewer.scene?.requestRender?.(); + if (Boolean(state.offs[key]) === visible) continue; + if (visible) { + // Looked up each time: a renderer bound later takes over. + const credits = findCredits(viewer); + if (credits) state.offs[key] = credits.addStatic(OSM_INLINE_CREDITS[key]); + } else { + state.offs[key](); + state.offs[key] = null; + } } } -/** Keep one short inline credit while an OSM display owner has visible data. */ +/** + * Keep one short inline credit, through the renderer's credits port, while + * an OSM display owner has visible data. + */ export function showOsmCredit(viewer, owner, { openMapTiles = false } = {}) { - if (!viewer?.creditDisplay?.addStaticCredit || !owner) return false; + if (!owner || !findCredits(viewer)) return false; let state = osmDisplays.get(viewer); if (!state) { - state = { - owners: new Map(), - osm: { - visible: false, - credit: new Cesium.Credit( - '© OpenStreetMap', - true, - ), - }, - tiles: { - visible: false, - credit: new Cesium.Credit( - '© OpenMapTiles', - true, - ), - }, - }; + state = { owners: new Map(), offs: { osm: null, tiles: null } }; osmDisplays.set(viewer, state); } if (state.owners.get(owner) === openMapTiles) return false; @@ -812,43 +817,84 @@ export const BHOTE_KOSHI_LOCATOR_CREDIT = { '(CC BY-NC 4.0)', }; +/** A link, its whole element. */ +const LINK = /"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/a\s*>/gi; +/** + * The separators text between two links can break at; it breaks at its + * last. A semicolon ending a character reference is not one. A full stop + * after an abbreviation reads as one, so keep "Dr." and "e.g." out of the + * text between links. + */ +const SEPARATOR = /\s*(?:[,·—–]|(? 0) { + const close = /^[)\]]*/.exec(gap)[0]; + gap = gap.slice(close.length); + const cut = [...gap.matchAll(SEPARATOR)].at(-1); + const before = cut ? gap.slice(0, cut.index) : ''; + const stop = cut && cut[0].trimStart().startsWith('.') ? '.' : ''; + pieces[pieces.length - 1] += close + before + stop; + pieces.push(cut ? gap.slice(cut.index + cut[0].length) : gap); + } else pieces[0] += gap; + pieces[pieces.length - 1] += link[0]; + at = link.index + link[0].length; + } + pieces[pieces.length - 1] += markup.slice(at); + return pieces + .map((piece) => ({ ...creditFromMarkup(piece), inline: false })) + .filter((credit) => credit.text); +} + +/** Add a data credit to the attribution list through the renderer. */ +function addDataCredit(viewer, credit) { + const credits = findCredits(viewer); + if (!credits) return false; + for (const one of creditsFromMarkup(credit.html)) credits.addStatic(one); + return true; +} + /** @type {Set} Keys of dynamic credits already registered this session. */ const _dynamicCreditKeys = new Set(); /** * Register a conditional credit at the moment its data source activates. - * Idempotent per `credit.key`; lands in the same "Data attribution" popover - * as the static credits (showOnScreen=false). - * @param {Cesium.Viewer} viewer — the initialized Cesium viewer + * Idempotent per `credit.key`; lands in the same "Data attribution" list + * as the static credits, through the renderer's credits port. + * @param {object} viewer — the scene object the renderer is bound to * @param {{ key: string, html: string }} credit — e.g. `TOMTOM_CREDIT` * @returns {boolean} True when the credit is (now) registered. */ export function registerDynamicCredit(viewer, credit) { - const creditDisplay = viewer?.creditDisplay; - if (!creditDisplay || typeof creditDisplay.addStaticCredit !== 'function') { - return false; - } - if (!credit?.key || !credit?.html) return false; - if (_dynamicCreditKeys.has(credit.key)) return true; - creditDisplay.addStaticCredit(new Cesium.Credit(credit.html, false)); + if (!viewer || !credit?.key || !credit?.html) return false; + if (_dynamicCreditKeys.has(credit.key)) return Boolean(findCredits(viewer)); + if (!addDataCredit(viewer, credit)) return false; _dynamicCreditKeys.add(credit.key); return true; } /** - * Register every per-layer data credit into the viewer's credit display. - * Idempotent: safe to call once at init. Credits are static and always - * present in the "Data attribution" popover. - * @param {Cesium.Viewer} viewer — the initialized Cesium viewer + * Register every per-layer data credit through the renderer's credits + * port. Safe to call once at init. Credits are static and always present + * in the "Data attribution" list, not on the map's credit line. + * @param {object} viewer — the scene object the renderer is bound to */ export function registerDataCredits(viewer, credits = DATA_CREDITS) { - const creditDisplay = viewer?.creditDisplay; - if (!creditDisplay || typeof creditDisplay.addStaticCredit !== 'function') { - return; - } - for (const { html } of credits) { - // showOnScreen=false → lives in the expandable "Data attribution" popover, - // not the on-globe credit line. - creditDisplay.addStaticCredit(new Cesium.Credit(html, false)); - } + if (!viewer) return; + for (const credit of credits) addDataCredit(viewer, credit); } diff --git a/src/data/dataCredits.test.mjs b/src/data/dataCredits.test.mjs index 3c9fb0feef..8036413793 100644 --- a/src/data/dataCredits.test.mjs +++ b/src/data/dataCredits.test.mjs @@ -7,6 +7,7 @@ import { transitFeedCredit, } from './dataCredits.js'; import { getTransitFeed } from './transitFeeds.js'; +import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; test('every credit carries a unique key and some markup to render', () => { const keys = DATA_CREDITS.map((entry) => entry.key); @@ -103,13 +104,13 @@ test('inline OSM attribution persists until its last display owner leaves', asyn const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js'); t.mock.timers.enable({ apis: ['setTimeout'] }); const visible = new Set(); - const viewer = { + const viewer = bindFakeCesiumCredits({ creditDisplay: { addStaticCredit: (c) => visible.add(c), removeStaticCredit: (c) => visible.delete(c), }, scene: { requestRender() {} }, - }; + }); assert.equal(showOsmCredit(viewer, 'alpr'), true); assert.equal(showOsmCredit(viewer, 'alpr'), false); assert.equal(visible.size, 1); @@ -143,13 +144,13 @@ test('tile attribution follows source changes and viewers have independent owner const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js'); const create = () => { const credits = new Set(); - return { + return bindFakeCesiumCredits({ credits, creditDisplay: { addStaticCredit: (c) => credits.add(c), removeStaticCredit: (c) => credits.delete(c), }, - }; + }); }; const a = create(), b = create(); @@ -197,6 +198,109 @@ test('every Street Level imagery source is in the attribution lightbox', () => { ); }); +test('a credit with several links becomes one credit per link, in order', async () => { + const { + creditsFromMarkup, + OSM_CREDIT, + OPENMAPTILES_CREDIT, + WOF_CREDIT, + BHOTE_KOSHI_CREDIT, + } = await import('./dataCredits.js'); + const html = (key) => DATA_CREDITS.find((entry) => entry.key === key).html; + const read = (markup) => + creditsFromMarkup(markup).map(({ text, href }) => [text, href]); + assert.deepEqual(read(OSM_CREDIT.html), [ + [ + 'Map and place data © OpenStreetMap contributors', + 'https://www.openstreetmap.org/copyright', + ], + ['(ODbL)', 'https://opendatacommons.org/licenses/odbl/1-0/'], + ]); + assert.deepEqual(read(OPENMAPTILES_CREDIT.html), [ + ['Vector tiles: OpenFreeMap', 'https://openfreemap.org'], + ['© OpenMapTiles', 'https://openmaptiles.org'], + ]); + assert.deepEqual(read(html('nasa-gibs'))[1], [ + 'HLS product page', + 'https://lpdaac.usgs.gov/products/hlss30v002/', + ]); + assert.deepEqual(read(html('wfigs')), [ + [ + 'Wildfire perimeters: National Interagency Fire Center (WFIGS)', + 'https://data-nifc.opendata.arcgis.com/', + ], + ['Incident information: InciWeb', 'https://inciweb.wildfire.gov/'], + ]); + assert.deepEqual(read(html('eccc-aqhi')), [ + [ + 'Air quality (AQHI): Environment and Climate Change Canada — MSC GeoMet (eccc-msc.github.io/open-data)', + 'https://eccc-msc.github.io/open-data/', + ], + [ + 'ECCC Data Servers End-use Licence', + 'https://eccc-msc.github.io/open-data/licence/readme_en/', + ], + ]); + assert.deepEqual( + read(BHOTE_KOSHI_CREDIT.html)[1][0].slice(0, 15), + 'and GeoPera (CC', + ); + assert.deepEqual( + read(WOF_CREDIT.html).map(([text]) => text), + [ + "Neighborhood boundaries: Who's On First and contributors, simplified", + '(sources and licences)', + ], + ); + const link = (text) => `${text}`; + assert.deepEqual( + read(`${link('A')} by Hoffleit & Warren ${link('B')}`).map( + ([text]) => text, + ), + ['A', 'by Hoffleit & Warren B'], + 'a character reference is not a separator', + ); + assert.deepEqual(read(html('usgs')), [ + ['Earthquakes: Data courtesy of the U.S. Geological Survey', undefined], + ]); + for (const entry of DATA_CREDITS) { + const credits = creditsFromMarkup(entry.html); + const links = entry.html.match(/ credit.inline === false), + `${entry.key} belongs in the attribution list`, + ); + } +}); + +test('data credits go through the renderer to the attribution list', async () => { + const { registerDataCredits, registerDynamicCredit, TOMTOM_CREDIT } = + await import('./dataCredits.js'); + const shown = []; + const viewer = bindFakeCesiumCredits({ + creditDisplay: { + addStaticCredit: (c) => shown.push(c), + removeStaticCredit() {}, + }, + }); + const credits = DATA_CREDITS.filter((entry) => + ['openstreetmap', 'usgs'].includes(entry.key), + ); + registerDataCredits(viewer, credits); + assert.equal(shown.length, 3); + assert.ok(shown.every((credit) => !credit.showOnScreen)); + const odbl = shown.find((credit) => credit.html.includes('opendatacommons')); + assert.match(odbl.html, /href="https:\/\/opendatacommons.org/); + // As the source wrote it: only the licence's name is the link. + assert.match(odbl.html, /\(]*>ODbL<\/a>\)/); + assert.equal(registerDynamicCredit(viewer, TOMTOM_CREDIT), true); + assert.equal(registerDynamicCredit(viewer, TOMTOM_CREDIT), true); + assert.equal(shown.length, 4, 'a dynamic credit is added once'); + assert.match(shown[3].html, /Traffic flow data © ]*>TomTom<\/a>/); + assert.equal(registerDynamicCredit({}, { key: 'none', html: 'x' }), false); +}); + test('the News layer credits its built-in sources', () => { const credit = (key) => DATA_CREDITS.find((entry) => entry.key === key); // GDELT's terms ask for a citation and a link. diff --git a/src/data/detection.js b/src/data/detection.js index 770b63fefe..c976455e60 100644 --- a/src/data/detection.js +++ b/src/data/detection.js @@ -1,5 +1,4 @@ import { paintTransitBracket } from './detectionDraw.js'; -import * as Cesium from 'cesium'; import { governorRequestRender } from '../renderGovernor.js'; import { DETECTION_ENABLE_FADE_MS, @@ -51,7 +50,7 @@ import { } from './detectionPolicy.js'; import { detectionBracketOpacity } from './detectionPresentation.js'; import { SurfaceOcclusion } from './detectionOcclusion.js'; -import { SceneOcclusionProbe } from './sceneOcclusionProbe.js'; +import { rendererOf } from '../render/rendererOf.js'; import { createCyberSonarSampler, cyberSonarFrameDelay, @@ -204,11 +203,9 @@ export function countFadingRenderEntries(renderEntries) { return count; } // --------------------------------------------------------------------------- -// Module-level state — singleton lifecycle tied to the Cesium viewer +// Module-level state — singleton lifecycle tied to the shared overlay host // --------------------------------------------------------------------------- -/** @type {Cesium.Viewer|null} */ -let _viewer = null; /** @type {number} Current mode index into MODE_LABELS */ let _mode = MODE_OFF; /** @type {HTMLCanvasElement|null} Shared host canvas used for QA diagnostics. */ @@ -270,14 +267,43 @@ let _allocationStrategy = ALLOCATION_ELASTIC; let _lastNonOffMode = MODE_BALANCED; /** @type {LabelArbiter} Shared stable callout selector. */ const _labelArbiter = new LabelArbiter(); +/** + * A probe that tests nothing: a renderer without an occlusion probe of its + * own draws every depth-tested contact's bracket and callout. + */ +const NO_OCCLUSION_PROBE = Object.freeze({ + mode: 'off', + maxPerFrame: 0, + lastFrameMs: 0, + lastFrameTests: 0, + beginFrame() {}, + add: () => false, + endFrame() {}, + reset() {}, + destroy() {}, +}); /** * Hides the bracket and callout of a depth-tested contact (a street vehicle) * that the scene drew something in front of. `_occlusionProbe` asks the GPU - * about each such contact without waiting for the answer; `_surfaceOcclusion` - * remembers the answers and decides, every frame, who is drawn. + * about each such contact without waiting for the answer (the renderer's + * `query.occlusionTest()`, where it has the `occlusionTest` capability); + * `_surfaceOcclusion` remembers the answers and decides, every frame, who is + * drawn. */ -const _occlusionProbe = new SceneOcclusionProbe(); +let _occlusionProbe = NO_OCCLUSION_PROBE; const _surfaceOcclusion = new SurfaceOcclusion(_occlusionProbe); + +/** Use the occlusion probe of `viewer`'s renderer, or none. */ +function _useOcclusionProbe(viewer) { + _occlusionProbe.destroy(); + const renderer = rendererOf(viewer); + _occlusionProbe = + (renderer?.capabilities?.has('occlusionTest') && + renderer.query.occlusionTest?.()) || + NO_OCCLUSION_PROBE; + _surfaceOcclusion.clear(); + _surfaceOcclusion.probe = _occlusionProbe; +} /** * Keys of callouts the label arbiter still holds for contacts last seen * hidden. A key stays here until its contact is seen drawn again or the @@ -311,7 +337,9 @@ let _cockpitModeListener = null; /** * Initializes detection inside the shared world-overlay host and stores * references to data layers. The host owns the canvas and render listener. - * @param {Cesium.Viewer} viewer - The active Cesium viewer instance. + * @param {object} viewer - The host the renderer is bound to. The + * world-overlay host hands each paint its camera; the renderer's occlusion + * probe, where it has one, tests depth-tested contacts. * @param {Array} layers - Data layer modules that may implement getDetectableObjects(). * @param {Function} onModeChange - Callback invoked with the new mode label string on mode changes. */ @@ -324,9 +352,9 @@ export function initDetection(viewer, layers, onModeChange) { } _hostLane?.unregister?.(); _calloutLane?.unregister?.(); - _viewer = viewer; _layers = layers; _onModeChange = onModeChange; + _useOcclusionProbe(viewer); _debugBanner = detectionDebugRequested( typeof window !== 'undefined' ? window.location?.search : '', ); @@ -380,7 +408,6 @@ export function destroyDetection() { _calloutLane = null; _transitBracketPaths.clear(); _calloutCount = 0; - _viewer = null; _layers = []; _onModeChange = null; _hostCanvas = null; @@ -392,7 +419,7 @@ export function destroyDetection() { _labelArbiter.clear(); _surfaceOcclusion.clear(); _surfaceSuppressedKeys.clear(); - _occlusionProbe.destroy(); + _useOcclusionProbe(null); _lastLabelSolveAt = 0; _labelSolveDirty = true; _lastDiagnostics = null; @@ -1194,6 +1221,15 @@ function _plateScaleForBackdrop(skyFactor) { return 1 + (SKY_PLATE_SCALE - 1) * skyFactor; } +/** + * The eye's height above the ellipsoid (m) for this paint, from the host + * frame (the camera port's pose); undefined when the pose has none. + */ +function _eyeHeight(frame) { + const height = frame.cameraHeight; + return Number.isFinite(height) ? height : undefined; +} + /** Materialize one bounded rich-callout candidate for the existing arbiter. */ function _materializeCandidate( obj, @@ -1318,9 +1354,7 @@ function _drawOverlay(frame) { profile: MODE_LABELS[_mode], densityPct: _densityPct, allocationStrategy: _allocationStrategy, - viewScale: viewScaleForAltitude( - _viewer?.camera?.positionCartographic?.height, - ), + viewScale: viewScaleForAltitude(_eyeHeight(frame)), candidateCount: 0, observationCount: 0, visibleCount: 0, @@ -1363,7 +1397,7 @@ function _drawOverlay(frame) { const camPos = frame.cameraPosition; // Answers to the occlusion tests started on earlier frames land here. _surfaceOcclusion.beginFrame(now); - _occlusionProbe.beginFrame(_viewer?.scene, _surfaceOcclusion.now); + _occlusionProbe.beginFrame(_surfaceOcclusion.now); const keyhole = frame.keyhole; // Read the OUTSIDE setting ONCE per paint, from the same module state the // host's own keyhole alpha comes from, so a bracket and its callout can never @@ -1450,8 +1484,11 @@ function _drawOverlay(frame) { let halfW; let halfH; if (obj.type === 'AIR') { + const dx = camPos.x - obj.position.x; + const dy = camPos.y - obj.position.y; + const dz = camPos.z - obj.position.z; const bscale = nearFarScale( - Cesium.Cartesian3.distance(camPos, obj.position), + Math.sqrt(dx * dx + dy * dy + dz * dz), BILL_NEAR, BILL_NEAR_SCALE, BILL_FAR, @@ -1600,7 +1637,7 @@ function _drawOverlay(frame) { // Start this frame's occlusion tests; nothing here waits for them. _occlusionProbe.endFrame(); - const altitude = _viewer?.camera?.positionCartographic?.height ?? 1e9; + const altitude = _eyeHeight(frame) ?? 1e9; const collectiveBudget = labelBudgetFor(altitude, _densityPct); const ambientBudget = Math.max( 0, diff --git a/src/data/detectionHost.test.mjs b/src/data/detectionHost.test.mjs index c602559938..9a8df9c97c 100644 --- a/src/data/detectionHost.test.mjs +++ b/src/data/detectionHost.test.mjs @@ -1,3 +1,4 @@ +import { bindOverlayPorts } from '../testSupport/fakeOverlayPorts.mjs'; import { readShellSource } from '../testSupport/readShellSource.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; @@ -41,7 +42,9 @@ import { createFakeGl, depthImage, viewDistanceToDepth, -} from './fixtures/fakeDepthScene.mjs'; +} from '../render/cesium/fixtures/fakeDepthScene.mjs'; +import { createSceneOcclusionTest } from '../render/cesium/sceneOcclusionProbe.js'; +import { rendererOf } from '../render/rendererOf.js'; test('detection diagnostics count rendered fading rows instead of absent selected identities', () => { assert.equal(countFadingRenderEntries([ @@ -264,6 +267,7 @@ function installEnvironment({ width = 800, height = 600, dpr = 2, search = '' } }, scene: { postRender, requestRender() {} }, }; + bindOverlayPorts(viewer); return { viewer, @@ -554,6 +558,25 @@ test('callouts stop painting the moment the last detectable object goes away', ( } }); +test('the view scale reads the camera height the overlay host gives each paint', () => { + const env = installEnvironment(); + try { + initWorldOverlay(env.viewer); + initDetection(env.viewer, [{ id: 'flights', getDetectableObjects: () => [] }], () => {}); + setMode('DENSE'); + const scaleAt = (height) => { + env.viewer.camera.positionCartographic.height = height; + env.advance(250); + env.postRender.raise(); + return getDetectionDiagnostics().viewScale; + }; + assert.equal(scaleAt(1000), 'street'); + assert.equal(scaleAt(10000), 'metro'); + } finally { + env.cleanup(); + } +}); + test('every style paints its OWN plate token through the production callout path', () => { // The token table and the direct painter are both pinned elsewhere, but a // pin on either one still passes if the runtime stops consulting the active @@ -1394,6 +1417,11 @@ function installDepthScene(env, surfaceDistance, { webgl2 = true } = {}) { const image = paint(); const scene = createFakeDepthScene({ gl, ranges: [{ near, far, image }] }); Object.assign(env.viewer.scene, scene, { camera }); + // The renderer's occlusion test, as the Cesium query port gives it. + const renderer = rendererOf(env.viewer); + renderer.capabilities = new Set(['occlusionTest']); + renderer.query.occlusionTest = () => + createSceneOcclusionTest(env.viewer.scene); return { gl, /** Draw the next frame's depth. */ diff --git a/src/data/detectionOcclusion.js b/src/data/detectionOcclusion.js index 83c6687255..8ef40d4c0f 100644 --- a/src/data/detectionOcclusion.js +++ b/src/data/detectionOcclusion.js @@ -9,9 +9,10 @@ * The fix compares each such contact with what the renderer actually drew: if * the drawn surface along the contact's ray is nearer than the contact by more * than a small margin, something stands in front of it and its bracket and - * callout are not drawn. `sceneOcclusionProbe.js` runs that comparison on the - * GPU, against the frame's own depth, and hands back a yes or no per contact a - * frame or two later without ever waiting on the GPU. This file holds the + * callout are not drawn. The renderer's occlusion test (`query.occlusionTest`; + * the GPU probe is `src/render/occlusion/depthProbe.js`) runs that comparison + * on the GPU, against the frame's own depth, and hands back a yes or no per + * contact a frame or two later without ever waiting on the GPU. This file holds the * arithmetic both sides share and the per-contact memory of the answers. * * Only contacts that opt in with `depthTested: true` are tested: the ones whose @@ -119,9 +120,12 @@ export function unpackDepth(bytes, offset) { */ export function depthToViewDistance(depth, near, far, logDepth) { if (!(depth > 0) || !(depth < 1)) return Number.NaN; - if (!(near > 0) || !(far > near)) return Number.NaN; + if (!(near >= 0) || !(far > near)) return Number.NaN; if (logDepth) return near + Math.pow(2, depth * Math.log2(far - near + 1)) - 1; + // Standard depth needs a near plane in front of the eye; log depth does not + // (it can be written with none, as log2(1 + d) / log2(far + 1)). + if (!(near > 0)) return Number.NaN; return (near * far) / (far - depth * (far - near)); } @@ -185,7 +189,7 @@ export function projectContact(view, tanHalfFovX, tanHalfFovY, position, out) { /** * One frame of depth read back to memory, with the camera it was drawn from. - * Only the synchronous fallback uses this (see `sceneOcclusionProbe.js`); the + * Only the synchronous fallback uses this (see `src/render/occlusion/depthProbe.js`); the * normal path never copies depth off the GPU. * * `bytes` holds `frustums.length` stacked images of `width` x `height` RGBA8 diff --git a/src/data/detectionOcclusion.test.mjs b/src/data/detectionOcclusion.test.mjs index 5aadc7c92c..139a11ad51 100644 --- a/src/data/detectionOcclusion.test.mjs +++ b/src/data/detectionOcclusion.test.mjs @@ -19,7 +19,7 @@ import { depthImage, packDepth, viewDistanceToDepth, -} from './fixtures/fakeDepthScene.mjs'; +} from '../render/cesium/fixtures/fakeDepthScene.mjs'; test('the margin is 3 m near the camera and 2% of the range beyond 150 m', () => { assert.equal(surfaceOcclusionMargin(10), SURFACE_OCCLUSION_MIN_MARGIN_M); @@ -107,9 +107,18 @@ test('the ends of the depth range, and a bad range, mean nothing was drawn', () assert.ok(Number.isNaN(depthToViewDistance(0, 1, 100, log))); assert.ok(Number.isNaN(depthToViewDistance(1, 1, 100, log))); assert.ok(Number.isNaN(depthToViewDistance(Number.NaN, 1, 100, log))); - assert.ok(Number.isNaN(depthToViewDistance(0.5, 0, 100, log))); + assert.ok(Number.isNaN(depthToViewDistance(0.5, -1, 100, log))); assert.ok(Number.isNaN(depthToViewDistance(0.5, 100, 100, log))); } + // No near plane: standard depth has nothing to decode against. + assert.ok(Number.isNaN(depthToViewDistance(0.5, 0, 100, false))); +}); + +test('log depth with no near plane decodes as log2(1 + d) / log2(far + 1)', () => { + const depth = Math.log2(1 + 400) / Math.log2(100_000 + 1); + assert.ok( + Math.abs(depthToViewDistance(depth, 0, 100_000, true) - 400) < 1e-6, + ); }); const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; diff --git a/src/data/directions.js b/src/data/directions.js index 8a871bfbf5..32d4a3fcde 100644 --- a/src/data/directions.js +++ b/src/data/directions.js @@ -4,20 +4,18 @@ import { createDirectionsSource } from '../layers/directions/source.js'; * @description Service bundle for the Directions layer. * * The layer itself lives in `src/layers/directions/`, which imports nothing - * but Cesium and the pure step formatter. This module is the one place that - * names the application's shared services — the render governor, sprite order, - * the pick registry, the world overlay, the annotation material, the camera - * verbs, the shared ground floor and the pointer arbiter — and it re-exports - * the layer's pure helpers for the tests and the share-link code. + * but the renderer's draw port, geodesy and the pure step formatter. This + * module is the one place that names the application's shared services — + * the render governor, sprite order, the pick registry, the world overlay, + * the camera verbs, the shared ground floor and the pointer arbiter — and it + * re-exports the layer's pure helpers for the tests and the share-link code. */ import * as credits from './dataCredits.js'; import * as render from '../renderGovernor.js'; import * as sprites from './spriteOrder.js'; import * as picking from './pickRegistry.js'; -import * as scenePick from './scenePick.js'; import * as overlays from '../overlays/worldOverlay.js'; -import * as annotations from '../annotations/worldAnnotationRenderer.js'; import * as camera from '../cameraVerbs.js'; import * as ground from './groundFloor.js'; import * as input from './inputOwnership.js'; @@ -29,9 +27,7 @@ const directionsServices = Object.freeze({ render, sprites, picking, - scenePick, overlays, - annotations, camera, ground, input, @@ -49,11 +45,12 @@ export { DIRECTIONS_MODES, DIRECTIONS_POINTER_OWNER, DIRECTIONS_ROUTE_COLOR, - POINTER_TOOL_EXITS, STEP_ANCHOR_DEADLINE_MS, STEP_ANCHOR_FAST_ATTEMPTS, STEP_ANCHOR_RETRY_MS, STEP_ANCHOR_SLOW_RETRY_MS, + DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, + createDirectionsMarkerOverlayEntry, createDirectionsStepOverlayEntry, directionsRequestUrl, directionsRowControls, @@ -62,7 +59,6 @@ export { directionsStepList, normalizeDirectionsParams, normalizeRoutePayload, - pointerBlockedMessage, stepAnchorDelayMs, stepIndexAtDistance, stepMarkerHeightM, diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index ae3ac51ff0..ddd144e81f 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -1,11 +1,14 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { DEFAULT_DIRECTIONS_MODE, DIRECTIONS_MODES, DIRECTIONS_POINTER_OWNER, DIRECTIONS_ROUTE_COLOR, + DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, + createDirectionsMarkerOverlayEntry, createDirectionsStepOverlayEntry, directionsRequestUrl, directionsRowControls, @@ -18,8 +21,6 @@ import { stepIndexAtDistance, stepMarkerHeightM, stepMarkerIndices, - pointerBlockedMessage, - POINTER_TOOL_EXITS, STEP_ANCHOR_DEADLINE_MS, STEP_ANCHOR_RETRY_MS, STEP_ANCHOR_SLOW_RETRY_MS, @@ -437,12 +438,6 @@ test('the FLY chip reports a flight in progress', () => { assert.equal(flying.active, true); }); -test('a blocked pointer is reported instead of silently doing nothing', () => { - const blocked = directionsStats({ ...idle, pointerBlocked: true }); - assert.match(blocked.error, /Another map tool is using clicks/); - assert.equal(blocked.count, 0); -}); - test('a step selection can be requested and cleared through params', () => { assert.deepEqual(normalizeDirectionsParams({ step: 3 }), { step: 3 }); assert.deepEqual(normalizeDirectionsParams({ step: 0 }), { step: 0 }); @@ -514,37 +509,40 @@ test('placing an endpoint takes the pointer, and every exit path gives it back', assert.equal(isPointerFree(), true, 'destroy releases'); }); -test('arming is refused, and said so, while another tool holds the pointer', (t) => { +test('arming takes the pointer from another tool, which is told', (t) => { ownershipFixture(t); - - const releaseDraw = claimAs('draw'); - assert.equal( - directionsLayer.setParams({ arm: 'a' }), - true, - 'the write is accepted', - ); - assert.equal( - pointerOwner(), - 'draw', - "the other tool's claim is never stolen", - ); + let lost = 0; + claimPointer('draw', { onLost: () => (lost += 1) }); + assert.equal(directionsLayer.setParams({ arm: 'a' }), true); + assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'the newest wins'); + assert.equal(lost, 1, 'the other tool is told once'); const chips = directionsLayer.getRowControls().chips; - assert.equal( - chips.find((chip) => chip.id === 'set-a').active, - false, - 'nothing is armed', - ); - assert.match( - directionsLayer.getStats().error, - /Another map tool is using clicks/, - 'the row says why the click did nothing', - ); + assert.equal(chips.find((chip) => chip.id === 'set-a').active, true); + assert.equal(directionsLayer.getStats().error, null); +}); - // Once the other tool lets go, arming works and the complaint clears. +test('a newer tool taking the pointer disarms, as Escape would', (t) => { + ownershipFixture(t); + let told = 0; + directionsLayer.setRowControlsListener(() => (told += 1)); + t.after(() => directionsLayer.setRowControlsListener(null)); + directionsLayer.setParams({ arm: 'b' }); + told = 0; + const releaseDraw = claimAs('draw'); + const chips = directionsLayer.getRowControls().chips; + assert.equal(chips.find((chip) => chip.id === 'set-b').active, false); + assert.ok(told > 0, 'the row hears it'); + assert.equal( + directionsLayer.getStats().error, + null, + 'nothing to complain of', + ); + // Its own later release frees nothing of the newer tool's. + directionsLayer.setParams({ arm: null }); + assert.equal(pointerOwner(), 'draw'); assert.equal(releaseDraw(), true); directionsLayer.setParams({ arm: 'a' }); - assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER); - assert.equal(directionsLayer.getStats().error, null); + assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'it arms again'); }); test('a release names this layer, so it cannot free a successor tool claim', (t) => { @@ -564,11 +562,10 @@ test('a release names this layer, so it cannot free a successor tool claim', (t) test('the pointer claim outlives the click that consumed it', async (t) => { ownershipFixture(t); - // Every layer binds its own handler to the same canvas and they all run - // inside ONE browser event. Releasing the claim the moment the endpoint is - // placed hands the rest of that same click to every ambient handler - // registered after this one — which is how placing A on top of a bikeshare - // station also deselected the station. + // The renderer's click comes from the pointer's up, and the browser's own + // `click` on the canvas follows inside ONE input event; DOM listeners there + // ask `isPointerFree()` then. Releasing the claim the moment the endpoint is + // placed hands the rest of that same click to them. directionsLayer.setParams({ arm: 'a' }); assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER); @@ -724,68 +721,6 @@ test('a stale lease cannot free the claim a later arming holds', async (t) => { ); }); -test('a refused arming names the tool holding the pointer and how to leave it', () => { - // Owner field test: he pressed SET A while Draw was open, nothing happened, - // and he concluded Directions was broken. Silence was the bug. - assert.equal( - pointerBlockedMessage('draw', 'a'), - 'Draw is active — press Escape twice to leave Draw, then set A', - ); - assert.equal( - pointerBlockedMessage('draw', 'b'), - 'Draw is active — press Escape twice to leave Draw, then set B', - ); - // A tool nobody has written an exit for still gets a usable sentence. - assert.equal( - pointerBlockedMessage('measure', 'a'), - 'measure is active — turn measure off, then set A', - ); - // A registered owner without an exit is named by its tool, not its id. - assert.equal( - pointerBlockedMessage('recent-imagery-box', 'a'), - 'Recent imagery is active — turn Recent imagery off, then set A', - ); - // Nothing to say when nothing is in the way, or when we are the holder. - assert.equal(pointerBlockedMessage(null, 'a'), null); - assert.equal(pointerBlockedMessage('', 'a'), null); - assert.equal(pointerBlockedMessage(' ', 'a'), null); - assert.equal(pointerBlockedMessage(DIRECTIONS_POINTER_OWNER, 'a'), null); - // Every exit the table knows names its tool and says how to leave it. - for (const [id, exit] of Object.entries(POINTER_TOOL_EXITS)) { - assert.match( - pointerBlockedMessage(id, 'a'), - new RegExp(`^${exit.name} is active — `), - ); - assert.match(pointerBlockedMessage(id, 'a'), /, then set A$/); - } -}); - -test('the refusal reaches the app toast, and a successful arming says nothing', (t) => { - ownershipFixture(t); - const toasts = []; - directionsLayer.attachShellServices({ - showToast: (text) => toasts.push(text), - }); - t.after(() => directionsLayer.attachShellServices(null)); - - const releaseDraw = claimAs('draw'); - directionsLayer.setParams({ arm: 'a' }); - assert.deepEqual(toasts, [ - 'Draw is active — press Escape twice to leave Draw, then set A', - ]); - // The row status the operator can also read is still set. - assert.match( - directionsLayer.getStats().error, - /Another map tool is using clicks/, - ); - - // Once Draw lets go, arming works and says nothing at all. - releaseDraw(); - directionsLayer.setParams({ arm: 'a' }); - assert.equal(toasts.length, 1, 'a successful arming is silent'); - assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER); -}); - test('maneuvers are phrased on the page, in English word for word as the proxy does', () => { const types = [ 'depart', @@ -950,3 +885,75 @@ test('the reroute tooltip keeps German mode nouns capitalized', (t) => { 'Fahrrad – Route im Modus „Fahrrad“ neu berechnen', ); }); + +test('the A and B letters are protected overlay labels in the marker colour', () => { + const position = Cesium.Cartesian3.fromDegrees(-122.39, 37.79); + const entry = createDirectionsMarkerOverlayEntry('B', position, '#ff6b6b'); + assert.equal(entry.id, 'directions-marker-b'); + assert.equal(entry.title, 'B'); + assert.equal(entry.variant, 'label'); + assert.equal(entry.accent, '#ff6b6b'); + assert.equal(entry.protected, true); + assert.equal(entry.position, position); + assert.equal(entry.placement, 'above'); +}); + +test('a placed endpoint draws its letter through the overlay, not as entity text', async (t) => { + const published = []; + const cleared = []; + const visibility = []; + const markerVisibility = () => + visibility + .filter(([source]) => source === DIRECTIONS_MARKER_OVERLAY_SOURCE_ID) + .at(-1)?.[1]; + directionsLayer = createApplicationDirectionsLayer(); + directionsLayer._setOverlayHostForTest({ + setEntries: (source, entries) => published.push([source, entries]), + setVisible: (source, visible) => visibility.push([source, visible]), + clearSource: (source) => cleared.push(source), + }); + resetPointerOwnership(); + const viewer = { + isDestroyed: () => false, + scene: { requestRender() {} }, + }; + const { draw, unbind } = bindFakeDraw(viewer); + t.after(() => { + unbind(); + directionsLayer.destroy(viewer); + directionsLayer._setOverlayHostForTest(null); + resetPointerOwnership(); + }); + directionsLayer.init(viewer); + assert.equal(markerVisibility(), false, 'hidden until enabled'); + directionsLayer.placeEndpoint('a', { lat: 37.7955, lon: -122.3937 }); + + const markers = [...draw.sets.values()].find( + (set) => !set.disposed && set.spec.id.endsWith(':markers'), + ); + assert.deepEqual([...markers.items.keys()], ['directions:marker:A']); + const marker = markers.items.get('directions:marker:A'); + assert.equal(marker.label, undefined, 'no renderer label on the marker'); + assert.equal(marker.height, 'clampGround', 'a dot on the ground'); + const [source, entries] = published.at(-1); + assert.equal(source, DIRECTIONS_MARKER_OVERLAY_SOURCE_ID); + assert.deepEqual( + entries.map((entry) => entry.title), + ['A'], + ); + // Hidden until the floor cell settles, then anchored (the ellipsoid here, + // where the test resolver finds no height). + assert.equal(entries[0].position(), null); + const started = Date.now(); + while (!entries[0].position() && Date.now() - started < 5000) + await new Promise((resolve) => setTimeout(resolve, 10)); + const anchor = Cesium.Cartographic.fromCartesian(entries[0].position()); + assert.ok(Math.abs(Cesium.Math.toDegrees(anchor.latitude) - 37.7955) < 1e-9); + + directionsLayer.setParams({ clear: true }); + assert.equal(markers.items.size, 0, 'CLEAR takes the markers'); + assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID)); + cleared.length = 0; + directionsLayer.destroy(viewer); + assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID)); +}); diff --git a/src/data/displayDelay.js b/src/data/displayDelay.js new file mode 100644 index 0000000000..745de2a5a4 --- /dev/null +++ b/src/data/displayDelay.js @@ -0,0 +1,178 @@ +/** + * @module data/displayDelay + * @description How far behind real time a live aircraft feed is drawn. + * + * Contacts are drawn at `now − delay` so that, at the time drawn, every + * contact has a report on both sides and is placed between two real reports + * instead of dead reckoned past its newest one. The delay has to cover how + * late the feed really is: a feed whose reports arrive 90 s old every 30 s + * needs about two minutes, a fresh one about half a minute. + * + * Each time a contact's report moves on, the feed's lag is how long the + * display had to wait for it: its receipt time less the contact's previous + * report time (lateness, the gap between reports and the wait for the next + * poll together). The delay aimed at is the 90th percentile of the newest 256 + * lags plus 5 s, within the layer's floor and a five-minute cap. Before a + * feed has given 16 lags, its first reports stand in: their age plus one poll + * interval. A delivery that comes more than three poll intervals after the + * one before it (a hidden tab's polls paused, or the feed failed) gives no + * lags: the wait was not the feed's lateness. + * + * The delay drawn with moves toward that aim at a bounded rate, rising by at + * most 0.2 s and falling by at most 0.05 s per second, so every contact + * slows or speeds up a little rather than the whole fleet jumping; an aim + * within 2 s of where it is leaves it there. Until a layer has drawn a + * contact, it takes its aim at once. + */ + +/** @constant {number} Percentile of the recent lags the delay covers. */ +export const DISPLAY_DELAY_RANK = 0.9; +/** @constant {number} How many recent lags the percentile is taken over. */ +export const DISPLAY_DELAY_LAGS = 256; +/** @constant {number} Lags before they, rather than first reports, set the aim. */ +export const DISPLAY_DELAY_MIN_LAGS = 16; +/** @constant {number} Added to the percentile for jitter (ms). */ +export const DISPLAY_DELAY_MARGIN_MS = 5_000; +/** @constant {number} The longest delay (ms). */ +export const DISPLAY_DELAY_CAP_MS = 300_000; +/** @constant {number} Delay gained per unit of real time, at most. */ +export const DISPLAY_DELAY_RISE = 0.2; +/** @constant {number} Delay shed per unit of real time, at most. */ +export const DISPLAY_DELAY_FALL = 0.05; +/** @constant {number} An aim this close (ms) to the delay leaves it be. */ +export const DISPLAY_DELAY_DEADBAND_MS = 2_000; +/** @constant {number} Poll intervals between deliveries past which a delivery gives no lags. */ +export const DISPLAY_DELAY_GAP_POLLS = 3; + +function createWindow(capacity) { + return { values: new Float64Array(capacity), count: 0, cursor: 0 }; +} + +function add(window, value) { + if (!Number.isFinite(value) || value < 0) return; + window.values[window.cursor] = value; + window.cursor = (window.cursor + 1) % window.values.length; + window.count = Math.min(window.count + 1, window.values.length); +} + +function percentile(window, rank) { + const sorted = window.values.slice(0, window.count).sort(); + return sorted[Math.max(0, Math.ceil(sorted.length * rank) - 1)]; +} + +/** + * One live feed's display delay. + * @param {object} options + * @param {number} options.floorMs The shortest delay (ms), and where it starts. + * @param {number} options.pollMs How often the feed is asked (ms). + * @param {number} [options.capMs] The longest delay (ms). + */ +export function createDisplayDelay({ + floorMs, + pollMs, + capMs = DISPLAY_DELAY_CAP_MS, +}) { + const lags = createWindow(DISPLAY_DELAY_LAGS); + const firstAges = createWindow(DISPLAY_DELAY_LAGS); + let aimMs = floorMs; + let fromMs = floorMs; + let fromAtMs = NaN; + let currentMs = floorMs; + // The delivery being noted, the one before it, and whether a pause + // separated them. + let deliveryMs = NaN; + let afterGap = false; + + const clamp = (ms) => Math.max(floorMs, Math.min(capMs, ms)); + + /** The delay at `nowMs` on its way from `fromMs` toward the aim. */ + function delayAt(nowMs) { + if (!Number.isFinite(fromAtMs)) return fromMs; + const elapsed = Math.max(0, nowMs - fromAtMs); + const change = Math.max( + -DISPLAY_DELAY_FALL * elapsed, + Math.min(DISPLAY_DELAY_RISE * elapsed, aimMs - fromMs), + ); + return fromMs + change; + } + + return { + /** The delay contacts are drawn with now (whole ms), as last stepped. */ + get currentMs() { + return currentMs; + }, + /** The delay it is moving toward (ms). */ + get aimMs() { + return aimMs; + }, + /** Lags seen so far, up to the window. */ + get lagCount() { + return lags.count; + }, + + /** + * A contact's report received at `receiptMs`: its time, and the + * contact's previous report time (none for a contact seen first). + */ + noteReport(receiptMs, reportMs, previousReportMs) { + if (receiptMs !== deliveryMs) { + afterGap = receiptMs - deliveryMs > DISPLAY_DELAY_GAP_POLLS * pollMs; + deliveryMs = receiptMs; + } + if (Number.isFinite(previousReportMs)) { + if (reportMs > previousReportMs && !afterGap) + add(lags, receiptMs - previousReportMs); + } else if (Number.isFinite(reportMs)) + add(firstAges, receiptMs - reportMs); + }, + + /** + * Aim again after a delivery. `jump`: nothing is drawn yet, so the delay + * takes the aim at once. + * @param {number} nowMs + * @param {{jump?: boolean}} [options] + * @returns {number} The delay now (whole ms). + */ + settle(nowMs, { jump = false } = {}) { + let next = aimMs; + if (lags.count >= DISPLAY_DELAY_MIN_LAGS) + next = clamp( + percentile(lags, DISPLAY_DELAY_RANK) + DISPLAY_DELAY_MARGIN_MS, + ); + else if (firstAges.count) + next = clamp( + percentile(firstAges, DISPLAY_DELAY_RANK) + + pollMs + + DISPLAY_DELAY_MARGIN_MS, + ); + const now = delayAt(nowMs); + fromMs = jump ? next : now; + fromAtMs = nowMs; + // An aim this close leaves the delay where it is. + aimMs = + Math.abs(next - now) < DISPLAY_DELAY_DEADBAND_MS && !jump ? now : next; + currentMs = Math.round(fromMs); + return currentMs; + }, + + /** + * Move the delay on to `nowMs`: what the contacts are drawn with until + * the next step. + * @returns {number} Whole ms. + */ + step(nowMs) { + currentMs = Math.round(delayAt(nowMs)); + return currentMs; + }, + + /** Forget the feed: back to the floor, nothing learned. */ + reset() { + lags.count = lags.cursor = 0; + firstAges.count = firstAges.cursor = 0; + aimMs = fromMs = currentMs = floorMs; + fromAtMs = NaN; + deliveryMs = NaN; + afterGap = false; + }, + }; +} diff --git a/src/data/displayDelay.test.mjs b/src/data/displayDelay.test.mjs new file mode 100644 index 0000000000..de8e4a1dcf --- /dev/null +++ b/src/data/displayDelay.test.mjs @@ -0,0 +1,185 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createDisplayDelay, + DISPLAY_DELAY_CAP_MS, + DISPLAY_DELAY_DEADBAND_MS, + DISPLAY_DELAY_FALL, + DISPLAY_DELAY_LAGS, + DISPLAY_DELAY_MARGIN_MS, + DISPLAY_DELAY_MIN_LAGS, + DISPLAY_DELAY_RISE, +} from './displayDelay.js'; + +// A live feed is drawn far enough behind real time that every contact has a +// report on both sides of the time drawn. + +const SEC = 1000; +const FLOOR = 30 * SEC; +const POLL = 30 * SEC; + +/** + * A feed polled every 30 s whose reports arrive `ageMs` old, one new report + * per contact per poll: each lag is the age plus the poll interval. + */ +function feed(delay, { contacts = 20, polls = 4, ageMs, startMs = 0 }) { + let now = startMs; + for (let p = 0; p < polls; p++) { + now += POLL; + for (let c = 0; c < contacts; c++) { + const reportMs = now - ageMs - c * 10; + delay.noteReport(now, reportMs, reportMs - POLL); + } + } + return now; +} + +test('the aim is the 90th percentile of recent lags plus the margin', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + const now = feed(delay, { ageMs: 90 * SEC }); + assert.ok(delay.lagCount >= DISPLAY_DELAY_MIN_LAGS); + delay.settle(now, { jump: true }); + // Lags 120 s (plus the spread of 0–190 ms): 125 s and a little. + assert.ok( + Math.abs(delay.currentMs - (120 * SEC + DISPLAY_DELAY_MARGIN_MS)) < 300, + `${delay.currentMs}`, + ); +}); + +test('a fresh feed stays at the floor', () => { + // Polled every 10 s, reports 2 s old: lags of 12 s, aim 17 s, under the floor. + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: 10 * SEC }); + for (let i = 1; i <= 40; i++) + delay.noteReport( + i * 10 * SEC, + i * 10 * SEC - 2 * SEC, + (i - 1) * 10 * SEC - 2 * SEC, + ); + assert.equal(delay.settle(400 * SEC, { jump: true }), FLOOR); +}); + +test('the delay never passes the cap', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + const now = feed(delay, { ageMs: 20 * 60 * SEC }); + assert.equal(delay.settle(now, { jump: true }), DISPLAY_DELAY_CAP_MS); +}); + +test('before enough lags, first reports stand in: their age plus a poll', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + for (let c = 0; c < 10; c++) + delay.noteReport(1_000 * SEC, 1_000 * SEC - 90 * SEC); + assert.equal(delay.lagCount, 0); + assert.equal( + delay.settle(1_000 * SEC, { jump: true }), + 90 * SEC + POLL + DISPLAY_DELAY_MARGIN_MS, + ); +}); + +test('a report that did not move on gives no lag', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + delay.noteReport(100 * SEC, 50 * SEC, 50 * SEC); + delay.noteReport(100 * SEC, 40 * SEC, 50 * SEC); + assert.equal(delay.lagCount, 0); +}); + +test('only the newest lags count', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + let now = feed(delay, { + ageMs: 200 * SEC, + contacts: DISPLAY_DELAY_LAGS, + polls: 1, + }); + now = feed(delay, { + ageMs: 10 * SEC, + contacts: DISPLAY_DELAY_LAGS, + polls: 1, + startMs: now, + }); + assert.ok(delay.settle(now, { jump: true }) < 50 * SEC); +}); + +test('the delay rises toward its aim at most 0.2 s per second, then holds there', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + const now = feed(delay, { ageMs: 90 * SEC }); + assert.equal(delay.settle(now), FLOOR, 'not jumped once drawing'); + const aim = delay.aimMs; + let prev = delay.currentMs; + for (let s = 1; s <= 600; s++) { + const d = delay.step(now + s * SEC); + assert.ok(d - prev <= DISPLAY_DELAY_RISE * SEC + 1, `rose ${d - prev} ms`); + assert.ok(d >= prev); + prev = d; + } + assert.equal(prev, aim); + // Rising by 0.2 s a second, the time drawn still moves forward at 0.8×. + assert.ok(DISPLAY_DELAY_RISE < 1); +}); + +test('the delay falls at most 0.05 s per second', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + let now = feed(delay, { ageMs: 90 * SEC }); + delay.settle(now, { jump: true }); + const high = delay.currentMs; + now = feed(delay, { + ageMs: 0, + polls: 13, + startMs: now, + }); + delay.settle(now); + assert.ok(Math.abs(delay.aimMs - 35 * SEC) < 300, `${delay.aimMs}`); + const later = delay.step(now + 100 * SEC); + assert.equal(high - later, DISPLAY_DELAY_FALL * 100 * SEC); +}); + +test('an aim within the deadband leaves the delay where it is', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + let now = feed(delay, { ageMs: 90 * SEC }); + delay.settle(now, { jump: true }); + const was = delay.currentMs; + now = feed(delay, { + ageMs: 90 * SEC + DISPLAY_DELAY_DEADBAND_MS / 2, + polls: 13, + startMs: now, + }); + delay.settle(now); + assert.equal(delay.aimMs, was); + assert.equal(delay.step(now + 60 * SEC), was); +}); + +test('a delivery mid-slew carries on from where the delay is', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + let now = feed(delay, { ageMs: 90 * SEC }); + delay.settle(now); + const mid = delay.step(now + 100 * SEC); + now = feed(delay, { + ageMs: 90 * SEC, + polls: 1, + startMs: now + 100 * SEC - POLL, + }); + assert.equal(delay.settle(now), mid); +}); + +test('reset forgets the feed', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + const now = feed(delay, { ageMs: 90 * SEC }); + delay.settle(now, { jump: true }); + delay.reset(); + assert.equal(delay.currentMs, FLOOR); + assert.equal(delay.lagCount, 0); + assert.equal(delay.settle(now, { jump: true }), FLOOR); +}); + +test('a delivery after a pause in polling gives no lags, and the next one does', () => { + const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL }); + let now = feed(delay, { ageMs: 10 * SEC, contacts: 20, polls: 2 }); + const learned = delay.lagCount; + // A hidden tab: ten minutes with no polls, then a delivery whose reports + // moved on from ones ten minutes old. + now += 10 * 60 * SEC; + for (let c = 0; c < 20; c++) + delay.noteReport(now, now - 10 * SEC, now - 10 * 60 * SEC); + assert.equal(delay.lagCount, learned, 'the pause is not the feed’s lateness'); + assert.ok(delay.settle(now, { jump: true }) < 60 * SEC); + feed(delay, { ageMs: 10 * SEC, contacts: 20, polls: 1, startMs: now }); + assert.equal(delay.lagCount, learned + 20, 'polling again, lags count again'); +}); diff --git a/src/data/earthquakes.test.mjs b/src/data/earthquakes.test.mjs index 5a014b1f53..4f7c897d12 100644 --- a/src/data/earthquakes.test.mjs +++ b/src/data/earthquakes.test.mjs @@ -10,6 +10,8 @@ import { EARTHQUAKE_OVERLAY_COLLISION_CAPACITY, createEarthquakeOverlayEntry, createEarthquakesLayer, + depthAccent, + depthColor, mapAnalystRecord, selectEarthquakeOverlayCohort, } from './earthquakes.js'; @@ -19,6 +21,11 @@ import { installRenderGovernor, _resetRenderGovernorForTest, } from '../renderGovernor.js'; +import { framePortFor } from '../testSupport/fakeFramePort.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; + +/** The layer's disc set, as the fake draw port holds it. */ +const discsOf = (draw) => draw.find('earthquakes:'); const FULL_RAW = { id: 'us7000abcd', @@ -92,25 +99,16 @@ test('earthquake overlay copy keeps source-side magnitude formatting and bounded assert.equal(cohort.at(-1).id, 'quake-020'); }); -test('real earthquake lifecycle publishes host labels while runtime entities carry no label graphic', async () => { +test('real earthquake lifecycle publishes host labels while the drawn discs carry no label graphic', async () => { const originalFetch = globalThis.fetch; const hostCalls = []; - const dataSources = []; const overlayHost = { setEntries: (...args) => hostCalls.push(['entries', ...args]), setVisible: (...args) => hostCalls.push(['visible', ...args]), clearSource: (...args) => hostCalls.push(['clear', ...args]), }; - const viewer = { - dataSources: { - add(dataSource) { dataSources.push(dataSource); return dataSource; }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, - }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer); globalThis.fetch = async () => ({ ok: true, json: async () => ({ @@ -134,9 +132,9 @@ test('real earthquake lifecycle publishes host labels while runtime entities car layer.enable(viewer); await layer.update(viewer); - const entities = dataSources[0].entities.values; - assert.equal(entities.length, 2, 'runtime guard requires populated real source entities'); - assert.ok(entities.every((entity) => entity.label === undefined)); + const discs = [...discsOf(draw).items.values()]; + assert.equal(discs.length, 2, 'runtime guard requires populated real discs'); + assert.ok(discs.every((disc) => disc.geometry.kind === 'ellipse'), 'discs, no label graphic'); const publication = hostCalls.find(([type]) => type === 'entries'); assert.ok(publication, 'real update path must publish the overlay source'); assert.deepEqual(publication[2].map(({ title }) => title), ['M5.2', 'M3.0']); @@ -147,13 +145,13 @@ test('real earthquake lifecycle publishes host labels while runtime entities car }); layer.disable(viewer); - assert.equal(dataSources[0].show, false); + assert.equal(discsOf(draw).show, false); assert.deepEqual(hostCalls.slice(-2), [ ['clear', 'earthquakes'], ['visible', 'earthquakes', false], ]); layer.destroy(viewer); - assert.equal(dataSources.length, 0); + assert.equal(discsOf(draw), undefined, 'the set is disposed'); assert.deepEqual(hostCalls.slice(-2), [ ['clear', 'earthquakes'], ['visible', 'earthquakes', false], @@ -164,20 +162,16 @@ test('real earthquake lifecycle publishes host labels while runtime entities car }); // ── Perf pin: the 2026-08-20 earthquakes frame-rate cliff ──────────────────── -// Every disc is a CLAMP_TO_GROUND ellipse. When its axes were a +// Every disc is a ground-clamped ellipse. When its axes were a Cesium // `CallbackProperty`, Cesium re-tessellated all 58 ground primitives on EVERY // frame: 32.4 ms/frame and 30 fps for 58 contacts, against 1.4 ms/60 fps with -// the layer off. Static axes restored 60 fps. Both halves of the fix are -// pinned — the runtime property shape, and the source-level guards. +// the layer off. Static axes restored 60 fps. The discs are plain draw items +// now, written once per poll; both the item shape and the source-level guards +// are pinned. test('quake disc axes are STATIC — a per-frame callback re-tessellates ground geometry', async () => { const originalFetch = globalThis.fetch; - const dataSources = []; - const viewer = { - dataSources: { - add(dataSource) { dataSources.push(dataSource); return dataSource; }, - remove() { return true; }, - }, - }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer); const layer = createEarthquakesLayer({ overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, }); @@ -196,19 +190,21 @@ test('quake disc axes are STATIC — a per-frame callback re-tessellates ground layer.enable(viewer); await layer.update(viewer); - const [entity] = dataSources[0].entities.values; - assert.ok(entity.ellipse, 'the disc is an ellipse graphic'); - for (const axis of ['semiMajorAxis', 'semiMinorAxis']) { - const property = entity.ellipse[axis]; - assert.equal( - property instanceof Cesium.CallbackProperty, - false, - `${axis} must not be a CallbackProperty — it rebuilds the ground primitive every frame`, - ); - assert.equal(property.isConstant, true, `${axis} must be a constant property`); - // Magnitude 5.5 → 2^5.5 * 1000 m, unchanged by the dropped pulse. - assert.equal(property.getValue(Cesium.JulianDate.now()), Math.pow(2, 5.5) * 1000); - } + const [disc] = discsOf(draw).items.values(); + // Magnitude 5.5 → 2^5.5 * 1000 m: plain numbers, drawn once per poll. + assert.deepEqual(disc, { + id: 'earthquake:us-static-1', + geometry: { + kind: 'ellipse', + center: { lon: -122.4, lat: 37.79 }, + semiMajor: Math.pow(2, 5.5) * 1000, + semiMinor: Math.pow(2, 5.5) * 1000, + }, + // Shallow (8.2 km): red; significant (M5+): 0.4 fill. + fill: [1, 0, 0, 0.4], + height: 'clampGround', + clampTo: 'both', + }); } finally { globalThis.fetch = originalFetch; layer.destroy(viewer); @@ -223,14 +219,10 @@ test('quake disc axes are STATIC — a per-frame callback re-tessellates ground test('a quake poll still reaches the screen with the render loop idle', async () => { const originalFetch = globalThis.fetch; const renderRequests = []; - const dataSources = []; const viewer = { scene: { requestRenderMode: false, requestRender: () => renderRequests.push(Date.now()) }, - dataSources: { - add(dataSource) { dataSources.push(dataSource); return dataSource; }, - remove() { return true; }, - }, }; + const { draw } = bindFakeDraw(viewer); const layer = createEarthquakesLayer({ overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, }); @@ -246,7 +238,7 @@ test('a quake poll still reaches the screen with the render loop idle', async () }); _resetRenderGovernorForTest(); - installRenderGovernor(viewer); + installRenderGovernor(framePortFor(viewer.scene)); // Installing the governor enters idle mode, which itself paints one settling // frame. Drop that from the baseline or the enable assertion below can pass on // the install alone, without the manager ever requesting anything. @@ -264,7 +256,7 @@ test('a quake poll still reaches the screen with the render loop idle', async () // ...and the poll that populated the discs must still have asked for a frame, // because in idle mode nothing repaints on its own. - assert.ok(dataSources[0].entities.values.length > 0, 'the enable poll produced discs'); + assert.ok(discsOf(draw).items.size > 0, 'the enable poll produced discs'); assert.ok(renderRequests.length > 0, 'enabling the layer must request a render in idle mode'); // Named, not merely counted: the frame has to come from the manager's // visibility request, not from some incidental repaint. @@ -298,7 +290,7 @@ test('the earthquakes layer installs no per-frame callback and no continuous-ren readFileSync(new URL(`../layers/earthquakes/${name}.js`, import.meta.url), 'utf8')).join('\n'); assert.doesNotMatch( source, - /new Cesium\.CallbackProperty/, + /CallbackProperty/, 'reverting the discs to a per-frame axis callback must fail this pin', ); assert.doesNotMatch( @@ -310,13 +302,8 @@ test('the earthquakes layer installs no per-frame callback and no continuous-ren test('earthquake refresh reports failure and clears it only after a successful response', async () => { const originalFetch = globalThis.fetch; - const dataSources = []; - const viewer = { - dataSources: { - add(dataSource) { dataSources.push(dataSource); return dataSource; }, - remove() { return true; }, - }, - }; + const viewer = {}; + bindFakeDraw(viewer); const layer = createEarthquakesLayer({ overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, }); @@ -340,13 +327,11 @@ test('earthquake refresh reports failure and clears it only after a successful r } }); -test('malformed earthquake refresh preserves entities, overlays, count and timestamp', async () => { +test('malformed earthquake refresh preserves discs, overlays, count and timestamp', async () => { const originalFetch = globalThis.fetch; - const dataSources = []; const publications = []; - const viewer = { dataSources: { - add(source) { dataSources.push(source); }, remove() { return true; }, - } }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer); const layer = createEarthquakesLayer({ overlayHost: { setEntries(...args) { publications.push(args); }, setVisible() {}, clearSource() {}, } }); @@ -358,15 +343,15 @@ test('malformed earthquake refresh preserves entities, overlays, count and times layer.enable(viewer); respond([good]); assert.equal(await layer.update(viewer), true); - const entity = dataSources[0].entities.values[0]; + const writes = discsOf(draw).writes; const stats = layer.getStats(); for (const properties of ['invalid', 123, [], true]) { const bad = { ...good, id: 'bad-properties', properties }; for (const features of [[bad], [good, bad]]) { respond(features); assert.equal(await layer.update(viewer), false); - assert.equal(dataSources[0].entities.values.length, 1); - assert.equal(dataSources[0].entities.values[0], entity); + assert.equal(discsOf(draw).items.size, 1); + assert.equal(discsOf(draw).writes, writes, 'not redrawn'); assert.equal(layer.getStats().count, stats.count); assert.equal(layer.getStats().lastUpdate, stats.lastUpdate); assert.equal(layer.getStats().error, 'Malformed USGS response'); @@ -382,8 +367,8 @@ test('malformed earthquake refresh preserves entities, overlays, count and times { ...good, properties: { mag: Infinity } }, good]) { respond([good, bad]); assert.equal(await layer.update(viewer), false); - assert.equal(dataSources[0].entities.values.length, 1); - assert.equal(dataSources[0].entities.values[0], entity); + assert.equal(discsOf(draw).items.size, 1); + assert.equal(discsOf(draw).writes, writes, 'not redrawn'); assert.equal(layer.getStats().count, stats.count); assert.equal(layer.getStats().lastUpdate, stats.lastUpdate); assert.equal(layer.getStats().error, 'Malformed USGS response'); @@ -391,14 +376,21 @@ test('malformed earthquake refresh preserves entities, overlays, count and times } respond([{ ...good, properties: { mag: null } }]); assert.equal(await layer.update(viewer), true); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(discsOf(draw).items.size, 0); assert.equal(layer.getStats().error, null); assert.equal(publications.at(-1)[1].length, 0); respond([good]); assert.equal(await layer.update(viewer), true); - assert.equal(dataSources[0].entities.values.length, 1); + assert.equal(discsOf(draw).items.size, 1); } finally { globalThis.fetch = originalFetch; layer.destroy(viewer); } }); + +test('depth bands keep the renderer colours and label accents they had as Cesium colours', () => { + for (const [depthKm, color] of [[10, Cesium.Color.RED], [100, Cesium.Color.ORANGE], [400, Cesium.Color.YELLOW]]) { + assert.deepEqual(depthColor(depthKm), [color.red, color.green, color.blue, color.alpha]); + assert.equal(depthAccent(depthKm), color.toCssColorString()); + } +}); diff --git a/src/data/entityRecords.js b/src/data/entityRecords.js new file mode 100644 index 0000000000..1f2c14a31a --- /dev/null +++ b/src/data/entityRecords.js @@ -0,0 +1,75 @@ +/** + * @module entityRecords + * @description Records for the entities layers draw, so layer state lives in the app + * rather than on the renderer's objects. A layer writes the record for an entity it draws; + * the tracked readout, follow camera, cockpit, share links and awareness read it back + * through the entity the renderer hands them (a pick or the tracked entity). + * + * Fields a record may hold: + * - `trackedId`: the normalized `layer:id` identity, e.g. `flights:a1b2c3`. + * - `displayPosition()`: the layer's cached display position (the follow camera's + * anti-jitter contract: the value the camera settled on, never recomputed late). + * - `visualPosition()`: where a 3D model is actually drawn, for the tracked card. + * - `labelModel`: the tracked card's `{ title, details, accent, … }`. + * - `selectionOrigin`: what started the selection (`'user'`, …). + * - `sprite`: a tracked billboard's pushed `{ width, height, scale, scaleByDistance }`, for + * the close-range camera guard and the screen annotations' tracked footprint. + * - `groundSets()`: the draw set ids a height sample under the contact sees through (its own + * icons and models), for Cockpit's ground probe. + * + * A layer's private per-entity state goes in its own store ({@link createEntityStore}). + */ + +/** + * A store of one record per renderer object, held by the app and dropped with the object. + * @returns {{ write: (entity: Object) => Object, read: (entity: unknown) => Object|null }} + * `write` makes the record empty on first use; `read` gives null when there is none. + */ +export function createEntityStore() { + const records = new WeakMap(); + return { + write(entity) { + let record = records.get(entity); + if (!record) { + record = {}; + records.set(entity, record); + } + return record; + }, + read(entity) { + if (!entity || typeof entity !== 'object') return null; + return records.get(entity) ?? null; + }, + }; +} + +const shared = createEntityStore(); + +/** + * The record for `entity`, made empty on first use. For layers writing their own state. + * @param {Object} entity An entity the layer draws. + * @returns {Object} + */ +export function entityRecord(entity) { + return shared.write(entity); +} + +/** + * The record for `entity`, or null when it has none (or there is no entity). For readers. + * @param {Object|null|undefined} entity + * @returns {Object|null} + */ +export function readEntityRecord(entity) { + return shared.read(entity); +} + +/** + * Write `fields` into `entity`'s record and return the entity. + * @param {Object} entity + * @param {Object} fields Record fields to set. + * @returns {Object} `entity` + */ +export function withEntityRecord(entity, fields) { + Object.assign(entityRecord(entity), fields); + return entity; +} diff --git a/src/data/entityRecords.test.mjs b/src/data/entityRecords.test.mjs new file mode 100644 index 0000000000..e6259a99d9 --- /dev/null +++ b/src/data/entityRecords.test.mjs @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createEntityStore, + entityRecord, + readEntityRecord, + withEntityRecord, +} from './entityRecords.js'; + +test('an entity record is made on first write and read back by the same entity', () => { + const entity = {}; + assert.equal(readEntityRecord(entity), null); + entityRecord(entity).trackedId = 'flights:a1b2c3'; + assert.equal(entityRecord(entity), entityRecord(entity), 'one record per entity'); + assert.equal(readEntityRecord(entity)?.trackedId, 'flights:a1b2c3'); + assert.equal(readEntityRecord({}), null, 'another entity has its own record'); +}); + +test('the record lives in the app, not on the entity', () => { + const entity = {}; + entityRecord(entity).labelModel = { title: 'DAL123', details: [] }; + assert.deepEqual(Object.keys(entity), []); +}); + +test('reading without an entity gives null', () => { + assert.equal(readEntityRecord(null), null); + assert.equal(readEntityRecord(undefined), null); + assert.equal(readEntityRecord('flights:a1b2c3'), null); +}); + +test('withEntityRecord writes fields into the record and returns the entity', () => { + const entity = withEntityRecord({ id: 'alpr:42' }, { trackedId: 'alpr:42' }); + assert.equal(entity.id, 'alpr:42'); + assert.equal(readEntityRecord(entity)?.trackedId, 'alpr:42'); + assert.equal(Object.hasOwn(entity, 'trackedId'), false); +}); + +test('a layer store is separate from the shared records and from other stores', () => { + const entity = {}; + const a = createEntityStore(); + const b = createEntityStore(); + a.write(entity).canvasPosition = 1; + assert.equal(a.read(entity)?.canvasPosition, 1); + assert.equal(b.read(entity), null); + assert.equal(readEntityRecord(entity), null); + assert.equal(a.read(null), null); + assert.deepEqual(Object.keys(entity), []); +}); diff --git a/src/data/firmsCards.test.mjs b/src/data/firmsCards.test.mjs index 9d6157324f..d241baea0c 100644 --- a/src/data/firmsCards.test.mjs +++ b/src/data/firmsCards.test.mjs @@ -16,6 +16,8 @@ import { import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js'; import { getLocale, setLocale } from '../i18n/index.js'; import { reportMeshFloorCell, setMeshFloorPreferred } from './groundFloor.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; const NOW = Date.UTC(2026, 6, 17, 4, 0); const H = 3600000; @@ -232,6 +234,8 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async () primitives: { contains() { return false; } }, }, }; + bindFakeCesiumScene(viewer); + fakeInput(viewer); const layer = createFirmsHeatmapLayer({ id: 'firms', name: 'FIRMS', @@ -240,7 +244,6 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async () setVisible: (...args) => calls.push(['visible', ...args]), clearSource: (...args) => calls.push(['clear', ...args]), }, - screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }), }); try { layer.init(viewer); diff --git a/src/data/firmsHeatmap.js b/src/data/firmsHeatmap.js index 95fed982de..1b63b33947 100644 --- a/src/data/firmsHeatmap.js +++ b/src/data/firmsHeatmap.js @@ -16,7 +16,6 @@ const helpers = createFirmsHelpers({ }); export const mapAnalystRecord = helpers.mapAnalystRecord; export const fireCullPosition = helpers.fireCullPosition; -export const applyHorizonCull = helpers.applyHorizonCull; export const buildSelectedFireCard = helpers.buildSelectedFireCard; export const buildFireCard = helpers.buildFireCard; export const buildCellCard = helpers.buildCellCard; diff --git a/src/data/firmsHorizonCull.test.mjs b/src/data/firmsHorizonCull.test.mjs index 198ffefdc2..0822ba66ae 100644 --- a/src/data/firmsHorizonCull.test.mjs +++ b/src/data/firmsHorizonCull.test.mjs @@ -1,11 +1,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { - applyHorizonCull, - createFirmsHeatmapLayer, - fireCullPosition, -} from './firmsHeatmap.js'; +import { createFirmsHeatmapLayer, fireCullPosition } from './firmsHeatmap.js'; import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js'; import { FIRMS_AMBIENT_COHORT_LIMIT, FIRMS_OVERLAY_SOURCE_ID } from './firmsLabels.js'; import { @@ -13,8 +9,12 @@ import { reportMeshFloorCell, setMeshFloorPreferred, } from './groundFloor.js'; -import { unregisterSpriteCollection } from './spriteOrder.js'; import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldOverlay.js'; +import { createIconSet, ICON_CULL_LIFT } from './iconSet.js'; +import { writeHoldSegment } from './iconSegment.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; +import { createCesiumDraw } from '../render/cesium/draw.js'; const AUSTIN = { lon: -97.7, lat: 30.2 }; /** Antipode of Austin — as far behind the limb as a point on Earth can be. */ @@ -28,24 +28,26 @@ const REPRO_HEIGHT_M = 1_500_000; * at −22 m but visible at +5/+12 m. Measured against Cesium's own occluder. */ const LIMB_DLON = 41.87; +/** Farther east, where 11 m reads hidden and 12 m visible from the same camera. */ +const LIFT_BAND_DLON = 41.9452; /** - * Billboard stub that records every write to `show` so the tests can assert - * the pass does not dirty the collection's vertex buffer needlessly. + * Whether the icon set's GPU pass draws `row` from `occluder`'s camera: the + * shader's horizon test on the row's cull point (its CPU twin). */ -function billboard(position, show = true) { - return { - position, - _show: show, - writes: 0, - get show() { return this._show; }, - set show(value) { this._show = value; this.writes += 1; }, - }; +function gpuShows(set, row, occluder) { + const position = set.position(row, 0, new Cesium.Cartesian3()); + return set.shown(row) && occluder.isPointVisible(set.cullPoint(row, position)); } -/** Cesium BillboardCollection-shaped stub. */ -function collection(items) { - return { length: items.length, get: (i) => items[i] }; +/** A fire-shaped row (shown, CULL_LIFT) held at `position`. */ +function fireRow(set, id, position) { + const row = set.add(id, { layer: 'firms', id }); + set.setFlag(row, ICON_CULL_LIFT, true); + set.setShown(row, true); + writeHoldSegment(set.segments, row, position, 0); + set.segmentWritten(row); + return row; } /** Horizon occluder for a camera directly above Austin at `heightM`. */ @@ -57,92 +59,71 @@ function occluderOverAustin(heightM) { } // --------------------------------------------------------------------------- -// The pure cull predicate +// The GPU horizon cull a fire row gets // --------------------------------------------------------------------------- -test('applyHorizonCull: far-side fires are hidden, near-side fires stay visible', () => { +test('icon cull: far-side fires are hidden, near-side fires stay visible', () => { const occluder = occluderOverAustin(REPRO_HEIGHT_M); - const near = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0)); - const nearby = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon + 6, AUSTIN.lat + 4, 0)); - const far = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 0)); - const otherSide = billboard(Cesium.Cartesian3.fromDegrees(TOKYO.lon, TOKYO.lat, 0)); + const set = createIconSet(); + const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, 0); + const near = fireRow(set, 'near', at(AUSTIN)); + const nearby = fireRow(set, 'nearby', at({ lon: AUSTIN.lon + 6, lat: AUSTIN.lat + 4 })); + const far = fireRow(set, 'far', at(ANTIPODE)); + const otherSide = fireRow(set, 'tokyo', at(TOKYO)); - const visible = applyHorizonCull(collection([near, nearby, far, otherSide]), occluder); - - assert.equal(near.show, true, 'the fire under the camera renders'); - assert.equal(nearby.show, true, 'a fire well inside the horizon renders'); - assert.equal(far.show, false, 'the antipodal fire must not shine through the planet'); - assert.equal(otherSide.show, false, 'Tokyo is beyond the limb from Austin at 1.5 Mm'); - assert.equal(visible, 2, 'returns the surviving count'); + assert.equal(gpuShows(set, near, occluder), true, 'the fire under the camera renders'); + assert.equal(gpuShows(set, nearby, occluder), true, 'a fire well inside the horizon renders'); + assert.equal(gpuShows(set, far, occluder), false, 'the antipodal fire must not shine through the planet'); + assert.equal(gpuShows(set, otherSide, occluder), false, 'Tokyo is beyond the limb from Austin at 1.5 Mm'); }); -test('applyHorizonCull: raising the camera reveals fires the low camera hid', () => { - const paris = () => billboard(Cesium.Cartesian3.fromDegrees(2.35, 48.86, 0)); - - const low = paris(); - applyHorizonCull(collection([low]), occluderOverAustin(REPRO_HEIGHT_M)); - assert.equal(low.show, false, 'Paris is over the horizon from a 1.5 Mm Austin camera'); - - const high = paris(); - applyHorizonCull(collection([high]), occluderOverAustin(35_000_000)); - assert.equal(high.show, true, 'from geostationary height the same fire is in view'); +test('icon cull: raising the camera reveals fires the low camera hid', () => { + const set = createIconSet(); + const paris = fireRow(set, 'paris', Cesium.Cartesian3.fromDegrees(2.35, 48.86, 0)); + assert.equal(gpuShows(set, paris, occluderOverAustin(REPRO_HEIGHT_M)), false); + assert.equal(gpuShows(set, paris, occluderOverAustin(35_000_000)), true, 'in view from geostationary height'); }); -test('applyHorizonCull: a hidden fire is restored when it swings back into view', () => { - const revealed = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0), false); - applyHorizonCull(collection([revealed]), occluderOverAustin(REPRO_HEIGHT_M)); - assert.equal(revealed.show, true, 'the cull un-hides as well as hides'); - assert.equal(revealed.writes, 1); -}); - -test('applyHorizonCull: only flipped billboards are written (vertex-buffer churn)', () => { +test('icon cull: a sub-ellipsoid anchor is judged lifted, a far-side one still culls', () => { const occluder = occluderOverAustin(REPRO_HEIGHT_M); - const stays = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0), true); - const flips = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 0), true); + const set = createIconSet(); + const sunken = fireRow(set, 'sunken', Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, -22)); + assert.equal(gpuShows(set, sunken, occluder), true, 'the lifted cull point keeps the near-limb fire on screen'); + set.setFlag(sunken, ICON_CULL_LIFT, false); + assert.equal(gpuShows(set, sunken, occluder), false, 'baseline: the raw anchor false-hides at the limb'); - applyHorizonCull(collection([stays, flips]), occluder); - applyHorizonCull(collection([stays, flips]), occluder); - - assert.equal(stays.writes, 0, 'an already-visible billboard is never re-assigned'); - assert.equal(flips.writes, 1, 'a hidden billboard is written once, not once per pass'); + const far = fireRow(set, 'far', Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, -22)); + assert.equal(gpuShows(set, far, occluder), false, '12 m of lift must not defeat the actual horizon cull'); }); -test('applyHorizonCull: missing collection/occluder/holes are no-ops, not throws', () => { - assert.equal(applyHorizonCull(null, occluderOverAustin(REPRO_HEIGHT_M)), 0); - assert.equal(applyHorizonCull({ length: 3 }, occluderOverAustin(REPRO_HEIGHT_M)), 0, 'non-collection shape'); - const item = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0)); - assert.equal(applyHorizonCull(collection([item]), null), 0, 'no occluder → leave the layer alone'); - assert.equal(applyHorizonCull(collection([item]), {}), 0, 'occluder without isPointVisible'); - assert.equal(item.writes, 0, 'a skipped pass must not touch show'); - assert.equal( - applyHorizonCull(collection([undefined, item]), occluderOverAustin(REPRO_HEIGHT_M)), - 1, - 'sparse slots are skipped, surviving neighbours still counted', - ); -}); - -// --------------------------------------------------------------------------- -// Sub-ellipsoid anchors: datum-correct render point, lifted CULL point -// --------------------------------------------------------------------------- - -test('applyHorizonCull: an index-aligned cull position overrides the render anchor', () => { +test('fireCullPosition: a card is judged where its sprite is', () => { const occluder = occluderOverAustin(REPRO_HEIGHT_M); - const sunken = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, -22)); - const lifted = Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, 12); - - applyHorizonCull(collection([sunken]), occluder); - assert.equal(sunken.show, false, 'baseline: the raw sub-ellipsoid anchor false-hides at the limb'); - - applyHorizonCull(collection([sunken]), occluder, [lifted]); - assert.equal(sunken.show, true, 'the lifted cull point keeps the near-limb fire on screen'); -}); - -test('applyHorizonCull: a lifted cull point does NOT resurrect a genuinely far-side fire', () => { - const occluder = occluderOverAustin(REPRO_HEIGHT_M); - const far = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, -22)); - const lifted = Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 12); - applyHorizonCull(collection([far]), occluder, [lifted]); - assert.equal(far.show, false, '12 m of lift must not defeat the actual horizon cull'); + const set = createIconSet(); + setMeshFloorPreferred(true); + try { + // Sunk, an 11 m anchor (floor 6 + lift), and well above: each card must + // agree with the GPU test on its own row, at limb points where they can. + for (const [i, floor] of [-27, 6, 900].entries()) { + _clearMeshFloorCellsForTest(); // a reported cell latches its first floor + for (const dLon of [LIMB_DLON, LIFT_BAND_DLON]) { + const lat = AUSTIN.lat; + const lon = AUSTIN.lon + dLon; + reportMeshFloorCell(lat, lon, floor); + const fire = { index: i, lat, lon, frp: 10, position: null }; + const cull = fireCullPosition(fire); + assert.equal(fire.positionHeight, floor + FIRE_ANCHOR_LIFT_M); + const row = fireRow(set, `${floor}:${dLon}`, fire.position); + assert.equal( + occluder.isPointVisible(cull), + gpuShows(set, row, occluder), + `floor ${floor} m at +${dLon}°`, + ); + } + } + } finally { + _clearMeshFloorCellsForTest(); + setMeshFloorPreferred(false); + } }); test('fireCullPosition: negative-geoid anchor renders at the datum but culls lifted', () => { @@ -226,8 +207,9 @@ test('isOverlayPointVisible: horizon test prefers entry.cullPosition when presen test('normalizeOverlayEntry: carries a valid cullPosition, nulls a junk one', () => { const position = { x: 1, y: 2, z: 3 }; - const kept = normalizeOverlayEntry('firms', { id: 'a', position, cullPosition: { x: 4, y: 5, z: 6 } }); - assert.ok(kept.cullPosition instanceof Cesium.Cartesian3, 'stored as a host-owned Cartesian3'); + const cullPosition = { x: 4, y: 5, z: 6 }; + const kept = normalizeOverlayEntry('firms', { id: 'a', position, cullPosition }); + assert.notEqual(kept.cullPosition, cullPosition, 'stored as a host-owned copy'); assert.deepEqual( [kept.cullPosition.x, kept.cullPosition.y, kept.cullPosition.z], [4, 5, 6], @@ -304,17 +286,21 @@ class MockEvent { emit() { for (const listener of [...this.listeners]) listener(); } } -/** Canvas stub good enough for the pre-baked glow sprites. */ +/** + * Canvas stub good enough for the pre-baked glow sprites. Its data URL names + * the gradient's colours, so each colour stop gets its own atlas slot. + */ function canvasStub() { + const stops = []; return { width: 0, height: 0, getContext: () => ({ - createRadialGradient: () => ({ addColorStop() {} }), + createRadialGradient: () => ({ addColorStop: (offset, color) => stops.push(color) }), fillStyle: null, fillRect() {}, }), - toDataURL: () => 'data:image/png;base64,iVBORw0KGgo=', + toDataURL: () => `data:image/png;base64,iVBORw0KGgo=#${stops.join('|')}`, }; } @@ -335,9 +321,8 @@ function rawFire(lat, lon, frp) { } /** - * Boots the REAL layer against a headless viewer stub with a REAL - * Cesium.BillboardCollection, so the production hooks (not just the pure - * predicate) are what the assertions exercise. + * Boots the REAL layer against a headless viewer stub; what the GPU would draw + * is read off the layer's real icon set (`gpuShows`) from the stub camera. */ function createHarness(rawFires) { const originalFetch = globalThis.fetch; @@ -383,13 +368,26 @@ function createHarness(rawFires) { preRender, primitives: { add: (value) => { primitives.push(value); return value; }, - remove: () => {}, + remove: (value) => { + const at = primitives.indexOf(value); + if (at < 0) return false; + primitives.splice(at, 1); + value.destroy(); + return true; + }, contains: () => false, }, frameState: { mode: Cesium.SceneMode.SCENE3D, mapProjection: new Cesium.GeographicProjection() }, mapProjection: new Cesium.GeographicProjection(), + requestRender: () => {}, + isDestroyed: () => false, }, }; + // The Cesium draw port over the stub scene: the glows are a real GPU icon + // set, whose rows say what the GPU would draw. + const draw = createCesiumDraw({ scene: viewer.scene, report: () => {} }); + bindFakeCesiumScene(viewer, { draw: draw.port }); + fakeInput(viewer); const layer = createFirmsHeatmapLayer({ id: 'firms', @@ -399,7 +397,6 @@ function createHarness(rawFires) { setVisible: () => {}, clearSource: () => {}, }, - screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }), }); return { @@ -407,15 +404,19 @@ function createHarness(rawFires) { viewer, preRender, moveEnd, - /** The real BillboardCollection the layer created. */ - billboards: () => primitives[0], + /** The icon set the layer draws its detections from. */ + icons: () => primitives[0].set, + /** Primitives currently in the stub scene. */ + primitives, /** Latest entry list published to the overlay host. */ latestEntries: () => entryCalls[entryCalls.length - 1] || [], - /** `show` flags keyed by billboard pick id. */ + /** Whether the GPU draws each row from the current camera, by pick id. */ showById() { - const bb = primitives[0]; + const set = primitives[0].set; + const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, viewer.camera.positionWC); const out = new Map(); - for (let i = 0; i < bb.length; i += 1) out.set(bb.get(i).id, bb.get(i).show); + for (let row = 0; row < set.count; row += 1) + out.set(set.idAt(row), primitives[0].show !== false && set.show && gpuShows(set, row, occluder)); return out; }, moveCameraTo(lon, lat, height = REPRO_HEIGHT_M) { @@ -424,7 +425,6 @@ function createHarness(rawFires) { }, cleanup() { layer.destroy(viewer); - unregisterSpriteCollection('firms'); Cesium.SceneTransforms.worldToWindowCoordinates = originalProject; globalThis.fetch = originalFetch; if (originalWindow === undefined) delete globalThis.window; else globalThis.window = originalWindow; @@ -433,7 +433,7 @@ function createHarness(rawFires) { }; } -test('layer: a detection rebuild culls its own freshly-added sprites', async () => { +test('layer: far-side detections are culled from the first frame', async () => { const harness = createHarness([ rawFire(AUSTIN.lat, AUSTIN.lon, 120), rawFire(ANTIPODE.lat, ANTIPODE.lon, 900), @@ -453,7 +453,7 @@ test('layer: a detection rebuild culls its own freshly-added sprites', async () } }); -test('layer: camera moveEnd re-culls without a rebuild', async () => { +test('layer: the GPU cull follows the camera with no CPU show pass', async () => { const harness = createHarness([ rawFire(AUSTIN.lat, AUSTIN.lon, 120), rawFire(TOKYO.lat, TOKYO.lon, 800), @@ -466,6 +466,9 @@ test('layer: camera moveEnd re-culls without a rebuild', async () => { harness.moveCameraTo(TOKYO.lon, TOKYO.lat); harness.moveEnd.emit(); + const set = harness.icons(); + for (let row = 0; row < set.count; row += 1) + assert.equal(set.shown(row), true, `${set.idAt(row)} keeps its row shown; the GPU decides`); const show = harness.showById(); assert.equal(show.get('firms-1'), true, 'Tokyo becomes visible once the camera is over it'); assert.equal(show.get('firms-0'), false, 'Austin drops behind the limb'); @@ -474,32 +477,34 @@ test('layer: camera moveEnd re-culls without a rebuild', async () => { } }); -test('layer: the throttled preRender watcher re-culls on a camera move', async () => { - const harness = createHarness([ - rawFire(AUSTIN.lat, AUSTIN.lon, 120), - rawFire(TOKYO.lat, TOKYO.lon, 800), - ]); +test('layer: a refresh keeps rows and restyles one whose index now holds another fire', async () => { + const fires = [rawFire(AUSTIN.lat, AUSTIN.lon, 400), rawFire(TOKYO.lat, TOKYO.lon, 800)]; + const harness = createHarness(fires); try { harness.layer.init(harness.viewer); await harness.layer.enable(harness.viewer); - harness.moveCameraTo(TOKYO.lon, TOKYO.lat); - // The watcher is throttled to LOD_CHECK_MS (650 ms) against - // performance.now(), whose value at this point depends on process - // start-up — so emit, wait out the full throttle window, and emit again. - // Whichever tick passes the gate, one of them must run the pass. - harness.preRender.emit(); - await new Promise((resolve) => { setTimeout(resolve, 700); }); - harness.preRender.emit(); + const set = harness.icons(); + const austin = set.row('firms-0'); + const handle = set.handleAt(austin); + const drawnPx = (row) => set.width(row) * set.scale(row); + const before = drawnPx(austin); + const beforeImage = set.imageFar(austin); - const show = harness.showById(); - assert.equal(show.get('firms-1'), true, 'Tokyo revealed by the preRender pass'); - assert.equal(show.get('firms-0'), false, 'Austin culled by the preRender pass'); + fires[0] = rawFire(AUSTIN.lat + 0.5, AUSTIN.lon, 1); + await harness.layer.update(); + + const row = set.row('firms-0'); + assert.equal(set.handleAt(row), handle, 'the row (and its pick id) survives the rebuild'); + assert.ok(drawnPx(row) < before, `restyled for the weaker fire: ${drawnPx(row)} < ${before}`); + assert.notEqual(set.imageFar(row), beforeImage, 'a red glow becomes a yellow one'); + const carto = Cesium.Cartographic.fromCartesian(set.position(row, 0, new Cesium.Cartesian3())); + assert.ok(Math.abs(Cesium.Math.toDegrees(carto.latitude) - (AUSTIN.lat + 0.5)) < 1e-6, 'moved to the new fire'); } finally { harness.cleanup(); } }); -test('layer: re-enabling after the camera moved does not expose stale far-side sprites', async () => { +test('layer: re-enabling after the camera moved shows the icons, culled from the new camera', async () => { const harness = createHarness([ rawFire(AUSTIN.lat, AUSTIN.lon, 120), rawFire(TOKYO.lat, TOKYO.lon, 800), @@ -516,10 +521,10 @@ test('layer: re-enabling after the camera moved does not expose stale far-side s await harness.layer.enable(harness.viewer); // Assert with NO camera event fired and NO refetch (fires are already - // loaded, so enable() does not reload): the enable path itself must have - // re-culled before the collection went visible. + // loaded, so enable() does not reload): the GPU culls from the current + // camera on the first frame. const show = harness.showById(); - assert.equal(harness.billboards().show, true, 'the collection is visible again'); + assert.notEqual(harness.primitives[0].show, false, 'the icon set is visible again'); assert.equal(show.get('firms-1'), true, 'the Tokyo fire is revealed at enable time'); assert.equal(show.get('firms-0'), false, 'the Austin fire is NOT left shining through the planet'); } finally { @@ -527,6 +532,48 @@ test('layer: re-enabling after the camera moved does not expose stale far-side s } }); +test('layer: a refresh drops rows whose fires left, and an empty one drops them all', async () => { + const fires = [ + rawFire(AUSTIN.lat, AUSTIN.lon, 120), + rawFire(AUSTIN.lat + 1, AUSTIN.lon, 300), + rawFire(AUSTIN.lat + 2, AUSTIN.lon, 200), + ]; + const harness = createHarness(fires); + try { + harness.layer.init(harness.viewer); + await harness.layer.enable(harness.viewer); + const set = harness.icons(); + assert.equal(set.count, 3); + + // Index 0 still holds a fire; 1 and 2 are gone, so their rows swap out. + fires.splice(1, 2); + await harness.layer.update(); + assert.deepEqual( + Array.from({ length: set.count }, (_, row) => set.idAt(row)), + ['firms-0'], + ); + const kept = Cesium.Cartographic.fromCartesian(set.position(set.row('firms-0'), 0, new Cesium.Cartesian3())); + assert.ok(Math.abs(Cesium.Math.toDegrees(kept.latitude) - AUSTIN.lat) < 1e-6, 'the kept row holds its own fire'); + + fires.length = 0; + await harness.layer.update(); + assert.equal(set.count, 0, 'an empty refresh leaves no sprite behind'); + assert.equal(harness.latestEntries().length, 0, 'nor any card'); + } finally { + harness.cleanup(); + } +}); + +test('layer: destroy takes the icons out of the scene', async () => { + const harness = createHarness([rawFire(AUSTIN.lat, AUSTIN.lon, 120)]); + harness.layer.init(harness.viewer); + await harness.layer.enable(harness.viewer); + const primitive = harness.primitives[0]; + harness.cleanup(); + assert.equal(harness.primitives.includes(primitive), false); + assert.equal(primitive.isDestroyed(), true); +}); + test('layer: a near-limb fire on a sub-ellipsoid anchor is not culled by its datum', async () => { const lat = AUSTIN.lat; const lon = AUSTIN.lon + LIMB_DLON; @@ -542,14 +589,14 @@ test('layer: a near-limb fire on a sub-ellipsoid anchor is not culled by its dat harness.layer.init(harness.viewer); await harness.layer.enable(harness.viewer); - const bb = harness.billboards(); - const sunken = bb.get(1); - const carto = Cesium.Cartographic.fromCartesian(sunken.position); + const set = harness.icons(); + const sunken = set.row('firms-1'); + const carto = Cesium.Cartographic.fromCartesian(set.position(sunken, 0, new Cesium.Cartesian3())); assert.ok( Math.abs(carto.height - (-27 + FIRE_ANCHOR_LIFT_M)) < 0.5, `the sprite still RENDERS at the datum-correct anchor, got ${carto.height}`, ); - assert.equal(sunken.show, true, 'the near-limb fire stays on screen (lifted cull anchor)'); + assert.equal(harness.showById().get('firms-1'), true, 'the near-limb fire stays on screen (lifted cull anchor)'); assert.equal(harness.showById().get('firms-0'), true, 'the camera-nadir fire is unaffected'); } finally { harness.cleanup(); diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index 384c72d6d3..ddd5f9b034 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -5,7 +5,11 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { createFirmsHeatmapLayer, applyFirmsOverlayPolicy, buildCellCard } from './firmsHeatmap.js'; +import { + createFirmsHeatmapLayer, + applyFirmsOverlayPolicy, + buildCellCard, +} from './firmsHeatmap.js'; import { fireDetectionKey } from './firmsLabels.js'; import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js'; import { getSelectedEntityContext } from './contextStore.js'; @@ -15,6 +19,11 @@ import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js'; import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; import { HEAT_REBUILD_MS } from '../layers/firms/policy.js'; const LAYER_SOURCE = readLayerSource( @@ -36,6 +45,9 @@ function makeFire(overrides = {}) { }; } +/** A pick of the layer's glow `id`, as the renderer reports one of its icons. */ +const glowPick = (id) => ({ glow: id }); + /** * Stand the layer up far enough to drive one click. `cardHit` is what the * overlay host reports under the click position — the real host only publishes @@ -43,8 +55,13 @@ function makeFire(overrides = {}) { * actionable card presents. */ function harness({ - fires = [makeFire()], picked = null, cardHit = null, cameraPosition = null, - withDataSource = false, feed = null, + fires = [makeFire()], + picked = null, + cardHit = null, + cameraPosition = null, + withDataSource = false, + withGlobe = false, + feed = null, } = {}) { const hadWindow = Object.hasOwn(globalThis, 'window'); const priorWindow = globalThis.window; @@ -60,7 +77,6 @@ function harness({ }; const published = []; - let handler = null; const layer = createFirmsHeatmapLayer({ ...(feed ? { feed } : {}), id: 'firms-test', @@ -71,28 +87,57 @@ function harness({ clearSource() {}, hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null), }, - screenSpaceEventHandlerFactory: () => { - handler = { click: null, setInputAction(cb) { this.click = cb; }, destroy() {} }; - return handler; - }, }); + const draw = fakeDrawPort(); + // A glow pick names the layer's own icon set, as the renderer's pick does. + const pick = () => + picked?.glow + ? { + primitive: {}, + id: { + set: [...draw.sets.values()].find( + (record) => record.kind === 'icons' && !record.disposed, + )?.spec.id, + id: picked.glow, + }, + } + : picked; const viewer = { scene: { - pick: () => picked, + pick, canvas: { clientWidth: 1280, clientHeight: 800 }, camera: cameraPosition ? { positionWC: cameraPosition } : undefined, globe: { ellipsoid: Cesium.Ellipsoid.WGS84 }, }, dataSources: { add() {}, remove() {} }, }; + // The camera the fade and the bands read, when the test places one. + if (cameraPosition) + viewer.camera = { + positionWC: cameraPosition, + positionCartographic: Cesium.Cartographic.fromCartesian(cameraPosition), + }; + // The heatmap drapes through the globe port, for the tests that give one. + const globe = fakeGlobePort(); + { + const { unbind, ...ports } = bindFakeCesiumScene(viewer, { draw }); + unbind(); + bindRenderer(viewer, withGlobe ? { ...ports, globe } : ports); + } + // Without one, the map stack has nowhere to drape imagery. + if (!withGlobe) + layer.attachShellServices({ imageryHost: () => ({ kind: 'none' }) }); + const input = fakeInput(viewer); // The LOD rebuild (and with it the context-registration sweep) is inert // without a data source, so tests that drive a real refresh need one. if (withDataSource) layer.init(viewer); layer._bindInteractionForTest(viewer, fires); const requests = []; - windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (e) => requests.push(e.detail)); + windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (e) => + requests.push(e.detail), + ); return { layer, @@ -101,7 +146,13 @@ function harness({ requests, published, fires, - click: () => handler.click({ position: { x: 400, y: 300 } }), + globe, + /** The live glow icon set. */ + icons: () => + [...draw.sets.values()].find( + (record) => record.kind === 'icons' && !record.disposed, + ), + click: () => input.click({ x: 400, y: 300 }), cleanup() { Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection; if (hadWindow) globalThis.window = priorWindow; @@ -112,10 +163,19 @@ function harness({ test('fire detection key survives a refetch that renumbers the index', () => { const fire = makeFire(); - assert.equal(fireDetectionKey(fire), fireDetectionKey({ ...fire, index: 999 })); + assert.equal( + fireDetectionKey(fire), + fireDetectionKey({ ...fire, index: 999 }), + ); // Different pass over the same pixel is a different detection. - assert.notEqual(fireDetectionKey(fire), fireDetectionKey({ ...fire, acqMs: fire.acqMs + 1 })); - assert.notEqual(fireDetectionKey(fire), fireDetectionKey({ ...fire, lat: 31.0 })); + assert.notEqual( + fireDetectionKey(fire), + fireDetectionKey({ ...fire, acqMs: fire.acqMs + 1 }), + ); + assert.notEqual( + fireDetectionKey(fire), + fireDetectionKey({ ...fire, lat: 31.0 }), + ); assert.match(fireDetectionKey({}), /^firms:x:x:0:x$/); }); @@ -131,11 +191,20 @@ test('two satellites over the same pixel at the same time stay distinct', () => assert.notEqual(fireDetectionKey(base), fireDetectionKey(suomi)); assert.notEqual(fireDetectionKey(twin), fireDetectionKey(suomi)); // Satellite naming variants normalize to one identity, not three. - assert.equal(fireDetectionKey(base), fireDetectionKey(makeFire({ satellite: 'NOAA-20' }))); - assert.equal(fireDetectionKey(suomi), fireDetectionKey(makeFire({ satellite: 'Suomi NPP' }))); + assert.equal( + fireDetectionKey(base), + fireDetectionKey(makeFire({ satellite: 'NOAA-20' })), + ); + assert.equal( + fireDetectionKey(suomi), + fireDetectionKey(makeFire({ satellite: 'Suomi NPP' })), + ); // A record with no satellite falls back to its sensor, not to a shared blank. const sensorOnly = makeFire({ satellite: '', sensor: 'MODIS' }); - assert.notEqual(fireDetectionKey(sensorOnly), fireDetectionKey(makeFire({ satellite: '', sensor: 'VIIRS' }))); + assert.notEqual( + fireDetectionKey(sensorOnly), + fireDetectionKey(makeFire({ satellite: '', sensor: 'VIIRS' })), + ); }); test('duplicate-coordinate detections get their own cards and focus targets', () => { @@ -147,11 +216,21 @@ test('duplicate-coordinate detections get their own cards and focus targets', () cardHit: `fire:${fireDetectionKey(n21)}`, }); try { - const cardIds = h.published.filter((e) => e.id.startsWith('fire:')).map((e) => e.id); - assert.equal(new Set(cardIds).size, 2, 'co-located detections must not collapse to one card'); + const cardIds = h.published + .filter((e) => e.id.startsWith('fire:')) + .map((e) => e.id); + assert.equal( + new Set(cardIds).size, + 2, + 'co-located detections must not collapse to one card', + ); h.click(); assert.equal(h.requests.length, 1); - assert.equal(h.requests[0].id, fireDetectionKey(n21), 'the clicked card wins, not its twin'); + assert.equal( + h.requests[0].id, + fireDetectionKey(n21), + 'the clicked card wins, not its twin', + ); } finally { h.cleanup(); } @@ -162,7 +241,9 @@ test('selection restoration uses the same key the cards and focus use', () => { // detections from different satellites — the selection could come back on // the wrong record. Reachable only through the 30-minute refetch, so this is // a source contract; the key's own behavior is proven above. - const match = LAYER_SOURCE.match(/function findMatchingFire\(previous\) \{([\s\S]*?)\n \}\n/); + const match = LAYER_SOURCE.match( + /function findMatchingFire\(previous\) \{([\s\S]*?)\n \}\n/, + ); assert.ok(match, 'findMatchingFire is missing'); assert.match(match[1], /fireDetectionKey\(previous\)/); assert.match(match[1], /fireDetectionKey\(fire\) === key/); @@ -175,7 +256,11 @@ test('painted detection cards are keyed by the stable detection key', () => { const card = h.published.find((entry) => entry.id.startsWith('fire:')); assert.ok(card, 'a detection card was painted'); assert.equal(card.id, `fire:${fireDetectionKey(h.fires[0])}`); - assert.equal(card.interactive, true, 'a detection card must publish a hit rect'); + assert.equal( + card.interactive, + true, + 'a detection card must publish a hit rect', + ); assert.match(card.accessibilityLabel, /^Focus fire detection /); assert.equal(card.activate(), true); assert.equal(h.requests.length, 1); @@ -187,7 +272,16 @@ test('painted detection cards are keyed by the stable detection key', () => { test('an aggregated cell card is never actionable — it is not one fire', () => { const cell = buildCellCard( - { cell: { count: 14, maxFrp: 210, newestAcqMs: 0, latCell: 30, lonCell: -98 }, position: {} }, + { + cell: { + count: 14, + maxFrp: 210, + newestAcqMs: 0, + latCell: 30, + lonCell: -98, + }, + position: {}, + }, Date.now(), ); assert.equal(applyFirmsOverlayPolicy(cell, 1e6).interactive, false); @@ -196,10 +290,16 @@ test('an aggregated cell card is never actionable — it is not one fire', () => test('far-side detections cannot consume the bounded ambient-card cohort', () => { const front = makeFire({ index: 1, lat: 30.51, lon: -98.21, frp: 100 }); const rear = makeFire({ index: 2, lat: -30.51, lon: 81.79, frp: 1000 }); - const cameraPosition = Cesium.Cartesian3.fromDegrees(front.lon, front.lat, 10_000_000); + const cameraPosition = Cesium.Cartesian3.fromDegrees( + front.lon, + front.lat, + 10_000_000, + ); const h = harness({ fires: [rear, front], cameraPosition }); try { - const cardIds = h.published.filter((entry) => entry.id.startsWith('fire:')).map((entry) => entry.id); + const cardIds = h.published + .filter((entry) => entry.id.startsWith('fire:')) + .map((entry) => entry.id); assert.deepEqual(cardIds, [`fire:${fireDetectionKey(front)}`]); } finally { h.cleanup(); @@ -208,7 +308,7 @@ test('far-side detections cannot consume the bounded ambient-card cohort', () => test('clicking a fire sprite selects it and requests the camera transfer', () => { const fire = makeFire(); - const h = harness({ fires: [fire], picked: { id: 'firms-7' } }); + const h = harness({ fires: [fire], picked: glowPick('firms-7') }); try { h.click(); assert.equal(h.requests.length, 1); @@ -220,6 +320,22 @@ test('clicking a fire sprite selects it and requests the camera transfer', () => } }); +test('an item named like a fire in another draw set is not a fire', () => { + const h = harness({ + fires: [makeFire()], + picked: { + primitive: {}, + id: { set: 'other-layer:1:icons', id: 'firms-7' }, + }, + }); + try { + h.click(); + assert.equal(h.requests.length, 0); + } finally { + h.cleanup(); + } +}); + test('clicking a fire CARD behaves exactly like clicking its sprite', () => { const fire = makeFire(); // The click lands on the card, but the scene pick returns the 3D-Tiles @@ -242,7 +358,7 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => { // The voice model reads these labels as data (track_entity, get_entity_context, // pointer_context); the voice card translates them where it shows them. test('fire labels stay English data in a translated interface', () => { - const h = harness({ fires: [makeFire()], picked: { id: 'firms-7' } }); + const h = harness({ fires: [makeFire()], picked: glowPick('firms-7') }); try { setLocale('ru'); h.click(); @@ -276,7 +392,7 @@ test('a click on neither sprite nor card clears without moving the camera', () = const SIBLING_PICKS = [ ['flights', 'a1b2c3', { id: 'a1b2c3' }], ['flights', 'a1b2c3', { primitive: { id: 'a1b2c3' } }], - ['ais-live-vessels', '353136000', { id: { id: '353136000', mmsi: '353136000', name: 'EVER GIVEN' } }], + ['ais-live-vessels', '353136000', { id: '353136000' }], ['cctv', 'atx-cam-3', { id: { id: 'atx-cam-3', name: 'entity-like' } }], ['satellites', '25544', { id: 25544 }], ]; @@ -292,7 +408,11 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) { }); try { h.click(); - assert.equal(h.requests.length, 0, `the ${layerId} layer is already acting on this click`); + assert.equal( + h.requests.length, + 0, + `the ${layerId} layer is already acting on this click`, + ); } finally { h.cleanup(); unregisterPickOwner(layerId); @@ -319,7 +439,11 @@ test('a refresh that drops the selected fire emits an eviction the readout can a // record first and the clear then fails its ownership guard silently. const kept = makeFire({ index: 0 }); const dropped = makeFire({ - index: 1, lat: 31.77, lon: -99.02, acqMs: 1_753_600_100_000, satellite: 'N20', + index: 1, + lat: 31.77, + lon: -99.02, + acqMs: 1_753_600_100_000, + satellite: 'N20', }); const h = harness({ fires: [dropped, kept], @@ -327,12 +451,18 @@ test('a refresh that drops the selected fire emits an eviction the readout can a withDataSource: true, }); const cleared = []; - h.windowTarget.addEventListener('gev:entity-selection-cleared', (e) => cleared.push(e.detail)); + h.windowTarget.addEventListener('gev:entity-selection-cleared', (e) => + cleared.push(e.detail), + ); const priorFetch = globalThis.fetch; try { h.click(); - assert.equal(h.requests.length, 1, 'the click must select the fire we are about to drop'); + assert.equal( + h.requests.length, + 1, + 'the click must select the fire we are about to drop', + ); assert.equal(h.requests[0].id, fireDetectionKey(dropped)); assert.deepEqual(cleared, [], 'selecting must not clear anything yet'); @@ -343,18 +473,20 @@ test('a refresh that drops the selected fire emits an eviction the readout can a json: async () => ({ fetchedAt: Date.now(), stale: false, - fires: [{ - lat: kept.lat, - lon: kept.lon, - frp: kept.frp, - confidence: 'h', - brightness: 330, - daynight: 'D', - acqDate: '2025-07-27', - acqTime: '0412', - instrument: 'VIIRS', - satellite: kept.satellite, - }], + fires: [ + { + lat: kept.lat, + lon: kept.lon, + frp: kept.frp, + confidence: 'h', + brightness: 330, + daynight: 'D', + acqDate: '2025-07-27', + acqTime: '0412', + instrument: 'VIIRS', + satellite: kept.satellite, + }, + ], }), }); await h.layer.update(); @@ -379,9 +511,17 @@ test('a refresh that drops the selected fire emits an eviction the readout can a test('disable cancels a pending source and a late response cannot repopulate the layer', async () => { let resolve, signal; - const h = harness({ withDataSource: true, feed: { getSnapshot(options) { - signal = options.signal; return new Promise(done => { resolve = done; }); - } } }); + const h = harness({ + withDataSource: true, + feed: { + getSnapshot(options) { + signal = options.signal; + return new Promise((done) => { + resolve = done; + }); + }, + }, + }); try { const before = h.layer.getStats(); const pending = h.layer.update(); @@ -392,7 +532,10 @@ test('disable cancels a pending source and a late response cannot repopulate the assert.equal(h.layer.getStats().count, before.count); assert.equal(h.layer.getStats().lastUpdate, before.lastUpdate); assert.equal(h.layer.getStats().loading, false); - } finally { h.layer.destroy(h.viewer); h.cleanup(); } + } finally { + h.layer.destroy(h.viewer); + h.cleanup(); + } }); test('the heatmap is preloaded under the markers before the first zoom-out', (t) => { @@ -401,7 +544,9 @@ test('the heatmap is preloaded under the markers before the first zoom-out', (t) globalThis.document = { createElement: () => ({ getContext: () => ({ - createImageData: (w, hh) => ({ data: new Uint8ClampedArray(w * hh * 4) }), + createImageData: (w, hh) => ({ + data: new Uint8ClampedArray(w * hh * 4), + }), putImageData() {}, createRadialGradient: () => ({ addColorStop() {} }), fillRect() {}, @@ -411,27 +556,12 @@ test('the heatmap is preloaded under the markers before the first zoom-out', (t) }; const h = harness({ withDataSource: true, + withGlobe: true, cameraPosition: Cesium.Cartesian3.fromDegrees(-98, 30, 1_000_000), }); - h.viewer.camera = { positionCartographic: { height: 1_000_000 } }; - h.viewer.scene.primitives = { add() {}, remove() {}, raiseToTop() {}, contains: () => true }; - h.viewer.scene.frameState = { mode: Cesium.SceneMode.SCENE3D }; - const added = []; + const added = h.globe.added; try { - h.layer.attachShellServices({ - imageryHost: () => ({ - kind: 'globe', - collection: { - addImageryProvider: (provider) => { - const layer = { provider, show: true, alpha: 1 }; - added.push(layer); - return layer; - }, - remove() {}, - raiseToTop() {}, - }, - }), - }); + h.layer.attachShellServices({ imageryHost: () => ({ kind: 'globe' }) }); h.layer._renderLodForTest('close'); assert.equal(added.length, 0, 'the markers paint first; the build trails'); t.mock.timers.tick(HEAT_REBUILD_MS); @@ -469,46 +599,34 @@ test('far zoom drapes one heatmap and the hand-off cross-fades it with the marke const h = harness({ fires: [makeFire(), makeFire({ index: 8, lat: 30.6, lon: -98.3, frp: 12 })], withDataSource: true, + withGlobe: true, cameraPosition: Cesium.Cartesian3.fromDegrees(-98, 30, 12_000_000), }); - const added = []; - const removed = []; - let markers = null; - // The fade reads the camera height; the cull reads scene.camera. + const added = h.globe.added; + // The fade and the bands read the camera height. const setHeight = (height) => { - h.viewer.camera = { positionCartographic: { height } }; + h.viewer.camera.positionCartographic.height = height; }; - setHeight(12_000_000); - h.viewer.scene.primitives = { - add(primitive) { - markers = primitive; - }, - remove() {}, - raiseToTop() {}, - contains: () => true, - }; - h.viewer.scene.frameState = { mode: Cesium.SceneMode.SCENE3D }; + const markers = () => h.icons(); + const glow = (i) => [...markers().items.values()][i]; try { - const collection = { - addImageryProvider: (provider) => { - const layer = { provider, show: true, alpha: 1 }; - added.push(layer); - return layer; - }, - remove: (layer, destroy) => removed.push({ layer, destroy }), - raiseToTop() {}, - }; - h.layer.attachShellServices({ - imageryHost: () => ({ kind: 'globe', collection }), - }); + h.layer.attachShellServices({ imageryHost: () => ({ kind: 'globe' }) }); h.layer._renderLodForTest('global'); assert.equal(added.length, 1, 'one heat imagery layer'); assert.equal(added[0].show, true); assert.equal(added[0].alpha, 1); assert.equal(h.layer._entityCountForTest(), 0, 'no rectangle entities'); assert.ok(h.published.length > 0, 'the far band still paints cards'); - assert.equal(markers.length, 2, 'the markers are built under the heatmap'); - assert.equal(markers.show, false, 'and hidden while the heatmap is whole'); + assert.equal( + markers().items.size, + 2, + 'the markers are built under the heatmap', + ); + assert.equal( + markers().show, + false, + 'and hidden while the heatmap is whole', + ); h.layer._renderLodForTest('regional'); assert.equal(added.length, 1, 'switching far bands reuses the raster'); @@ -518,27 +636,25 @@ test('far zoom drapes one heatmap and the hand-off cross-fades it with the marke assert.equal(added.length, 1, 'the markers band keeps the same heat layer'); assert.equal(added[0].show, true, 'still mapped onto the globe tiles'); assert.equal(added[0].alpha, 0, 'faded out under the markers'); - assert.equal(markers.show, true); - assert.equal(markers.get(0).color.alpha, 1); + assert.equal(markers().show, true); + assert.equal(glow(0).alpha, 1); // Mid hand-off both are drawn, half each, in either band. setHeight(4_500_000); h.layer._applyHandoffFadeForTest(); assert.equal(added[0].alpha, 0.5); - assert.equal(markers.show, true); - assert.equal(markers.get(0).color.alpha, 0.5); + assert.equal(markers().show, true); + assert.equal(glow(0).alpha, 0.5); h.layer._renderLodForTest('regional'); assert.equal(added[0].alpha, 0.5); - assert.equal(markers.get(1).color.alpha, 0.5, 'rebuilt markers get the fade'); + assert.equal(glow(1).alpha, 0.5, 'rebuilt markers get the fade'); h.layer.disable(); assert.equal(added[0].show, false, 'disable hides the heatmap'); h.layer.destroy(h.viewer); - assert.deepEqual( - removed.map((entry) => [entry.layer, entry.destroy]), - [[added[0], true]], - ); + assert.equal(added[0].removed, true); + assert.equal(h.globe.imagery.list().length, 0); } finally { h.cleanup(); restoreDocument(); diff --git a/src/data/fixCurve.js b/src/data/fixCurve.js new file mode 100644 index 0000000000..b8bf50949b --- /dev/null +++ b/src/data/fixCurve.js @@ -0,0 +1,310 @@ +/** + * @module data/fixCurve + * @description The path an aircraft is drawn along between two of its + * reports, and the trail drawn behind it: a smooth curve that passes through + * both reports and leaves each one along its reported track. + * + * The curve is a biarc: two constant-rate turns, each a renderer `arc` + * motion segment (`render/contract/draw.d.ts`), joined where they share a + * course. So the renderer draws exactly this curve, the app reads it back with + * `render/motion/iconMotion`, and the trail samples the same segments: the + * icon always sits on its own trail. Speed is constant between the two + * reports, height changes evenly with time. + * + * The straight line between the reports is drawn instead (no curve) when + * either report has no track, the pair is slower than 40 m/s (taxiing, + * hovering, holding still), or a track points more than 75° off the line + * between them: the reports do not describe one smooth turn. + * + * Each segment runs on for two seconds past its end along the same turn, so + * when the next segment comes a little late the renderer keeps the icon moving + * instead of holding it. + */ +import { eastNorthUp } from '../geo/frames.js'; +import { motionCourse, motionPosition } from '../render/motion/iconMotion.js'; +import { norm180, norm360 } from '../geo/vector.js'; + +/** @constant {number} Pairs slower than this (m/s) are joined straight. */ +export const CURVE_MIN_SPEED_MPS = 40; +/** @constant {number} A track further than this (°) off the chord is joined straight. */ +export const CURVE_MAX_TRACK_OFF_DEG = 75; +/** @constant {number} How long (s) a segment runs on past its end. */ +export const CURVE_RUN_ON_S = 2; +/** @constant {number} Turn (°) between points a trail samples along a curve. */ +export const CURVE_POINT_STEP_DEG = 1; + +const DEG = Math.PI / 180; +/** Turn rates under this (rad/s) fly straight, as `iconMotion` draws them. */ +const STRAIGHT_BELOW_RAD_PER_S = 1e-4; + +function sinc(x) { + return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x; +} + +const dot3 = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z; +const sub3 = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }); + +/** A course (degrees) at `from`'s frame, read in `to`'s frame. */ +function courseIn(courseDeg, fromFrame, toFrame) { + const s = Math.sin(courseDeg * DEG); + const c = Math.cos(courseDeg * DEG); + const t = { + x: s * fromFrame.x.x + c * fromFrame.y.x, + y: s * fromFrame.x.y + c * fromFrame.y.y, + z: s * fromFrame.x.z + c * fromFrame.y.z, + }; + return Math.atan2(dot3(t, toFrame.x), dot3(t, toFrame.y)) / DEG; +} + +/** + * A constant-rate turn from `from` at `t0` setting off on `courseDeg`, that + * reaches `to` at `t1` (epoch ms): an `arc` segment, straight when the turn + * is too slow to draw as one. + * @returns {{segment: object, endCourseDeg: number}} + */ +function arcThrough(from, frame, t0, t1, courseDeg, to) { + const d = sub3(to, from); + const e = dot3(d, frame.x); + const n = dot3(d, frame.y); + const u = dot3(d, frame.z); + const seconds = (t1 - t0) / 1000; + const chord = Math.hypot(e, n); + const bearing = Math.atan2(e, n) / DEG; + let turn = 2 * norm180(bearing - courseDeg); + let track = courseDeg; + if (Math.abs((turn * DEG) / seconds) < STRAIGHT_BELOW_RAD_PER_S) { + turn = 0; + track = bearing; + } + const length = chord / sinc((turn * DEG) / 2); + return { + segment: { + kind: 'arc', + fix: { x: from.x, y: from.y, z: from.z }, + t0, + minDtS: 0, + maxDtS: seconds + CURVE_RUN_ON_S, + speedMps: length / seconds, + trackDeg: norm360(track), + turnRateDps: turn / seconds, + climbMps: u / seconds, + }, + endCourseDeg: track + turn, + }; +} + +/** + * A straight `arc` segment from `from` at `t0` that reaches `to` at `t1` + * (epoch ms) and runs on past it for CURVE_RUN_ON_S. + */ +export function straightSegment(from, t0, t1, to) { + const frame = eastNorthUp(from); + const d = sub3(to, from); + const bearing = Math.atan2(dot3(d, frame.x), dot3(d, frame.y)) / DEG; + return arcThrough(from, frame, t0, t1, bearing, to).segment; +} + +/** + * The curve between two reports, or null to join them straight. + * @param {{x: number, y: number, z: number}} fromPos The earlier report (ECEF). + * @param {number} fromMs Its time, epoch ms. + * @param {number} fromTrackDeg Its reported track. + * @param {{x: number, y: number, z: number}} toPos The later report. + * @param {number} toMs + * @param {number} toTrackDeg + * @returns {{pieces: Array<{segment: object, t0: number, t1: number}>}|null} + * One or two pieces in time order, together running from `fromMs` to + * `toMs`; each `segment` is a contract `arc` motion segment. + */ +export function fixCurve( + fromPos, + fromMs, + fromTrackDeg, + toPos, + toMs, + toTrackDeg, +) { + if (!Number.isFinite(fromTrackDeg) || !Number.isFinite(toTrackDeg)) + return null; + if (!(toMs > fromMs) || !fromPos || !toPos) return null; + const seconds = (toMs - fromMs) / 1000; + const frame = eastNorthUp(fromPos); + const d = sub3(toPos, fromPos); + const e = dot3(d, frame.x); + const n = dot3(d, frame.y); + const u = dot3(d, frame.z); + const chord = Math.hypot(e, n); + if (!(chord / seconds >= CURVE_MIN_SPEED_MPS)) return null; + const toFrame = eastNorthUp(toPos); + const startDeg = fromTrackDeg; + // The later report's track, read in the earlier report's frame. + const endDeg = courseIn(toTrackDeg, toFrame, frame); + const bearing = Math.atan2(e, n) / DEG; + if ( + Math.abs(norm180(startDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG || + Math.abs(norm180(endDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG + ) + return null; + + // The biarc's join with equal tangent lengths: p0 = 0, p1 = (e, n), + // unit tangents t0 and t1. + const t0x = Math.sin(startDeg * DEG); + const t0y = Math.cos(startDeg * DEG); + const t1x = Math.sin(endDeg * DEG); + const t1y = Math.cos(endDeg * DEG); + const vv = e * e + n * n; + const vt = e * (t0x + t1x) + n * (t0y + t1y); + const tt = t0x * t1x + t0y * t1y; + const denom = 2 * (1 - tt); + const reach = + denom < 1e-9 + ? vv / (4 * (e * t1x + n * t1y)) + : (-vt + Math.sqrt(vt * vt + denom * vv)) / denom; + if (!(reach > 0) || !Number.isFinite(reach)) return null; + const jx = (reach * t0x + e - reach * t1x) / 2; + const jy = (reach * t0y + n - reach * t1y) / 2; + + // Each arc's length from its chord and turn, to share the time by. + const arcLength = (cx, cy, courseDeg) => { + const c = Math.hypot(cx, cy); + const turn = 2 * norm180(Math.atan2(cx, cy) / DEG - courseDeg); + return { length: c / sinc((turn * DEG) / 2), turn }; + }; + const first = arcLength(jx, jy, startDeg); + const second = arcLength(e - jx, n - jy, startDeg + first.turn); + const total = first.length + second.length; + if (!(total > 0)) return null; + // One arc where a piece would be under a metre. + if (first.length < 1 || second.length < 1) { + const only = arcThrough(fromPos, frame, fromMs, toMs, startDeg, toPos); + return { pieces: [{ segment: only.segment, t0: fromMs, t1: toMs }] }; + } + const joinMs = fromMs + (toMs - fromMs) * (first.length / total); + const share = first.length / total; + const join = { + x: fromPos.x + frame.x.x * jx + frame.y.x * jy + frame.z.x * u * share, + y: fromPos.y + frame.x.y * jx + frame.y.y * jy + frame.z.y * u * share, + z: fromPos.z + frame.x.z * jx + frame.y.z * jy + frame.z.z * u * share, + }; + const a = arcThrough(fromPos, frame, fromMs, joinMs, startDeg, join); + // The second arc starts exactly where the first is drawn to end. + const joined = motionPosition(a.segment, null, joinMs); + const joinFrame = eastNorthUp(joined); + const b = arcThrough( + joined, + joinFrame, + joinMs, + toMs, + courseIn(a.endCourseDeg, frame, joinFrame), + toPos, + ); + return { + pieces: [ + { segment: a.segment, t0: fromMs, t1: joinMs }, + { segment: b.segment, t0: joinMs, t1: toMs }, + ], + }; +} + +const cache = new WeakMap(); + +/** + * `fixCurve` for two report objects that keep their position object, kept + * per earlier report's position until either report changes. + */ +export function fixCurveCached( + fromPos, + fromMs, + fromTrackDeg, + toPos, + toMs, + toTrackDeg, +) { + if (!fromPos || typeof fromPos !== 'object') return null; + const hit = cache.get(fromPos); + if ( + hit && + hit.toPos === toPos && + hit.fromMs === fromMs && + hit.toMs === toMs && + hit.fromTrackDeg === fromTrackDeg && + hit.toTrackDeg === toTrackDeg && + hit.fx === fromPos.x && + hit.fy === fromPos.y && + hit.fz === fromPos.z && + hit.tx === toPos.x && + hit.ty === toPos.y && + hit.tz === toPos.z + ) + return hit.curve; + const curve = fixCurve( + fromPos, + fromMs, + fromTrackDeg, + toPos, + toMs, + toTrackDeg, + ); + cache.set(fromPos, { + toPos, + fromMs, + toMs, + fromTrackDeg, + toTrackDeg, + fx: fromPos.x, + fy: fromPos.y, + fz: fromPos.z, + tx: toPos?.x, + ty: toPos?.y, + tz: toPos?.z, + curve, + }); + return curve; +} + +/** The piece of `curve` drawn at `tMs` (the last one past its end). */ +export function curvePieceAt(curve, tMs) { + const pieces = curve.pieces; + for (let i = 0; i < pieces.length - 1; i++) + if (tMs < pieces[i].t1) return pieces[i]; + return pieces[pieces.length - 1]; +} + +/** Where the curve puts the aircraft at `tMs`, and its course. */ +export function curvePositionAt(curve, tMs) { + const piece = curvePieceAt(curve, tMs); + const t = Math.min(tMs, piece.t1); + return { + position: motionPosition(piece.segment, null, t), + courseDeg: motionCourse(piece.segment, undefined, t), + }; +} + +/** + * Points along the curve from `fromMs` to `toMs` (exclusive of both ends), + * one at least every CURVE_POINT_STEP_DEG of turn, so the line drawn + * through them stays within a couple of metres of the curve. + * @returns {Array<{x: number, y: number, z: number}>} + */ +export function curvePoints(curve, fromMs, toMs) { + const out = []; + for (const piece of curve.pieces) { + const start = Math.max(fromMs, piece.t0); + const end = Math.min(toMs, piece.t1); + if (!(end > start)) continue; + const seconds = (end - start) / 1000; + const turned = Math.abs(piece.segment.turnRateDps * seconds); + const steps = Math.max(1, Math.ceil(turned / CURVE_POINT_STEP_DEG)); + // The piece's start, unless it is the curve's own start. + if (start > fromMs) out.push(motionPosition(piece.segment, null, start)); + for (let k = 1; k < steps; k++) + out.push( + motionPosition( + piece.segment, + null, + start + ((end - start) * k) / steps, + ), + ); + } + return out; +} diff --git a/src/data/fixCurve.test.mjs b/src/data/fixCurve.test.mjs new file mode 100644 index 0000000000..068af8d9ea --- /dev/null +++ b/src/data/fixCurve.test.mjs @@ -0,0 +1,141 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + CURVE_RUN_ON_S, + curvePieceAt, + curvePoints, + curvePositionAt, + fixCurve, + straightSegment, +} from './fixCurve.js'; +import { motionPosition } from '../render/motion/iconMotion.js'; + +// Between two reports an aircraft is drawn along a curve through both that +// leaves each along its reported track, made of contract `arc` segments. + +const SEC = 1000; +const T0 = Date.UTC(2026, 10, 9, 12); +const enu = Cesium.Transforms.eastNorthUpToFixedFrame( + Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 0), +); +const at = (e, n, u = 3_000) => + Cesium.Matrix4.multiplyByPoint( + enu, + new Cesium.Cartesian3(e, n, u), + new Cesium.Cartesian3(), + ); +const near = (a, b, m, label) => { + const d = Cesium.Cartesian3.distance(a, b); + assert.ok(d < m, `${label}: ${d.toFixed(2)} m`); +}; +const angleDiff = (a, b) => Math.abs(((a - b + 540) % 360) - 180); + +// A 100 m/s left turn on a 2 km circle centred at (0, R), heading east at +// the origin. +const R = 2_000; +const W = 100 / R; +const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t)); +const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360; + +test('the curve passes through both reports and leaves each along its track', () => { + const curve = fixCurve( + circle(0), + T0, + trackAt(0), + circle(15), + T0 + 15 * SEC, + trackAt(15), + ); + assert.ok(curve); + near(curvePositionAt(curve, T0).position, circle(0), 0.01, 'start'); + near(curvePositionAt(curve, T0 + 15 * SEC).position, circle(15), 0.01, 'end'); + assert.ok(angleDiff(curvePositionAt(curve, T0).courseDeg, trackAt(0)) < 0.1); + assert.ok( + angleDiff(curvePositionAt(curve, T0 + 15 * SEC).courseDeg, trackAt(15)) < + 0.1, + ); + // A true turn: the curve is the turn, within a couple of metres. + for (let s = 0; s <= 15; s += 0.5) + near(curvePositionAt(curve, T0 + s * SEC).position, circle(s), 3, `${s} s`); +}); + +test('its pieces are contiguous arc segments in time order', () => { + // Tracks that need an S: the first turn and the second do not agree. + const curve = fixCurve(at(0, 0), T0, 45, at(3_000, 0), T0 + 30 * SEC, 45); + assert.ok(curve); + assert.equal(curve.pieces.length, 2); + assert.equal(curve.pieces[0].t0, T0); + assert.equal(curve.pieces.at(-1).t1, T0 + 30 * SEC); + for (const piece of curve.pieces) assert.equal(piece.segment.kind, 'arc'); + const [a, b] = curve.pieces; + assert.equal(a.t1, b.t0); + near( + motionPosition(a.segment, null, a.t1), + motionPosition(b.segment, null, b.t0), + 0.01, + 'join', + ); + assert.equal(curvePieceAt(curve, a.t1 - 1), a); + assert.equal(curvePieceAt(curve, a.t1), b); + assert.equal(curvePieceAt(curve, T0 + 60 * SEC), b); +}); + +test('each segment runs on past its end rather than holding', () => { + const curve = fixCurve( + circle(0), + T0, + trackAt(0), + circle(15), + T0 + 15 * SEC, + trackAt(15), + ); + const last = curve.pieces.at(-1); + const end = motionPosition(last.segment, null, last.t1); + const later = motionPosition( + last.segment, + null, + last.t1 + CURVE_RUN_ON_S * SEC, + ); + near(later, circle(15 + CURVE_RUN_ON_S), 3, 'run on'); + assert.ok(Cesium.Cartesian3.distance(end, later) > 150); +}); + +test('no curve without tracks, below 40 m/s, or with a track far off the line', () => { + const a = at(0, 0); + const b = at(1_500, 0); + assert.equal(fixCurve(a, T0, undefined, b, T0 + 15 * SEC, 90), null); + assert.equal(fixCurve(a, T0, 90, b, T0 + 60 * SEC, 90), null, 'slow'); + assert.equal(fixCurve(a, T0, 180, b, T0 + 15 * SEC, 90), null, 'off line'); + assert.equal(fixCurve(a, T0, 90, b, T0, 90), null, 'no time between'); +}); + +test('trail points follow the curve, exclusive of both ends, a degree of turn apart', () => { + const curve = fixCurve( + circle(0), + T0, + trackAt(0), + circle(15), + T0 + 15 * SEC, + trackAt(15), + ); + const points = curvePoints(curve, T0, T0 + 15 * SEC); + // 15 s at 2.86°/s: about 43° of turn. + assert.ok(points.length >= 42 && points.length <= 46, `${points.length}`); + for (const p of points) + assert.ok( + Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 3, + 'off the turn', + ); + assert.ok(Cesium.Cartesian3.distance(points[0], circle(0)) > 1); + assert.ok(Cesium.Cartesian3.distance(points.at(-1), circle(15)) > 1); +}); + +test('a straight segment reaches its end at its time and runs on along the same line', () => { + const a = at(0, 0); + const b = at(1_000, 0); + const segment = straightSegment(a, T0, T0 + 10 * SEC, b); + near(motionPosition(segment, null, T0), a, 0.01, 'start'); + near(motionPosition(segment, null, T0 + 5 * SEC), at(500, 0), 1, 'middle'); + near(motionPosition(segment, null, T0 + 10 * SEC), b, 0.01, 'end'); +}); diff --git a/src/data/fleetModelInstances.js b/src/data/fleetModelInstances.js index e3147c8126..5144eee392 100644 --- a/src/data/fleetModelInstances.js +++ b/src/data/fleetModelInstances.js @@ -1,131 +1,84 @@ -import * as Cesium from 'cesium'; -import { horizonOccluder } from './iconOrientation.js'; import { selectModelEligible } from './modelEligibility.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; import { fleetModelSet } from './fleetModels.js'; +import { findCamera, findDraw } from '../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { horizonFrom } from '../geo/horizon.js'; +import { + distanceSquared, + dot, + RADIANS_PER_DEGREE, + sub, +} from '../geo/vector.js'; /** - * Cesium models of the procedural fleet set (`fleetModels.js`), and the - * icon-to-model handoff the Vessels, Transit and Rail layers share. + * Models of the procedural fleet set (`fleetModels.js`) drawn through the + * renderer's draw port, and the icon-to-model handoff the Vessels, Transit + * and Rail layers share. */ -/** Every fleet GLB is nose -X: opposite Cesium's heading 0. */ +/** Every fleet GLB is nose -X: opposite the draw contract's heading 0. */ export const FLEET_HEADING_OFFSET_DEG = 180; +/** How long (ms) a model whose load failed waits before it loads again. */ +const RETRY_MS = 5000; + +/** A white tint: what a model under the NVG/FLIR styles draws with. */ +const WHITE = Object.freeze([1, 1, 1, 1]); + /** - * Create a Cesium Model of `spec` from the up-front loaded bytes, so no model - * is fetched mid-session. Each model keeps its own URL as its base path: the - * glTF cache keys by it, and two models sharing one would share geometry. - * Rejects when the set is not loaded or the model's GLB failed to load. + * A colour as the draw contract takes it: a CSS string or `[r, g, b, a]` + * as given, `{red, green, blue, alpha}` as an array; null for none. + */ +export function fleetColor(color) { + if (color === undefined || color === null) return null; + if (typeof color === 'string' || Array.isArray(color)) return color; + if (typeof color.red === 'number') + return [color.red, color.green, color.blue, color.alpha ?? 1]; + return null; +} + +/** + * The per-axis stretch a fleet spec draws with on top of its length scale, + * along the model's glTF axes (`x` its length, `y` its height, `z` its + * beam), or undefined when it keeps its proportions. * @param {object} spec `fleetModelSpec`. - * @param {object} options Cesium `Model.fromGltfAsync` options. - * @param {{resolveAsset?: (url: string) => string, set?: object|null, - * load?: (options: object) => Promise}} [context] - * @returns {Promise} Cesium Model. + * @returns {[number, number, number]|undefined} */ -export function createFleetModel( - spec, - options, - { - resolveAsset = (url) => url, - set = fleetModelSet(), - // Looked up when called, so a replaced `fromGltfAsync` (tests) is the one used. - load = (o) => Cesium.Model.fromGltfAsync(o), - } = {}, -) { - const bytes = set?.bytes?.get(spec?.model); - if (!bytes) - return Promise.reject(new Error(`fleet model ${spec?.model} not loaded`)); - return load({ - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - ...options, - gltf: bytes, - basePath: resolveAsset(spec.url), - }); -} - -const tintShaders = new Map(); - -/** Models under the NVG/FLIR styles render unlit, as aircraft models do. */ -const IR_UNLIT_SHADER = new Cesium.CustomShader({ - lightingModel: Cesium.LightingModel.UNLIT, -}); - -/** - * The custom shader that paints a route colour where a transit model's - * `_TINT` vertex attribute marks it: drawn colour = vertex colour × - * mix(1, colour, _TINT). One shader per colour, shared by every model drawn in - * it (Cesium compiles the program once; uniforms are per shader). - * @param {Cesium.Color} color - * @returns {Cesium.CustomShader} - */ -export function fleetTintShader(color) { - const key = color.toCssHexString(); - let shader = tintShaders.get(key); - if (!shader) { - shader = new Cesium.CustomShader({ - mode: Cesium.CustomShaderMode.MODIFY_MATERIAL, - uniforms: { - u_routeColor: { - type: Cesium.UniformType.VEC3, - value: new Cesium.Cartesian3(color.red, color.green, color.blue), - }, - }, - fragmentShaderText: ` - void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { - vec3 route = czm_srgbToLinear(u_routeColor); - material.diffuse *= mix(vec3(1.0), route, fsInput.attributes.tint); - } - `, - }); - tintShaders.set(key, shader); - } - return shader; +export function fleetAxisScale(spec) { + const [length, beam, height] = spec?.scaleXYZ ?? []; + if (!(length > 0) || (beam === length && height === length)) return; + return [1, height / length, beam / length]; } /** - * Write the world matrix of a fleet model standing at `position` heading - * `headingDeg` (clockwise from north) into `result`, stretched by the spec's - * beam and height scales relative to its length scale (a Model's own `scale` - * carries the length scale, so its minimum pixel size still applies). - * @param {Cesium.Cartesian3} position - * @param {number} headingDeg - * @param {object} spec `fleetModelSpec`. - * @param {Cesium.Matrix4} result - * @param {Cesium.HeadingPitchRoll} scratchHpr - * @returns {Cesium.Matrix4} + * Whether `point` is inside the eye's view cone (`pose`), a metre's slack. + * @param {object} pose The camera port's pose. + * @param {{x:number,y:number,z:number}} point + * @returns {boolean} */ -export function fleetModelMatrix( - position, - headingDeg, - spec, - result, - scratchHpr, -) { - scratchHpr.heading = Cesium.Math.toRadians( - (headingDeg || 0) + FLEET_HEADING_OFFSET_DEG, +function inView(pose, point) { + const v = sub(point, pose.position); + const depth = dot(v, pose.direction); + if (depth < -1) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * pose.aspectRatio; + return ( + Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 && + Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1 ); - scratchHpr.pitch = 0; - scratchHpr.roll = 0; - Cesium.Transforms.headingPitchRollToFixedFrame( - position, - scratchHpr, - Cesium.Ellipsoid.WGS84, - undefined, - result, - ); - const [sx, sy, sz] = spec.scaleXYZ; - if (sx > 0 && (sy !== sx || sz !== sx)) { - // Cesium's glTF axis correction puts the model's length on local Y, its - // beam on local X and its height on local Z. - scratchScale.x = sy / sx; - scratchScale.y = 1; - scratchScale.z = sz / sx; - Cesium.Matrix4.multiplyByScale(result, scratchScale, result); - } - return result; } -const scratchScale = new Cesium.Cartesian3(); + +/** Two colours as `fleetColor` gives them, alike (arrays element by element). */ +function sameColor(a, b) { + if (a === b) return true; + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + return true; +} + +let instances = 0; /** * 3D models for one layer's vehicles under the DISPLAY rail's 3D toggle (the @@ -135,28 +88,34 @@ const scratchScale = new Cesium.Cartesian3(); * icon stays the visual until its model is loaded and placed; the layer reads * `modelOwnsVisual` back from each item and hides that icon. * + * The models are one `models` set of the viewer's draw port, built from the + * fleet set's bytes loaded up front (`gltf`), so none is fetched + * mid-session. Without a draw port that draws models the layer stays icons. + * * Each frame the layer passes its vehicles as items: * `{position, headingDeg, spec, tint, pickId, show, groundLiftM}`, - * `position` the point the model's origin stands on (the waterline, the road - * or rail top; the spec's `elevationM` is added here), `groundLiftM` any lift - * the layer's icon carries above that point (taken off again), `tint` a - * Cesium.Color for a tinted model's route colour (or null), `show` false to - * keep it hidden. + * `position` the ECEF point the model's origin stands on (the waterline, + * the road or rail top; the spec's `elevationM` is added here), + * `groundLiftM` any lift the layer's icon carries above that point (taken + * off again), `tint` the route colour a tinted model paints where its + * `_TINT` attribute marks it (a CSS colour or `[r, g, b, a]`, or null), + * `pickId` what a pick on the model hands back (the item's `meta`), `show` + * false to keep it hidden. * - * Under the luminance-mapped NVG/FLIR styles (`irBoost`) models render - * unlit flat white, as aircraft models do. With `waterline`, each model is - * clipped at its origin's horizontal plane and only the part above it is - * drawn: a ship's hull below the waterline would otherwise show through a - * plain globe, which Cesium does not depth-test models against. + * Under the luminance-mapped NVG/FLIR styles (`irBoost`) models draw unlit + * flat white, as aircraft models do. With `waterline`, each model is clipped + * at its origin's horizontal plane and only the part above it is drawn: a + * ship's hull below the waterline would otherwise show through a plain + * globe, which models are not depth-tested against. * @param {object} options - * @param {object} options.viewer Cesium viewer. + * @param {object} options.viewer The scene host. * @param {() => object|null} [options.display] `{models3d, models3dMode, * irBoost}`. * @param {object} options.policy `{altitudeCeilingM, minimumPixelSize, * cap, capAll, addM, addAllM, keepM, keepAllM, intervalMs}`. * @param {(url: string) => string} [options.resolveAsset] - * @param {(spec: object, options: object) => Promise} [options.createModel] * @param {boolean} [options.waterline] Clip each model at its waterline. + * @param {object} [options.draw] Stands in for the viewer's draw port (tests). * @returns {object} */ export function createFleetModelLayer({ @@ -165,145 +124,92 @@ export function createFleetModelLayer({ policy, waterline = false, resolveAsset = (url) => url, - createModel = (spec, options) => - createFleetModel(spec, options, { resolveAsset }), + draw, }) { - const collection = new Cesium.PrimitiveCollection(); - viewer.scene.primitives.add(collection); + const port = draw ?? findDraw(viewer); + const set = + typeof port?.models === 'function' + ? port.models({ id: `fleet-models:${++instances}` }) + : null; /** @type {Map} id -> admitted model */ const models = new Map(); - /** @type {Map} id -> generation of an in-flight load */ - const pending = new Map(); - let generation = 0; let destroyed = false; let lastEligibilityAt = -Infinity; let eligible = new Set(); let settling = 0; - /** Whether the models drawn now were built for the NVG/FLIR styles. */ - let irBoost = false; - const scratchHpr = new Cesium.HeadingPitchRoll(); - const scratchSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO, 1); - const scratchCarto = new Cesium.Cartographic(); - const scratchPosition = new Cesium.Cartesian3(); + const offs = set + ? [ + set.on('ready', (id) => { + const record = models.get(id); + if (!record) return; + record.ready = true; + record.failedAt = 0; + }), + set.on('loadFailed', (id) => { + const record = models.get(id); + if (record) record.failedAt = Date.now(); + }), + ] + : []; function release(id) { - pending.delete(id); - const model = models.get(id); - if (!model) return; - models.delete(id); - if (!collection.isDestroyed()) collection.remove(model); + if (!models.delete(id)) return; + set?.remove([id]); } function releaseAll() { - for (const id of models.keys()) release(id); - pending.clear(); - generation += 1; + if (models.size) set?.clear(); + models.clear(); } function preferences() { return display?.() || null; } - function regime(prefs) { - if (!prefs?.models3d || !fleetModelSet()) return false; - const height = viewer.camera?.positionCartographic?.height ?? Infinity; + function pose() { + try { + return findCamera(viewer)?.pose() ?? null; + } catch { + return null; + } + } + + function regime(prefs, eye = pose()) { + if (!set || !prefs?.models3d || !fleetModelSet()) return false; + const height = eye?.height ?? Infinity; return height < policy.altitudeCeilingM; } - function shaderFor(item) { - if (irBoost) return IR_UNLIT_SHADER; - return item.spec.tinted && item.tint - ? fleetTintShader(item.tint) - : undefined; - } - - /** The clipping that keeps a model's part above its waterline. */ - function waterlineClipping() { - return new Cesium.ClippingPlaneCollection({ - // The planes sit in the model matrix's frame: its origin is the - // waterline and its Z axis the local vertical, so the plane z = 0 with - // its normal up keeps the hull above the water. - planes: [new Cesium.ClippingPlane(Cesium.Cartesian3.UNIT_Z, 0)], - edgeWidth: 0, + function admit(id, item, cap) { + const fleet = fleetModelSet(); + const gltf = fleet?.bytes?.get(item.spec.model); + // A model whose GLB did not load draws nothing: the icon stays. + if (!gltf) return; + const current = models.get(id); + if (current && current.specKey === item.spec.key) return; + if (current) release(id); + if (models.size >= cap) return; + models.set(id, { + specKey: item.spec.key, + url: resolveAsset(item.spec.url), + gltf, + ready: false, + failedAt: 0, + sent: null, }); } - async function ensure(id, item, cap) { - const key = item.spec.key; - const current = models.get(id); - if (current && current._gevSpecKey === key) return; - if (current) release(id); - if (pending.has(id) || models.size + pending.size >= cap) return; - const loadGeneration = generation; - pending.set(id, loadGeneration); - let model; - try { - model = await createModel(item.spec, { - asynchronous: false, - minimumPixelSize: policy.minimumPixelSize, - scale: item.spec.scale, - customShader: shaderFor(item), - ...(irBoost - ? { - color: Cesium.Color.WHITE, - colorBlendMode: Cesium.ColorBlendMode.MIX, - colorBlendAmount: 1, - } - : {}), - ...(waterline ? { clippingPlanes: waterlineClipping() } : {}), - id: item.pickId ?? id, - }); - } catch { - if (pending.get(id) === loadGeneration) pending.delete(id); - return; - } - const stale = - destroyed || - pending.get(id) !== loadGeneration || - generation !== loadGeneration || - !eligible.has(id) || - models.has(id); - if (pending.get(id) === loadGeneration) pending.delete(id); - if (stale) { - model.destroy?.(); - return; - } - model.id = item.pickId ?? id; - model._gevSpecKey = key; - model._gevTint = item.spec.tinted && !irBoost ? item.tint : null; - model._gevIrBoost = irBoost; - // Admitted, not yet the visual: placement turns it on. - model.show = false; - collection.add(model); - models.set(id, model); - } - - function refreshEligibility(items, prefs) { + function refreshEligibility(items, prefs, eye) { const all = prefs.models3dMode === 'all'; const cap = all ? policy.capAll : policy.cap; const addM = all ? policy.addAllM : policy.addM; const keepM = all ? policy.keepAllM : policy.keepM; - const camera = viewer.camera; - const cameraPosition = camera.positionWC; - const cull = camera.frustum.computeCullingVolume( - cameraPosition, - camera.directionWC, - camera.upWC, - ); const candidates = []; for (const [id, item] of items) { - if (!item.position || item.show === false || !item.spec) continue; - const distanceSq = Cesium.Cartesian3.distanceSquared( - cameraPosition, - item.position, - ); + if (!item.position || item.show === false || !item.spec?.url) continue; + const distanceSq = distanceSquared(eye.position, item.position); if (distanceSq > keepM * keepM) continue; - Cesium.Cartesian3.clone(item.position, scratchSphere.center); - candidates.push([ - id, - distanceSq, - cull.computeVisibility(scratchSphere) !== Cesium.Intersect.OUTSIDE, - ]); + candidates.push([id, distanceSq, inView(eye, item.position)]); } candidates.sort((a, b) => a[1] - b[1]); eligible = selectModelEligible(candidates, { @@ -311,28 +217,91 @@ export function createFleetModelLayer({ addDistSq: addM * addM, isModeled: (id) => models.has(id), }); - for (const id of models.keys()) if (!eligible.has(id)) release(id); - for (const id of pending.keys()) if (!eligible.has(id)) release(id); - for (const id of eligible) void ensure(id, items.get(id), cap); + for (const id of [...models.keys()]) if (!eligible.has(id)) release(id); + for (const id of eligible) admit(id, items.get(id), cap); } /** Where the model's origin stands: the item's point raised by the spec's elevation. */ function placement(item) { const lift = (item.spec.elevationM || 0) - (item.groundLiftM || 0); if (!lift) return item.position; - const carto = Cesium.Cartographic.fromCartesian( - item.position, - Cesium.Ellipsoid.WGS84, - scratchCarto, - ); - if (!carto) return item.position; - return Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height + lift, - Cesium.Ellipsoid.WGS84, - scratchPosition, - ); + const at = toLonLatH(item.position); + if (!at) return item.position; + return fromDegrees(at.lon, at.lat, at.height + lift); + } + + /** The draw item for an admitted model, as the set draws it, at `at`. */ + function itemOf(id, record, item, show, boost, at = placement(item)) { + const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null; + return { + id, + pos: { x: at.x, y: at.y, z: at.z }, + url: record.url, + gltf: record.gltf, + orientation: { + heading: + ((item.headingDeg || 0) + FLEET_HEADING_OFFSET_DEG) * + RADIANS_PER_DEGREE, + pitch: 0, + roll: 0, + }, + scale: item.spec.scale, + ...(fleetAxisScale(item.spec) + ? { axisScale: fleetAxisScale(item.spec) } + : {}), + minPixelSize: policy.minimumPixelSize, + environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + ...(boost + ? { + shading: 'unlit', + tint: WHITE, + colorBlend: { mode: 'mix', amount: 1 }, + } + : { shading: 'pbr' }), + ...(mask ? { maskColor: mask } : {}), + ...(waterline ? { clip: 'belowOrigin' } : {}), + meta: item.pickId ?? id, + show, + }; + } + + /** + * The item to write for a record, or null when nothing it draws changed: + * what it was last written with is compared value by value, and the item + * is built only when something did (a fleet passes every model each + * frame, and most of what it draws stays). + */ + function changed(id, record, item, show, boost) { + const at = placement(item); + const heading = item.headingDeg || 0; + const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null; + const meta = item.pickId ?? id; + const sent = record.sent; + if ( + sent !== null && + sent.x === at.x && + sent.y === at.y && + sent.z === at.z && + sent.heading === heading && + sent.specKey === item.spec.key && + sameColor(sent.mask, mask) && + sent.boost === boost && + sent.show === show && + sent.meta === meta + ) + return null; + const next = (record.sent ??= {}); + next.x = at.x; + next.y = at.y; + next.z = at.z; + next.heading = heading; + next.specKey = item.spec.key; + // A colour array is kept as a copy: the layer may change its own. + next.mask = Array.isArray(mask) ? [...mask] : mask; + next.boost = boost; + next.show = show; + next.meta = meta; + return itemOf(id, record, item, show, boost, at); } return { @@ -352,68 +321,66 @@ export function createFleetModelLayer({ frame(items, nowMs) { if (destroyed) return false; const prefs = preferences(); - if (!regime(prefs)) { + const eye = pose(); + if (!eye || !regime(prefs, eye)) { settling = 0; - if (models.size || pending.size) releaseAll(); + if (models.size) releaseAll(); eligible = new Set(); for (const item of items.values()) item.modelOwnsVisual = false; return false; } - // A model's look under NVG/FLIR is set when it is built (a custom - // shader on a ready model does not take), so a style change rebuilds. const boost = prefs.irBoost === true; - if (boost !== irBoost) { - releaseAll(); - irBoost = boost; - lastEligibilityAt = -Infinity; - } if (nowMs - lastEligibilityAt >= policy.intervalMs) { lastEligibilityAt = nowMs; - refreshEligibility(items, prefs); + refreshEligibility(items, prefs, eye); } - const occluder = horizonOccluder(viewer.camera); + for (const item of items.values()) item.modelOwnsVisual = false; + const horizon = horizonFrom(eye.position); + const writes = []; let drawn = false; - settling = pending.size; - for (const [id, item] of items) { - const model = models.get(id); - item.modelOwnsVisual = false; - if (!model) continue; - if ( - !item.position || - item.show === false || - !occluder.isPointVisible(item.position) - ) { - model.show = false; + settling = 0; + for (const [id, record] of models) { + const item = items.get(id); + if (!item) { + release(id); continue; } - if (item.spec.key !== model._gevSpecKey) { - // A new type or size: the next eligibility pass loads it. - model.show = false; + if (item.spec?.key !== record.specKey) { + // A new type or size: the next eligibility pass admits it. lastEligibilityAt = -Infinity; + release(id); continue; } - const tint = item.spec.tinted && !irBoost ? item.tint : null; - if (tint && !Cesium.Color.equals(tint, model._gevTint)) { - model.customShader = fleetTintShader(tint); - model._gevTint = tint; + if (record.failedAt && Date.now() - record.failedAt >= RETRY_MS) { + // Removed and added again, the set loads it again. + record.failedAt = 0; + record.sent = null; + record.ready = false; + set.remove([id]); } - fleetModelMatrix( - placement(item), - item.headingDeg, - item.spec, - model.modelMatrix, - scratchHpr, - ); - if (!model.ready) { - model.show = false; - settling += 1; + const visible = + !!item.position && + item.show !== false && + horizon.isPointVisible(item.position); + if (!visible) { + if (record.sent !== null) { + const write = changed(id, record, item, false, boost); + if (write) writes.push(write); + } + continue; + } + // Placed before the readiness test: its first drawn frame is here. + const show = record.ready; + const write = changed(id, record, item, show, boost); + if (write) writes.push(write); + if (!show) { + if (!record.failedAt) settling += 1; continue; } - model.show = true; item.modelOwnsVisual = true; drawn = true; } - for (const id of models.keys()) if (!items.has(id)) release(id); + if (writes.length) set.upsert(writes); return drawn; }, @@ -434,14 +401,14 @@ export function createFleetModelLayer({ return !destroyed && regime(preferences()); }, - /** The model drawing `id`, if one is admitted. */ + /** The record of the model drawing `id`, if one is admitted. */ modelFor(id) { return models.get(id) || null; }, /** Show or hide every model (the layer's own visibility). */ setVisible(show) { - if (!collection.isDestroyed()) collection.show = show; + if (set) set.show = show; }, /** Drop every model (3D off, layer disabled). */ @@ -452,11 +419,17 @@ export function createFleetModelLayer({ return models.size; }, + /** The draw set's id, for picks and height queries to name it. */ + get setId() { + return set?.id ?? null; + }, + destroy() { + if (destroyed) return; destroyed = true; releaseAll(); - if (!viewer.isDestroyed?.() && !collection.isDestroyed()) - viewer.scene.primitives.remove(collection); + for (const off of offs) off(); + set?.dispose(); }, }; } diff --git a/src/data/fleetModelInstances.test.mjs b/src/data/fleetModelInstances.test.mjs index 1892e1751c..0cf79bf492 100644 --- a/src/data/fleetModelInstances.test.mjs +++ b/src/data/fleetModelInstances.test.mjs @@ -1,17 +1,16 @@ // The icon-to-model handoff the Vessels, Transit and Rail layers share // (fleetModelInstances.js): models only under the DISPLAY 3D toggle and the // altitude ceiling, at most `cap` of the nearest, each vehicle's icon the -// visual until its model is loaded, ready and placed, and a tinted model +// visual until its model is loaded, ready and placed, drawn through the +// renderer's model sets from the bytes loaded up front, and a tinted model // painted with its route colour. import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; -import * as Cesium from 'cesium'; import { - createFleetModel, createFleetModelLayer, - fleetModelMatrix, - fleetTintShader, + fleetAxisScale, + fleetColor, FLEET_HEADING_OFFSET_DEG, } from './fleetModelInstances.js'; import { @@ -20,6 +19,10 @@ import { vesselModelSpec, } from './fleetModels.js'; import { fetchPublicFile } from '../testSupport/fleetGlb.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { eastNorthUp } from '../geo/frames.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { add, distance, scale } from '../geo/vector.js'; const realInfo = console.info; console.info = () => {}; @@ -38,115 +41,65 @@ const POLICY = Object.freeze({ intervalMs: 80, }); -const CENTRE = Cesium.Cartesian3.fromDegrees(-122.4, 37.8, 0); +const CENTRE = fromDegrees(-122.4, 37.8, 0); +/** A scene host with a fake draw port and a camera `height` m above CENTRE, looking down. */ function fakeViewer(height = 1_000) { - const primitives = []; - const position = Cesium.Cartesian3.fromDegrees(-122.4, 37.8, height); - const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal( - position, - new Cesium.Cartesian3(), - ); - const camera = { - positionWC: position, - positionCartographic: { height }, - directionWC: Cesium.Cartesian3.negate(up, new Cesium.Cartesian3()), - upWC: Cesium.Cartesian3.UNIT_Z, - frustum: { - computeCullingVolume: () => ({ - computeVisibility: () => Cesium.Intersect.INSIDE, + const viewer = {}; + const position = fromDegrees(-122.4, 37.8, height); + const enu = eastNorthUp(position); + const { draw } = bindFakeDraw(viewer, { + camera: { + pose: () => ({ + lon: -122.4, + lat: 37.8, + height, + position, + direction: scale(enu.z, -1), + up: enu.y, + right: enu.x, + fovy: Math.PI / 3, + aspectRatio: 1.5, }), }, - }; - return { - camera, - scene: { - primitives: { - add(p) { - primitives.push(p); - return p; - }, - remove(p) { - const i = primitives.indexOf(p); - if (i >= 0) primitives.splice(i, 1); - return i >= 0; - }, - }, - }, - primitives, - isDestroyed: () => false, - }; -} - -function fakeModel(options) { - return { - ...options, - ready: false, - show: true, - modelMatrix: new Cesium.Matrix4(), - destroyed: false, - destroy() { - this.destroyed = true; - }, - isDestroyed() { - return this.destroyed; - }, - update() {}, - }; + }); + return { viewer, draw }; } /** A vehicle `metres` east of the camera's foot. */ function itemAt(metres, spec, extra = {}) { - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(CENTRE); - const position = Cesium.Matrix4.multiplyByPoint( - enu, - new Cesium.Cartesian3(metres, 0, 0), - new Cesium.Cartesian3(), - ); + const position = add(CENTRE, scale(eastNorthUp(CENTRE).x, metres)); return { position, headingDeg: 90, spec, tint: null, pickId: null, ...extra }; } -const flush = () => new Promise((resolve) => setImmediate(resolve)); +/** The layer's model set in the fake draw port. */ +const modelSet = (draw) => draw.find('fleet-models:'); -test('models load from the up-front set, never by URL', async () => { +test('models are drawn from the up-front set, never fetched by URL', () => { + const { viewer, draw } = fakeViewer(); + const layer = createFleetModelLayer({ + viewer, + display: () => ({ models3d: true }), + policy: POLICY, + resolveAsset: (url) => `/base${url}`, + }); const spec = vesselModelSpec(set, { type: '70', length: 200, beam: 32 }); - let options = null; - await createFleetModel( - spec, - { scale: spec.scale }, - { - set, - resolveAsset: (url) => `/base${url}`, - load: async (o) => { - options = o; - return {}; - }, - }, - ); - assert.ok(options.gltf instanceof Uint8Array, 'the loaded GLB bytes'); - assert.equal(options.gltf, set.bytes.get(spec.model)); - assert.equal(options.basePath, `/base${spec.url}`); - assert.equal(options.url, undefined, 'no fetch by URL'); - assert.deepEqual({ ...options.environmentMapOptions }, { enabled: false }); - await assert.rejects( - createFleetModel({ model: 'missing' }, {}, { set, load: async () => ({}) }), - /not loaded/, - ); + layer.frame(new Map([['s', itemAt(10, spec, { pickId: 's' })]]), 0); + const item = modelSet(draw).items.get('s'); + assert.ok(item.gltf instanceof Uint8Array, 'the loaded GLB bytes'); + assert.equal(item.gltf, set.bytes.get(spec.model)); + assert.equal(item.url, `/base${spec.url}`, 'the url names it'); + assert.equal(item.environmentMap, false); + layer.destroy(); }); -test('the icon stays the visual until the model is ready; only the nearest are drawn', async () => { - const viewer = fakeViewer(); +test('the icon stays the visual until the model is ready; only the nearest are drawn', () => { + const { viewer, draw } = fakeViewer(); const display = { models3d: true, models3dMode: 'proximity' }; - const created = []; const layer = createFleetModelLayer({ viewer, display: () => display, policy: POLICY, - createModel: async (spec, options) => { - const model = fakeModel({ spec, ...options }); - created.push(model); - return model; - }, }); const spec = transitModelSpec(set, { mode: 'tram' }); const items = new Map([ @@ -155,15 +108,18 @@ test('the icon stays the visual until the model is ready; only the nearest are d ['far', itemAt(4_000, spec, { pickId: 'far' })], ]); layer.frame(items, 0); - await flush(); - assert.equal(created.length, POLICY.cap, 'the cap holds'); + const models = modelSet(draw); + assert.equal(models.items.size, POLICY.cap, 'the cap holds'); assert.deepEqual( - created.map((m) => m.id).sort(), + [...models.items.keys()].sort(), ['mid', 'near'], 'the nearest are modelled', ); - assert.equal(created[0].scale, spec.scale, 'drawn life size'); - assert.equal(created[0].minimumPixelSize, POLICY.minimumPixelSize); + const near = models.items.get('near'); + assert.equal(near.scale, spec.scale, 'drawn life size'); + assert.equal(near.minPixelSize, POLICY.minimumPixelSize); + assert.equal(near.meta, 'near', 'picked as its vehicle'); + assert.equal(near.show, false, 'hidden until ready'); layer.frame(items, 100); for (const item of items.values()) @@ -173,119 +129,89 @@ test('the icon stays the visual until the model is ready; only the nearest are d 'the layer asks for frames while models settle', ); - for (const model of created) model.ready = true; + draw.ready(models.spec.id, 'near'); + draw.ready(models.spec.id, 'mid'); layer.frame(items, 200); assert.equal(items.get('near').modelOwnsVisual, true); assert.equal(items.get('mid').modelOwnsVisual, true); assert.equal(items.get('far').modelOwnsVisual, false); assert.equal(layer.settling, 0); + assert.equal(models.items.get('near').show, true); // A placed model stands on its item's point, nose along its heading. - const near = created.find((m) => m.id === 'near'); - const origin = Cesium.Matrix4.getTranslation( - near.modelMatrix, - new Cesium.Cartesian3(), - ); + const placed = models.items.get('near'); + assert.ok(distance(placed.pos, items.get('near').position) < 1e-6); assert.ok( - Cesium.Cartesian3.distance(origin, items.get('near').position) < 1e-6, + Math.abs( + placed.orientation.heading - + ((90 + FLEET_HEADING_OFFSET_DEG) * Math.PI) / 180, + ) < 1e-12, ); // 3D off: every model goes and every icon comes back. display.models3d = false; layer.frame(items, 300); assert.equal(layer.size, 0); + assert.equal(models.items.size, 0, 'released from the set'); for (const item of items.values()) assert.equal(item.modelOwnsVisual, false); - assert.ok( - created.every((m) => m.destroyed), - 'released models are destroyed', - ); layer.destroy(); - assert.equal(viewer.primitives.length, 0); + assert.equal(models.disposed, true); }); -test('models stay off above the altitude ceiling', async () => { - const viewer = fakeViewer(POLICY.altitudeCeilingM + 1); - let calls = 0; +test('models stay off above the altitude ceiling', () => { + const { viewer, draw } = fakeViewer(POLICY.altitudeCeilingM + 1); const layer = createFleetModelLayer({ viewer, display: () => ({ models3d: true }), policy: POLICY, - createModel: async (spec, options) => { - calls += 1; - return fakeModel(options); - }, }); assert.equal(layer.active(), false); layer.frame(new Map([['a', itemAt(0, transitModelSpec(set, {}))]]), 0); - await flush(); - assert.equal(calls, 0); + assert.equal(modelSet(draw).items.size, 0); layer.destroy(); }); -test('a tinted model is painted with its route colour; an untinted one is not', async () => { - const viewer = fakeViewer(); - const created = []; +test('a tinted model is painted with its route colour; an untinted one is not', () => { + const { viewer, draw } = fakeViewer(); const layer = createFleetModelLayer({ viewer, display: () => ({ models3d: true }), policy: POLICY, - createModel: async (spec, options) => { - const model = fakeModel(options); - created.push(model); - return model; - }, }); - const red = Cesium.Color.RED; const tram = transitModelSpec(set, { mode: 'tram' }); const ship = vesselModelSpec(set, { type: '70', length: 180 }); assert.equal(tram.tinted, true); assert.equal(ship.tinted, false); - layer.frame( - new Map([ - ['tram', itemAt(10, tram, { pickId: 'tram', tint: red })], - ['ship', itemAt(20, ship, { pickId: 'ship', tint: red })], - ]), - 0, - ); - await flush(); - const byId = Object.fromEntries(created.map((m) => [m.id, m])); - assert.equal(byId.tram.customShader, fleetTintShader(red)); - assert.equal(byId.ship.customShader, undefined); - assert.equal( - fleetTintShader(red), - fleetTintShader(Cesium.Color.RED), - 'one shader per colour', - ); + const items = new Map([ + ['tram', itemAt(10, tram, { pickId: 'tram', tint: '#ff0000' })], + ['ship', itemAt(20, ship, { pickId: 'ship', tint: '#ff0000' })], + ]); + layer.frame(items, 0); + const models = modelSet(draw); + assert.equal(models.items.get('tram').maskColor, '#ff0000'); + assert.equal(models.items.get('ship').maskColor, undefined); + // A new route colour is written in place. + items.get('tram').tint = [0, 0, 1, 1]; + layer.frame(items, 10); + assert.deepEqual(models.items.get('tram').maskColor, [0, 0, 1, 1]); + assert.deepEqual(fleetColor({ red: 1, green: 0, blue: 0 }), [1, 0, 0, 1]); layer.destroy(); }); -test('an elevated vehicle is raised by its type elevation', async () => { - const viewer = fakeViewer(); - const created = []; +test('an elevated vehicle is raised by its type elevation', () => { + const { viewer, draw } = fakeViewer(); const layer = createFleetModelLayer({ viewer, display: () => ({ models3d: true }), policy: POLICY, - createModel: async (spec, options) => { - const model = fakeModel({ ...options, ready: true }); - model.ready = true; - created.push(model); - return model; - }, }); const monorail = transitModelSpec(set, { mode: 'monorail' }); assert.equal(monorail.elevationM, set.types.transit.elevation.monorail); const item = itemAt(10, monorail, { pickId: 'm' }); - const items = new Map([['m', item]]); - layer.frame(items, 0); - await flush(); - layer.frame(items, 100); - const origin = Cesium.Matrix4.getTranslation( - created[0].modelMatrix, - new Cesium.Cartesian3(), - ); - const lifted = Cesium.Cartographic.fromCartesian(origin).height; - const ground = Cesium.Cartographic.fromCartesian(item.position).height; + layer.frame(new Map([['m', item]]), 0); + const placed = modelSet(draw).items.get('m'); + const lifted = toLonLatH(placed.pos).height; + const ground = toLonLatH(item.position).height; assert.ok(Math.abs(lifted - ground - monorail.elevationM) < 1e-3); layer.destroy(); }); @@ -293,18 +219,29 @@ test('an elevated vehicle is raised by its type elevation', async () => { test('a vessel stretched to its reported beam keeps its length scale on the model', () => { const spec = vesselModelSpec(set, { type: '70', length: 200, beam: 60 }); assert.ok(spec.scaleXYZ[1] > spec.scaleXYZ[0], 'a wide hull for its length'); - const matrix = fleetModelMatrix( - CENTRE, - 0, - spec, - new Cesium.Matrix4(), - new Cesium.HeadingPitchRoll(), + // Along the model's glTF axes: x its length, y its height, z its beam. + const [x, y, z] = fleetAxisScale(spec); + assert.equal(x, 1); + assert.ok(Math.abs(y - spec.scaleXYZ[2] / spec.scaleXYZ[0]) < 1e-12); + assert.ok(Math.abs(z - spec.scaleXYZ[1] / spec.scaleXYZ[0]) < 1e-12); + assert.equal( + fleetAxisScale(transitModelSpec(set, { mode: 'tram' })), + undefined, + 'a model at its own proportions is not stretched', ); - const scale = Cesium.Matrix4.getScale(matrix, new Cesium.Cartesian3()); - // Cesium's axis correction puts the beam on local X, the length on local Y. - assert.ok(Math.abs(scale.x - spec.scaleXYZ[1] / spec.scaleXYZ[0]) < 1e-9); - assert.ok(Math.abs(scale.y - 1) < 1e-9); assert.equal(FLEET_HEADING_OFFSET_DEG, 180, 'fleet models are built nose -X'); + + const { viewer, draw } = fakeViewer(); + const layer = createFleetModelLayer({ + viewer, + display: () => ({ models3d: true }), + policy: POLICY, + }); + layer.frame(new Map([['s', itemAt(10, spec, { pickId: 's' })]]), 0); + const item = modelSet(draw).items.get('s'); + assert.equal(item.scale, spec.scale, 'its length scale'); + assert.deepEqual(item.axisScale, [x, y, z], 'stretched to its beam'); + layer.destroy(); }); test('Vessels, Transit and Rail draw fleet models under the shared 3D toggle', () => { @@ -359,107 +296,156 @@ test('Vessels, Transit and Rail draw fleet models under the shared 3D toggle', ( ); }); -/** A layer whose models are all ready as soon as they are created. */ +/** A layer whose models are all ready as soon as they are written. */ function readyLayer({ display, waterline = false } = {}) { - const viewer = fakeViewer(); - const created = []; + const { viewer, draw } = fakeViewer(); const layer = createFleetModelLayer({ viewer, display: () => display, policy: POLICY, waterline, - createModel: async (spec, options) => { - const model = fakeModel(options); - model.ready = true; - created.push(model); - return model; - }, }); - return { layer, created }; + const frame = (items, nowMs) => { + layer.frame(items, nowMs); + const models = modelSet(draw); + for (const id of models.items.keys()) draw.ready(models.spec.id, id); + layer.frame(items, nowMs + 1); + return models; + }; + return { layer, draw, frame }; } -test('a model stands on the floor its icon is lifted above', async () => { - const { layer, created } = readyLayer({ display: { models3d: true } }); +test('a model stands on the floor its icon is lifted above', () => { + const { layer, frame } = readyLayer({ display: { models3d: true } }); const tram = transitModelSpec(set, { mode: 'tram' }); const item = itemAt(10, tram, { pickId: 't', groundLiftM: 1.5 }); - const items = new Map([['t', item]]); - layer.frame(items, 0); - await flush(); - layer.frame(items, 100); - const origin = Cesium.Matrix4.getTranslation( - created[0].modelMatrix, - new Cesium.Cartesian3(), - ); + const models = frame(new Map([['t', item]]), 0); const drop = - Cesium.Cartographic.fromCartesian(item.position).height - - Cesium.Cartographic.fromCartesian(origin).height; + toLonLatH(item.position).height - + toLonLatH(models.items.get('t').pos).height; assert.ok(Math.abs(drop - 1.5) < 1e-3, `dropped ${drop} m`); layer.destroy(); }); -test('under NVG/FLIR models are rebuilt unlit white, and rebuilt again on exit', async () => { - const display = { models3d: true, irBoost: false }; - const { layer, created } = readyLayer({ display }); +test('a model that did not change is not written, nor built anew to find that out', () => { + const { layer, frame } = readyLayer({ display: { models3d: true } }); const tram = transitModelSpec(set, { mode: 'tram' }); - const items = new Map([ - ['t', itemAt(10, tram, { pickId: 't', tint: Cesium.Color.RED })], - ]); - layer.frame(items, 0); - await flush(); - assert.equal(created[0].customShader, fleetTintShader(Cesium.Color.RED)); - display.irBoost = true; - layer.frame(items, 100); - assert.ok(created[0].destroyed, 'the lit model is released'); - await flush(); - const boosted = created[1]; - assert.equal(boosted.customShader.lightingModel, Cesium.LightingModel.UNLIT); - assert.ok(Cesium.Color.equals(boosted.color, Cesium.Color.WHITE)); - assert.equal(boosted.colorBlendAmount, 1); - display.irBoost = false; - layer.frame(items, 200); - await flush(); - assert.ok(boosted.destroyed); - assert.equal(created[2].customShader, fleetTintShader(Cesium.Color.RED)); + // Reads of what only the draw item takes (its scales): a model whose item + // is built again reads them. + let shapeReads = 0; + const spec = new Proxy(tram, { + get(target, key) { + if (key === 'scale' || key === 'scaleXYZ') shapeReads += 1; + return target[key]; + }, + }); + const tint = [1, 0, 0, 1]; + const item = itemAt(10, spec, { pickId: 't', tint }); + const items = new Map([['t', item]]); + const models = frame(items, 0); + const writes = models.writes; + shapeReads = 0; + for (let at = 2; at < 6; at++) layer.frame(items, at); + assert.equal(models.writes, writes, 'nothing written'); + assert.equal(shapeReads, 0, 'no draw item built'); + + // A move, a turn and a route colour the layer changes in its own array + // are each written. + item.position = add(item.position, { x: 1, y: 0, z: 0 }); + layer.frame(items, 6); + assert.equal(models.writes, writes + 1, 'a move is written'); + item.headingDeg += 10; + layer.frame(items, 7); + assert.equal(models.writes, writes + 2, 'a turn is written'); + tint[2] = 1; + layer.frame(items, 8); + assert.equal(models.writes, writes + 3, 'a colour changed in place'); + assert.deepEqual(models.items.get('t').maskColor, [1, 0, 1, 1]); + layer.frame(items, 9); + assert.equal(models.writes, writes + 3, 'and then nothing'); layer.destroy(); }); -test('a waterline layer clips each model at its origin, keeping the part above', async () => { - const { layer, created } = readyLayer({ +test('under NVG/FLIR models draw unlit white, and lit again on exit, without loading again', () => { + const display = { models3d: true, irBoost: false }; + const { layer, frame } = readyLayer({ display }); + const tram = transitModelSpec(set, { mode: 'tram' }); + const items = new Map([ + ['t', itemAt(10, tram, { pickId: 't', tint: '#ff0000' })], + ]); + let models = frame(items, 0); + let item = models.items.get('t'); + assert.equal(item.shading, 'pbr'); + assert.equal(item.maskColor, '#ff0000'); + display.irBoost = true; + layer.frame(items, 100); + item = models.items.get('t'); + assert.equal(item.shading, 'unlit'); + assert.deepEqual(item.tint, [1, 1, 1, 1]); + assert.deepEqual(item.colorBlend, { mode: 'mix', amount: 1 }); + assert.equal(item.maskColor, undefined, 'no route colour under NVG/FLIR'); + assert.equal(item.show, true, 'still the visual: restyled in place'); + display.irBoost = false; + layer.frame(items, 200); + item = models.items.get('t'); + assert.equal(item.shading, 'pbr'); + assert.equal(item.maskColor, '#ff0000'); + layer.destroy(); +}); + +test('a waterline layer clips each model at its origin, keeping the part above', () => { + const { layer, frame } = readyLayer({ display: { models3d: true }, waterline: true, }); const ship = vesselModelSpec(set, { type: '70', length: 200, beam: 32 }); - layer.frame(new Map([['s', itemAt(10, ship, { pickId: 's' })]]), 0); - await flush(); - const planes = created[0].clippingPlanes; - assert.ok(planes instanceof Cesium.ClippingPlaneCollection); - assert.equal(planes.length, 1); - const plane = planes.get(0); - assert.equal(plane.distance, 0); - assert.ok(Cesium.Cartesian3.equals(plane.normal, Cesium.Cartesian3.UNIT_Z)); - assert.equal(planes.unionClippingRegions, false); - // Cesium keeps a point where normal · p + distance >= 0: above the waterline. - const above = Cesium.Cartesian3.dot( - plane.normal, - new Cesium.Cartesian3(0, 0, 3), - ); - const below = Cesium.Cartesian3.dot( - plane.normal, - new Cesium.Cartesian3(0, 0, -3), - ); - assert.ok(above + plane.distance > 0 && below + plane.distance < 0); + const models = frame(new Map([['s', itemAt(10, ship, { pickId: 's' })]]), 0); + assert.equal(models.items.get('s').clip, 'belowOrigin'); layer.destroy(); const plain = readyLayer({ display: { models3d: true } }); - plain.layer.frame( + const others = plain.frame( new Map([['t', itemAt(10, transitModelSpec(set, { mode: 'tram' }))]]), 0, ); - await flush(); - assert.equal(plain.created[0].clippingPlanes, undefined, 'others unclipped'); + assert.equal(others.items.get('t').clip, undefined, 'others unclipped'); plain.layer.destroy(); }); +test('a failed model loads again after a while; the icon stays meanwhile', () => { + const { viewer, draw } = fakeViewer(); + const layer = createFleetModelLayer({ + viewer, + display: () => ({ models3d: true }), + policy: POLICY, + }); + const tram = transitModelSpec(set, { mode: 'tram' }); + const items = new Map([['t', itemAt(10, tram, { pickId: 't' })]]); + layer.frame(items, 0); + const models = modelSet(draw); + draw.loadFailed(models.spec.id, 't'); + layer.frame(items, 100); + assert.equal(items.get('t').modelOwnsVisual, false); + assert.equal(layer.settling, 0, 'a failed model is not waited on'); + layer.destroy(); +}); + +test('without a draw port that draws models, vehicles stay icons', () => { + const viewer = {}; + const layer = createFleetModelLayer({ + viewer, + display: () => ({ models3d: true }), + policy: POLICY, + draw: { models: undefined }, + }); + const items = new Map([ + ['t', itemAt(10, transitModelSpec(set, { mode: 'tram' }))], + ]); + assert.equal(layer.active(), false); + assert.equal(layer.frame(items, 0), false); + assert.equal(items.get('t').modelOwnsVisual, false); + layer.destroy(); +}); test('a vehicle drawn as its model keeps its card and its detection entry', () => { const read = (file) => fs.readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8'); @@ -477,7 +463,7 @@ test('a vehicle drawn as its model keeps its card and its detection entry', () = ); assert.match( read('src/layers/vessels/queries.js'), - /!visual\.billboard\.show &&\s*!visual\.modelOwnsVisual/, + /if \(!visual\.visible\) continue;/, ); assert.match( read('src/layers/transit/rendering.js'), diff --git a/src/data/flights.js b/src/data/flights.js index 815ae41ed6..b98f28af6c 100644 --- a/src/data/flights.js +++ b/src/data/flights.js @@ -9,7 +9,6 @@ const flightsLayer = createApplicationFlights({ source: createFlightSource(), militaryRegistry, }); -export { TRACKED_MODEL_MAX_PX } from '../layers/flights/policy.js'; export const _floorGroundedDisplayPositionForTest = flightsLayer.testing._floorGroundedDisplayPositionForTest; export const _clearDisplayFloorStateForTest = @@ -40,6 +39,14 @@ export const _driveFleetModelHandoffForTest = flightsLayer.testing._driveFleetModelHandoffForTest; export const _ensureFleetModelForTest = flightsLayer.testing._ensureFleetModelForTest; +export const _trackedModelForTest = flightsLayer.testing._trackedModelForTest; +export const _trackedIconLookForTest = + flightsLayer.testing._trackedIconLookForTest; +export const _modelSetIdsForTest = flightsLayer.testing._modelSetIdsForTest; +export const _iconForTest = flightsLayer.testing._iconForTest; +export const _setIconForTest = flightsLayer.testing._setIconForTest; +export const _floorGroundedIconsForTest = + flightsLayer.testing._floorGroundedIconsForTest; export const _resetEnrichmentForTest = flightsLayer.testing._resetEnrichmentForTest; export const mapAnalystRecord = flightsLayer.mapAnalystRecord; diff --git a/src/data/flights.test.mjs b/src/data/flights.test.mjs index 5005723d9b..33a6e8aad3 100644 --- a/src/data/flights.test.mjs +++ b/src/data/flights.test.mjs @@ -3,6 +3,8 @@ // Pure function — no viewer/DOM needed; imported directly. import { after, afterEach, before, test } from 'node:test'; import assert from 'node:assert/strict'; +import { followedOf } from './followed.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import * as Cesium from 'cesium'; import flightsLayer, { _addFlightTrackingCandidateForTest, @@ -14,6 +16,8 @@ import flightsLayer, { _setTrackedFlightRefreshStateForTest, _floorGroundedDisplayPositionForTest, _clearDisplayFloorStateForTest, + _iconForTest, + _floorGroundedIconsForTest, _resetEnrichmentForTest, mapAnalystRecord, } from './flights.js'; @@ -35,6 +39,7 @@ import { destroyTrackedReadout, initTrackedReadout, } from './trackedReadout.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; // Unit tests never reach the network. A test that tracks a plane queues its // enrichment (type, route, photo), so every test ends on an empty queue, and a @@ -216,9 +221,12 @@ test('flights first update forwards caller cancellation into the feed request', test('nonempty OpenSky payload with zero usable rows cannot prove share target absence', async () => { _setTrackedFlightRefreshStateForTest({ icao24: 'abc123', - entity: { gevLabelModel: { title: 'WARM', details: [] } }, - billboard: { show: false }, - billboardCollection: { show: true, remove() {} }, + entity: withEntityRecord( + {}, + { labelModel: { title: 'WARM', details: [] } }, + ), + icon: { show: false }, + iconLayer: { show: true, remove() {} }, viewer: { camera: { positionCartographic: null }, scene: {} }, meta: { rawLat: 30.2, rawLon: -97.7, onGround: false }, }); @@ -256,27 +264,18 @@ test('nonempty OpenSky payload with zero usable rows cannot prove share target a test('a newly seen aircraft appears at its delayed position, not ahead of it', async () => { // The fleet renders RENDER_DELAY_SEC behind real time, so a fresh contact's // first displayed position is its fix projected back to that delayed time. - // Creating the billboard at the raw fix drew it ahead until the next fleet + // Creating the icon at the raw fix drew it ahead until the next fleet // tick, which then jumped it back about one delay of travel. - const added = []; - const billboardCollection = { - show: false, - add(options) { - const billboard = { ...options }; - added.push(billboard); - return billboard; - }, - remove() {}, - }; + const iconLayer = { show: false }; const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedFlightRefreshStateForTest({ icao24: 'seed00', entity: null, - billboard: { + icon: { show: false, position: Cesium.Cartesian3.fromDegrees(0, 0, 0), }, - billboardCollection, + iconLayer, viewer, meta: { rawLat: 0, rawLon: 0, onGround: false }, tracked: false, @@ -324,9 +323,9 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a }; try { await flightsLayer.update(viewer); - const billboard = added.find((entry) => entry.id === icao24); - assert.ok(billboard, 'the new contact gets a billboard'); - const shown = Cesium.Cartographic.fromCartesian(billboard.position); + const icon = _iconForTest(icao24); + assert.ok(icon, 'the new contact gets an icon'); + const shown = Cesium.Cartographic.fromCartesian(icon.position); const fix = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_700); const behindM = Cesium.Cartesian3.distance( Cesium.Cartesian3.fromRadians(shown.longitude, shown.latitude, 10_700), @@ -349,19 +348,22 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STALE', async () => { const icao24 = 'a1b2c3'; - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord( + {}, + { labelModel: { title: 'OLD', details: [] } }, + ); const billboard = { position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000), color: Cesium.Color.WHITE, show: false, }; - const billboardCollection = { show: false, remove() {} }; + const iconLayer = { show: false, remove() {} }; const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedFlightRefreshStateForTest({ icao24, entity, - billboard, - billboardCollection, + icon: billboard, + iconLayer, viewer, meta: { callsign: 'OLD1', @@ -420,13 +422,22 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA try { await flightsLayer.update(viewer); - assert.equal(entity.gevLabelModel.title, 'DAL123'); - assert.match(entity.gevLabelModel.details.join(' · '), /FL350/); - assert.match(entity.gevLabelModel.details.join(' · '), /486 kts/); + assert.equal(readEntityRecord(entity)?.labelModel.title, 'DAL123'); + assert.match( + readEntityRecord(entity)?.labelModel.details.join(' · '), + /FL350/, + ); + assert.match( + readEntityRecord(entity)?.labelModel.details.join(' · '), + /486 kts/, + ); await flightsLayer.update(viewer); assert.match( - [entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '), + [ + readEntityRecord(entity)?.labelModel.title, + ...readEntityRecord(entity)?.labelModel.details, + ].join(' · '), /STALE/, ); } finally { @@ -703,6 +714,7 @@ test('real civil track path creates no native label and publishes every cached h }, }); viewer.scene.camera = viewer.camera; + bindFakeCesiumCamera(viewer); const billboard = { position, rotation: 0.3, @@ -737,8 +749,8 @@ test('real civil track path creates no native label and publishes every cached h _setTrackedFlightRefreshStateForTest({ icao24, entity: null, - billboard, - billboardCollection: { show: true, remove() {} }, + icon: billboard, + iconLayer: { show: true, remove() {} }, viewer, tracked: false, history: [ @@ -776,16 +788,27 @@ test('real civil track path creates no native label and publishes every cached h flightsLayer.trackById(icao24, { origin: 'programmatic' }), true, ); - const entity = viewer.trackedEntity; + const entity = followedOf(viewer)?.entity; assert.ok( - entity instanceof Cesium.Entity, - 'trackById must create the real Cesium entity', + readEntityRecord(entity)?.trackedId, + 'trackById must record the tracked contact', ); + assert.ok( + !(entity instanceof Cesium.Entity), + 'tracking draws through the draw port, not a viewer entity', + ); + assert.ok(entity.position, 'Cockpit sees a contact it can fly'); + assert.equal(readEntityRecord(entity).drawn(), true); + assert.ok( + Array.isArray(readEntityRecord(entity).groundSets()), + 'Cockpit asks which draw sets its ground probe sees through', + ); + assert.equal(entity.show, true); assert.equal(entity.label, undefined); assert.ok( entities.values.every((candidate) => candidate.label === undefined), ); - assert.deepEqual(entity.gevLabelModel, { + assert.deepEqual(readEntityRecord(entity)?.labelModel, { title: 'N12345 · FL350 · 486 kts', details: ['TEST AIR · A320', 'AUS → LAX'], accent: '#39d0ff', @@ -804,7 +827,7 @@ test('real civil track path creates no native label and publishes every cached h 'user', 'same-target selection upgrades durable authority', ); - assert.equal(entity.gevSelectionOrigin, 'user'); + assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user'); assert.equal(flightsLayer.refocusTrackedById('different-flight'), false); assert.equal( flightsLayer.refocusTrackedById(icao24, { origin: 'voice' }), @@ -818,7 +841,7 @@ test('real civil track path creates no native label and publishes every cached h assert.equal(flightsLayer.refocusTrackedById(icao24), true); viewer.scene.preUpdate.raiseEvent(); assert.equal( - viewer.trackedEntity, + followedOf(viewer)?.entity, entity, 'refocus must retain the exact tracked entity', ); @@ -837,11 +860,14 @@ test('real civil track path creates no native label and publishes every cached h const entry = publication.entries[0]; assert.equal(entry.protected, true); assert.equal(entry.paintLane, 'tracked'); - assert.equal(entry.title, entity.gevLabelModel.title); - assert.deepEqual(entry.details, entity.gevLabelModel.details); + assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title); + assert.deepEqual( + entry.details, + readEntityRecord(entity)?.labelModel.details, + ); - const display = entity.position.getValue(now); - assert.ok(display, 'tracked position callback must seed its frame cache'); + const display = followedOf(viewer)?.position(Date.now()); + assert.ok(display, 'the follow target must seed the frame cache'); assert.equal( entry.position(), display, @@ -861,7 +887,7 @@ test('real civil track path creates no native label and publishes every cached h ); _addFlightTrackingCandidateForTest({ icao24: 'late001', - billboard: { + icon: { ...billboard, position: Cesium.Cartesian3.fromDegrees(-97.5, 30.4, 9_000), }, @@ -885,7 +911,7 @@ test('real civil track path creates no native label and publishes every cached h ); _addFlightTrackingCandidateForTest({ icao24: 'late002', - billboard: { + icon: { ...billboard, position: Cesium.Cartesian3.fromDegrees(-97.4, 30.5, 8_000), }, @@ -908,7 +934,7 @@ test('real civil track path creates no native label and publishes every cached h ); _addFlightTrackingCandidateForTest({ icao24: 'late003', - billboard: { + icon: { ...billboard, position: Cesium.Cartesian3.fromDegrees(-97.3, 30.6, 7_000), }, @@ -925,7 +951,7 @@ test('real civil track path creates no native label and publishes every cached h assert.equal(_pendingFlightTrackingRestoreForTest(), 'late004'); _addFlightTrackingCandidateForTest({ icao24: 'late004', - billboard: { + icon: { ...billboard, position: Cesium.Cartesian3.fromDegrees(-97.2, 30.7, 6_000), }, @@ -950,7 +976,7 @@ test('real civil track path creates no native label and publishes every cached h ); _addFlightTrackingCandidateForTest({ icao24: 'late005', - billboard: { + icon: { ...billboard, position: Cesium.Cartesian3.fromDegrees(-97.1, 30.8, 5_000), }, @@ -996,12 +1022,12 @@ function seedLabelContact({ _setTrackedFlightRefreshStateForTest({ icao24: LABEL_ICAO, entity: null, - billboard: { + icon: { position: LABEL_POSITION, color: Cesium.Color.WHITE, show: true, }, - billboardCollection: { show: true, remove() {} }, + iconLayer: { show: true, remove() {} }, viewer: { camera: { positionCartographic: null }, scene: {} }, tracked, meta: { @@ -1199,17 +1225,20 @@ test('civil label chain: the awareness selection EVENT uses the canonical chain' }); test('civil tracked readout: a callsign-less enriched contact reads as its registration', async () => { - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord( + {}, + { labelModel: { title: 'OLD', details: [] } }, + ); seedLabelContact({ callsign: ' ', registration: ' N123AB ', tracked: true }); _setTrackedFlightRefreshStateForTest({ icao24: LABEL_ICAO, entity, - billboard: { + icon: { position: LABEL_POSITION, color: Cesium.Color.WHITE, show: false, }, - billboardCollection: { show: false, remove() {} }, + iconLayer: { show: false, remove() {} }, viewer: { camera: { positionCartographic: null }, scene: {} }, meta: { callsign: ' ', @@ -1239,9 +1268,12 @@ test('civil tracked readout: a callsign-less enriched contact reads as its regis camera: { positionCartographic: null }, scene: {}, }); - assert.match(entity.gevLabelModel.title, /^N123AB\b/); + assert.match(readEntityRecord(entity)?.labelModel.title, /^N123AB\b/); assert.doesNotMatch( - [entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '), + [ + readEntityRecord(entity)?.labelModel.title, + ...readEntityRecord(entity)?.labelModel.details, + ].join(' · '), /ae1fa4/, ); } finally { @@ -1323,30 +1355,21 @@ const _floorCarto = (pos) => test('a newly seen taxiing aircraft starts on the floor under its delayed position', async () => { // A grounded contact is drawn at its delayed position lifted onto the floor - // under it. Creating the billboard without that lift started it on the + // under it. Creating the icon without that lift started it on the // floor of its reported fix, then the next fleet tick raised it. _clearDisplayFloorStateForTest(); _clearMeshFloorCellsForTest(); setMeshFloorPreferred(true); - const added = []; - const billboardCollection = { - show: false, - add(options) { - const billboard = { ...options }; - added.push(billboard); - return billboard; - }, - remove() {}, - }; + const iconLayer = { show: false }; const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedFlightRefreshStateForTest({ icao24: 'seed00', entity: null, - billboard: { + icon: { show: false, position: Cesium.Cartesian3.fromDegrees(0, 0, 0), }, - billboardCollection, + iconLayer, viewer, meta: { rawLat: 0, rawLon: 0, onGround: false }, tracked: false, @@ -1399,9 +1422,9 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi }; try { await flightsLayer.update(viewer); - const billboard = added.find((entry) => entry.id === icao24); - assert.ok(billboard, 'the new contact gets a billboard'); - const shown = _floorCarto(billboard.position); + const icon = _iconForTest(icao24); + assert.ok(icon, 'the new contact gets an icon'); + const shown = _floorCarto(icon.position); assert.ok( Cesium.Math.toDegrees(shown.longitude) < fixLon, 'drawn behind the fix', @@ -1417,6 +1440,99 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi } }); +test('far grounded contacts take turns on the floor; near ones refloor every tick', async () => { + // The floor pass is the fleet tick's only per-contact CPU work. Past + // FLOOR_NEAR_M a contact is refloored once per FLOOR_FAR_EVERY_TICKS. + _clearDisplayFloorStateForTest(); + _clearMeshFloorCellsForTest(); + setMeshFloorPreferred(true); + const viewer = { camera: { positionCartographic: null }, scene: {} }; + _setTrackedFlightRefreshStateForTest({ + icao24: 'seed00', + entity: null, + icon: { + show: false, + position: Cesium.Cartesian3.fromDegrees(0, 0, 0), + }, + iconLayer: { show: false }, + viewer, + meta: { rawLat: 0, rawLon: 0, onGround: false }, + tracked: false, + }); + const icao24 = 'taxi02'; + const fixLon = -97.66; + const fixLat = 30.2; + for (let k = -40; k <= 40; k += 1) { + reportMeshFloorCell(fixLat, fixLon + k * 0.0001, 131.5); + } + const nowSec = Math.floor(Date.now() / 1000); + const realFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + if (!String(url).startsWith('/api/flights')) { + return { ok: true, status: 200, json: async () => ({ ac: [] }) }; + } + return { + ok: true, + status: 200, + headers: { get: () => null }, + json: async () => ({ + time: nowSec, + states: [ + [ + icao24, + 'TAXI02 ', + 'United States', + nowSec - 2, + nowSec - 2, + fixLon, + fixLat, + null, + true, + 10, + 90, + 0, + null, + null, + null, + null, + null, + 5, + ], + ], + }), + }; + }; + try { + await flightsLayer.update(viewer); + // A grounded report holds once its time is past, so the ticks run in + // the 40 s before it, while the contact still taxis toward its fix. + const start = Cesium.JulianDate.fromDate( + new Date((nowSec - 2 - 40) * 1000), + ); + const at = (s) => + Cesium.JulianDate.addSeconds(start, s, new Cesium.JulianDate()); + const far = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 3_000_000); + const near = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_000); + let last = _iconForTest(icao24).position; + const moves = (camera, from, to) => { + let count = 0; + for (let tick = from; tick <= to; tick += 1) { + _floorGroundedIconsForTest(at(tick), camera); + const now = _iconForTest(icao24).position; + if (Cesium.Cartesian3.distance(now, last) > 1) count += 1; + last = now; + } + return count; + }; + assert.equal(moves(far, 1, 24), 2, 'far: once per 12 ticks'); + assert.equal(moves(near, 25, 30), 6, 'near: every tick'); + } finally { + globalThis.fetch = realFetch; + _clearMeshFloorCellsForTest(); + _clearDisplayFloorStateForTest(); + } +}); + test('display floor: a grounded contact that drifted onto a higher cell is lifted', () => { _clearDisplayFloorStateForTest(); _clearMeshFloorCellsForTest(); diff --git a/src/data/focusAllocations.test.mjs b/src/data/focusAllocations.test.mjs index f58e5f1217..2ed92a1e3c 100644 --- a/src/data/focusAllocations.test.mjs +++ b/src/data/focusAllocations.test.mjs @@ -23,6 +23,6 @@ test('converged focus treatment stays within the GC-bracketed allocation budget' assert.equal(result.status, 0, result.stderr || result.stdout); const report = JSON.parse(result.stdout.trim()); assert.ok(report.advanceSpriteFocus.roundedMedian <= 16, result.stdout); - assert.ok(report.applyAircraftBillboardTreatment.roundedMedian <= 16, result.stdout); + assert.ok(report.aircraftTreatmentAlpha.roundedMedian <= 16, result.stdout); assert.ok(report.productionSpriteTick.roundedMedian <= 212, result.stdout); }); diff --git a/src/data/focusDeemphasis.js b/src/data/focusDeemphasis.js index f3e8792a1c..59ebfd87f3 100644 --- a/src/data/focusDeemphasis.js +++ b/src/data/focusDeemphasis.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { findCamera, findQuery } from '../render/rendererOf.js'; /** * Focus-aware sprite treatment shared by the live contact layers. @@ -30,7 +30,6 @@ export const DEFAULT_FOCUS_DEEMPHASIS_PARAMS = Object.freeze({ let _params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS }; let _focusTarget = null; const _spriteStates = new WeakMap(); -const _scratchScreen = new Cesium.Cartesian2(); const _advanceResult = { factor: 1, changed: false, @@ -172,47 +171,76 @@ export function resetFocusDeemphasisParams() { /** * Publish a focus target from the exact world position already cached by its - * tracking/render path. Callers must never re-derive a position here: a second + * tracking/render path, through the renderer bound to `viewer`: its query + * port projects the position and its camera's pose gives the distance. + * Callers must never re-derive a position here: a second * propagation/dead-reckoning sample at a different frame phase recreates the * tracked-target jitter class this service is designed to avoid. * * @param {object} input * @param {string} input.ownerLayer * @param {string|number} input.id - * @param {Cesium.Scene} input.scene - * @param {Cesium.Camera} input.camera - * @param {Cesium.Cartesian3} input.displayPosition Cached display position. - * @param {number} [input.widthPx=24] Projected visual width before padding. - * @param {number} [input.heightPx=24] Projected visual height before padding. + * @param {object} input.viewer The host the renderer is bound to. + * @param {{x: number, y: number, z: number}} input.displayPosition Cached display position. + * @param {number} [input.widthPx=24] + * @param {number} [input.heightPx=24] * @param {Partial} [input.params] * @returns {object|null} Published target, or null when it cannot be projected. */ -export function publishFocusTargetFromCachedPosition({ +export function publishFocusTargetAt({ ownerLayer, id, - scene, - camera, + viewer, displayPosition, widthPx = 24, heightPx = 24, params, }) { + const query = viewer ? findQuery(viewer) : null; + let eye = null; + try { + eye = viewer ? (findCamera(viewer)?.pose().position ?? null) : null; + } catch { + eye = null; + } if ( !ownerLayer || id === null || id === undefined || - !scene || - !camera || + !query || + !eye || !displayPosition ) { clearFocusTarget(ownerLayer, id); return null; } - const screen = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - displayPosition, - _scratchScreen, - ); + return publishFocusRect({ + ownerLayer, + id, + screen: query.project(displayPosition), + cameraDistance: Math.hypot( + displayPosition.x - eye.x, + displayPosition.y - eye.y, + displayPosition.z - eye.z, + ), + frameNumber: -1, + widthPx, + heightPx, + params, + }); +} + +/** Publish the focus rectangle around `screen`, or clear it when there is none. */ +function publishFocusRect({ + ownerLayer, + id, + screen, + cameraDistance, + frameNumber, + widthPx, + heightPx, + params, +}) { if (!screen || !Number.isFinite(screen.x) || !Number.isFinite(screen.y)) { clearFocusTarget(ownerLayer, id); return null; @@ -232,11 +260,8 @@ export function publishFocusTargetFromCachedPosition({ bottom: screen.y + halfHeight + padding, }, paddingPx: padding, - cameraDistance: Cesium.Cartesian3.distance( - camera.positionWC, - displayPosition, - ), - frameNumber: scene.frameState?.frameNumber ?? -1, + cameraDistance, + frameNumber, }; if (appeared) { for (const listener of _focusAppearListeners) { @@ -440,68 +465,6 @@ export function advanceSpriteFocus( return _advanceResult; } -/** - * Project and advance one world-anchored sprite using an owning layer's - * existing render pass. - * @param {object} sprite Stable primitive identity. - * @param {Cesium.Cartesian3} position Current cached/rendered world position. - * @param {Cesium.Scene} scene - * @param {Cesium.Camera} camera - * @param {number} nowMs - * @param {object|null} [target] - * @param {Partial} [params] - * @param {number} [spriteHalfWidthPx=0] - * @param {number} [spriteHalfHeightPx=spriteHalfWidthPx] - * @returns {{factor:number, changed:boolean, transitioning:boolean,active:boolean,desired:number}} - */ -export function advanceProjectedSpriteFocus( - sprite, - position, - scene, - camera, - nowMs, - target = _focusTarget, - params, - spriteHalfWidthPx = 0, - spriteHalfHeightPx = spriteHalfWidthPx, -) { - // Common case: nothing tracked and this sprite holds no dimming state — - // advanceSpriteFocus would return identity without reading the projection, - // so skip the worldToWindowCoordinates round trip entirely (it was N - // wasted projections per fleet tick with nothing tracked). Sprites still - // relaxing keep their state entry until fully settled (see the delete at - // the transition tail), so they keep projecting until done. (perf item 8) - if (!target && !_spriteStates.has(sprite)) { - _advanceResult.factor = 1; - _advanceResult.changed = false; - _advanceResult.transitioning = false; - _advanceResult.active = false; - _advanceResult.desired = 1; - return _advanceResult; - } - const screen = - position && scene - ? Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - _scratchScreen, - ) - : null; - const cameraDistance = - position && camera?.positionWC - ? Cesium.Cartesian3.distance(camera.positionWC, position) - : Number.NaN; - return advanceSpriteFocus(sprite, { - screenPosition: screen, - cameraDistance, - nowMs, - target, - params, - spriteHalfWidthPx, - spriteHalfHeightPx, - }); -} - /** * A gated consumer must keep ticking until every previously dimmed sprite has * returned to identity, even when no target remains. diff --git a/src/data/focusResumeGate.test.mjs b/src/data/focusResumeGate.test.mjs index ecd30e831a..ef7555a8f6 100644 --- a/src/data/focusResumeGate.test.mjs +++ b/src/data/focusResumeGate.test.mjs @@ -4,6 +4,8 @@ import { applyVesselFocusDeemphasis } from './aisLiveVessels.js'; import { applyCctvFocusDeemphasis } from './cctv.js'; import { applySatellitePointFocusDeemphasis } from './satellites.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; +import { createIconBook } from '../render/motion/iconBook.js'; +import { createVesselIconBook } from '../layers/vessels/iconBook.js'; const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 }; const target = { @@ -27,7 +29,11 @@ function assertResumeGate(name, makePass) { const { pass, readAlpha } = makePass(); let activeCount = 0; const tick = (nowMs, focusTarget) => { - const result = pass({ nowMs, target: focusTarget, previousActiveCount: activeCount }); + const result = pass({ + nowMs, + target: focusTarget, + previousActiveCount: activeCount, + }); activeCount = result.activeCount; return result; }; @@ -38,7 +44,11 @@ function assertResumeGate(name, makePass) { assert.equal(readAlpha(), params.dimFloor); const releaseStart = tick(params.attackMs + 1, null); - assert.equal(releaseStart.ran, true, 'active count keeps the no-target release pass alive'); + assert.equal( + releaseStart.ran, + true, + 'active count keeps the no-target release pass alive', + ); assert.equal(releaseStart.activeCount, 1); const restored = tick(params.attackMs + params.releaseMs + 2, null); @@ -46,71 +56,71 @@ function assertResumeGate(name, makePass) { assert.equal(restored.activeCount, 0); assert.equal(readAlpha(), 1); - assert.equal(tick(params.attackMs + params.releaseMs + 82, null).ran, false); + assert.equal( + tick(params.attackMs + params.releaseMs + 82, null).ran, + false, + ); }); } assertResumeGate('vessel', () => { - const billboard = { + const icons = createVesselIconBook(); + icons.put({ id: '353136000', size: [32, 32], meta: { id: '353136000' } }); + const record = { + iconId: '353136000', position: { x: 1, y: 2, z: 3 }, - show: true, - width: 32, - height: 32, - scale: 1, - color: color(), + visible: true, }; return { - pass: ({ nowMs, target: focusTarget, previousActiveCount }) => ( + pass: ({ nowMs, target: focusTarget, previousActiveCount }) => applyVesselFocusDeemphasis({ - records: [{ billboard }], + records: [record], + icons, target: focusTarget, previousActiveCount, nowMs, screenPositionFor: () => ({ x: 50, y: 50 }), cameraDistanceFor: () => 1200, params, - }) - ), - readAlpha: () => billboard.color.alpha, + }), + readAlpha: () => icons.focus('353136000'), }; }); assertResumeGate('CCTV', () => { - const billboard = { - position: { x: 1, y: 2, z: 3 }, - show: true, - width: 24, - height: 24, - scale: 1, - color: color(), - }; - const record = { camera: { id: 'cam-1' }, billboard }; + const icons = createIconBook(); + icons.put({ + id: 'cam-1', + pos: { x: 1, y: 2, z: 3 }, + size: [24, 24], + meta: { id: 'cam-1' }, + }); + const record = { camera: { id: 'cam-1' }, position: { x: 1, y: 2, z: 3 } }; return { - pass: ({ nowMs, target: focusTarget, previousActiveCount }) => ( + pass: ({ nowMs, target: focusTarget, previousActiveCount }) => applyCctvFocusDeemphasis({ records: [record], + icons, target: focusTarget, previousActiveCount, nowMs, screenPositionFor: () => ({ x: 50, y: 50 }), cameraDistanceFor: () => 1200, - baseColorFor: () => color(), params, - }) - ), - readAlpha: () => billboard.color.alpha, + }), + readAlpha: () => icons.focus('cam-1'), }; }); assertResumeGate('satellite', () => { const point = { - position: { x: 1, y: 2, z: 3 }, + pos: { x: 1, y: 2, z: 3 }, show: true, pixelSize: 6, - color: color(), + color: [1, 1, 1, 1], }; return { - pass: ({ nowMs, target: focusTarget, previousActiveCount }) => ( + pass: ({ nowMs, target: focusTarget, previousActiveCount }) => applySatellitePointFocusDeemphasis({ points: new Map([[42, point]]), trackedId: null, @@ -119,10 +129,9 @@ assertResumeGate('satellite', () => { nowMs, screenPositionFor: () => ({ x: 50, y: 50 }), cameraDistanceFor: () => 1200, - baseColorFor: () => color(), + baseColorFor: () => [1, 1, 1, 1], params, - }) - ), - readAlpha: () => point.color.alpha, + }), + readAlpha: () => point.color[3], }; }); diff --git a/src/data/followed.js b/src/data/followed.js new file mode 100644 index 0000000000..fd7612afba --- /dev/null +++ b/src/data/followed.js @@ -0,0 +1,172 @@ +/** + * @module data/followed + * @description What the camera follows, for the code that reads it. + * + * A layer follows through the camera port with a FollowTarget that also + * carries what the app shows about it (key, display position, sprite, label). + * A layer that keeps its target as a holder of its own (an entity record) + * follows through the port with `entityFollowTarget`, whose presentation + * fields read that record. Readers ask this module, never the renderer. + * + * Its readers (the tracked card, Cockpit, the share link's thing view, + * north-up) read where the target is shown (`followedPosition`): its + * `displayPosition`, else its own `position` at scene time. + */ +import { findCamera, findFrame } from '../render/rendererOf.js'; +import { readEntityRecord } from './entityRecords.js'; + +/** + * @typedef {object} Followed + * @property {string|null} key Stable id, e.g. `'flights:a1b2c3'`. + * @property {string} [name] Display name, when the target has one. + * @property {() => object|null} [displayPosition] Where the follow camera + * frames the target this frame (the layer's display cache). + * @property {() => object|null} [visualPosition] Where the target is drawn. + * @property {object} [sprite] Size of the drawn billboard. + * @property {object} [labelModel] + * @property {string} [selectionOrigin] + * @property {object} [entity] The holder whose entity record the + * presentation fields read (`entityFollowTarget`). + */ + +/** @type {WeakMap} */ +const entityViews = new WeakMap(); + +function entityView(entity) { + let view = entityViews.get(entity); + if (!view) { + const id = String(entity.id ?? '').trim(); + view = { + entity, + get key() { + const explicit = String(readEntityRecord(entity)?.trackedId ?? ''); + return explicit.trim() || (id ? `entity:${id}` : null); + }, + get name() { + return entity.name; + }, + get displayPosition() { + return readEntityRecord(entity)?.displayPosition; + }, + get visualPosition() { + return readEntityRecord(entity)?.visualPosition; + }, + get sprite() { + return readEntityRecord(entity)?.sprite; + }, + get labelModel() { + return readEntityRecord(entity)?.labelModel; + }, + get selectionOrigin() { + return readEntityRecord(entity)?.selectionOrigin; + }, + }; + entityViews.set(entity, view); + } + return view; +} + +/** + * What `viewer`'s camera follows, or null. The same object comes back for + * as long as the same thing is followed. + * @param {object|null|undefined} viewer + * @returns {Followed|null} + */ +export function followedOf(viewer) { + if (!viewer) return null; + return findCamera(viewer)?.followed ?? null; +} + +/** Whether `viewer`'s camera follows anything. */ +export function isFollowing(viewer) { + return followedOf(viewer) !== null; +} + +/** + * Run `cb` whenever what `viewer`'s camera follows changes. + * @param {object} viewer + * @param {(followed: Followed|null) => void} cb + * @returns {() => void} Off. + */ +export function onFollowChanged(viewer, cb) { + let last = followedOf(viewer); + let port = null; + let offPort = null; + // The port is looked up again on every change: a renderer bound after + // this subscribed replaces the one it listened to. + const listenToPort = () => { + const current = findCamera(viewer); + if (current === port) return; + offPort?.(); + port = current; + offPort = port?.on('followChanged', check) ?? null; + }; + function check() { + listenToPort(); + const now = followedOf(viewer); + if (now === last) return; + last = now; + cb(now); + } + listenToPort(); + return () => { + offPort?.(); + offPort = null; + }; +} + +/** Stop the camera following anything. */ +export function stopFollowing(viewer) { + if (!viewer) return; + const camera = findCamera(viewer); + if (camera?.followed) camera.follow(null); +} + +/** + * A FollowTarget for a layer that draws its target as an entity of its own: + * the camera fields given (`position`, `viewFrom`, `frame`, `minRange`, ...) + * plus what the app shows about it, read live from the entity's record, so the + * layer keeps writing that record as before. `entity` is the drawn entity. + * @param {object} entity + * @param {object} camera The FollowTarget's camera fields. + * @returns {Followed & object} + */ +export function entityFollowTarget(entity, camera) { + const target = Object.create(entityView(entity)); + // Defined, not assigned: the record's fields are getters, and a camera + // field of the same name (`key`, say) takes their place. + for (const [name, value] of Object.entries(camera)) + Object.defineProperty(target, name, { + value, + enumerable: true, + writable: true, + configurable: true, + }); + return target; +} + +/** + * Follow `followed` again after `stopFollowing`, through the camera port. + * @param {object} viewer + * @param {Followed|null} followed What `followedOf` gave. + */ +export function resumeFollowing(viewer, followed) { + if (!viewer || !followed) return; + findCamera(viewer)?.follow(followed); +} + +/** + * Where `followed` is shown this frame: the layer's display cache, else the + * target's own position at the frame port's scene time; null when neither + * answers. + * @param {object} viewer + * @param {Followed|null} followed + */ +export function followedPosition(viewer, followed) { + const display = followed?.displayPosition; + const shown = typeof display === 'function' ? display() : null; + if (shown) return shown; + if (typeof followed?.position !== 'function') return null; + const time = findFrame(viewer)?.time?.(); + return followed.position(Number.isFinite(time) ? time : Date.now()) || null; +} diff --git a/src/data/followed.test.mjs b/src/data/followed.test.mjs new file mode 100644 index 0000000000..71e8480633 --- /dev/null +++ b/src/data/followed.test.mjs @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { entityRecord } from './entityRecords.js'; +import { + entityFollowTarget, + followedOf, + followedPosition, + isFollowing, + onFollowChanged, + resumeFollowing, + stopFollowing, +} from './followed.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { createCameraEvents } from '../render/camera/events.js'; +import { createStubRenderer } from '../render/stub/index.js'; + +/** A camera port that follows, for a viewer bound to a renderer. */ +function followingPort() { + const events = createCameraEvents({ pose: () => ({}), report: () => {} }); + let followed = null; + return { + on: (event, cb) => events.on(event, cb), + get followed() { + return followed; + }, + follow(target) { + if (followed === target) return; + followed = target; + events.emit('followChanged'); + }, + }; +} + +test('what the camera port follows is the target itself', (t) => { + const viewer = {}; + assert.equal(followedOf(viewer), null, 'nothing without a renderer'); + const camera = followingPort(); + t.after(bindRenderer(viewer, { camera })); + assert.equal(followedOf(viewer), null); + assert.equal(isFollowing(viewer), false); + const target = { key: 'flights:abc', position: () => null }; + camera.follow(target); + assert.equal(followedOf(viewer), target); + assert.equal(isFollowing(viewer), true); +}); + +test('onFollowChanged fires once per change', (t) => { + const viewer = {}; + const camera = followingPort(); + t.after(bindRenderer(viewer, { camera })); + const seen = []; + const off = onFollowChanged(viewer, (f) => seen.push(f?.key ?? null)); + const target = { key: 'flights:abc' }; + camera.follow(target); + camera.follow(target); + camera.follow(null); + off(); + camera.follow({ key: 'after' }); + assert.deepEqual(seen, ['flights:abc', null]); +}); + +test('stopFollowing ends a port follow', (t) => { + const viewer = {}; + stopFollowing(viewer); + const camera = followingPort(); + t.after(bindRenderer(viewer, { camera })); + camera.follow({ key: 'k' }); + stopFollowing(viewer); + assert.equal(camera.followed, null); + stopFollowing(null); +}); + +test('an entity follow target reads its entity record live', () => { + const entity = new Cesium.Entity({ id: 'drawn', name: 'N2' }); + const position = () => ({ x: 1, y: 2, z: 3 }); + const target = entityFollowTarget(entity, { position, minRange: 150 }); + assert.equal(target.key, 'entity:drawn'); + entityRecord(entity).trackedId = 'flights:abc'; + entityRecord(entity).labelModel = { title: 'N2' }; + assert.equal(target.key, 'flights:abc'); + assert.equal(target.labelModel.title, 'N2'); + assert.equal(target.entity, entity); + assert.equal(target.position, position); + assert.equal(target.minRange, 150); + const keyed = entityFollowTarget(entity, { key: 'flights:given' }); + assert.equal(keyed.key, 'flights:given', 'a camera field takes the place'); + assert.equal(keyed.labelModel.title, 'N2'); +}); + +test('resumeFollowing follows a port target again', (t) => { + const viewer = {}; + const camera = followingPort(); + t.after(bindRenderer(viewer, { camera })); + const target = entityFollowTarget(new Cesium.Entity({ id: 'p' }), {}); + camera.follow(target); + stopFollowing(viewer); + resumeFollowing(viewer, target); + assert.equal(camera.followed, target); + resumeFollowing(viewer, null); + assert.equal(camera.followed, target); +}); + +test('followedPosition reads the display cache', () => { + const entity = new Cesium.Entity({ id: 'e' }); + const view = entityFollowTarget(entity, {}); + assert.equal(followedPosition({}, view), null, 'none without a cache'); + entityRecord(entity).displayPosition = () => ({ x: 7, y: 8, z: 9 }); + assert.deepEqual(followedPosition({}, view), { x: 7, y: 8, z: 9 }); + assert.equal(followedPosition({}, null), null); +}); + +test('followedPosition falls back to the target position at scene time', () => { + const renderer = createStubRenderer(); + const viewer = {}; + bindRenderer(viewer, renderer); + renderer.frame.setTime(1234); + const seen = []; + const target = { + key: 't', + frame: 'enu', + viewFrom: { x: 0, y: 0, z: 1 }, + position: (time) => (seen.push(time), { x: 1, y: 2, z: 3 }), + }; + assert.deepEqual(followedPosition(viewer, target), { x: 1, y: 2, z: 3 }); + assert.deepEqual(seen, [1234]); + target.displayPosition = () => ({ x: 4, y: 5, z: 6 }); + assert.deepEqual(followedPosition(viewer, target), { x: 4, y: 5, z: 6 }); +}); diff --git a/src/data/geoFileImport.js b/src/data/geoFileImport.js index 2d444092e0..d489577636 100644 --- a/src/data/geoFileImport.js +++ b/src/data/geoFileImport.js @@ -1,23 +1,27 @@ /** Session-local geodata loading with bounded geometry and local-only file references. */ -import * as Cesium from 'cesium'; import { createImportImageBudget } from './geoImportImages.js'; -import { createImportedPins } from './geoImportPins.js'; +import { readGeoJsonFeatures, readKmlFeatures } from './geoImportFeatures.js'; +import { settleImportedDrawing } from './geoImportPins.js'; +import { + GeoImportError, + MAX_IMPORT_ENTITIES, + boundedImport, + importFeatureName, +} from './geoImportShared.js'; import { msg } from '../i18n/marker.js'; +export { GeoImportError, MAX_IMPORT_ENTITIES, importFeatureName }; + /** Largest file accepted, in bytes. */ const MAX_IMPORT_BYTES = 50 * 1024 * 1024; /** Largest total a KMZ may inflate to — a zip bomb stops here. */ const MAX_KMZ_INFLATED_BYTES = 120 * 1024 * 1024; /** Most files on the globe at once. */ export const MAX_IMPORTED_FILES = 12; -/** Most entities one file may create before it is refused. */ -export const MAX_IMPORT_ENTITIES = 20_000; /** Most vertices (points of every line, ring and marker) in one file. */ export const MAX_IMPORT_POSITIONS = 250_000; /** Most normalized style definitions and local image links in one KML/KMZ. */ const MAX_KML_LINKS = 2_000; -/** Longest plain-text name kept from a file's features. */ -const MAX_IMPORT_NAME_LENGTH = 120; /** What the file picker offers. */ export const GEO_FILE_ACCEPT = '.geojson,.json,.kml,.kmz,.gpx'; @@ -62,21 +66,6 @@ const KML_REMOVED_ELEMENTS = new Set([ 'httpQuery', ]); -/** - * An error whose message is meant for the person who chose the file. The - * message stays English; `template` and `values`, when given, let the UI show - * it in the active language. Numbers stay numbers in `values`: the UI formats - * them in that language's numerals. - */ -export class GeoImportError extends Error { - constructor(message, template = message, values = {}) { - super(message); - this.name = 'GeoImportError'; - this.template = template; - this.values = values; - } -} - /** * The format of a file, from its name first and its first bytes second. * @param {string} name File name. @@ -212,8 +201,8 @@ export function countGeoJsonGeometry( MultiPolygon: 3, }[node.type]; if (depth !== undefined) { - // Multipart geometries create one Cesium entity per component, even - // when the document wraps them in just one Feature. + // Multipart geometries are one map object per component, even when + // the document wraps them in just one Feature. entities += node.type.startsWith('Multi') ? Array.isArray(node.coordinates) ? node.coordinates.length @@ -293,7 +282,7 @@ function overLimitError({ over, features }) { } // The import uses WGS84 ground footprints and a short name only. Remove -// loader-sensitive metadata before Cesium allocates properties or entity IDs. +// everything else before the features are read. function prepareGeoJson(geojson) { const stack = [geojson]; while (stack.length) { @@ -520,7 +509,7 @@ export function kmzImageResolver( * Strip everything from a parsed KML document that would make the page reach * outside the file. `resolveLocal(href)` returns a URL for an image packed in * the same KMZ (or null); every other href is removed, so icons fall back to - * Cesium's default pin and a ground overlay without a local image is dropped. + * the default pin and a ground overlay without a local image is dropped. * @param {Document} doc * @param {(href: string) => string|null} [resolveLocal] * @returns {{removed: number}} How many elements were taken out. @@ -534,8 +523,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) { } }; // One snapshot and pass, rather than rescanning the whole XML tree for - // every discarded element type. Strip unused metadata before the loader - // constructs descriptions, availability intervals and camera objects. + // every discarded element type. Strip unused metadata (descriptions, + // times and cameras) before the features are read. for (const el of [...doc.getElementsByTagName('*')]) if ( KML_REMOVED_ELEMENTS.has(el.localName) || @@ -557,8 +546,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) { drop(overlay); continue; } - // An empty Icon explicitly hides the billboard in Cesium. Remove the - // blocked icon definition so the loader supplies its local default pin. + // An empty Icon explicitly hides the icon. Remove the blocked icon + // definition so the placemark gets the local default pin. // Authored empty Icons (with no blocked href) still mean no marker. drop( icon?.localName === 'Icon' && icon.parentNode?.localName === 'IconStyle' @@ -579,9 +568,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) { !childrenNamed(pair, 'Style').length) ) drop(pair); - // Draw recorded KML paths as their original static vertices. Letting the - // loader build time-dynamic tracks would expand each into thousands of - // interpolated points later and exceed the checked geometry budget. + // Draw recorded KML paths as their original static vertices, the + // geometry the budget checked, never as time-dynamic tracks. for (const track of elementsNamed(doc, 'Track')) { const line = doc.createElementNS( 'http://www.opengis.net/kml/2.2', @@ -647,11 +635,11 @@ const childText = (el, localName) => (childrenNamed(el, localName)[0]?.textContent || '').trim(); /** - * Share identical styles before the loader builds their graphics. Inline + * Share identical styles before the features are read. Inline * overrides stay inline StyleMaps, so an existing styleUrl still supplies * properties the override leaves unset. Named references are redirected. * Random-color styles remain unchanged; duplicate IDs - * keep the loader's original precedence instead of being rewritten. + * keep their original precedence instead of being rewritten. * @param {Document} doc Sanitized KML. * @param {{serializeStyle?: Function, maxStyles?: number}} [options] * @returns {number} Number of original style blocks replaced. @@ -754,8 +742,8 @@ export function deduplicateKmlStyles( } /** - * Count placemarks and vertices in a parsed KML document before Cesium reads - * it: every `` tuple and every `gx:coord`, plus normalized + * Count placemarks and vertices in a parsed KML document before it is read: + * every `` tuple and every `gx:coord`, plus normalized * style definitions and distinct image `` values (`links`). * Inline StyleMaps are references, not additional shared style definitions. * @param {Document} doc @@ -805,8 +793,8 @@ export function countKmlGeometry( ) throw new GeoImportError(msg('That KML has invalid geometry bounds.')); } - // Cesium creates entities for folders, a parent for every placemark, and - // a child for each geometry in a MultiGeometry, including nested containers. + // A map object for each folder, a parent for every placemark, and a + // child for each geometry in a MultiGeometry, including nested containers. if ( name === 'Placemark' || name === 'Folder' || @@ -952,95 +940,6 @@ export function gpxToGeoJson( return { type: 'FeatureCollection', features }; } -/** A feature name as short plain text (no control characters), or undefined. */ -export function importFeatureName(value) { - const text = String(value ?? '') - .replace(/[\u0000-\u001f\u007f]/g, ' ') - .replace(/\s+/g, ' ') - .trim(); - if (!text) return undefined; - return text.length > MAX_IMPORT_NAME_LENGTH - ? `${text.slice(0, MAX_IMPORT_NAME_LENGTH - 1)}…` - : text; -} - -/** - * Make every entity of an imported data source inert: no description, - * balloon, extended data or properties, no native label, and a name that is - * short plain text. Generated pin canvases share a data URL so Cesium uploads - * each image once, rather than allocating a texture entry for every entity. - * Returns how many entities were touched. - * @param {{entities: {values: object[]}}} dataSource - * @returns {number} - */ -export function scrubImportedEntities(dataSource) { - const collection = dataSource?.entities; - const list = collection?.values || []; - const images = new Map(); - collection?.suspendEvents?.(); - try { - for (let i = 0; i < list.length; i++) { - const entity = list[i]; - let name; - try { - name = importFeatureName( - typeof entity.name === 'string' ? entity.name : undefined, - ); - } catch { - name = undefined; - } - entity.name = name; - entity.description = undefined; - entity.label = undefined; - entity.properties = undefined; - if (entity.kml && typeof entity.kml === 'object') entity.kml = undefined; - if ( - entity.billboard?.heightReference?.getValue?.() === - Cesium.HeightReference.CLAMP_TO_GROUND - ) - entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY; - const property = entity.billboard?.image; - if (property?.isConstant === false) continue; - const image = property?.getValue?.(); - if (image?.tagName === 'CANVAS') { - let url = images.get(image); - if (!url) { - url = image.toDataURL(); - images.set(image, url); - } - entity.billboard.image = url; - } - } - } finally { - collection?.resumeEvents?.(); - } - return list.length; -} - -/** - * Take time out of an imported data source so adding it cannot move the app's - * shared clock: the data source reports no clock (the viewer adopts the clock - * of every added source that has one), every entity is available for all - * time. KML tracks have already become their original static vertices in - * `sanitizeKmlDocument`, so no sampled-position fallback is needed here. - * @param {object} dataSource - * @returns {object} The same data source. - */ -export function detachImportedTime(dataSource) { - Object.defineProperty(dataSource, 'clock', { - configurable: true, - enumerable: false, - get: () => undefined, - set: () => {}, - }); - const list = dataSource?.entities?.values || []; - for (let i = 0; i < list.length; i++) { - const entity = list[i]; - entity.availability = undefined; - } - return dataSource; -} - /** Repair only the first KML opening tag, scanning its delimiter once. */ export function repairKmlRootNamespaces(value, what = 'KML') { const text = String(value); @@ -1137,7 +1036,7 @@ export function repairKmlRootNamespaces(value, what = 'KML') { /** Parse KML or GPX with the shared namespace repairs and XML validation. */ export function parseXml(text, what) { - // Match the namespace repairs Cesium applies to ordinary exported KML. + // The namespace repairs ordinary exported KML needs. if (what !== 'GPX') text = repairKmlRootNamespaces(text, what); const doc = new DOMParser().parseFromString( String(text).replace(/^/, ''), @@ -1195,172 +1094,12 @@ function checkLocalImages(doc, entries = new Map(), main = '') { } } -// Cesium also processes KML in deferred tasks; an exception there does not -// reject its load promise. Keep a failed file from blocking the serial queue. -async function loadKml(doc, viewer, signal) { - let removeError; - try { - return await boundedImport( - Promise.race([ - Cesium.KmlDataSource.load(doc, { - camera: viewer.scene.camera, - canvas: viewer.scene.canvas, - clampToGround: true, - }), - new Promise((_, reject) => { - const failed = () => { - reject(new GeoImportError(msg('That KML could not be read.'))); - }; - globalThis.addEventListener?.('error', failed); - removeError = () => globalThis.removeEventListener?.('error', failed); - }), - ]), - signal, - ); - } finally { - removeError?.(); - } -} - -// Resolve a static file's ground pins in batches before they are visualized. -// Per-billboard CLAMP_TO_GROUND subscriptions scale poorly on large imports. -const groundPins = new WeakMap(); -async function settleGroundPins(dataSource, viewer, signal) { - let pins = groundPins.get(dataSource); - if (!pins) { - pins = []; - for (const entity of dataSource.entities.values) { - const reference = entity.billboard?.heightReference?.getValue?.(); - if ( - reference === Cesium.HeightReference.CLAMP_TO_GROUND || - reference === Cesium.HeightReference.RELATIVE_TO_GROUND - ) { - const position = entity.position?.getValue?.(Cesium.JulianDate.now()); - if (!position) continue; - const cartographic = Cesium.Cartographic.fromCartesian(position); - if (!cartographic) - throw new GeoImportError( - msg('That file has invalid point coordinates.'), - ); - pins.push({ - entity, - original: position, - cartographic, - offset: - reference === Cesium.HeightReference.RELATIVE_TO_GROUND - ? cartographic.height - : 0, - }); - entity.billboard.heightReference = Cesium.HeightReference.NONE; - entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY; - } - } - groundPins.set(dataSource, pins); - } - for (let at = 0; at < pins.length; at += 256) { - signal?.throwIfAborted(); - const batch = pins.slice(at, at + 256); - const positions = batch.map( - ({ cartographic: c }) => - new Cesium.Cartographic(c.longitude, c.latitude, 0), - ); - const mesh = - viewer.scene?.globe?.show === false && - viewer.scene?.clampToHeightSupported; - // A coarse rendered ellipsoid mesh can report a height kilometres below - // zero. Its provider's exact height is zero even while a 3D map hides it; - // a buried starting point can make the downward mesh ray miss the surface. - const ellipsoid = - viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider; - for (let i = 0; i < positions.length; i++) { - const sampled = ellipsoid - ? 0 - : viewer.scene?.globe?.getHeight?.(positions[i]); - positions[i].height = mesh - ? (batch[i].groundHeight ?? - Math.max(0, Number.isFinite(sampled) ? sampled : 0)) - : Number.isFinite(sampled) - ? sampled - : batch[i].groundHeight || 0; - } - const points = positions.map((c) => - Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height), - ); - const height = viewer.camera?.positionCartographic?.height; - if (mesh && Number.isFinite(height) && height < 250_000) { - const rectangle = viewer.camera.computeViewRectangle?.(); - const indices = []; - for (let i = 0; i < positions.length; i++) - if (rectangle && Cesium.Rectangle.contains(rectangle, positions[i])) - indices.push(i); - if (indices.length) { - const resolved = await boundedImport( - viewer.scene.clampToHeightMostDetailed( - indices.map((i) => { - const c = positions[i]; - return Cesium.Cartesian3.fromRadians( - c.longitude, - c.latitude, - Math.max(0, c.height), - ); - }), - ), - signal, - ); - for (let i = 0; i < indices.length; i++) - if (resolved[i]) points[indices[i]] = resolved[i]; - } - } - signal?.throwIfAborted(); - for (let i = 0; i < batch.length; i++) { - const item = batch[i]; - const c = points[i] && Cesium.Cartographic.fromCartesian(points[i]); - if (!c) - throw new GeoImportError( - msg( - 'Ground heights are not available for that file. Try again when the map has loaded.', - ), - ); - item.groundHeight = c.height; - c.height += item.offset; - item.entity.position = - Math.abs(c.height - item.cartographic.height) < 1e-6 - ? item.original - : Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height); - } - if (at + batch.length < pins.length) - await new Promise((resolve) => setTimeout(resolve, 0)); - } -} - -async function boundedImport(promise, signal) { - let timer, abort; - try { - signal?.throwIfAborted(); - return await Promise.race([ - promise, - new Promise((_, reject) => { - abort = () => reject(signal.reason); - signal?.addEventListener('abort', abort, { once: true }); - timer = setTimeout( - () => - reject(new GeoImportError(msg('That file took too long to read.'))), - 60_000, - ); - }), - ]); - } finally { - clearTimeout(timer); - signal?.removeEventListener('abort', abort); - } -} - /** - * Load a ground footprint, retaining explicit KML altitude modes. Call mount after - * adding the source; revoke owns pin and blob cleanup. + * Load a ground footprint, retaining explicit KML altitude modes. Call mount + * to draw it; revoke owns the drawing and blob cleanup. * @param {File|Blob & {name?: string}} file - * @param {{viewer: Cesium.Viewer, color?: string}} options `color` is a CSS color. - * @returns {Promise<{dataSource: Cesium.DataSource, name: string, + * @param {{viewer: object, color?: string}} options `color` is a CSS color. + * @returns {Promise<{drawing: object, name: string, * format: string, entityCount: number, removed: number, mount: Function, revoke: Function}>} */ export async function loadGeoFile( @@ -1385,15 +1124,14 @@ export async function loadGeoFile( throw new GeoImportError( msg('Only GeoJSON, KML, KMZ and GPX files can be imported.'), ); - const stroke = Cesium.Color.fromCssColorString(color); const urls = []; - let pins; + let drawn; const revoke = () => { - pins?.destroy(); + drawn?.drawing.destroy(); urls.splice(0).forEach((url) => URL.revokeObjectURL(url)); }; const name = importDisplayName(file.name); - let dataSource; + let read; let removed = 0; try { if (format === 'geojson' || format === 'gpx') { @@ -1409,18 +1147,7 @@ export async function loadGeoFile( throw new GeoImportError(msg('That file has nothing to draw.')); prepareGeoJson(geojson); bytes = null; - dataSource = await boundedImport( - Cesium.GeoJsonDataSource.load(geojson, { - clampToGround: true, - stroke, - fill: stroke.withAlpha(0.25), - strokeWidth: 3, - markerColor: stroke, - // No HTML description table is built from the file's properties. - describe: () => undefined, - }), - signal, - ); + read = readGeoJsonFeatures(geojson, color); } else { let text; let entries; @@ -1449,7 +1176,7 @@ export async function loadGeoFile( deduplicateKmlStyles(doc); const normalizedSize = countKmlGeometry(doc); if (normalizedSize.over) throw overLimitError(normalizedSize); - dataSource = await loadKml(doc, viewer, signal); + read = readKmlFeatures(doc); } } catch (error) { revoke(); @@ -1460,69 +1187,22 @@ export async function loadGeoFile( { format: format.toUpperCase() }, ); } - const entityCount = dataSource.entities.values.length; - if (entityCount > MAX_IMPORT_ENTITIES) { - revoke(); - throw new GeoImportError( - `That file has ${entityCount.toLocaleString()} map objects; the limit is ${MAX_IMPORT_ENTITIES.toLocaleString()}.`, - msg('That file has {count} map objects; the limit is {limit}.'), - { - count: entityCount, - limit: MAX_IMPORT_ENTITIES, - }, - ); - } - const now = Cesium.JulianDate.now(); - const drawable = dataSource.entities.values.some( - (e) => - e.billboard?.image?.getValue(now) || - e.point || - e.rectangle || - e.polyline?.positions?.getValue(now)?.length >= 2 || - e.wall?.positions?.getValue(now)?.length >= 2 || - e.polygon?.hierarchy?.getValue(now)?.positions?.length >= 3, - ); - if (!drawable) { - revoke(); - throw new GeoImportError(msg('That file has nothing to draw.')); - } - scrubImportedEntities(dataSource); try { - await settleGroundPins(dataSource, viewer, signal); + drawn = await settleImportedDrawing(read, viewer, signal); } catch (error) { revoke(); - throw error instanceof GeoImportError - ? error - : new GeoImportError( - msg('Ground heights could not be read. Try that file again.'), - ); + throw error; } - // Keep the clock invariant explicit even though unused KML dates have - // already been stripped and all supported geometries are static. - detachImportedTime(dataSource); - try { - pins = createImportedPins(dataSource, viewer); - } catch { - revoke(); - throw new GeoImportError(msg('That file has invalid point graphics.')); - } - // The display name travels beside the data source (the file name, not + // The display name travels beside the drawing (the file name, not // anything the document says about itself). return { - dataSource, + drawing: drawn.drawing, name, format, - entityCount, + entityCount: drawn.entityCount, removed, revoke, - mount: () => pins.mount(), - refreshGround: (refreshSignal) => - settleGroundPins( - dataSource, - viewer, - refreshSignal - ? AbortSignal.any([refreshSignal, AbortSignal.timeout(15_000)]) - : AbortSignal.timeout(15_000), - ).then(() => pins.sync()), + mount: () => drawn.drawing.mount(), + refreshGround: drawn.refreshGround, }; } diff --git a/src/data/geoFileImport.test.mjs b/src/data/geoFileImport.test.mjs index 9b147e1d28..8a6fa36c18 100644 --- a/src/data/geoFileImport.test.mjs +++ b/src/data/geoFileImport.test.mjs @@ -2,7 +2,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { deflateRawSync } from 'node:zlib'; import { spawnSync } from 'node:child_process'; -import * as Cesium from 'cesium'; import { GeoImportError, repairKmlRootNamespaces, @@ -12,10 +11,8 @@ import { countGeoJsonGeometry, countKmlGeometry, deduplicateKmlStyles, - detachImportedTime, gpxToGeoJson, importFeatureName, - scrubImportedEntities, sanitizeKmlDocument, detectGeoFileFormat, importDisplayName, @@ -26,105 +23,125 @@ import { readZipEntries, resolveKmzPath, } from './geoFileImport.js'; +import { readKmlFeatures } from './geoImportFeatures.js'; +import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; + +/** The point `at` (lon, lat) at `height`, ECEF. */ +const fromDegreesHeight = (at, height) => fromDegrees(at.lon, at.lat, height); import { createImportImageBudget, importImageSize } from './geoImportImages.js'; -test('real loader grounds XYZ GeoJSON and strips loader-sensitive metadata before allocation', async () => { - const previous = Cesium.PinBuilder.prototype.fromColor; - Cesium.PinBuilder.prototype.fromColor = () => ({ - toDataURL: () => 'data:image/png;base64,local', - tagName: 'CANVAS', +/** + * A viewer bound to a renderer double for the import: draw sets kept, + * terrain heights from `terrain` (the globe shown) or from `hidden` (the + * globe hidden over a mesh), mesh clamps from `clamp`, and a camera + * `eyeHeight` up looking at `view`. + */ +function importViewer({ + terrain = () => null, + hidden = null, + clamp = null, + eyeHeight = 1_000_000, + view = { west: -180, south: -90, east: 180, north: 90 }, +} = {}) { + const viewer = {}; + const ground = bindFakeGroundRenderer(viewer, { + sampleHeight: Boolean(clamp), + eye: { lon: 0, lat: 0, height: eyeHeight }, }); - try { - const object = { - type: 'FeatureCollection', - crs: { type: 'name', properties: { name: 'unsupported' } }, - features: [ - { - type: 'Feature', - id: 'kartaview-owned', - properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' }, - geometry: { type: 'Point', coordinates: [1, 2, 999] }, - }, - { - type: 'Feature', - geometry: { - type: 'Polygon', - coordinates: [ - [ - [1, 2, 0], - [2, 2, 0], - [2, 3, 0], - [1, 2, 0], - ], - ], - }, - }, - ], - }; - const loaded = await loadGeoFile( - new File([JSON.stringify(object)], 'xyz.geojson'), + ground.globe.show = !hidden; + ground.globe.terrain = terrain; + const query = ground.renderer.query; + const sampleHeightNow = query.sampleHeightNow; + query.sampleHeightNow = (point, options = {}) => + hidden && options.against === 'terrain' + ? hidden(point) + : sampleHeightNow(point, options); + if (clamp) query.clampToSurface = async (points) => clamp(points); + ground.renderer.camera.viewRectangle = () => view; + return { viewer, camera: ground.renderer.camera, ...ground }; +} + +/** The live import set of a kind (`pins`, `lines`, `shapes`). */ +const importSet = (ground, kind) => + [...ground.draw.sets.values()].find( + (record) => + !record.disposed && + record.spec.id.startsWith('geo-import:') && + record.spec.id.endsWith(`:${kind}`), + ); + +test('GeoJSON points stand on the ground and lose everything but a name', async () => { + const object = { + type: 'FeatureCollection', + crs: { type: 'name', properties: { name: 'unsupported' } }, + features: [ { - viewer: { - scene: { - frameState: { mode: Cesium.SceneMode.SCENE3D }, - primitives: new Cesium.PrimitiveCollection(), - globe: { getHeight: () => 1234 }, - }, + type: 'Feature', + id: 'kartaview-owned', + properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' }, + geometry: { type: 'Point', coordinates: [1, 2, 999] }, + }, + { + type: 'Feature', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [1, 2, 0], + [2, 2, 0], + [2, 3, 0], + [1, 2, 0], + ], + ], }, }, + ], + }; + const t = importViewer({ terrain: () => 1234 }); + try { + const loaded = await loadGeoFile( + new File([JSON.stringify(object)], 'xyz.geojson'), + { viewer: t.viewer, color: '#ff0000' }, ); - const [point, polygon] = - loaded.dataSource.importedEntities || loaded.dataSource.entities.values; - assert.notEqual(point.id, 'kartaview-owned'); - assert.equal(point.name, 'Test'); - assert.equal(point.properties, undefined); - assert.equal( - point.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, - ); - assert.equal(point.billboard.disableDepthTestDistance.getValue(), Infinity); - assert.ok( - Math.abs( - Cesium.Cartographic.fromCartesian( - point.position.getValue(Cesium.JulianDate.now()), - ).height - 1234, - ) < 1e-6, - ); - assert.notEqual(polygon.polygon.perPositionHeight?.getValue(), true); - assert.equal(loaded.dataSource.clock, undefined); - assert.equal( - loaded.dataSource.entities.values.length, - 1, - 'only polygon geometry remains in the per-frame entity collection', - ); - assert.equal(loaded.dataSource.importedBillboards.length, 1); - const update = Cesium.BillboardCollection.prototype.update; - let passes = 0; - Cesium.BillboardCollection.prototype.update = () => passes++; - try { - const collection = loaded.dataSource.importedBillboards; - collection.update({ passes: { pick: true, offscreen: true } }); - assert.equal(passes, 0, 'height picks ignore imported markers'); - collection.update({ passes: { pick: true, offscreen: false } }); - collection.update({ passes: { render: true, offscreen: true } }); - assert.equal(passes, 2, 'ordinary picks and screenshots include markers'); - } finally { - Cesium.BillboardCollection.prototype.update = update; - } - + assert.equal(importSet(t, 'pins'), undefined, 'nothing drawn before mount'); loaded.mount(); - loaded.dataSource.show = false; - assert.equal(loaded.dataSource.importedBillboards.show, false); - loaded.dataSource.show = true; + const [pin] = importSet(t, 'pins').items.values(); + assert.equal(pin.meta.name, 'Test'); + assert.deepEqual(Object.keys(pin.meta), ['name']); + assert.equal(pin.height, 'absolute'); + assert.equal(pin.pos.height, 1234, 'on the terrain, not at 999 m'); + assert.equal(pin.disableDepthTest, Infinity); + assert.equal(pin.anchor, 'bottom'); + assert.deepEqual(pin.size, [48, 48]); + assert.match(pin.image.svg, /rgba\(255,0,0,1\)/); + assert.equal( + importSet(t, 'pins').spec.includeInHeightQueries, + undefined, + 'height queries never see imported markers', + ); + const [polygon] = importSet(t, 'shapes').items.values(); + assert.equal(polygon.height, 'clampGround'); + assert.deepEqual(polygon.fill, [1, 0, 0, 0.25]); + assert.equal(polygon.outline, undefined, 'no outline on the ground'); + assert.equal(loaded.entityCount, 2); + + loaded.drawing.show = false; + assert.equal(importSet(t, 'pins').show, false); + assert.equal(importSet(t, 'shapes').show, false); + loaded.drawing.show = true; + t.globe.terrain = () => 50; await loaded.refreshGround(); assert.equal( - point.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, + [...importSet(t, 'pins').items.values()][0].pos.height, + 50, + 'a refresh moves the pin onto the ground now under it', ); loaded.revoke(); - assert.ok(loaded.dataSource.importedBillboards.isDestroyed()); + assert.equal(importSet(t, 'pins'), undefined); + assert.equal(importSet(t, 'shapes'), undefined); } finally { - Cesium.PinBuilder.prototype.fromColor = previous; + t.unbind(); } }); @@ -241,81 +258,54 @@ test('pending file reads can be cancelled without waiting for the loader timeout }); test('a hidden coarse globe never seeds a mesh-clamp ray below the surface', async () => { - const previous = Cesium.PinBuilder.prototype.fromColor; - Cesium.PinBuilder.prototype.fromColor = () => ({ - tagName: 'CANVAS', - toDataURL: () => 'data:image/png;base64,local', - }); const starts = []; + const t = importViewer({ + eyeHeight: 100_000, + hidden: () => -12311, + clamp: (points) => + points.map((p) => { + const at = toLonLatH(p); + starts.push(at.height); + return at.height < -9000 + ? null + : { ...p, ...fromDegreesHeight(at, 2000) }; + }), + }); try { - for (const terrainProvider of [new Cesium.EllipsoidTerrainProvider(), {}]) { - const viewer = { - terrainProvider, - camera: { - positionCartographic: { height: 100000 }, - computeViewRectangle: () => Cesium.Rectangle.MAX_VALUE, - }, - scene: { - frameState: { mode: Cesium.SceneMode.SCENE3D }, - globe: { show: false, getHeight: () => -12311 }, - clampToHeightSupported: true, - clampToHeightMostDetailed: async (points) => - points.map((p) => { - const c = Cesium.Cartographic.fromCartesian(p); - starts.push(c.height); - return c.height < -9000 - ? undefined - : Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 2000); - }), - }, - }; - const loaded = await loadGeoFile( - new File( - [JSON.stringify({ type: 'Point', coordinates: [1, 2] })], - 'surface.geojson', - ), - { viewer }, - ); - assert.ok( - Math.abs(starts.at(-1)) < 1e-6, - `ray started at ${starts.at(-1)}`, - ); - assert.ok( - Math.abs( - Cesium.Cartographic.fromCartesian( - loaded.dataSource.importedBillboards.get(0).position, - ).height - 2000, - ) < 1e-6, - ); - const sampled = starts.length; - viewer.camera.computeViewRectangle = () => undefined; - await loaded.refreshGround(); - assert.equal( - starts.length, - sampled, - 'distant points do not start a detailed mesh sweep', - ); - assert.ok( - Math.abs( - Cesium.Cartographic.fromCartesian( - loaded.dataSource.importedBillboards.get(0).position, - ).height - 2000, - ) < 1e-6, - 'the last valid mesh height survives outside the camera footprint', - ); - const point = loaded.dataSource.importedEntities[0]; - const other = new Cesium.Entity({ id: 'unrelated-aircraft' }); - viewer.trackedEntity = starts.length === 1 ? other : point; - viewer.selectedEntity = point; - loaded.revoke(); - assert.equal(viewer.selectedEntity, undefined); - assert.equal( - viewer.trackedEntity, - starts.length === 1 ? other : undefined, - ); - } + const loaded = await loadGeoFile( + new File( + [JSON.stringify({ type: 'Point', coordinates: [1, 2] })], + 'surface.geojson', + ), + { viewer: t.viewer }, + ); + loaded.mount(); + const height = () => [...importSet(t, 'pins').items.values()][0].pos.height; + assert.ok( + Math.abs(starts.at(-1)) < 1e-6, + `ray started at ${starts.at(-1)}`, + ); + assert.ok(Math.abs(height() - 2000) < 1e-6); + const sampled = starts.length; + t.camera.viewRectangle = () => ({ + west: 10, + south: 10, + east: 11, + north: 11, + }); + await loaded.refreshGround(); + assert.equal( + starts.length, + sampled, + 'distant points do not start a detailed mesh sweep', + ); + assert.ok( + Math.abs(height() - 2000) < 1e-6, + 'the last valid mesh height survives outside the camera footprint', + ); + loaded.revoke(); } finally { - Cesium.PinBuilder.prototype.fromColor = previous; + t.unbind(); } }); @@ -709,7 +699,7 @@ test('distinct style definitions and named StyleMaps still have a pre-loader bud assert.equal(countKmlGeometry(maps, { maxLinks: 1 }).over, 'links'); }); -test('KML extended metadata is removed before the document reaches the loader', () => { +test('KML extended metadata is removed before the document is read for drawing', () => { const point = xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2,0')]); const metadata = xmlEl('ExtendedData', {}, [ xmlEl('Data', { name: 'note' }, [xmlEl('value', {}, 'ordinary metadata')]), @@ -810,7 +800,7 @@ test('GPX keeps each track segment as its own line, names as text, no times', () assert.throws(() => gpxToGeoJson(xmlDoc(xmlEl('kml'))), GeoImportError); }); -test('GPX past the point limit is refused while reading, before Cesium', () => { +test('GPX past the point limit is refused while reading, before anything is drawn', () => { const seg = xmlEl( 'trkseg', {}, @@ -967,7 +957,7 @@ test('KML vertex counting recognizes the Unicode whitespace Cesium accepts', () } }); -test('KML multipart geometries count every Cesium entity before loading', () => { +test('KML multipart geometries count every map object before drawing', () => { const doc = xmlDoc( xmlEl('kml', {}, [ xmlEl('Placemark', {}, [ @@ -1050,69 +1040,47 @@ test('a KMZ image gets one blob URL however many hrefs name it', () => { assert.deepEqual(kept, ['blob:test/1', 'blob:test/2']); }); -test('imported entities keep only a short plain-text name: no description, label or properties', () => { - const ds = new Cesium.CustomDataSource('t'); - const e = ds.entities.add({ - name: 'Trail\u0007 head\n' + 'x'.repeat(300), - description: '', - label: { text: 'Trail head' }, - properties: { note: '' }, - position: Cesium.Cartesian3.fromDegrees(1, 2), - }); - e.kml = { extendedData: { note: { value: '