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.
This commit is contained in:
Sameh Khamis committed 2026-11-07 01:50:52 -08:00
1 parent 03ff8f291f
commit 2061f5647c
9 files changed
+186 -82

No files matched your search

+6
View File
@@ -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 M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or
destroying the layer cancels pending work and ignores late results. 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 ## Vessel components and sources
`src/data/aisLiveVessels.js` assembles `createVesselLayer` from the `src/data/aisLiveVessels.js` assembles `createVesselLayer` from the
+4
View File
@@ -5997,6 +5997,10 @@
"exports": ["./layers/air-quality"], "exports": ["./layers/air-quality"],
"modules": [ "modules": [
"src/layers/airQuality/index.js", "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/model.js",
"src/layers/airQuality/source.js", "src/layers/airQuality/source.js",
"src/sources/httpBody.js", "src/sources/httpBody.js",
@@ -7,6 +7,7 @@ import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js';
import { LayerPanel } from '../../ui/layerPanel.js'; import { LayerPanel } from '../../ui/layerPanel.js';
import { translateFeedError } from '../../ui/statusText.js'; import { translateFeedError } from '../../ui/statusText.js';
import { createAirQualityLayer } from './index.js'; import { createAirQualityLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function inLocale(locale, run) { function inLocale(locale, run) {
setLocale(locale); setLocale(locale);
@@ -22,7 +23,8 @@ function harness(source) {
source, source,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
}); });
const viewer = { dataSources: { add() {}, remove() {} } }; const viewer = {};
bindFakeDraw(viewer);
layer.init(viewer); layer.init(viewer);
layer.enable(viewer); layer.enable(viewer);
return layer; return layer;
+59 -62
View File
@@ -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 { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js'; import { translateFeedError } from '../../ui/statusText.js';
import { import {
@@ -22,6 +24,15 @@ const STATION_MARKER_RADIUS_M = 6_000;
/** Readings listed in the readout card. */ /** Readings listed in the readout card. */
const READOUT_LIMIT = 5; 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. */ /** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({ source, overlayHost } = {}) { export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function') 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'); if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
let _viewer = null; let _viewer = null;
let _request = null; let _request = null;
let _dataSource = null; let _markers = null;
let _readings = []; let _readings = [];
let _count = 0; let _count = 0;
let _lastUpdate = null; let _lastUpdate = null;
@@ -40,17 +51,8 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
const notify = () => rowControlsListener?.(); const notify = () => rowControlsListener?.();
/** The camera's lon/lat rectangle in degrees, or null when unresolvable. */ /** The camera's lon/lat rectangle in degrees, or null when unresolvable. */
const viewRectangle = () => { const viewRectangle = () =>
const rectangle = _viewer?.camera?.computeViewRectangle?.(); _viewer ? (findCamera(_viewer)?.viewRectangle() ?? null) : null;
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 layer = { const layer = {
id: 'air-quality', id: 'air-quality',
@@ -61,10 +63,11 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
init(viewer) { init(viewer) {
if (_viewer) throw new Error('Air quality layer is already initialized'); 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; _viewer = viewer;
_dataSource = new Cesium.CustomDataSource('air-quality');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_readings = []; _readings = [];
_count = 0; _count = 0;
_lastUpdate = null; _lastUpdate = null;
@@ -75,7 +78,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
enable() { enable() {
_enabled = true; _enabled = true;
if (_dataSource) _dataSource.show = true; if (_markers) _markers.show = true;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true); overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true);
notify(); notify();
}, },
@@ -85,14 +88,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
_request?.abort(); _request?.abort();
_request = null; _request = null;
_enabled = false; _enabled = false;
if (_dataSource) _dataSource.show = false; if (_markers) _markers.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID); overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false); overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
notify(); notify();
}, },
async update() { async update() {
if (!_enabled || !_dataSource) return false; if (!_enabled || !_markers) return false;
_request?.abort(); _request?.abort();
const request = new AbortController(); const request = new AbortController();
_request = request; _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() { _render() {
if (!_dataSource) return; if (!_markers) return;
_dataSource.entities.removeAll(); const markers = [];
const overlayEntries = []; const overlayEntries = [];
for (const reading of _readings) { for (const reading of _readings) {
const position = Cesium.Cartesian3.fromDegrees( const position = fromDegrees(reading.lon, reading.lat);
reading.lon, // A filled disc on the ground with static axes, as in the earthquake
reading.lat, // layer: a per-frame axis re-tessellates clamped ground geometry
); // every frame. No outline: clamped to the ground, the default
const color = Cesium.Color.fromCssColorString(reading.color); // renderer never drew one.
_dataSource.entities.add( markers.push({
new Cesium.Entity({ id: `air-quality:${reading.id}`,
id: `air-quality:${reading.id}`, geometry: {
position, kind: 'ellipse',
ellipse: { center: { lon: reading.lon, lat: reading.lat },
// Static axes, as in the earthquake layer: a per-frame axis semiMajor: STATION_MARKER_RADIUS_M,
// re-tessellates the clamped ground primitive every frame. semiMinor: STATION_MARKER_RADIUS_M,
semiMajorAxis: STATION_MARKER_RADIUS_M, },
semiMinorAxis: STATION_MARKER_RADIUS_M, fill: withAlpha(reading.color, 0.35),
material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)), height: 'clampGround',
outline: true, clampTo: 'both',
outlineColor: color.withAlpha(0.9), meta: {
outlineWidth: 2, provider: reading.provider,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, scale: reading.scale,
}, value: reading.value,
properties: { band: reading.band,
provider: reading.provider, name: reading.name,
scale: reading.scale, zone: reading.zone,
value: reading.value, risk: reading.risk,
band: reading.band, observedMs: reading.observedMs,
name: reading.name, note: reading.note,
zone: reading.zone, lat: reading.lat,
risk: reading.risk, lon: reading.lon,
observedMs: reading.observedMs, },
note: reading.note, });
lat: reading.lat,
lon: reading.lon,
},
}),
);
overlayEntries.push( overlayEntries.push(
createAirQualityOverlayEntry({ createAirQualityOverlayEntry({
id: reading.id, id: reading.id,
@@ -171,6 +169,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}), }),
); );
} }
_markers.set(markers);
if (_enabled) { if (_enabled) {
overlayHost.setEntries( overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID, AIR_QUALITY_OVERLAY_SOURCE_ID,
@@ -184,16 +183,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
} }
}, },
destroy(viewer = _viewer) { destroy() {
_request?.abort(); _request?.abort();
_request = null; _request = null;
_enabled = false; _enabled = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID); overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false); overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
if (_dataSource) { _markers?.dispose();
viewer?.dataSources?.remove(_dataSource, true); _markers = null;
_dataSource = null;
}
_viewer = null; _viewer = null;
_readings = []; _readings = [];
_count = 0; _count = 0;
+66 -17
View File
@@ -3,20 +3,12 @@ import test from 'node:test';
import { createAirQualityLayer } from './index.js'; import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js'; import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js'; import { STALE_AFTER_MS } from './model.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness(source) { function harness(source, renderer = {}) {
const sources = [];
const events = []; const events = [];
const viewer = { const viewer = {};
dataSources: { const { draw } = bindFakeDraw(viewer, renderer);
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const layer = createAirQualityLayer({ const layer = createAirQualityLayer({
source, source,
overlayHost: { overlayHost: {
@@ -29,7 +21,8 @@ function harness(source) {
}); });
layer.init(viewer); layer.init(viewer);
layer.enable(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 = {}) => ({ 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', () => { test('initialization is single-use and owns exactly one draw set', () => {
const { layer, viewer, sources } = harness(staticSource([])); const { layer, viewer, draw, markers } = harness(staticSource([]));
assert.equal(sources.length, 1); 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/); assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer); 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 () => { test('a refresh renders readings and publishes an overlay cohort', async () => {
+43
View File
@@ -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); 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 () => { test('the cyclones layer draws clamped dots, draped tracks and holed cones on a viewer of its own', async () => {
const { createCycloneRendering } = const { createCycloneRendering } =
await import('../../layers/cyclones/rendering.js'); await import('../../layers/cyclones/rendering.js');
-1
View File
@@ -38,7 +38,6 @@
"src/data/trailRenderer.js", "src/data/trailRenderer.js",
"src/input/dispatcher.js", "src/input/dispatcher.js",
"src/input/sensorPick.js", "src/input/sensorPick.js",
"src/layers/airQuality/index.js",
"src/layers/cctv/projection.js", "src/layers/cctv/projection.js",
"src/layers/cctv/rendering.js", "src/layers/cctv/rendering.js",
"src/layers/directions/index.js", "src/layers/directions/index.js",
+1
View File
@@ -83,6 +83,7 @@ const DRAW_FROM_CALLER = new Set([
'./layers/street-level/mapillary', './layers/street-level/mapillary',
'./layers/street-level/kartaview', './layers/street-level/kartaview',
'./layers/street-level/panoramax', './layers/street-level/panoramax',
'./layers/air-quality',
]); ]);
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
+4 -1
View File
@@ -6,6 +6,7 @@ import { setLocale } from '../i18n/index.js';
import { createWeatherPanel } from './weatherPanel.js'; import { createWeatherPanel } from './weatherPanel.js';
import { railDocumentFixture as railFixture } from './railTestFixture.mjs'; import { railDocumentFixture as railFixture } from './railTestFixture.mjs';
import { createAirQualityLayer } from '../layers/airQuality/index.js'; 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 ticks = ['2026-09-22T01:00:00Z', '2026-09-22T01:05:00Z'];
const wind = { const wind = {
id: 'wind', id: 'wind',
@@ -725,7 +726,9 @@ test('air-quality readout renders its band legend, Canada coverage and worst-fir
}, },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
}); });
layer.init({ dataSources: { add() {}, remove() {} } }); const viewer = {};
bindFakeDraw(viewer);
layer.init(viewer);
layer.enable(); layer.enable();
await layer.update(); await layer.update();
const f = fixture(); const f = fixture();