From bb3106991e972c159ff5ae753914b8d4ee222c8d Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Fri, 6 Nov 2026 18:44:56 -0800 Subject: [PATCH] Draw earthquakes through the renderer's draw port The earthquake discs are now one draw set of ground-clamped filled ellipses per layer, with the same colours, alphas and radii; they had no visible outline before either (Cesium turns outlines off on clamped entity ellipses). The layer and its model no longer import Cesium and leave the allow-list. depthColor now returns a renderer colour [r, g, b, a] rather than a Cesium colour, and depthAccent its CSS. A caller handing the layer a Cesium viewer of their own, with no renderer bound, first loads the new ./render/cesium/unbound export, which provides every unbound factory; the camera factory now loads the draw factory too, so entries that already load it draw as well. A fake draw port for layer tests comes with it. --- docs/CURRENT-STATE.md | 7 +- package.json | 2 +- scripts/package-boundaries.json | 29 ++++- src/data/earthquakes.test.mjs | 123 ++++++++++------------ src/data/infrastructure.test.mjs | 1 + src/layers/earthquakes/index.js | 90 +++++++++------- src/layers/earthquakes/model.js | 25 +++-- src/layers/earthquakes/ownership.test.mjs | 79 +++++++++++--- src/render/cesium/camera.js | 3 +- src/render/cesium/draw.js | 3 - src/render/cesium/draw.test.mjs | 37 +++++++ src/render/cesium/unbound.js | 9 ++ src/render/cesiumAllowList.json | 2 - src/render/rendererOf.js | 2 +- src/render/unboundCamera.test.mjs | 32 ++++-- src/testSupport/fakeDrawPort.mjs | 89 ++++++++++++++++ 16 files changed, 384 insertions(+), 149 deletions(-) create mode 100644 src/render/cesium/unbound.js create mode 100644 src/testSupport/fakeDrawPort.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index cf4711224..dd5d22bfb 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1091,8 +1091,11 @@ identity without announcing a new user selection. Source/label, LOD thresholds, card limits, fire identities, altitude placement and analyst records are retained. 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. diff --git a/package.json b/package.json index e19a63c36..cd98ee3f7 100644 --- a/package.json +++ b/package.json @@ -298,7 +298,7 @@ "./geo": "./src/geo/index.js", "./render/contract": "./src/render/contract/index.js", "./render/stub": "./src/render/stub/index.js", - "./render/cesium/draw": "./src/render/cesium/draw.js", + "./render/cesium/unbound": "./src/render/cesium/unbound.js", "./render/conformance": "./src/render/conformance/index.js" } } diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 95af5853e..8cc7df77d 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -9,6 +9,7 @@ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -872,6 +873,7 @@ "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1003,6 +1005,7 @@ "src/styles/thermal.js", "src/ui/applicationShell.js", "src/render/cesium/effects.js", + "src/render/cesium/draw.js", "src/data/followed.js", "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", @@ -1274,6 +1277,7 @@ "src/scenes/director.js", "src/data/followed.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1419,6 +1423,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1513,6 +1518,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1668,9 +1674,11 @@ ], "external": ["cesium"] }, - "render-cesium-draw": { - "exports": ["./render/cesium/draw"], + "render-cesium-unbound": { + "exports": ["./render/cesium/unbound"], "modules": [ + "src/render/cesium/unbound.js", + "src/render/cesium/effects.js", "src/render/cesium/draw.js", "src/render/cesium/camera.js", "src/render/camera/events.js", @@ -1695,6 +1703,9 @@ "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" @@ -1811,6 +1822,7 @@ "src/layers/satellites/testing.js", "src/layers/satellites/tracking.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1860,6 +1872,7 @@ "src/layers/launches/controls.js", "src/layers/launches/index.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1927,6 +1940,7 @@ "src/data/installationNames.js", "src/layers/installations/controls.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2011,6 +2025,7 @@ "src/layers/awareness/dependencies.js", "src/layers/awareness/focus.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/cameraInput.js", "src/render/cesium/credits.js", @@ -2201,6 +2216,7 @@ "src/layers/cctv/modelSpecs.js", "src/layers/cctv/navigation.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2270,6 +2286,7 @@ "modules": [ "src/layers/streetLevel/index.js", "src/render/cesium/credits.js", + "src/render/cesium/draw.js", "src/geo/index.js", "src/layers/streetLevel/credits.js", "src/render/creditMarkup.js", @@ -2367,6 +2384,7 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2443,6 +2461,7 @@ "src/layers/radio/navigation.js", "src/data/followed.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2504,6 +2523,7 @@ "src/geo/index.js", "src/layers/submarineCables/interaction.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2592,6 +2612,7 @@ "src/render/cesium/globe.js", "src/render/cesium/credits.js", "src/render/cesium/tileRequests.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraInput.js", "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", @@ -3791,6 +3812,7 @@ "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/follow.js", "src/data/bhoteKoshiIncidentPlaces.js", @@ -4440,6 +4462,7 @@ "src/layers/firms/anchors.js", "src/locations.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/cameraInput.js", "src/render/cesium/credits.js", @@ -4549,6 +4572,7 @@ "src/geo/index.js", "src/ui/navigationController.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/cameraInput.js", "src/render/cesium/credits.js", @@ -5080,6 +5104,7 @@ "src/cyberSonar.js", "src/celestialRing.js", "src/render/cesium/camera.js", + "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", diff --git a/src/data/earthquakes.test.mjs b/src/data/earthquakes.test.mjs index 87f9ffd7b..4f7c897d1 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'; @@ -20,6 +22,10 @@ import { _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', @@ -93,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 () => ({ @@ -135,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']); @@ -148,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], @@ -165,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() {} }, }); @@ -197,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); @@ -224,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() {} }, }); @@ -265,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. @@ -299,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( @@ -311,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() {} }, }); @@ -341,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() {}, } }); @@ -359,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'); @@ -383,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'); @@ -392,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/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 36ee961f7..5e9c518fc 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -195,6 +195,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'credits.js', 'ctrlWheelZoom.js', 'dispatcher.js', + 'draw.js', 'events.js', 'follow.js', 'heights.js', diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 023c3017b..3db74cf52 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -1,9 +1,11 @@ -import * as Cesium from 'cesium'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { drawOf } from '../../render/rendererOf.js'; import { EARTHQUAKE_OVERLAY_SOURCE_ID, EARTHQUAKE_OVERLAY_COHORT_LIMIT, EARTHQUAKE_OVERLAY_COLLISION_CAPACITY, depthColor, + depthAccent, createEarthquakeOverlayEntry, selectEarthquakeOverlayCohort, mapAnalystRecord, @@ -15,15 +17,29 @@ export { createUsgsEarthquakeSource } from './source.js'; // panel shows it translated. const msg = (text) => text; -/** Own one earthquake display and its refresh lifecycle. */ +/** + * The draw sets the discs are drawn in start with this; each layer has its + * own (`earthquakes:1`, …), so several can share a renderer. Picks name it + * as `Hit.set`. + */ +export const EARTHQUAKE_DISC_SET_ID = 'earthquakes'; +let instances = 0; + +/** + * Own one earthquake display and its refresh lifecycle. + * + * The discs are one renderer draw set (`drawOf(viewer)`), made at `init`. + * Given a Cesium viewer with no renderer bound, the + * caller loads the package's `./render/cesium/unbound` export first. + */ export function createEarthquakesLayer({ source, overlayHost } = {}) { if (typeof source?.getSnapshot !== 'function') throw new TypeError('Earthquakes require a snapshot source'); if (!overlayHost) throw new TypeError('Earthquakes require an overlay host'); let _viewer = null; let _request = null; - let _dataSource = null; - // What the discs were drawn from, so analyst reads come from the app, not the entities. + let _discs = null; + // What the discs were drawn from, so analyst reads come from the app, not the drawing. let _events = []; let _count = 0; let _lastUpdate = null; @@ -39,10 +55,11 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { init(viewer) { if (_viewer) throw new Error('Earthquake layer is already initialized'); + _discs = drawOf(viewer).shapes({ + id: `${EARTHQUAKE_DISC_SET_ID}:${++instances}`, + show: false, + }); _viewer = viewer; - _dataSource = new Cesium.CustomDataSource('earthquakes'); - _dataSource.show = false; - viewer.dataSources.add(_dataSource); _count = 0; _lastUpdate = null; _lastError = null; @@ -55,7 +72,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _enabled = true; // No continuous-render hold: the discs are static geometry now, so the // layer has no per-frame animator to keep the render loop alive for. - if (_dataSource) _dataSource.show = true; + if (_discs) _discs.show = true; overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true); }, @@ -63,13 +80,13 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _request?.abort(); _request = null; _enabled = false; - if (_dataSource) _dataSource.show = false; + if (_discs) _discs.show = false; overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); }, async update(viewer) { - if (!_enabled || !_dataSource) return false; + if (!_enabled || !_discs) return false; _request?.abort(); const request = new AbortController(); _request = request; @@ -78,7 +95,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { if (request.signal.aborted || _request !== request || !_enabled) return false; - const nextEntities = []; + const nextDiscs = []; const nextEvents = []; let count = 0; const overlayEntries = []; @@ -96,43 +113,38 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { count++; const baseRadius = Math.pow(2, mag) * 1000; const color = depthColor(depthKm || 0); + const [r, g, b] = color; const isSignificant = mag >= 5.0; const fillAlpha = isSignificant ? 0.4 : 0.3; - const outlineAlpha = isSignificant ? 1.0 : 0.8; - const position = Cesium.Cartesian3.fromDegrees(lon, lat); + const position = fromDegrees(lon, lat); nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat }); - nextEntities.push( - new Cesium.Entity({ - id: `earthquake:${stableId}`, - position, - ellipse: { - // Static axes — see the module header. A CallbackProperty here - // re-tessellates the clamped ground geometry every frame. - semiMajorAxis: baseRadius, - semiMinorAxis: baseRadius, - material: new Cesium.ColorMaterialProperty( - color.withAlpha(fillAlpha), - ), - outline: true, - outlineColor: color.withAlpha(outlineAlpha), - outlineWidth: isSignificant ? 3 : 2, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - }, - }), - ); + // A filled disc on the ground, with static axes: re-tessellating + // clamped ground geometry every frame is what once cost 30 fps. + // No outline: clamped to the ground, Cesium never drew one. + nextDiscs.push({ + id: `earthquake:${stableId}`, + geometry: { + kind: 'ellipse', + center: { lon, lat }, + semiMajor: baseRadius, + semiMinor: baseRadius, + }, + fill: [r, g, b, fillAlpha], + height: 'clampGround', + clampTo: 'both', + }); overlayEntries.push( createEarthquakeOverlayEntry({ id: String(stableId), position, magnitude: mag, - accent: color.toCssColorString(), + accent: depthAccent(depthKm || 0), }), ); } - _dataSource.entities.removeAll(); - for (const entity of nextEntities) _dataSource.entities.add(entity); + _discs.set(nextDiscs); _events = nextEvents; if (_enabled) { overlayHost.setEntries( @@ -169,10 +181,8 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _enabled = false; overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); - if (_dataSource) { - viewer.dataSources.remove(_dataSource, true); - _dataSource = null; - } + _discs?.dispose(); + _discs = null; _events = []; _count = 0; _lastUpdate = null; @@ -188,7 +198,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { * @returns {Array} See mapAnalystRecord for the record shape. */ getAnalystRecords(maxCount = 2000) { - if (!_dataSource || !_enabled || !_events.length) return []; + if (!_discs || !_enabled || !_events.length) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) : 2000; diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js index c88063b7b..86eca72d4 100644 --- a/src/layers/earthquakes/model.js +++ b/src/layers/earthquakes/model.js @@ -1,27 +1,40 @@ -import * as Cesium from 'cesium'; export const EARTHQUAKE_OVERLAY_SOURCE_ID = 'earthquakes'; export const EARTHQUAKE_OVERLAY_COHORT_LIMIT = 96; export const EARTHQUAKE_OVERLAY_COLLISION_CAPACITY = 48; +// The depth bands' colours: CSS red, orange and yellow, as the renderer's +// colour tuples (`[r, g, b, a]`, 0..1) and as CSS for the labels' accent. +const SHALLOW = Object.freeze({ rgba: [1, 0, 0, 1], css: 'rgb(255,0,0)' }); +const INTERMEDIATE = Object.freeze({ + rgba: [1, 165 / 255, 0, 1], + css: 'rgb(255,165,0)', +}); +const DEEP = Object.freeze({ rgba: [1, 1, 0, 1], css: 'rgb(255,255,0)' }); + +const depthBand = (depthKm) => + depthKm < 70 ? SHALLOW : depthKm < 300 ? INTERMEDIATE : DEEP; + /** - * Color by depth: + * Color by depth, as a renderer colour `[r, g, b, a]` (0..1): * - Shallow (<70km): Red * - Intermediate (70-300km): Orange * - Deep (>300km): Yellow */ export function depthColor(depthKm) { - if (depthKm < 70) return Cesium.Color.RED; - if (depthKm < 300) return Cesium.Color.ORANGE; - return Cesium.Color.YELLOW; + return [...depthBand(depthKm).rgba]; } +/** The depth band's colour as CSS, for the magnitude label's accent. */ +export const depthAccent = (depthKm) => depthBand(depthKm).css; + /** * Build the source-owned presentation for one ambient magnitude label. * Magnitude formatting deliberately remains here instead of moving into the * shared renderer. * @param {object} input * @param {string} input.id Stable USGS or deterministic fallback id. - * @param {Cesium.Cartesian3} input.position Ground anchor shared with the pulse. + * @param {{x: number, y: number, z: number}} input.position ECEF ground + * anchor, shared with the disc. * @param {number} input.magnitude USGS magnitude. * @param {string} input.accent Source-owned depth-band color. * @returns {object} diff --git a/src/layers/earthquakes/ownership.test.mjs b/src/layers/earthquakes/ownership.test.mjs index b13cc005e..45fd35dad 100644 --- a/src/layers/earthquakes/ownership.test.mjs +++ b/src/layers/earthquakes/ownership.test.mjs @@ -2,19 +2,11 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createEarthquakesLayer } from './index.js'; import { createUsgsEarthquakeSource } from './source.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function harness(source) { - const sources = []; const events = []; - const viewer = { - dataSources: { - add(value) { - sources.push(value); - }, - remove(value) { - sources.splice(sources.indexOf(value), 1); - }, - }, - }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer); const layer = createEarthquakesLayer({ source, overlayHost: { @@ -27,7 +19,7 @@ function harness(source) { }); layer.init(viewer); layer.enable(viewer); - return { layer, viewer, sources, events }; + return { layer, viewer, draw, events }; } const row = { stableId: 'event-a', @@ -61,17 +53,19 @@ test('late refresh cannot publish after disable, re-enable, or destroy', async ( h.layer.destroy(h.viewer); } }); -test('two displays own separate data sources and destruction', async () => { +test('two displays own separate draw sets and destruction', async () => { const a = harness({ getSnapshot: async () => [row] }); const b = harness({ getSnapshot: async () => [] }); await a.layer.update(a.viewer); await b.layer.update(b.viewer); assert.equal(a.layer.getStats().count, 1); assert.equal(b.layer.getStats().count, 0); + assert.equal(a.draw.find('earthquakes:').items.size, 1); a.layer.destroy(); - assert.equal(a.sources.length, 0); - assert.equal(b.sources.length, 1); + assert.equal(a.draw.find('earthquakes:'), undefined, 'disposed'); + assert.equal(b.draw.find('earthquakes:').items.size, 0); b.layer.destroy(); + assert.equal(b.draw.find('earthquakes:'), undefined); }); test('USGS body completion honors cancellation even with an uncooperative transport', async () => { const abort = new AbortController(); @@ -117,9 +111,60 @@ test('analyst records come from the events the layer drew, and only while it is }, ]); assert.equal(h.layer.getAnalystRecords(1).length, 1); - const [entity] = h.sources[0].entities.values; - assert.equal(entity.properties, undefined, 'the entity carries drawing only'); + const [disc] = h.draw.find('earthquakes:').items.values(); + assert.equal(disc.meta, undefined, 'the disc carries drawing only'); h.layer.disable(h.viewer); assert.deepEqual(h.layer.getAnalystRecords(), []); h.layer.destroy(h.viewer); }); +test('two layers share one renderer, each with its own disc set', async () => { + const events = []; + const overlayHost = { + setEntries: (...args) => events.push(args), + setVisible() {}, + clearSource() {}, + }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + const a = createEarthquakesLayer({ + source: { getSnapshot: async () => [row] }, + overlayHost, + }); + const b = createEarthquakesLayer({ + source: { getSnapshot: async () => [] }, + overlayHost, + }); + a.init(viewer); + b.init(viewer); + a.enable(viewer); + b.enable(viewer); + await a.update(viewer); + await b.update(viewer); + const live = [...draw.sets.values()].filter((set) => !set.disposed); + assert.equal(live.length, 2); + assert.deepEqual( + live.map((set) => set.items.size), + [1, 0], + ); + a.destroy(); + a.init(viewer); + assert.equal( + [...draw.sets.values()].filter((set) => !set.disposed).length, + 2, + 'destroyed, then started again', + ); + a.destroy(); + b.destroy(); +}); +test('a viewer with nothing to draw with is refused at init, and init can be retried', () => { + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [] }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + const viewer = {}; + assert.throws(() => layer.init(viewer), /no renderer to draw with/); + const { unbind } = bindFakeDraw(viewer); + layer.init(viewer); + layer.destroy(); + unbind(); +}); diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 4dc2f08b5..47e979312 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -12,8 +12,9 @@ import { cameraFlightActive } from './internals.js'; import { createCesiumFollow } from './follow.js'; import { createCesiumControls } from './cameraControls.js'; import { cameraOf, findCamera, provideUnboundCamera } from '../rendererOf.js'; -// Loads the factory an unbound viewer gets its credits port from. +// Loads the factories an unbound viewer gets its credits and draw ports from. import './credits.js'; +import './draw.js'; /** * `cameraOf` and `findCamera`, for code that already reaches Cesium: diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 697e686f5..c25956202 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -22,9 +22,6 @@ import * as Cesium from 'cesium'; import { provideUnboundDraw } from '../rendererOf.js'; import { listenerList, toCartesian, uncaught } from './common.js'; -// A caller loads this module for a viewer of its own; what draws there -// flies through `cameraOf` too, so the camera factory comes with it. -import './camera.js'; /** The contract's colour as Cesium's. */ export function toColor(color, alpha = 1) { diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 12bc5cd13..3f0def823 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -322,3 +322,40 @@ test('clamped shapes refuse what they cannot draw', () => { ); set.dispose(); }); + +test('the earthquakes layer draws its discs as ground fills on a viewer of its own', async () => { + const { createEarthquakesLayer } = + await import('../../layers/earthquakes/index.js'); + const scene = fakeScene(); + const viewer = { scene }; + const row = (stableId, lon, mag) => ({ + stableId, + usgsId: stableId, + lon, + lat: 0, + depthKm: 10, + mag, + place: null, + time: null, + }); + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [row('a', 0, 5), row('b', 0.2, 3)] }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + layer.init(viewer); + layer.enable(viewer); + assert.equal(await layer.update(viewer), true); + const host = scene.added[0]; + const grounds = []; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) + grounds.push(host.get(i)); + // Overlapping discs: one batch each, as the entities' batches had them. + assert.equal(grounds.length, 2); + const [instance] = grounds[0].geometryInstances; + assert.ok(instance.geometry instanceof Cesium.EllipseGeometry); + assert.equal(instance.id.id, 'earthquake:a'); + assert.equal(grounds[0].classificationType, Cesium.ClassificationType.BOTH); + layer.destroy(); + assert.equal(scene.added.length, 0); +}); diff --git a/src/render/cesium/unbound.js b/src/render/cesium/unbound.js new file mode 100644 index 000000000..9b0100ce7 --- /dev/null +++ b/src/render/cesium/unbound.js @@ -0,0 +1,9 @@ +/** + * @module render/cesium/unbound + * @description What to load, once, before handing the Cesium-free + * layers a Cesium viewer with no renderer bound: the factories + * that build a camera, credits, effects and draw port over such a viewer + * when code first asks for one (`rendererOf.js`). + */ +import './camera.js'; +import './effects.js'; diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index afd65e7e9..04adac958 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -70,8 +70,6 @@ "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", "src/layers/directions/index.js", - "src/layers/earthquakes/index.js", - "src/layers/earthquakes/model.js", "src/layers/firms/cards.js", "src/layers/firms/lifecycle.js", "src/layers/firms/model.js", diff --git a/src/render/rendererOf.js b/src/render/rendererOf.js index 389e1c77a..587eb85da 100644 --- a/src/render/rendererOf.js +++ b/src/render/rendererOf.js @@ -248,7 +248,7 @@ export function drawOf(host) { host?.isDestroyed?.() ? 'This scene has been destroyed' : 'This scene has no renderer to draw with: bind one, or load the ' + - "Cesium adapter's draw port (render/cesium/draw.js) for a viewer " + + "Cesium adapter's factories (the ./render/cesium/unbound export) for a viewer " + 'with no renderer bound', ); } diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 113c0b6db..dd00c73e1 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -9,9 +9,10 @@ * `render/cesium/effects.js`, which provides the effects factory, and one * that reaches a caller of `findGlobe` must load `render/cesium/globe.js`. * An entry that reaches a caller of `findDraw` or `drawOf` loads - * `render/cesium/draw.js` the same way, unless it is Cesium-free: then it - * is listed in `DRAW_FROM_CALLER`, and a caller handing it a viewer of - * their own loads the package's `./render/cesium/draw` export once. + * `render/cesium/draw.js` the same way (the camera factory loads it), + * unless it is Cesium-free: then it is listed in `DRAW_FROM_CALLER`, and + * a caller handing it a viewer with no renderer bound loads the package's + * `./render/cesium/unbound` export once. * * The graph is every static import, re-export and literal dynamic import of * the entry's module and those it reaches, read by the parsers the Cesium @@ -34,6 +35,7 @@ const FACTORY = 'src/render/cesium/camera.js'; const EFFECTS_FACTORY = 'src/render/cesium/effects.js'; const GLOBE_FACTORY = 'src/render/cesium/globe.js'; const DRAW_FACTORY = 'src/render/cesium/draw.js'; +const UNBOUND = 'src/render/cesium/unbound.js'; /** * Entries that take their Cesium code injected: the module named here is @@ -57,10 +59,12 @@ const FALLS_BACK = new Set(['src/data/followed.js']); /** * Cesium-free entries that draw through `drawOf`: their own modules cannot * load the Cesium adapter (the Cesium ratchet), so a viewer with no - * renderer bound draws once its owner has loaded `./render/cesium/draw`; - * until then `drawOf` throws, naming it, rather than draw nothing. + * renderer bound draws once its owner has loaded `./render/cesium/unbound`; + * until then `drawOf` throws, naming it, rather than draw nothing. That + * export loads the camera factory too, so these entries' camera is the + * caller's to load the same way. */ -const DRAW_FROM_CALLER = new Set([]); +const DRAW_FROM_CALLER = new Set(['./layers/earthquakes']); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); @@ -171,6 +175,7 @@ test('every public entry that reaches the renderer bridge loads the unbound came bridged += 1; const carrier = INJECTED[key]; const loads = (file) => reachable(file, { eager: true }).has(FACTORY); + if (DRAW_FROM_CALLER.has(key)) continue; if (!loads(entry) && !(carrier && loads(carrier))) missing.push(key); } assert.ok(bridged > 0, 'no entry reaches the bridge: the walk is broken'); @@ -220,6 +225,17 @@ test('every public entry that reaches a findGlobe caller loads the unbound globe checkLookupFactory('findGlobe', GLOBE_FACTORY, { reached: false }); }); +test('the unbound export brings every unbound factory', () => { + const loaded = reachable(UNBOUND, { eager: true }); + for (const factory of [ + FACTORY, + EFFECTS_FACTORY, + DRAW_FACTORY, + 'src/render/cesium/credits.js', + ]) + assert.ok(loaded.has(factory), factory); +}); + test('every public entry that reaches a findDraw caller loads the unbound draw factory, or its caller can', () => { const missing = []; const callsFindDraw = (file) => @@ -227,8 +243,8 @@ test('every public entry that reaches a findDraw caller loads the unbound draw f /\.(m?js|vue)$/.test(file) && /\b(findDraw|drawOf)\(/.test(readFileSync(path.join(root, file), 'utf8')); assert.equal( - pkg.exports['./render/cesium/draw'], - `./${DRAW_FACTORY}`, + pkg.exports['./render/cesium/unbound'], + `./${UNBOUND}`, 'the factory loads through this export', ); for (const [key, declaration] of Object.entries(pkg.exports)) { diff --git a/src/testSupport/fakeDrawPort.mjs b/src/testSupport/fakeDrawPort.mjs new file mode 100644 index 000000000..b8c61ac1e --- /dev/null +++ b/src/testSupport/fakeDrawPort.mjs @@ -0,0 +1,89 @@ +/** + * A draw port (`src/render/contract/draw.d.ts`) that keeps what it is + * given, for layer tests: each set's spec, items by id, `show` and whether + * it was disposed. `bindFakeDraw` binds it to a viewer double, as the + * application binds its renderer, so the layer's `drawOf(viewer)` finds it. + */ +import { bindRenderer } from '../render/rendererOf.js'; + +export function fakeDrawPort() { + const sets = new Map(); + const make = (kind) => (spec) => { + const live = sets.get(spec.id); + if (live && !live.disposed) + throw new Error(`a set with id ${spec.id} is live`); + const record = { + kind, + spec: { ...spec }, + items: new Map(), + show: spec.show !== false, + disposed: false, + writes: 0, + }; + sets.set(spec.id, record); + const write = (fn) => { + if (record.disposed) throw new Error(`set ${spec.id} is disposed`); + fn(); + record.writes += 1; + }; + return { + id: spec.id, + set: (items) => + write(() => { + record.items.clear(); + for (const item of items) record.items.set(item.id, item); + }), + upsert: (items) => + write(() => { + for (const item of items) record.items.set(item.id, item); + }), + remove: (ids) => + write(() => { + for (const id of ids) record.items.delete(id); + }), + clear: () => write(() => record.items.clear()), + setOptions(options) { + Object.assign(record.spec, options); + if ('show' in options) record.show = options.show !== false; + }, + size: () => record.items.size, + get show() { + return record.show; + }, + set show(value) { + record.show = value; + }, + on: () => () => {}, + dispose() { + record.disposed = true; + }, + }; + }; + return { + sets, + /** The live set with this id, or undefined. */ + set: (id) => (sets.get(id)?.disposed ? undefined : sets.get(id)), + /** The live set whose id starts with `prefix`, or undefined. */ + find: (prefix) => + [...sets.values()].find( + (record) => !record.disposed && record.spec.id.startsWith(prefix), + ), + icons: make('icons'), + points: make('points'), + lines: make('lines'), + shapes: make('shapes'), + clampState: () => 'draped', + on: () => () => {}, + atlas() {}, + }; +} + +/** + * Bind a fake draw port to `viewer`; `renderer` adds other ports. + * @returns {{draw: ReturnType, unbind: () => void}} + */ +export function bindFakeDraw(viewer, renderer = {}) { + const draw = fakeDrawPort(); + const unbind = bindRenderer(viewer, { ...renderer, draw }); + return { draw, unbind }; +}