Merge branch 'sameh/renderer-layer-wrappers-2' into sameh/renderer-seam

# Conflicts:
#	src/data/localGeojsonCore.js
#	src/render/cesiumAllowList.json
This commit is contained in:
Sameh Khamis committed 2026-11-08 19:49:29 -08:00
commit 5b1920d65b
42 files changed
+1814 -937

No files matched your search

-96
View File
@@ -1,96 +0,0 @@
// src/data/cameraSensitivity.js
/**
* Shared claims on `camera.percentageChanged`.
*
* `camera.changed` fires once the view has moved by this fraction, and it is a
* single number on the camera that every listener in the app shares. Several
* layers want it finer than the default — transit asks for 0.05 so it
* notices it has entered a coverage area (bikeshare and traffic did too,
* before they listened through the renderer's camera port at their own
* threshold) — and
* each of them used to write the number directly and hand back whatever it
* remembered.
*
* That cannot work, because a number is not an owner. Two layers asking for the
* same 0.05 write the same value, so when the first one leaves it sees its own
* number still in place, concludes nothing else has claimed it, and restores
* the coarse default out from under a layer that is still running. The symptom
* is a camera-driven layer that quietly stops noticing the camera: Transit is
* turned off and Bikeshare stops loading new cities until something else nudges
* it.
*
* So ownership is tracked explicitly. Claims are named, the camera gets the
* finest value anyone has asked for, and the original value returns only when
* the last claim is gone. Claiming twice under one name replaces that claim.
*
* This is bookkeeping, not policy: it never decides what a layer should ask
* for, only that nobody's answer is taken away while they still need it.
*/
/** @type {WeakMap<object, {base: number, claims: Map<string, number>}>} */
const _cameras = new WeakMap();
/** The value Cesium starts a camera at, used when the camera reports nothing. */
const DEFAULT_PERCENTAGE_CHANGED = 0.5;
function ledgerFor(camera) {
let ledger = _cameras.get(camera);
if (!ledger) {
const base = Number.isFinite(camera.percentageChanged)
? camera.percentageChanged
: DEFAULT_PERCENTAGE_CHANGED;
ledger = { base, claims: new Map() };
_cameras.set(camera, ledger);
}
return ledger;
}
function applyLedger(camera, ledger) {
let value = ledger.base;
for (const claimed of ledger.claims.values()) {
if (claimed < value) value = claimed;
}
camera.percentageChanged = value;
return value;
}
/**
* Ask for a camera-change sensitivity at least as fine as `value`.
* @param {object|null|undefined} camera A Cesium camera (or anything with `percentageChanged`).
* @param {string} owner Stable claim name, usually the layer id.
* @param {number} value Requested `percentageChanged`.
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function claimCameraSensitivity(camera, owner, value) {
if (!camera || !owner || !Number.isFinite(value)) return null;
const ledger = ledgerFor(camera);
ledger.claims.set(owner, value);
return applyLedger(camera, ledger);
}
/**
* Give up one claim. The camera keeps the finest value still claimed by
* somebody else, and returns to its original only when none are left.
* @param {object|null|undefined} camera
* @param {string} owner
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function releaseCameraSensitivity(camera, owner) {
if (!camera || !owner) return null;
const ledger = _cameras.get(camera);
if (!ledger) return null;
if (!ledger.claims.delete(owner)) return camera.percentageChanged;
const applied = applyLedger(camera, ledger);
if (ledger.claims.size === 0) _cameras.delete(camera);
return applied;
}
/**
* Who currently holds a claim. For tests and diagnostics only.
* @param {object|null|undefined} camera
* @returns {Array<string>}
*/
export function cameraSensitivityClaims(camera) {
const ledger = camera ? _cameras.get(camera) : null;
return ledger ? [...ledger.claims.keys()] : [];
}
+4 -4
View File
@@ -114,10 +114,10 @@ assertResumeGate('CCTV', () => {
assertResumeGate('satellite', () => {
const point = {
position: { x: 1, y: 2, z: 3 },
pos: { x: 1, y: 2, z: 3 },
show: true,
pixelSize: 6,
color: color(),
color: [1, 1, 1, 1],
};
return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
@@ -129,9 +129,9 @@ assertResumeGate('satellite', () => {
nowMs,
screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200,
baseColorFor: () => color(),
baseColorFor: () => [1, 1, 1, 1],
params,
}),
readAlpha: () => point.color.alpha,
readAlpha: () => point.color[3],
};
});
+59 -19
View File
@@ -28,6 +28,26 @@ import {
import * as Cesium from 'cesium';
import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
import { drawOf } from '../render/rendererOf.js';
/** The installations layer's live site-dot set on `viewer`'s draw port. */
function dotSetOf(viewer) {
return [...drawOf(viewer).sets.values()].find(
(set) => !set.disposed && /^military-installations:\d+:dots$/.test(set.spec.id),
);
}
/** The installations layer's live selected-dot set on `viewer`'s draw port. */
function selectedSetOf(viewer) {
return [...drawOf(viewer).sets.values()].find(
(set) => !set.disposed && /^military-installations:\d+:selected$/.test(set.spec.id),
);
}
/** The drawn site dots on `viewer`, in drawing order. */
function dotsOf(viewer) {
return [...(dotSetOf(viewer)?.items.values() ?? [])];
}
test('clicking a selected installation again or empty map clears it through refresh', async () => {
const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42,
@@ -40,7 +60,7 @@ test('clicking a selected installation again or empty map clears it through refr
assert.equal(getSelectedEntityContext(), null);
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(), null, 'refresh must not resurrect selection');
assert.equal(run.entities()[0].point.pixelSize.getValue(), 9);
assert.equal(run.dots()[0].pixelSize, 9);
}
} finally { run.restore(); }
});
@@ -58,7 +78,7 @@ test('background installation paints neither reopen Contacts nor resurrect a cle
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(),null);
assert.equal(selected(),1,'an external clear must survive the next paint');
assert.equal(run.entities()[0].point.pixelSize.getValue(),9);
assert.equal(run.dots()[0].pixelSize,9);
} finally { run.restore(); }
});
@@ -90,8 +110,9 @@ test('switching sites keeps the new selection through refresh and disable clears
assert.equal(getSelectedEntityContext()?.id, 'osm:node:43');
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext()?.id, 'osm:node:43');
assert.equal(run.entities().find(e => e.id === 'osm:node:42').point.pixelSize.getValue(), 9);
assert.equal(run.entities().find(e => e.id === 'osm:node:43').point.pixelSize.getValue(), 13);
assert.equal(run.dots().find(e => e.id === 'osm:node:42').show, true);
assert.equal(run.dots().find(e => e.id === 'osm:node:43').show, false);
assert.deepEqual(run.selectedDots().map(e => [e.id, e.pixelSize]), [['osm:node:43', 13]]);
militaryInstallationsLayer.disable();
run.click('osm:node:42');
assert.equal(getSelectedEntityContext(), null, 'disabled layer ignores clicks');
@@ -133,7 +154,7 @@ test('places installation anchors on the shared cached rendered floor', () => {
_clearMeshFloorCellsForTest();
});
test('real enabled installation entities carry no native label graphics', async () => {
test('real enabled installation markers carry no native label graphics', async () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
const originalFetch = globalThis.fetch;
@@ -205,9 +226,11 @@ test('real enabled installation entities carry no native label graphics', async
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update();
const entities = dataSources[0].entities.values;
assert.ok(entities.length > 0, 'runtime guard requires rendered installation records');
assert.ok(entities.every((entity) => entity.label === undefined));
// The dots are a draw-port point set, which draws no text of its own.
const dots = dotsOf(viewer);
assert.ok(dots.length > 0, 'runtime guard requires rendered installation records');
assert.equal(dotSetOf(viewer).kind, 'points');
assert.ok(dots.every((dot) => dot.text === undefined && dot.label === undefined));
} finally {
militaryInstallationsLayer.destroy(viewer);
globalThis.fetch = originalFetch;
@@ -362,12 +385,20 @@ async function runInstallationLoad({
return {
requests,
cameraFlights,
entities: () => dataSources[0]?.entities?.values || [],
// Each drawn site's carrier: its id, and its record of what the tracked
// card and the shared selection read.
entities: () => dotsOf(viewer).map((dot) => dot.meta),
dots: () => dotsOf(viewer),
dotWrites: () => dotSetOf(viewer)?.writes ?? 0,
selectedDots: () => [...(selectedSetOf(viewer)?.items.values() ?? [])],
contextLabels: () => contextEvents,
stats: () => militaryInstallationsLayer.getStats(),
click(target) {
const entity = typeof target === 'string' ? dataSources[0].entities.getById(target) : target;
picked = entity ? { id: entity } : undefined;
// A site's dot, picked as the draw port's pick id names it.
const dot = typeof target === 'string' ? dotSetOf(viewer)?.items.get(target) : null;
picked = dot
? { id: { set: dotSetOf(viewer).spec.id, id: dot.id, meta: dot.meta } }
: target ? { id: target } : undefined;
clickAction({ position: { x: 0, y: 0 } });
},
renderRequests: () => getRenderGovernorDiagnostics().recentRequests.map((item) => item.reason),
@@ -638,16 +669,23 @@ test('a floor that lands after the render deadline lifts the dots off the ellips
};
bindFakeCesiumCamera(viewer, fakeScenePorts(viewer));
const heightOf = (entity) => Cesium.Cartographic.fromCartesian(
entity.position.getValue(Cesium.JulianDate.now()),
).height;
// Where the dot stands (its display position, which the follow and the
// tracked card read), and the height it is drawn at before clamping.
const heightOf = (dot) => {
const at = readEntityRecord(dot.meta).displayPosition();
const height = Cesium.Cartographic.fromCartesian(
new Cesium.Cartesian3(at.x, at.y, at.z),
).height;
assert.ok(Math.abs(dot.pos.height - height) < 1e-6);
return height;
};
try {
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update();
const buried = dataSources[0].entities.values[0];
const buried = dotsOf(viewer)[0];
assert.ok(buried, 'the cold-floor pass still renders the record');
assert.ok(Math.abs(heightOf(buried)) < 1, 'a cold floor anchors at the ellipsoid, as before');
@@ -657,7 +695,7 @@ test('a floor that lands after the render deadline lifts the dots off the ellips
}
assert.equal(cachedGroundFloor(lat, lon), 2400, 'the late floor landed in the shared cache');
const lifted = dataSources[0].entities.values[0];
const lifted = dotsOf(viewer)[0];
assert.ok(
Math.abs(heightOf(lifted) - 2401.5) < 0.5,
`re-render must lift the dot onto the resolved floor, got ${heightOf(lifted)}`,
@@ -885,16 +923,18 @@ test('a Contacts anchor replaces the viewport and ignores small subject moves',
} finally { run.restore(); }
});
test('unchanged installations keep their entities across reloads', async () => {
test('unchanged installations keep their markers across reloads', async () => {
const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42,
lat: 30.2, lon: -97.7, tags: { military: 'base', name: 'Site' } }] });
try {
const before = run.entities().slice();
assert.ok(before.length > 0);
const writes = run.dotWrites();
await militaryInstallationsLayer.update();
const after = run.entities();
assert.equal(after.length, before.length);
assert.ok(after.every((entity, index) => entity === before[index]),
'a reload with the same geometry must not recreate entities');
assert.ok(after.every((carrier, index) => carrier === before[index]),
'a reload with the same geometry must not recreate markers');
assert.equal(run.dotWrites(), writes, 'nor write them again');
} finally { run.restore(); }
});
+3 -3
View File
@@ -96,7 +96,7 @@ test('satellite getAnalystRecords: disabled or empty catalog returns []', () =>
test('satellite getAnalystRecords: core rows beat dense extras under the cap', () => {
const satrec = twoline2satrec(ISS_L1, ISS_L2);
const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
};
_setTrackedSatelliteRefreshStateForTest({
noradId: ISS_NORAD,
@@ -112,7 +112,7 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
name: 'STARLINK-TEST',
satrec,
group: 'dense',
point: { position: Cesium.Cartesian3.fromDegrees(-90, 20, 550_000) },
point: { pos: Cesium.Cartesian3.fromDegrees(-90, 20, 550_000) },
},
{
noradId: 24876,
@@ -120,7 +120,7 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
satrec,
group: 'gps-ops',
point: {
position: Cesium.Cartesian3.fromDegrees(-100, 10, 20_200_000),
pos: Cesium.Cartesian3.fromDegrees(-100, 10, 20_200_000),
},
},
],
+29 -40
View File
@@ -18,6 +18,7 @@ import {
} from './satellites.js';
import { followedOf } from './followed.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import satellitesLayer from './satellites.js';
import { createTrackedOverlayEntry } from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
@@ -110,23 +111,17 @@ test('satellite first update aborts every parallel catalog request', async () =>
test('selected satellite params survive delayed arrival and yield to newer explicit intent', (t) => {
const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
show: true,
pixelSize: 12,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
color: [1, 0, 0, 1],
outlineColor: [1, 1, 1, 1],
outlineWidth: 2,
disableDepthTestDistance: 0,
disableDepthTest: 0,
};
const viewer = {
entities: new Cesium.EntityCollection(),
trackedEntity: undefined,
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
t.after(bindRenderer(viewer, { camera: followingPort() }));
const viewer = {};
const draw = fakeDrawPort();
t.after(bindRenderer(viewer, { camera: followingPort(), draw }));
_setSatelliteLabelLifecycleStateForTest({
viewer,
satrec: twoline2satrec(L1, L2),
@@ -215,13 +210,13 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
// consolidate them as secondary info on that card, and suppress only those
// members — never unrelated satellites that merely happen to be nearby.
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const point = { pos: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
// The tracked satellite moves ~7.6 km/s, so neighbours are defined RELATIVE to
// wherever it is at scan time rather than pinned to a stale sample.
const near = (metres) => ({
get position() {
get pos() {
const tracked = _trackedFrameCartesianForTest();
return new Cesium.Cartesian3(tracked.x + metres, tracked.y, tracked.z);
},
@@ -246,7 +241,6 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
// The cluster scan is throttled, so advance past its interval before the frame
// that must observe the cluster.
nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
const details = readEntityRecord(entity)?.labelModel.details;
@@ -273,7 +267,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
});
test('satellite pre-render refreshes the tracked altitude on each propagated frame', () => {
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const point = { pos: new Cesium.Cartesian3() };
const viewer = {
camera: null,
scene: { frameState: { frameNumber: 1 } },
@@ -297,7 +291,6 @@ test('satellite pre-render refreshes the tracked altitude on each propagated fra
assert.equal(readEntityRecord(entity)?.labelModel.details[1], '353\u00a0km · NORAD 25544');
epochIndex = 1;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
assert.equal(readEntityRecord(entity)?.labelModel.details[1], '366\u00a0km · NORAD 25544');
assert.equal(
@@ -315,23 +308,17 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
clearSource: (...args) => calls.push(['clear', ...args]),
};
const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
show: true,
pixelSize: 12,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
color: [1, 0, 0, 1],
outlineColor: [1, 1, 1, 1],
outlineWidth: 2,
disableDepthTestDistance: 0,
disableDepthTest: 0,
};
const viewer = {
entities: new Cesium.EntityCollection(),
trackedEntity: undefined,
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
t.after(bindRenderer(viewer, { camera: followingPort() }));
const viewer = {};
const draw = fakeDrawPort();
t.after(bindRenderer(viewer, { camera: followingPort(), draw }));
let cleaned = false;
_setSatelliteLabelLifecycleStateForTest({
viewer,
@@ -348,7 +335,7 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
assert.equal(ambient.title, 'ISS');
assert.equal(
ambient.position(),
point.position,
point.pos,
'ISS getter reads the existing point cache',
);
assert.equal(
@@ -359,16 +346,17 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
const trackedEntity = _trackIssForTest();
assert.ok(trackedEntity);
const tracked = [...draw.sets.values()].find(
(set) => !set.disposed && /^satellites:\d+:tracked$/.test(set.spec.id),
);
assert.ok(tracked, 'the tracked dot has a set of its own');
_runSatellitePreRenderForTest();
assert.equal(
viewer.entities.values.length,
1,
'runtime guard requires a real tracked entity',
tracked.items.get('25544')?.pixelSize,
14,
'the tracked dot draws, as the follow camera frames it',
);
assert.equal(trackedEntity.label, undefined);
assert.ok(
trackedEntity.point,
'tracked dot remains on the entity for camera framing',
);
const trackedEntry = createTrackedOverlayEntry(trackedEntity);
assert.ok(trackedEntry);
assert.equal(trackedEntry.id, 'satellites:25544');
@@ -393,7 +381,8 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
_clearSatelliteLabelLifecycleForTest();
cleaned = true;
assert.equal(viewer.entities.values.length, 0);
assert.equal(tracked.items.size, 0);
assert.ok(tracked.disposed);
assert.equal(
calls.filter(
([type, sourceId]) =>
+2 -3
View File
@@ -18,11 +18,11 @@ const L2 =
function run(locale) {
setLocale(locale);
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const point = { pos: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
const near = (metres) => ({
get position() {
get pos() {
const tracked = _trackedFrameCartesianForTest();
return new Cesium.Cartesian3(tracked.x + metres, tracked.y, tracked.z);
},
@@ -42,7 +42,6 @@ function run(locale) {
});
_runSatellitePreRenderForTest();
nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
const details = readEntityRecord(entity)?.labelModel.details;
setLocale('en');