From 2061f5647c40273f1241d633cd4030112179f6ba Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 01:47:55 -0800 Subject: [PATCH] Draw the air quality stations through the renderer's draw port The station discs are now one draw set of ground-clamped filled ellipses per layer, with the same band colours, alpha and radius, and their readings as item meta; they had no visible outline before either (Cesium turns outlines off on clamped entity ellipses). The readout's in-view list reads the view rectangle through the camera port. The layer no longer imports Cesium and leaves the allow-list; a caller handing it a Cesium viewer of their own, with no renderer bound, loads the ./render/cesium/unbound export once first. Double-clicking a station no longer starts the viewer's entity follow, since draw items are not entities. --- docs/CURRENT-STATE.md | 6 + scripts/package-boundaries.json | 4 + .../airQuality/airQualityLocale.test.mjs | 4 +- src/layers/airQuality/index.js | 121 +++++++++--------- src/layers/airQuality/ownership.test.mjs | 83 +++++++++--- src/render/cesium/draw.test.mjs | 43 +++++++ src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 1 + src/ui/weatherPanel.test.mjs | 5 +- 9 files changed, 186 insertions(+), 82 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index d36bbe144..ccbcf8e78 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1103,6 +1103,12 @@ colour `[r, g, b, a]` and `depthAccent` its CSS. The standalone adapter keeps th M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or destroying the layer cancels pending work and ignores late results. +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, +own, with no renderer bound, loads the `./render/cesium/unbound` export once +first. + ## Vessel components and sources `src/data/aisLiveVessels.js` assembles `createVesselLayer` from the diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 93212a729..f2c313561 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -5997,6 +5997,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", diff --git a/src/layers/airQuality/airQualityLocale.test.mjs b/src/layers/airQuality/airQualityLocale.test.mjs index 66f4942f4..c5b765cbd 100644 --- a/src/layers/airQuality/airQualityLocale.test.mjs +++ b/src/layers/airQuality/airQualityLocale.test.mjs @@ -7,6 +7,7 @@ import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js'; import { LayerPanel } from '../../ui/layerPanel.js'; import { translateFeedError } from '../../ui/statusText.js'; import { createAirQualityLayer } from './index.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function inLocale(locale, run) { setLocale(locale); @@ -22,7 +23,8 @@ function harness(source) { source, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, }); - const viewer = { dataSources: { add() {}, remove() {} } }; + const viewer = {}; + bindFakeDraw(viewer); layer.init(viewer); layer.enable(viewer); return layer; diff --git a/src/layers/airQuality/index.js b/src/layers/airQuality/index.js index febee5423..0754a9e95 100644 --- a/src/layers/airQuality/index.js +++ b/src/layers/airQuality/index.js @@ -1,4 +1,6 @@ -import * as Cesium from 'cesium'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { cssColor } from '../../render/color.js'; +import { drawOf, findCamera } from '../../render/rendererOf.js'; import { msg, t, tn } from '../../i18n/index.js'; import { translateFeedError } from '../../ui/statusText.js'; import { @@ -22,6 +24,15 @@ const STATION_MARKER_RADIUS_M = 6_000; /** Readings listed in the readout card. */ const READOUT_LIMIT = 5; +export const AIR_QUALITY_MARKER_SET_ID = 'air-quality'; +let instances = 0; + +/** A reading's colour at `alpha`; an unreadable colour falls back to white. */ +function withAlpha(css, alpha) { + const [r, g, b] = cssColor(css) ?? [1, 1, 1]; + return [r, g, b, alpha]; +} + /** Own one air-quality display, its refresh lifecycle, and its readout card. */ export function createAirQualityLayer({ source, overlayHost } = {}) { if (typeof source?.getSnapshot !== 'function') @@ -29,7 +40,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { if (!overlayHost) throw new TypeError('Air quality requires an overlay host'); let _viewer = null; let _request = null; - let _dataSource = null; + let _markers = null; let _readings = []; let _count = 0; let _lastUpdate = null; @@ -40,17 +51,8 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { const notify = () => rowControlsListener?.(); /** The camera's lon/lat rectangle in degrees, or null when unresolvable. */ - const viewRectangle = () => { - const rectangle = _viewer?.camera?.computeViewRectangle?.(); - if (!rectangle) return null; - const toDeg = Cesium.Math.toDegrees; - return { - west: toDeg(rectangle.west), - south: toDeg(rectangle.south), - east: toDeg(rectangle.east), - north: toDeg(rectangle.north), - }; - }; + const viewRectangle = () => + _viewer ? (findCamera(_viewer)?.viewRectangle() ?? null) : null; const layer = { id: 'air-quality', @@ -61,10 +63,11 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { init(viewer) { if (_viewer) throw new Error('Air quality layer is already initialized'); + _markers = drawOf(viewer).shapes({ + id: `${AIR_QUALITY_MARKER_SET_ID}:${++instances}`, + show: false, + }); _viewer = viewer; - _dataSource = new Cesium.CustomDataSource('air-quality'); - _dataSource.show = false; - viewer.dataSources.add(_dataSource); _readings = []; _count = 0; _lastUpdate = null; @@ -75,7 +78,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { enable() { _enabled = true; - if (_dataSource) _dataSource.show = true; + if (_markers) _markers.show = true; overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true); notify(); }, @@ -85,14 +88,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { _request?.abort(); _request = null; _enabled = false; - if (_dataSource) _dataSource.show = false; + if (_markers) _markers.show = false; overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID); overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false); notify(); }, async update() { - if (!_enabled || !_dataSource) return false; + if (!_enabled || !_markers) return false; _request?.abort(); const request = new AbortController(); _request = request; @@ -120,47 +123,42 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { } }, - /** Rebuild entities and overlay labels from the current readings. */ + /** Redraw the station markers and overlay labels from the current readings. */ _render() { - if (!_dataSource) return; - _dataSource.entities.removeAll(); + if (!_markers) return; + const markers = []; const overlayEntries = []; for (const reading of _readings) { - const position = Cesium.Cartesian3.fromDegrees( - reading.lon, - reading.lat, - ); - const color = Cesium.Color.fromCssColorString(reading.color); - _dataSource.entities.add( - new Cesium.Entity({ - id: `air-quality:${reading.id}`, - position, - ellipse: { - // Static axes, as in the earthquake layer: a per-frame axis - // re-tessellates the clamped ground primitive every frame. - semiMajorAxis: STATION_MARKER_RADIUS_M, - semiMinorAxis: STATION_MARKER_RADIUS_M, - material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)), - outline: true, - outlineColor: color.withAlpha(0.9), - outlineWidth: 2, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - }, - properties: { - provider: reading.provider, - scale: reading.scale, - value: reading.value, - band: reading.band, - name: reading.name, - zone: reading.zone, - risk: reading.risk, - observedMs: reading.observedMs, - note: reading.note, - lat: reading.lat, - lon: reading.lon, - }, - }), - ); + const position = fromDegrees(reading.lon, reading.lat); + // A filled disc on the ground with static axes, as in the earthquake + // layer: a per-frame axis re-tessellates clamped ground geometry + // every frame. No outline: clamped to the ground, the default + // renderer never drew one. + markers.push({ + id: `air-quality:${reading.id}`, + geometry: { + kind: 'ellipse', + center: { lon: reading.lon, lat: reading.lat }, + semiMajor: STATION_MARKER_RADIUS_M, + semiMinor: STATION_MARKER_RADIUS_M, + }, + fill: withAlpha(reading.color, 0.35), + height: 'clampGround', + clampTo: 'both', + meta: { + provider: reading.provider, + scale: reading.scale, + value: reading.value, + band: reading.band, + name: reading.name, + zone: reading.zone, + risk: reading.risk, + observedMs: reading.observedMs, + note: reading.note, + lat: reading.lat, + lon: reading.lon, + }, + }); overlayEntries.push( createAirQualityOverlayEntry({ id: reading.id, @@ -171,6 +169,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { }), ); } + _markers.set(markers); if (_enabled) { overlayHost.setEntries( AIR_QUALITY_OVERLAY_SOURCE_ID, @@ -184,16 +183,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) { } }, - destroy(viewer = _viewer) { + destroy() { _request?.abort(); _request = null; _enabled = false; overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID); overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false); - if (_dataSource) { - viewer?.dataSources?.remove(_dataSource, true); - _dataSource = null; - } + _markers?.dispose(); + _markers = null; _viewer = null; _readings = []; _count = 0; diff --git a/src/layers/airQuality/ownership.test.mjs b/src/layers/airQuality/ownership.test.mjs index 78ab8a0bb..0eb3df8cd 100644 --- a/src/layers/airQuality/ownership.test.mjs +++ b/src/layers/airQuality/ownership.test.mjs @@ -3,20 +3,12 @@ import test from 'node:test'; import { createAirQualityLayer } from './index.js'; import { layerFeedState } from '../../data/feedState.js'; import { STALE_AFTER_MS } from './model.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; -function harness(source) { - const sources = []; +function harness(source, renderer = {}) { const events = []; - const viewer = { - dataSources: { - add(value) { - sources.push(value); - }, - remove(value) { - sources.splice(sources.indexOf(value), 1); - }, - }, - }; + const viewer = {}; + const { draw } = bindFakeDraw(viewer, renderer); const layer = createAirQualityLayer({ source, overlayHost: { @@ -29,7 +21,8 @@ function harness(source) { }); layer.init(viewer); layer.enable(viewer); - return { layer, viewer, sources, events }; + const markers = () => draw.find('air-quality:'); + return { layer, viewer, draw, markers, events }; } const reading = (id, value, overrides = {}) => ({ @@ -61,12 +54,68 @@ test('a layer requires both a snapshot source and an overlay host', () => { ); }); -test('initialization is single-use and owns exactly one data source', () => { - const { layer, viewer, sources } = harness(staticSource([])); - assert.equal(sources.length, 1); +test('initialization is single-use and owns exactly one draw set', () => { + const { layer, viewer, draw, markers } = harness(staticSource([])); + const owned = markers(); + assert.equal(owned.kind, 'shapes'); + assert.equal( + [...draw.sets.values()].filter((set) => !set.disposed).length, + 1, + ); assert.throws(() => layer.init(viewer), /already initialized/); layer.destroy(viewer); - assert.equal(sources.length, 0); + assert.equal(owned.disposed, true); +}); + +test('stations are ground discs in their band colour, shown only while enabled', async () => { + const { layer, markers } = harness( + staticSource([reading('A', 2), reading('B', 7, { color: '#c1121f' })]), + ); + assert.equal(await layer.update(), true); + const set = markers(); + assert.equal(set.show, true); + assert.deepEqual( + [...set.items.keys()], + ['air-quality:eccc:A', 'air-quality:eccc:B'], + ); + const disc = set.items.get('air-quality:eccc:B'); + assert.deepEqual(disc.geometry, { + kind: 'ellipse', + center: { lon: -79.38, lat: 43.65 }, + semiMajor: 6_000, + semiMinor: 6_000, + }); + assert.equal(disc.height, 'clampGround'); + assert.equal(disc.clampTo, 'both'); + assert.deepEqual(disc.fill, [0xc1 / 255, 0x12 / 255, 0x1f / 255, 0.35]); + assert.equal(disc.outline, undefined); + assert.equal(disc.meta.name, 'B'); + assert.equal(disc.meta.value, 7); + layer.disable(); + assert.equal(set.show, false); + layer.enable(); + assert.equal(set.show, true); + assert.equal(await layer.update(), true); + assert.equal(set.items.size, 2, 'a refresh replaces, not appends'); +}); + +test('the readout lists only readings inside the camera port view rectangle', async () => { + const { layer } = harness( + staticSource([ + reading('Toronto', 2), + reading('Vancouver', 4, { lat: 49.28, lon: -123.12 }), + ]), + { + camera: { + viewRectangle: () => ({ west: -90, south: 40, east: -70, north: 50 }), + }, + }, + ); + await layer.update(); + assert.deepEqual( + layer.getRowControls().list.items.map((item) => item.text), + ['Toronto ยท Low health risk'], + ); }); test('a refresh renders readings and publishes an overlay cohort', async () => { diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 374f3fc32..7472bb8ee 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -431,6 +431,49 @@ test('the earthquakes layer draws its discs as ground fills on a viewer of its o assert.equal(scene.added.length, 0); }); +test('the air quality layer draws its stations as ground fills on a viewer of its own', async () => { + const { createAirQualityLayer } = + await import('../../layers/airQuality/index.js'); + const scene = fakeScene(); + const viewer = { scene }; + const reading = (id, lon) => ({ + id, + provider: 'eccc', + scale: 'AQHI', + value: 3, + band: 'low', + name: id, + lat: 45, + lon, + observedMs: 0, + color: '#4cc9f0', + label: '3', + risk: 'Low health risk', + note: null, + }); + const layer = createAirQualityLayer({ + source: { getSnapshot: async () => [reading('a', -75), reading('b', -60)] }, + 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)); + const instances = grounds.flatMap((ground) => ground.geometryInstances); + assert.deepEqual(instances.map((instance) => instance.id.id).sort(), [ + 'air-quality:a', + 'air-quality:b', + ]); + assert.ok(instances[0].geometry instanceof Cesium.EllipseGeometry); + assert.equal(grounds[0].classificationType, Cesium.ClassificationType.BOTH); + layer.destroy(); + assert.equal(scene.added.length, 0); +}); + test('the cyclones layer draws clamped dots, draped tracks and holed cones on a viewer of its own', async () => { const { createCycloneRendering } = await import('../../layers/cyclones/rendering.js'); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 01c8e79d0..ee8520b4a 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -38,7 +38,6 @@ "src/data/trailRenderer.js", "src/input/dispatcher.js", "src/input/sensorPick.js", - "src/layers/airQuality/index.js", "src/layers/cctv/projection.js", "src/layers/cctv/rendering.js", "src/layers/directions/index.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index a4fa2cd0d..6767477fe 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -83,6 +83,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/street-level/mapillary', './layers/street-level/kartaview', './layers/street-level/panoramax', + './layers/air-quality', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/ui/weatherPanel.test.mjs b/src/ui/weatherPanel.test.mjs index d3e3d30cb..b3978e070 100644 --- a/src/ui/weatherPanel.test.mjs +++ b/src/ui/weatherPanel.test.mjs @@ -6,6 +6,7 @@ import { setLocale } from '../i18n/index.js'; import { createWeatherPanel } from './weatherPanel.js'; import { railDocumentFixture as railFixture } from './railTestFixture.mjs'; import { createAirQualityLayer } from '../layers/airQuality/index.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; const ticks = ['2026-09-22T01:00:00Z', '2026-09-22T01:05:00Z']; const wind = { id: 'wind', @@ -725,7 +726,9 @@ test('air-quality readout renders its band legend, Canada coverage and worst-fir }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, }); - layer.init({ dataSources: { add() {}, remove() {} } }); + const viewer = {}; + bindFakeDraw(viewer); + layer.init(viewer); layer.enable(); await layer.update(); const f = fixture();