Draw nine layers' fills through engine.ground, one display each

Earthquakes, air quality, GNSS Integrity, fire perimeters, Prohibited &
Restricted Airspace, Active Fires, S2 GhostMaps, cyclone advisories and
submarine cables each have one render/display.js on the globe contract;
their render/cesium* and render/navara* files go. Their discs, cells,
polygons and corridors are engine.ground sets, so on Navara they come from
the one ground screen pass with exact colours instead of nine hand-written
classification passes and lit SDK vector layers. Cesium's look stays the
reference:

- Earthquake and air-quality discs have no outline (Cesium drew none on
  clamped ellipses); earthquake discs can now be picked on Navara too.
- Perimeters, drone zones and GhostMaps polygons outline their outer
  ring only, as Cesium did.
- GNSS cells stay out of the pick pass; cyclone cones, tracks and centres
  are culled by a port of Cesium's horizon occluder.
- Submarine cables are one ground corridor set, as Cesium batched them;
  landing points, tips and stems are movers and lines.
- FIRMS glows are a sprite set and its cells a ground set. The far-zoom
  heat raster, which no primitive draws yet, sits behind one seam,
  render/heatField.js, with a Cesium and a Navara backend.

The shared Navara ground helpers that only these layers used go
(navaraGroundCells, the cell and ground geometry, the zone renderers), as
does the ground prototype script.

Coupling: layer renderer lines fall from 1636/6953 to 1011/4832
(Cesium/Navara), Navara ground passes from 7 to 5, Cesium-importing files
from 65 to 53, engine.extensions reads from 26 to 19.
This commit is contained in:
German Khokhlov committed 2026-11-07 06:20:48 +04:00
1 parent 974a0b6361
commit 54fe0aea40
124 files changed
+8407 -9576

No files matched your search

