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

+618
View File
@@ -0,0 +1,618 @@
// The FIRMS display on the fake engine and on the Cesium engine over a stub
// scene: the same calls, the same drawing, read back from each engine's own
// store (the fake's mover and ground sets, Cesium's billboards and ground
// primitives).
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { createFakeEventHandlers } from '../../../globe/cesium/testing/fakeViewer.mjs';
import { createCesiumMoversEngine } from '../../../testSupport/cesiumMoversEngine.mjs';
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
import { constantRgba } from '../../shared/color.js';
import { createFirmsDisplay } from './display.js';
import { FIRMS_SPRITE_ORDER } from './sprites.js';
const settle = async () => {
for (let i = 0; i < 4; i++) await new Promise((r) => setImmediate(r));
};
const FIRE = { lon: -98.2, lat: 30.5 };
const at = (lon, lat, height = 0) =>
geo.cartesian3.fromDegrees(lon, lat, height);
// Glow PNGs as their size: `glow-<side>`.
const loadImage = async (url) => {
const side = Number(url.split('-')[1]);
return { width: side, height: side };
};
const createCanvas = () => ({
width: 0,
height: 0,
getContext: () => ({ drawImage() {} }),
});
// What each ground set was given, by id.
function watchGround(engine) {
const items = new Map();
const createSet = engine.ground.createSet.bind(engine.ground);
engine.ground.createSet = (options) => {
const set = createSet(options);
const { replace } = set;
set.replace = (next) => {
replace(next);
items.set(options.id, next);
};
return set;
};
return {
items: (id) => items.get(id) ?? [],
listed: (id) => engine.ground.list().find((entry) => entry.id === id),
};
}
function fakeHarness() {
const engine = createFakeEngine();
engine.fake.setPose({
longitude: geo.math.toRadians(FIRE.lon),
latitude: geo.math.toRadians(FIRE.lat),
height: 2_000_000,
});
const ground = watchGround(engine);
return {
name: 'the fake engine',
engine,
ground,
/** The sprite set as drawn: its options and shown instances. */
sprites(id) {
const set = engine.fake.moverSet(id);
if (!set) return null;
const { store, options } = set;
return {
options,
count: store.count,
instances: Array.from({ length: store.count }, (_, i) => ({
show: store.shows[i] === 1,
scale: store.scales[i],
alpha: store.colors[i * 4 + 3],
pickId: store.pickIds[i],
})),
};
},
click(picked) {
engine.fake.script('pick', picked);
engine.fake.script('drillPick', picked ? [picked] : []);
engine.fake.input('click', { position: { x: 10, y: 20 } });
engine.fake.unscript('pick');
engine.fake.unscript('drillPick');
},
pickOf: (setId, instance, pickId) => ({
id: pickId,
owner: setId,
instance,
}),
destroy: () => engine.destroy(),
};
}
function cesiumHarness() {
const handlers = createFakeEventHandlers();
const { engine, viewer, primitive } = createCesiumMoversEngine({
engineOptions: {
createEventHandler: handlers.create,
scheduleFrame: (run) => run(),
},
});
viewer.scene.groundPrimitives = new Cesium.PrimitiveCollection();
engine.camera.setView({ destination: at(FIRE.lon, FIRE.lat, 2_000_000) });
let native;
viewer.scene.pick = () => native;
viewer.scene.drillPick = () => (native ? [native] : []);
const ground = watchGround(engine);
return {
name: 'the Cesium engine',
engine,
viewer,
ground,
sprites(id) {
const collection = primitive(id);
if (!collection) return null;
const listed = engine.movers.list().find((entry) => entry.id === id);
const count = listed?.count ?? 0;
return {
collection,
count,
instances: Array.from({ length: count }, (_, i) => {
const billboard = collection.get(i);
return {
show: billboard.show,
scale: billboard.scale,
alpha: billboard.color.alpha,
pickId: billboard.id,
billboard,
};
}),
};
},
/** The Cesium ground primitives of a set. */
groundPrimitives(id) {
const root = viewer.scene.groundPrimitives.get(0);
for (let i = 0; i < (root?.length ?? 0); i++) {
const slot = root.get(i);
const values = Array.from({ length: slot.length }, (_, j) =>
slot.get(j),
);
if (values.some((value) => value.gevGroundSet === id))
return { slot, values };
}
return null;
},
click(picked) {
native = picked;
for (const handler of handlers.handlers)
handler.fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, {
position: new Cesium.Cartesian2(10, 20),
});
native = undefined;
},
// A Cesium pick of the instance's billboard.
pickOf(setId, instance) {
const billboard = primitive(setId).get(instance);
return { primitive: billboard, id: billboard.id };
},
destroy: () => engine.destroy(),
};
}
const HARNESSES = [fakeHarness, cesiumHarness];
const display = (h, options = {}) =>
createFirmsDisplay(h.engine, {
id: 'firms-fixture',
loadImage,
createCanvas,
...options,
});
for (const make of HARNESSES) {
const name = make().name;
test(`${name}: cells are one ground cell set in each cell's colour, committed once per batch`, async () => {
const h = make();
try {
const r = display(h);
const id = 'firms-fixture:cells';
assert.equal(h.ground.listed(id).shown, false, 'hidden until shown');
r.setVisible(true);
assert.equal(h.ground.listed(id).shown, true);
r.clearCells();
r.addCell({
west: 179,
south: 40,
east: 180,
north: 42,
color: constantRgba(1, 165 / 255, 0, 0.66),
position: at(179.5, 41),
properties: { count: 7 },
});
r.addCell({
west: 0,
south: 0,
east: 1,
north: 1,
color: constantRgba(1, 0, 0, 0.3),
});
assert.equal(r.cellCount(), 0, 'drawn on the next microtask');
await settle();
assert.equal(r.cellCount(), 2);
assert.deepEqual(h.ground.items(id)[0], {
west: 179,
south: 40,
east: 180,
north: 42,
fill: [1, 165 / 255, 0, 0.66],
});
if (h.groundPrimitives) {
const { values } = h.groundPrimitives(id);
assert.equal(values.length, 1, 'fills only: no outline');
const [fills] = values;
assert.equal(fills.classificationType, Cesium.ClassificationType.BOTH);
assert.equal(fills.gevPickable, false, 'cells stay out of picks');
const rectangle = fills.geometryInstances[0].geometry._rectangle;
assert.ok(
Math.abs(rectangle.west - Cesium.Math.toRadians(179)) < 1e-12,
);
assert.ok(
Math.abs(rectangle.north - Cesium.Math.toRadians(42)) < 1e-12,
);
assert.deepEqual(
Array.from(fills.geometryInstances[0].attributes.color.value),
[255, 165, 0, Math.round(0.66 * 255)],
);
}
r.setVisible(false);
assert.equal(h.ground.listed(id).shown, false);
assert.equal(r.dataSource.show, false);
r.clearCells();
await settle();
assert.equal(r.cellCount(), 0);
r.destroy();
assert.equal(h.ground.listed(id), undefined);
} finally {
h.destroy();
}
});
test(`${name}: glows are one sprite set at their own size, over the scene, in the firms sprite slot`, async () => {
const h = make();
try {
const r = display(h);
r.setVisible(true);
const collection = r.ensureSprites();
assert.equal(collection, r.ensureSprites());
const small = r.addSprite({
id: 'firms-0',
position: at(FIRE.lon, FIRE.lat),
image: 'glow-16',
});
r.addSprite({
id: 'firms-1',
position: at(FIRE.lon + 1, FIRE.lat),
image: 'glow-56',
});
assert.equal(collection.length, 2);
await settle();
const drawn = h.sprites('firms:firms-fixture');
assert.equal(drawn.count, 2);
assert.ok(Math.abs(drawn.instances[0].scale - 16 / 56) < 1e-7);
assert.equal(drawn.instances[1].scale, 1);
assert.deepEqual(
drawn.instances.map((i) => i.pickId),
['firms-0', 'firms-1'],
);
assert.deepEqual(
drawn.instances.map((i) => i.alpha),
[1, 1],
);
assert.equal(FIRMS_SPRITE_ORDER, SPRITE_LAYER_ORDER.indexOf('firms'));
if (drawn.options) {
assert.equal(drawn.options.order, FIRMS_SPRITE_ORDER);
assert.equal(drawn.options.depthTest, 'always');
assert.equal(drawn.options.pickable, true);
assert.equal(drawn.options.sharpen, true);
assert.equal(drawn.options.sprite.sizePx, 56);
} else {
const { billboard } = drawn.instances[0];
assert.equal(billboard.disableDepthTestDistance, Infinity);
assert.equal(billboard.width, 56);
assert.equal(billboard.verticalOrigin, Cesium.VerticalOrigin.CENTER);
assert.equal(
billboard.horizontalOrigin,
Cesium.HorizontalOrigin.CENTER,
);
}
// The horizon cull flips one marker: only that instance is rewritten.
small.show = false;
await settle();
assert.deepEqual(
h.sprites('firms:firms-fixture').instances.map((i) => i.show),
[false, true],
);
r.setVisible(false);
await settle();
assert.equal(
h.sprites('firms:firms-fixture').count,
0,
'hidden: none drawn',
);
r.setVisible(true);
await settle();
assert.deepEqual(
h.sprites('firms:firms-fixture').instances.map((i) => i.show),
[false, true],
);
collection.removeAll();
await settle();
assert.equal(h.sprites('firms:firms-fixture').count, 0);
r.removeSprites();
assert.equal(h.sprites('firms:firms-fixture'), null);
assert.equal(r.addSprite({ id: 'late', image: 'glow-16' }), null);
r.destroy();
} finally {
h.destroy();
}
});
test(`${name}: the hand-off fades every marker and hides them all once the heatmap is whole`, async () => {
const h = make();
try {
const r = display(h);
r.setVisible(true);
r.ensureSprites();
r.addSprite({
id: 'firms-0',
position: at(FIRE.lon, FIRE.lat),
image: 'glow-56',
});
r.addSprite({
id: 'firms-1',
position: at(FIRE.lon, FIRE.lat + 1),
image: 'glow-56',
});
await settle();
r.fadeSprites(0.25, true);
await settle();
assert.deepEqual(
h.sprites('firms:firms-fixture').instances.map((i) => i.alpha),
[0.25, 0.25],
);
r.fadeSprites(0, false);
await settle();
assert.equal(
h.sprites('firms:firms-fixture').count,
0,
'the heatmap alone: no marker',
);
r.fadeSprites(1, true);
await settle();
assert.deepEqual(
h.sprites('firms:firms-fixture').instances.map((i) => i.alpha),
[1, 1],
);
r.destroy();
} finally {
h.destroy();
}
});
test(`${name}: clicks reach the layer with the pick under them while it shows, and release on destroy`, async () => {
const h = make();
try {
const r = display(h);
r.ensureSprites();
r.addSprite({
id: 'firms-7',
position: at(FIRE.lon, FIRE.lat),
image: 'glow-56',
});
r.setVisible(true);
await settle();
const clicks = [];
const remove = r.onClick((event) => clicks.push(event));
h.click(h.pickOf('firms:firms-fixture', 0, 'firms-7'));
assert.equal(clicks.length, 1);
assert.equal(clicks[0].picked.id, 'firms-7');
assert.deepEqual(
{ x: clicks[0].position.x, y: clicks[0].position.y },
{ x: 10, y: 20 },
);
h.click(undefined);
assert.equal(clicks.length, 2, 'a click on nothing is the layer’s too');
assert.equal(clicks[1].picked, undefined);
r.setVisible(false);
h.click(undefined);
assert.equal(clicks.length, 2, 'a hidden layer takes no click');
r.setVisible(true);
remove();
remove();
h.click(undefined);
assert.equal(clicks.length, 2, 'removed');
r.onClick((event) => clicks.push(event));
r.destroy();
h.click(undefined);
assert.equal(clicks.length, 2, 'destroy releases every subscription');
} finally {
h.destroy();
}
});
test(`${name}: the camera, projection, view rectangle and horizon are the engine's`, () => {
const h = make();
try {
const r = display(h);
const pose = h.engine.camera.pose();
assert.ok(
Math.abs(
r.view.camera.positionCartographic.height - pose.cartographic.height,
) < 1e-6,
);
assert.ok(
geo.cartesian3.equalsEpsilon(
r.view.camera.positionWC,
pose.position,
0,
1e-6,
),
);
assert.equal(r.view.camera.moveEnd, h.engine.camera.moveEnd);
assert.equal(r.view.scene.preRender, h.engine.frames.preRender);
const near = at(FIRE.lon, FIRE.lat);
assert.deepEqual(
r.project(near, {}),
h.engine.projector.worldToWindow(near, {}),
);
assert.deepEqual(r.viewRectangle({}), {
...h.engine.camera.viewRectangle(),
});
const far = at(FIRE.lon + 180, -FIRE.lat);
assert.equal(r.horizon().isPointVisible(near), true);
assert.equal(r.horizon().isPointVisible(far), false);
r.destroy();
} finally {
h.destroy();
}
});
test(`${name}: an image that decodes after hide or destroy draws nothing`, async () => {
const h = make();
try {
let finish;
const r = display(h, {
loadImage: () => new Promise((resolve) => (finish = resolve)),
});
r.ensureSprites();
r.addSprite({
id: 'firms-0',
position: at(FIRE.lon, FIRE.lat),
image: 'glow-16',
});
r.setVisible(true);
await settle();
r.setVisible(false);
finish({ width: 16, height: 16 });
await settle();
assert.equal(h.sprites('firms:firms-fixture'), null);
r.setVisible(true);
await settle();
assert.equal(
h.sprites('firms:firms-fixture').count,
1,
'the decoded image draws once shown',
);
r.destroy();
r.destroy();
assert.equal(h.sprites('firms:firms-fixture'), null);
assert.equal(h.engine.movers.list().length, 0);
assert.equal(h.engine.ground.list().length, 0);
assert.equal(r.ensureSprites(), null);
assert.equal(r.createHeatImagery(), null);
} finally {
h.destroy();
}
});
}
test('the fake engine: clearing rows during a decode commits only the replacement', async () => {
const h = fakeHarness();
try {
const complete = new Map();
const r = display(h, {
loadImage: (url) => new Promise((resolve) => complete.set(url, resolve)),
});
r.setVisible(true);
const sprites = r.ensureSprites();
r.addSprite({ id: 'old', position: at(0, 0), image: 'glow-16' });
await settle();
sprites.removeAll();
r.addSprite({ id: 'new', position: at(0, 1), image: 'glow-56' });
await settle();
complete.get('glow-16')({ width: 16, height: 16 });
await settle();
assert.equal(h.sprites('firms:firms-fixture'), null);
complete.get('glow-56')({ width: 56, height: 56 });
await settle();
const drawn = h.engine.fake.moverSet('firms:firms-fixture');
assert.equal(drawn.store.count, 1);
assert.equal(drawn.store.pickIds[0], 'new');
assert.equal(drawn.commits, 1);
r.destroy();
} finally {
h.destroy();
}
});
test('the heatmap: the Cesium engine drapes one imagery layer on the viewer, the host when there is one', () => {
const priorDocument = globalThis.document;
globalThis.document = {
createElement: () => ({
getContext: () => ({
createImageData: (w, hh) => ({
data: new Uint8ClampedArray(w * hh * 4),
}),
putImageData() {},
}),
toDataURL: () => 'data:image/png;base64,AAAA',
}),
};
const h = cesiumHarness();
try {
const layers = (added) => ({
addImageryProvider(provider) {
const layer = { provider, show: true, alpha: 1 };
added.push(layer);
return layer;
},
remove: (layer) => added.splice(added.indexOf(layer), 1),
raiseToTop() {},
});
const onViewer = [];
h.viewer.imageryLayers = layers(onViewer);
const onHost = [];
let host = null;
const r = display(h);
const heat = r.createHeatImagery(() => host);
const raster = { width: 2, height: 1, rgba: new Uint8ClampedArray(8) };
heat.setRaster(raster);
assert.equal(heat.hasRaster(), true);
assert.equal(onViewer.length, 1, 'no host: the viewer’s imagery layers');
assert.ok(onViewer[0].provider instanceof Cesium.SingleTileImageryProvider);
heat.setOpacity(0.5);
heat.setShow(false);
assert.deepEqual([onViewer[0].alpha, onViewer[0].show], [0.5, false]);
host = { kind: 'tiles', collection: layers(onHost) };
heat.rehome();
assert.deepEqual(
[onViewer.length, onHost.length],
[0, 1],
'it follows the host',
);
assert.deepEqual([onHost[0].alpha, onHost[0].show], [0.5, false]);
heat.destroy();
assert.equal(onHost.length, 0);
r.destroy();
} finally {
h.destroy();
if (priorDocument === undefined) delete globalThis.document;
else globalThis.document = priorDocument;
}
});
test('the heatmap: Navara draws through the backend the mode passes in; an engine without one keeps the state', () => {
const h = fakeHarness();
try {
const first = display(h);
const plain = first.createHeatImagery();
plain.setRaster({ width: 1, height: 1, rgba: new Uint8ClampedArray(4) });
plain.setOpacity(2);
plain.setShow(false);
plain.rehome();
assert.equal(plain.hasRaster(), true);
assert.deepEqual(
{ ...plain.state(), raster: Boolean(plain.state().raster) },
{ raster: true, show: false, opacity: 1, drawn: false },
);
plain.destroy();
first.destroy();
const native = { view: {} };
h.engine.extensions = { navara: native };
const calls = [];
const navaraHeat = (engine, navara) => {
calls.push(['create', engine === h.engine, navara === native]);
return {
setRaster: (raster) => calls.push(['raster', raster.width]),
setShow: (show) => calls.push(['show', show]),
setOpacity: (opacity) => calls.push(['opacity', opacity]),
rehome: () => calls.push(['rehome']),
destroy: () => calls.push(['destroy']),
};
};
const second = display(h, { navaraHeat });
const heat = second.createHeatImagery();
heat.setRaster({ width: 3, height: 1, rgba: new Uint8ClampedArray(12) });
heat.setOpacity(0.25);
heat.setShow(true);
heat.rehome();
heat.destroy();
heat.setShow(false);
assert.deepEqual(calls, [
['create', true, true],
['raster', 3],
['opacity', 0.25],
['show', true],
['rehome'],
['destroy'],
]);
second.destroy();
} finally {
h.destroy();
}
});