@@ -6,6 +6,7 @@ import { setLocale, t } from '../../i18n/index.js';
import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js';
import { LayerPanel } from '../../ui/layerPanel.js';
import { translateFeedError } from '../../ui/statusText.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
import { createAirQualityLayer } from './index.js';
function inLocale(locale, run) {
@@ -22,9 +23,8 @@ function harness(source) {
source,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const viewer = { dataSources: { add() {}, remove() {} } };
layer.init(viewer);
layer.enable(viewer);
layer.init(null, { engine: createFakeEngine() });
layer.enable();
return layer;
}
+5 -5
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/cartesian3.js';
import { toDegrees } from '../../geo/math.js';
import { createAirQualityCesiumRenderer } from './render/cesium.js';
import { createAirQualityDisplay } from './render/display.js';
import { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
@@ -28,7 +28,7 @@ const READOUT_LIMIT = 5;
export function createAirQualityLayer({
source,
overlayHost,
createRenderer = createAirQualityCesiumRenderer,
createRenderer = ({ engine }) => createAirQualityDisplay(engine),
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Air quality requires a snapshot source');
@@ -69,7 +69,7 @@ export function createAirQualityLayer({
throw new Error('Air quality layer is already initialized');
initialized = true;
try {
if (viewer || engine) this.attachRenderer(viewer, { engine });
if (engine) this.attachRenderer(viewer, { engine });
} catch (error) {
this.destroy();
throw error;
@@ -79,7 +79,7 @@ export function createAirQualityLayer({
attachRenderer(viewer, { engine = null } = {}) {
if (!initialized || renderer)
throw new Error('Invalid air quality scene attachment');
renderer = createRenderer({ viewer, engine });
renderer = createRenderer({ engine });
renderer.setVisible(_enabled);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, _enabled);
if (_readings.length) this._render();
@@ -139,7 +139,7 @@ export function createAirQualityLayer({
}
},
/** Rebuild entities and overlay labels from the current readings. */
/** Redraw the station discs and overlay labels from the current readings. */
_render() {
if (!renderer) return;
renderer.replace(_readings, STATION_MARKER_RADIUS_M);
+17 -25
View File
@@ -1,22 +1,14 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFakeGroundHarness } from '../../testSupport/groundDisplayEngines.mjs';
import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js';
function harness(source) {
const sources = [];
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const ground = createFakeGroundHarness();
const { engine } = ground;
const layer = createAirQualityLayer({
source,
overlayHost: {
@@ -27,9 +19,9 @@ function harness(source) {
clearSource() {},
},
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
layer.init(null, { engine });
layer.enable();
return { layer, engine, ground, events };
}
const reading = (id, value, overrides = {}) => ({
@@ -61,12 +53,12 @@ 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);
assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer);
assert.equal(sources.length, 0);
test('initialization is single-use and owns exactly one ground set', () => {
const { layer, engine, ground } = harness(staticSource([]));
assert.equal(ground.sets(), 1);
assert.throws(() => layer.init(null, { engine }), /already initialized/);
layer.destroy();
assert.equal(ground.sets(), 0);
});
test('a refresh renders readings and publishes an overlay cohort', async () => {
@@ -188,14 +180,14 @@ test('the readout reports an error rather than a silent empty card', async () =>
});
test('row-control listeners are notified on refresh and teardown-safe', async () => {
const { layer, viewer } = harness(staticSource([reading('A', 2)]));
const { layer } = harness(staticSource([reading('A', 2)]));
let calls = 0;
layer.setRowControlsListener(() => {
calls += 1;
});
await layer.update();
assert.ok(calls >= 1, 'a refresh notifies the card');
layer.destroy(viewer);
layer.destroy();
const after = calls;
layer.setRowControlsListener(() => {
calls += 1;
@@ -284,13 +276,13 @@ test('station data stays queryable and attaches to a fresh scene without polling
});
try {
h.layer.detachRenderer();
assert.equal(h.sources.length, 0);
assert.equal(h.ground.sets(), 0);
assert.equal(await h.layer.update(), true);
assert.equal(h.events.length, 0);
assert.equal(h.layer.getAnalystRecords()[0].value, 7);
h.layer.attachRenderer(h.viewer);
h.layer.attachRenderer(null, { engine: h.engine });
assert.equal(h.events.at(-1)[0], 'air-quality');
assert.equal(h.sources[0].entities.values.length, 1);
assert.equal(h.ground.set('air-quality').items.length, 1);
assert.equal(polls, 1);
} finally {
h.layer.destroy();
-56
View File
@@ -1,56 +0,0 @@
import * as Cesium from 'cesium';
export function createAirQualityCesiumRenderer({ viewer }) {
const dataSource = new Cesium.CustomDataSource('air-quality');
dataSource.show = false;
viewer.dataSources.add(dataSource);
return {
viewRectangle: () => viewer.camera?.computeViewRectangle?.(),
setVisible(visible) {
dataSource.show = visible;
},
replace(readings, radius) {
dataSource.entities.removeAll();
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: radius,
semiMinorAxis: radius,
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,
},
}),
);
}
},
destroy() {
viewer.dataSources.remove(dataSource, true);
},
};
}
+55
View File
@@ -0,0 +1,55 @@
// The air-quality stations on the globe contract (engine.ground,
// engine.camera), the same on every engine: one ground disc per reading,
// of the layer's marker radius, filled in its band colour at 0.35, picked
// as `air-quality:${id}`. No outline: Cesium draws none on a ground-clamped
// ellipse, so none showed on either engine.
import { rgbaFromCss } from '../../shared/color.js';
const SET_ID = 'air-quality';
const FILL_ALPHA = 0.35;
/** What a pick of a station disc returns. */
export const airQualityPickId = (reading) => `air-quality:${reading.id}`;
/**
* The station discs: `{ viewRectangle, setVisible, replace(readings,
* radiusM), destroy }`. viewRectangle() is the camera's (radians), or
* undefined when the globe is out of view.
* @param {import('../../../globe/contract.js').GlobeEngine} engine
*/
export function createAirQualityDisplay(engine) {
if (!engine?.ground)
throw new TypeError('The air-quality display needs a globe engine');
const set = engine.ground.createSet({
id: SET_ID,
kind: 'disc',
pickable: true,
});
set.show(false);
let destroyed = false;
return {
viewRectangle: () =>
destroyed ? undefined : engine.camera.viewRectangle(),
setVisible(visible) {
if (!destroyed) set.show(visible);
},
replace(readings, radiusM) {
if (destroyed) return;
set.replace(
readings.map((reading) => ({
center: [reading.lon, reading.lat],
radiusM,
fill: rgbaFromCss(reading.color).withAlpha(FILL_ALPHA).rgba(),
pickId: airQualityPickId(reading),
})),
);
set.commit();
},
destroy() {
if (destroyed) return;
destroyed = true;
set.destroy();
},
};
}
@@ -0,0 +1,180 @@
// The air-quality stations on the engine contract, on the fake engine and
// on the Cesium engine (its ground batches over fake primitives): a 6 km
// disc per reading in its band colour at 0.35, no outline, picks, the view
// rectangle the readout reads, visibility through the layer and teardown.
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import {
GROUND_HARNESSES,
createFakeGroundHarness,
instanceColor,
} from '../../../testSupport/groundDisplayEngines.mjs';
import { rgbaFromCss } from '../../shared/color.js';
import { createAirQualityLayer } from '../index.js';
import { createAirQualityDisplay } from './display.js';
const reading = (id, value, lon, lat, color) => ({
id: `eccc:${id}`,
provider: 'eccc',
scale: 'AQHI',
value,
band: 'low',
stationId: id,
name: id,
zone: 'ont',
lat,
lon,
observedMs: Date.now() - 10 * 60_000,
color,
label: String(value),
risk: 'Low health risk',
note: null,
});
const readings = [
reading('Toronto', 2, -79.38, 43.65, '#4cc9f0'),
reading('Hamilton', 8, -79.87, 43.26, '#ff6b35'),
];
const RADIUS_M = 6_000;
function fixture(makeHarness) {
const h = makeHarness();
const entries = [];
const layer = createAirQualityLayer({
source: { getSnapshot: async () => readings },
overlayHost: {
setEntries: (...args) => entries.push(args),
setVisible() {},
clearSource() {},
},
});
layer.init(null, { engine: h.engine });
layer.enable();
return { ...h, layer, entries };
}
const near = (actual, expected, label, tolerance = 1e-9) =>
assert.ok(
Math.abs(actual - expected) < tolerance,
`${label}: ${actual} vs ${expected}`,
);
test('the display needs a globe engine', () => {
assert.throws(() => createAirQualityDisplay(null), TypeError);
});
for (const makeHarness of GROUND_HARNESSES) {
const { name } = makeHarness();
test(`each reading is a 6 km ground disc in its band colour at 0.35, without an outline (${name})`, async () => {
const f = fixture(makeHarness);
try {
assert.equal(await f.layer.update(), true);
const set = f.set('air-quality');
assert.equal(set.options.kind, 'disc');
assert.equal(set.options.pickable, true);
assert.equal(set.shown, true);
assert.deepEqual(
set.items.map(({ center, radiusM, pickId, outline }) => ({
center,
radiusM,
pickId,
outline,
})),
readings.map((row) => ({
center: [row.lon, row.lat],
radiusM: RADIUS_M,
pickId: `air-quality:${row.id}`,
outline: undefined,
})),
);
set.items.forEach(({ fill }, index) => {
const expected = rgbaFromCss(readings[index].color)
.withAlpha(0.35)
.rgba();
fill.forEach((channel, at) =>
near(channel, expected[at], `fill ${index}.${at}`),
);
});
assert.equal(f.entries.at(-1)[0], 'air-quality', 'labels published');
if (f.cesium) {
const { fills, lines } = f.primitives('air-quality');
assert.equal(fills.length, 1, 'one ground batch');
assert.equal(lines.length, 0, 'no outline batch');
assert.equal(
fills[0].options.classificationType,
Cesium.ClassificationType.BOTH,
);
fills[0].options.geometryInstances.forEach((instance, index) => {
assert.ok(instance.geometry instanceof Cesium.EllipseGeometry);
assert.equal(instance.geometry._semiMajorAxis, RADIUS_M);
const expected = rgbaFromCss(readings[index].color)
.withAlpha(0.35)
.rgba();
instanceColor(instance).forEach((channel, at) =>
near(channel, expected[at], `colour ${index}.${at}`, 0.5 / 255),
);
});
}
f.layer.disable();
assert.equal(f.set('air-quality').shown, false);
if (f.cesium) assert.equal(f.collectionShown('air-quality'), false);
f.layer.enable();
assert.equal(f.set('air-quality').shown, true);
} finally {
f.layer.destroy();
}
assert.equal(f.sets(), 0);
f.destroy();
});
test(`the readout lists the readings in the camera's view (${name})`, async () => {
const f = fixture(makeHarness);
try {
f.engine.camera.setView({
destination: geo.cartesian3.fromDegrees(-79.38, 43.65, 30_000),
});
await f.layer.update();
assert.deepEqual(
f.layer.getRowControls().list.items.map((item) => item.text),
['Toronto · Low health risk'],
'Hamilton is out of a 30 km high view over Toronto',
);
} finally {
f.layer.destroy();
f.destroy();
}
});
}
test('a pick of a station names its reading (the fake engine)', async () => {
const f = fixture(createFakeGroundHarness);
try {
await f.layer.update();
f.engine.camera.setView({
destination: geo.cartesian3.fromDegrees(-79.87, 43.26, 50_000),
});
const { width, height } = f.engine.host.size();
const picked = f.engine.picker.pick({ x: width / 2, y: height / 2 });
assert.equal(picked.id, 'air-quality:eccc:Hamilton');
assert.equal(picked.owner, 'air-quality');
} finally {
f.layer.destroy();
f.destroy();
}
});
test('the display ignores calls after destroy and destroys once', () => {
const h = createFakeGroundHarness();
const display = createAirQualityDisplay(h.engine);
assert.equal(h.set('air-quality').shown, false, 'hidden until shown');
display.destroy();
display.destroy();
assert.equal(h.sets(), 0);
display.setVisible(true);
display.replace(readings, RADIUS_M);
assert.equal(display.viewRectangle(), undefined);
h.destroy();
});
-62
View File
@@ -1,62 +0,0 @@
import { createNavaraPolygonDisplay } from '../../shared/render/navaraPolygons.js';
import * as geo from '../../../geo/index.js';
function stationFeature(reading, radius) {
const origin = geo.cartesian3.fromDegrees(reading.lon, reading.lat);
const frame = geo.transforms.eastNorthUpToFixedFrame(origin);
const ring = [];
for (let i = 0; i < 48; i++) {
const angle = (i * 2 * Math.PI) / 48;
const local = geo.cartesian3.create(
radius * Math.cos(angle),
radius * Math.sin(angle),
0,
);
const world = geo.matrix4.multiplyByPoint(
frame,
local,
geo.cartesian3.create(),
);
const point = geo.cartographic.fromCartesian(world);
ring.push([
geo.math.toDegrees(point.longitude),
geo.math.toDegrees(point.latitude),
]);
}
ring.push(ring[0]);
return {
type: 'Feature',
id: `air-quality:${reading.id}`,
properties: { ...reading },
geometry: { type: 'Polygon', coordinates: [ring] },
};
}
/** One native GeoJSON layer per AQHI colour, independent of station count. */
export function createAirQualityNavaraRenderer(engine, { view }) {
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polygon: {
color,
transparent: true,
opacity: 0.35,
clampToGround: true,
outline: true,
outlineShow: true,
outlineColor: color,
outlineWidth: 2,
},
}));
return {
viewRectangle: () => engine.camera.viewRectangle(),
setVisible: display.setVisible,
destroy: display.destroy,
replace(rows, radius) {
const groups = new Map();
for (const row of rows) {
if (!groups.has(row.color)) groups.set(row.color, []);
groups.get(row.color).push(stationFeature(row, radius));
}
display.replace(groups);
},
};
}