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

+20 -5
View File
@@ -1072,6 +1072,12 @@ a fresh winning record. Dense removal clears only its own provenance, and a
fresh core rebuild or lifecycle reset replaces the corresponding ownership. fresh core rebuild or lifecycle reset replaces the corresponding ownership.
Source adapters retain the existing CelesTrak and Launch Library Source adapters retain the existing CelesTrak and Launch Library
endpoints; standalone entries provide scene services and the satellite dependency. endpoints; standalone entries provide scene services and the satellite dependency.
The satellites layer draws through the renderer's draw port and no longer
reaches Cesium: the dots are one point set moved in a single write a frame, the
tracked satellite's dot a set of its own drawn where the follow camera framed
it, and the orbit rings a line set dimmed behind the globe and turned with the
Earth each second. A caller handing it a Cesium viewer, with no
renderer bound, loads the `./render/cesium/unbound` export once first.
The mission factory separates paths, replay, camera, panel, overlays and placement. The mission factory separates paths, replay, camera, panel, overlays and placement.
Its markers, lines, live rings and pad zone are renderer draw sets, and it Its markers, lines, live rings and pad zone are renderer draw sets, and it
follows a mission through the camera port, so a caller handing it a Cesium follows a mission through the camera port, so a caller handing it a Cesium
@@ -2280,9 +2286,17 @@ which embeds the MAP_KEY.
windows reuse the active load. Disabling or returning Contacts to passive mode windows reuse the active load. Disabling or returning Contacts to passive mode
clears its anchor; passive refreshes cannot reclaim it. Background repaints clears its anchor; passive refreshes cannot reclaim it. Background repaints
refresh context records without publishing a new selection. refresh context records without publishing a new selection.
Installation tiles decode only the `landuse` layer. Reloads keep the Cesium Installation tiles decode only the `landuse` layer. The site dots, the
entities of sites whose geometry is unchanged, so outlines and fills do not selected site's dot (a set of its own, so selecting one redraws no other),
blink. While Contacts has a subject, the layer loads a window around it their ground outlines and the selected site's fill are renderer draw sets;
reloads keep the drawn items of sites whose geometry is unchanged, so
outlines and fills do not blink. A double-click on a dot follows the site
through the camera port, centred on the surface under it (one on an outline
or fill zooms to it), as the default renderer's double-click followed its
entity; hiding the layer stops that follow. The layer no longer reaches
Cesium; a caller handing it a Cesium viewer, with no
renderer bound, loads the `./render/cesium/unbound` export once first.
While Contacts has a subject, the layer loads a window around it
instead of the camera view (100 km half-width at mid latitudes, shrinking so instead of the camera view (100 km half-width at mid latitudes, shrinking so
it fits 16 z9 tiles), moves it only after the subject travels 20 km, and it fits 16 z9 tiles), moves it only after the subject travels 20 km, and
ignores camera `moveEnd`; clearing the subject returns to the viewport. The ignores camera `moveEnd`; clearing the subject returns to the viewport. The
@@ -4619,8 +4633,9 @@ Playback reserves numeric scratch before the first sample, including unknown
heights, and reuses caller-owned sample and segment storage. heights, and reuses caller-owned sample and segment storage.
**Scene work.** Stationary and animated billboards use separate, adjacent **Scene work.** Stationary and animated billboards use separate, adjacent
collections above CCTV and Bikeshare. Traffic, Bikeshare and Transit share camera collections above CCTV and Bikeshare. Transit listens to the camera port at its
sensitivity claims; the original sensitivity returns after the last release. own `changed` threshold (0.05); the port measures each listener separately, so no
layer changes another's camera trigger.
Visibility checks combine the camera frustum and ellipsoid occlusion at no more Visibility checks combine the camera frustum and ellipsoid occlusion at no more
than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals
rebuild an unprepared or cold marker corridor during that visibility sweep, rebuild an unprepared or cold marker corridor during that visibility sweep,
-1
View File
@@ -834,7 +834,6 @@
"src/tooling/transitProvider.test.mjs", "src/tooling/transitProvider.test.mjs",
"src/app/layers/transit.js", "src/app/layers/transit.js",
"src/data/transitIcons.js", "src/data/transitIcons.js",
"src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
"src/data/contactTrailRenderer.test.mjs", "src/data/contactTrailRenderer.test.mjs",
+2 -10
View File
@@ -2171,7 +2171,6 @@
"installations-layer": { "installations-layer": {
"exports": ["./layers/installations"], "exports": ["./layers/installations"],
"modules": [ "modules": [
"src/data/cameraSensitivity.js",
"src/data/installationFeedback.js", "src/data/installationFeedback.js",
"src/data/militaryInstallationData.js", "src/data/militaryInstallationData.js",
"src/data/installationNames.js", "src/data/installationNames.js",
@@ -2217,7 +2216,8 @@
"src/render/color.js", "src/render/color.js",
"src/layers/installations/policy.js", "src/layers/installations/policy.js",
"src/layers/installations/rendering.js", "src/layers/installations/rendering.js",
"src/layers/installations/markerState.js", "src/geo/sphere.js",
"src/data/followed.js",
"src/layers/installations/selection.js", "src/layers/installations/selection.js",
"src/layers/installations/source.js", "src/layers/installations/source.js",
"src/layers/installations/state.js", "src/layers/installations/state.js",
@@ -2337,7 +2337,6 @@
"traffic-layer": { "traffic-layer": {
"exports": ["./layers/traffic"], "exports": ["./layers/traffic"],
"modules": [ "modules": [
"src/data/cameraSensitivity.js",
"src/data/flowMatch.js", "src/data/flowMatch.js",
"src/data/tomtomTiles.js", "src/data/tomtomTiles.js",
"src/data/trafficBounds.js", "src/data/trafficBounds.js",
@@ -2456,7 +2455,6 @@
"src/layers/bikeshare/viewport.js", "src/layers/bikeshare/viewport.js",
"src/geo/vector.js", "src/geo/vector.js",
"src/data/inputOwnership.js", "src/data/inputOwnership.js",
"src/data/cameraSensitivity.js",
"src/i18n/index.js", "src/i18n/index.js",
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/ar.json", "src/i18n/locales/ar.json",
@@ -3523,7 +3521,6 @@
"src/layers/installations/model.js", "src/layers/installations/model.js",
"src/layers/installations/policy.js", "src/layers/installations/policy.js",
"src/layers/installations/rendering.js", "src/layers/installations/rendering.js",
"src/layers/installations/markerState.js",
"src/layers/installations/selection.js", "src/layers/installations/selection.js",
"src/layers/installations/source.js", "src/layers/installations/source.js",
"src/layers/installations/state.js", "src/layers/installations/state.js",
@@ -3916,7 +3913,6 @@
"src/layers/transit/state.js", "src/layers/transit/state.js",
"src/layers/transit/testing.js", "src/layers/transit/testing.js",
"src/layers/transit/viewport.js", "src/layers/transit/viewport.js",
"src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
"src/data/transitProxy.js", "src/data/transitProxy.js",
@@ -4489,7 +4485,6 @@
"src/layers/installations/model.js", "src/layers/installations/model.js",
"src/layers/installations/policy.js", "src/layers/installations/policy.js",
"src/layers/installations/rendering.js", "src/layers/installations/rendering.js",
"src/layers/installations/markerState.js",
"src/layers/installations/selection.js", "src/layers/installations/selection.js",
"src/layers/installations/source.js", "src/layers/installations/source.js",
"src/layers/installations/state.js", "src/layers/installations/state.js",
@@ -4712,7 +4707,6 @@
"src/layers/transit/state.js", "src/layers/transit/state.js",
"src/layers/transit/testing.js", "src/layers/transit/testing.js",
"src/layers/transit/viewport.js", "src/layers/transit/viewport.js",
"src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
"src/data/transitProxy.js", "src/data/transitProxy.js",
@@ -5641,7 +5635,6 @@
"src/geo/vector.js", "src/geo/vector.js",
"src/render/cesium/common.js", "src/render/cesium/common.js",
"src/data/approxDistance.js", "src/data/approxDistance.js",
"src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
"src/render/color.js", "src/render/color.js",
@@ -5781,7 +5774,6 @@
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
"src/render/motion/iconMotion.js", "src/render/motion/iconMotion.js",
"src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
"src/render/color.js", "src/render/color.js",
+31 -14
View File
@@ -40,9 +40,29 @@ try {
page.on('console', (m) => { page.on('console', (m) => {
if (m.type() === 'error') result.errors.push(m.text()); if (m.type() === 'error') result.errors.push(m.text());
}); });
await page.evaluateOnNewDocument(() => await page.evaluateOnNewDocument(() => {
sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'), sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed');
); // The site dots the layer draws, read from its draw-port point set: each
// row is a drawn dot whose pick id is the draw port's `{set, id, meta}`;
// `meta` is the site's carrier, kept while the site's geometry is.
window.__qaInstallationDots = () => {
const out = [];
const visit = (node) => {
if (!node || typeof node.get !== 'function') return;
if (typeof node.length !== 'number') return;
for (let index = 0; index < node.length; index += 1) {
const child = node.get(index);
const id = child?.id;
if (id && typeof id === 'object' && typeof id.set === 'string') {
if (/^military-installations:\d+:dots$/.test(id.set))
out.push({ id: id.id, meta: id.meta, primitive: child });
} else visit(child);
}
};
visit(window.__godsEyeView.viewer.scene.primitives);
return out;
};
});
await page.goto( await page.goto(
args.find((a) => /^https?:/.test(a)), args.find((a) => /^https?:/.test(a)),
{ waitUntil: 'domcontentloaded' }, { waitUntil: 'domcontentloaded' },
@@ -156,14 +176,15 @@ try {
.catch(() => {}); .catch(() => {});
const snapshot = await page.evaluate(() => { const snapshot = await page.evaluate(() => {
const g = window.__godsEyeView; const g = window.__godsEyeView;
const ds = g.viewer.dataSources.getByName('military-installations')[0]; const points = window.__qaInstallationDots();
const points = ds.entities.values.filter((e) => e.point);
const stable = points.every( const stable = points.every(
(e) => (e) =>
!window.installationEntityRefs.has(e.id) || !window.installationEntityRefs.has(e.id) ||
window.installationEntityRefs.get(e.id) === e, window.installationEntityRefs.get(e.id) === e.meta,
);
window.installationEntityRefs = new Map(
points.map((e) => [e.id, e.meta]),
); );
window.installationEntityRefs = new Map(points.map((e) => [e.id, e]));
return { return {
...g.dataManager.layers ...g.dataManager.layers
.get('military-installations') .get('military-installations')
@@ -186,7 +207,7 @@ try {
new Set(row.ids).size !== row.ids.length new Set(row.ids).size !== row.ids.length
) )
result.failures.push( result.failures.push(
`${name}/${height}: unstable or duplicate site entities`, `${name}/${height}: unstable or duplicate site markers`,
); );
if (name.endsWith('return')) { if (name.endsWith('return')) {
const first = result.views.find( const first = result.views.find(
@@ -244,10 +265,7 @@ try {
0.6, 0.6,
); );
await page.waitForFunction( await page.waitForFunction(
() => () => window.__qaInstallationDots().length > 0,
window.__godsEyeView.viewer.dataSources
.getByName('military-installations')[0]
.entities.values.some((e) => e.point),
{ timeout: 5000 }, { timeout: 5000 },
); );
await page.evaluate(() => { await page.evaluate(() => {
@@ -268,8 +286,7 @@ try {
await sleep(1000); await sleep(1000);
await page.evaluate(async () => { await page.evaluate(async () => {
const g = window.__godsEyeView; const g = window.__godsEyeView;
const ds = g.viewer.dataSources.getByName('military-installations')[0]; const id = window.__qaInstallationDots()[0].id;
const id = ds.entities.values.find((e) => e.point).id;
window.installationSubjectId = id; window.installationSubjectId = id;
await g.dataManager.layers await g.dataManager.layers
.get('military-awareness') .get('military-awareness')
+38 -30
View File
@@ -177,18 +177,13 @@ export async function checkInstallationSelection(
await import('/src/data/contextStore.js'); await import('/src/data/contextStore.js');
const { getOverlayPaintRect, getWorldOverlayDiagnostics } = const { getOverlayPaintRect, getWorldOverlayDiagnostics } =
await import('/src/overlays/worldOverlay.js'); await import('/src/overlays/worldOverlay.js');
const knownFills = new Set(); // The selected site's fill parts, as the ground primitives built for
const fillEntities = () => { // the layer's fill set hold them: each instance's id is the
const list = []; // draw port's pick id `{set, id}`. Only built, shown instances count,
for (let i = 0; i < g.viewer.dataSources.length; i++) // so this proves the ground primitive actually built, not just an
for (const e of g.viewer.dataSources.get(i).entities.values) // item declaration.
if (e.id.startsWith(`${record.id}:selected-fill:`)) list.push(e); const fillParts = () => {
for (const e of list) knownFills.add(e); const parts = [];
return list;
};
// Geometry-instance ids prove the ground primitive actually built, not just an entity declaration.
const primitives = () => {
let count = 0;
const walk = (collection) => { const walk = (collection) => {
if (collection?._collectionsArray) { if (collection?._collectionsArray) {
for (const child of collection._collectionsArray) walk(child); for (const child of collection._collectionsArray) walk(child);
@@ -196,31 +191,44 @@ export async function checkInstallationSelection(
} }
for (let i = 0; i < (collection?.length || 0); i++) { for (let i = 0; i < (collection?.length || 0); i++) {
const p = collection.get(i); const p = collection.get(i);
if ( const ids = p?._primitive?._primitive?._instanceIds;
p.ready && if (p?.ready && Array.isArray(ids))
typeof p.getGeometryInstanceAttributes === 'function' for (const id of ids) {
) { if (
for (const e of knownFills) { !/^military-installations:\d+:fills$/.test(id?.set) ||
!String(id.id).startsWith(`${record.id}:selected-fill:`)
)
continue;
try { try {
const a = p.getGeometryInstanceAttributes(e); const a = p.getGeometryInstanceAttributes(id);
if (a && (!a.show || a.show[0])) count++; if (a && (!a.show || a.show[0]))
parts.push({
id: id.id,
classification: p.classificationType,
});
} catch {} } catch {}
} }
} if (typeof p?.get === 'function' || p?._collectionsArray)
if (typeof p.get === 'function' || p._collectionsArray) walk(p); walk(p);
} }
}; };
// The draw port adds its ground primitives under the scene's
// primitives, in its set's collection.
walk(g.viewer.scene.groundPrimitives); walk(g.viewer.scene.groundPrimitives);
return count; walk(g.viewer.scene.primitives);
return parts;
};
window.__polishFillProbe = () => {
const parts = fillParts();
return {
// Distinct fill parts drawn, and the built instances drawing them
// (a ground swap can draw a part twice while it lasts).
entities: new Set(parts.map((part) => part.id)).size,
primitives: parts.length,
classification: parts.map((part) => part.classification),
selected: getSelectedEntityContext()?.id || null,
};
}; };
window.__polishFillProbe = () => ({
entities: fillEntities().length,
primitives: primitives(),
classification: fillEntities().map((e) =>
e.polygon.classificationType.getValue(),
),
selected: getSelectedEntityContext()?.id || null,
});
window.__stopPolishSelection = window.__stopPolishSelection =
g.viewer.scene.postRender.addEventListener(() => { g.viewer.scene.postRender.addEventListener(() => {
window.__polishSelectionFrames.push({ window.__polishSelectionFrames.push({
-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', () => { assertResumeGate('satellite', () => {
const point = { const point = {
position: { x: 1, y: 2, z: 3 }, pos: { x: 1, y: 2, z: 3 },
show: true, show: true,
pixelSize: 6, pixelSize: 6,
color: color(), color: [1, 1, 1, 1],
}; };
return { return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) => pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
@@ -129,9 +129,9 @@ assertResumeGate('satellite', () => {
nowMs, nowMs,
screenPositionFor: () => ({ x: 50, y: 50 }), screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200, cameraDistanceFor: () => 1200,
baseColorFor: () => color(), baseColorFor: () => [1, 1, 1, 1],
params, params,
}), }),
readAlpha: () => point.color.alpha, readAlpha: () => point.color[3],
}; };
}); });
+59 -19
View File
@@ -28,6 +28,26 @@ import {
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js'; import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js';
import { readEntityRecord } from './entityRecords.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 () => { test('clicking a selected installation again or empty map clears it through refresh', async () => {
const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42, 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); assert.equal(getSelectedEntityContext(), null);
await militaryInstallationsLayer.update(); await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(), null, 'refresh must not resurrect selection'); 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(); } } finally { run.restore(); }
}); });
@@ -58,7 +78,7 @@ test('background installation paints neither reopen Contacts nor resurrect a cle
await militaryInstallationsLayer.update(); await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(),null); assert.equal(getSelectedEntityContext(),null);
assert.equal(selected(),1,'an external clear must survive the next paint'); 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(); } } 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'); assert.equal(getSelectedEntityContext()?.id, 'osm:node:43');
await militaryInstallationsLayer.update(); await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext()?.id, 'osm:node:43'); 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.dots().find(e => e.id === 'osm:node:42').show, true);
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:43').show, false);
assert.deepEqual(run.selectedDots().map(e => [e.id, e.pixelSize]), [['osm:node:43', 13]]);
militaryInstallationsLayer.disable(); militaryInstallationsLayer.disable();
run.click('osm:node:42'); run.click('osm:node:42');
assert.equal(getSelectedEntityContext(), null, 'disabled layer ignores clicks'); assert.equal(getSelectedEntityContext(), null, 'disabled layer ignores clicks');
@@ -133,7 +154,7 @@ test('places installation anchors on the shared cached rendered floor', () => {
_clearMeshFloorCellsForTest(); _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 originalDocument = globalThis.document;
const originalWindow = globalThis.window; const originalWindow = globalThis.window;
const originalFetch = globalThis.fetch; const originalFetch = globalThis.fetch;
@@ -205,9 +226,11 @@ test('real enabled installation entities carry no native label graphics', async
militaryInstallationsLayer.init(viewer); militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.enable(); militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update(); await militaryInstallationsLayer.update();
const entities = dataSources[0].entities.values; // The dots are a draw-port point set, which draws no text of its own.
assert.ok(entities.length > 0, 'runtime guard requires rendered installation records'); const dots = dotsOf(viewer);
assert.ok(entities.every((entity) => entity.label === undefined)); 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 { } finally {
militaryInstallationsLayer.destroy(viewer); militaryInstallationsLayer.destroy(viewer);
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
@@ -362,12 +385,20 @@ async function runInstallationLoad({
return { return {
requests, requests,
cameraFlights, 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, contextLabels: () => contextEvents,
stats: () => militaryInstallationsLayer.getStats(), stats: () => militaryInstallationsLayer.getStats(),
click(target) { click(target) {
const entity = typeof target === 'string' ? dataSources[0].entities.getById(target) : target; // A site's dot, picked as the draw port's pick id names it.
picked = entity ? { id: entity } : undefined; 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 } }); clickAction({ position: { x: 0, y: 0 } });
}, },
renderRequests: () => getRenderGovernorDiagnostics().recentRequests.map((item) => item.reason), 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)); bindFakeCesiumCamera(viewer, fakeScenePorts(viewer));
const heightOf = (entity) => Cesium.Cartographic.fromCartesian( // Where the dot stands (its display position, which the follow and the
entity.position.getValue(Cesium.JulianDate.now()), // tracked card read), and the height it is drawn at before clamping.
).height; 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 { try {
militaryInstallationsLayer.init(viewer); militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.enable(); militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update(); 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(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'); 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'); 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( assert.ok(
Math.abs(heightOf(lifted) - 2401.5) < 0.5, Math.abs(heightOf(lifted) - 2401.5) < 0.5,
`re-render must lift the dot onto the resolved floor, got ${heightOf(lifted)}`, `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(); } } 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, const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42,
lat: 30.2, lon: -97.7, tags: { military: 'base', name: 'Site' } }] }); lat: 30.2, lon: -97.7, tags: { military: 'base', name: 'Site' } }] });
try { try {
const before = run.entities().slice(); const before = run.entities().slice();
assert.ok(before.length > 0); assert.ok(before.length > 0);
const writes = run.dotWrites();
await militaryInstallationsLayer.update(); await militaryInstallationsLayer.update();
const after = run.entities(); const after = run.entities();
assert.equal(after.length, before.length); assert.equal(after.length, before.length);
assert.ok(after.every((entity, index) => entity === before[index]), assert.ok(after.every((carrier, index) => carrier === before[index]),
'a reload with the same geometry must not recreate entities'); 'a reload with the same geometry must not recreate markers');
assert.equal(run.dotWrites(), writes, 'nor write them again');
} finally { run.restore(); } } 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', () => { test('satellite getAnalystRecords: core rows beat dense extras under the cap', () => {
const satrec = twoline2satrec(ISS_L1, ISS_L2); const satrec = twoline2satrec(ISS_L1, ISS_L2);
const point = { const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000), pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
}; };
_setTrackedSatelliteRefreshStateForTest({ _setTrackedSatelliteRefreshStateForTest({
noradId: ISS_NORAD, noradId: ISS_NORAD,
@@ -112,7 +112,7 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
name: 'STARLINK-TEST', name: 'STARLINK-TEST',
satrec, satrec,
group: 'dense', group: 'dense',
point: { position: Cesium.Cartesian3.fromDegrees(-90, 20, 550_000) }, point: { pos: Cesium.Cartesian3.fromDegrees(-90, 20, 550_000) },
}, },
{ {
noradId: 24876, noradId: 24876,
@@ -120,7 +120,7 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
satrec, satrec,
group: 'gps-ops', group: 'gps-ops',
point: { 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'; } from './satellites.js';
import { followedOf } from './followed.js'; import { followedOf } from './followed.js';
import { bindRenderer } from '../render/rendererOf.js'; import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import satellitesLayer from './satellites.js'; import satellitesLayer from './satellites.js';
import { createTrackedOverlayEntry } from './trackedReadout.js'; import { createTrackedOverlayEntry } from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.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) => { test('selected satellite params survive delayed arrival and yield to newer explicit intent', (t) => {
const point = { const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000), pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
show: true, show: true,
pixelSize: 12, pixelSize: 12,
color: Cesium.Color.RED, color: [1, 0, 0, 1],
outlineColor: Cesium.Color.WHITE, outlineColor: [1, 1, 1, 1],
outlineWidth: 2, outlineWidth: 2,
disableDepthTestDistance: 0, disableDepthTest: 0,
}; };
const viewer = { const viewer = {};
entities: new Cesium.EntityCollection(), const draw = fakeDrawPort();
trackedEntity: undefined, t.after(bindRenderer(viewer, { camera: followingPort(), draw }));
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
t.after(bindRenderer(viewer, { camera: followingPort() }));
_setSatelliteLabelLifecycleStateForTest({ _setSatelliteLabelLifecycleStateForTest({
viewer, viewer,
satrec: twoline2satrec(L1, L2), 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 // consolidate them as secondary info on that card, and suppress only those
// members — never unrelated satellites that merely happen to be nearby. // members — never unrelated satellites that merely happen to be nearby.
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); 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 } } }; const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30); let nowMs = Date.UTC(2008, 8, 20, 12, 30);
// The tracked satellite moves ~7.6 km/s, so neighbours are defined RELATIVE to // 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. // wherever it is at scan time rather than pinned to a stale sample.
const near = (metres) => ({ const near = (metres) => ({
get position() { get pos() {
const tracked = _trackedFrameCartesianForTest(); const tracked = _trackedFrameCartesianForTest();
return new Cesium.Cartesian3(tracked.x + metres, tracked.y, tracked.z); 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 // The cluster scan is throttled, so advance past its interval before the frame
// that must observe the cluster. // that must observe the cluster.
nowMs += 2000; nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest(); _runSatellitePreRenderForTest();
const details = readEntityRecord(entity)?.labelModel.details; 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', () => { test('satellite pre-render refreshes the tracked altitude on each propagated frame', () => {
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() }; const point = { pos: new Cesium.Cartesian3() };
const viewer = { const viewer = {
camera: null, camera: null,
scene: { frameState: { frameNumber: 1 } }, 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'); assert.equal(readEntityRecord(entity)?.labelModel.details[1], '353\u00a0km · NORAD 25544');
epochIndex = 1; epochIndex = 1;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest(); _runSatellitePreRenderForTest();
assert.equal(readEntityRecord(entity)?.labelModel.details[1], '366\u00a0km · NORAD 25544'); assert.equal(readEntityRecord(entity)?.labelModel.details[1], '366\u00a0km · NORAD 25544');
assert.equal( 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]), clearSource: (...args) => calls.push(['clear', ...args]),
}; };
const point = { const point = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000), pos: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000),
show: true, show: true,
pixelSize: 12, pixelSize: 12,
color: Cesium.Color.RED, color: [1, 0, 0, 1],
outlineColor: Cesium.Color.WHITE, outlineColor: [1, 1, 1, 1],
outlineWidth: 2, outlineWidth: 2,
disableDepthTestDistance: 0, disableDepthTest: 0,
}; };
const viewer = { const viewer = {};
entities: new Cesium.EntityCollection(), const draw = fakeDrawPort();
trackedEntity: undefined, t.after(bindRenderer(viewer, { camera: followingPort(), draw }));
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
t.after(bindRenderer(viewer, { camera: followingPort() }));
let cleaned = false; let cleaned = false;
_setSatelliteLabelLifecycleStateForTest({ _setSatelliteLabelLifecycleStateForTest({
viewer, 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.title, 'ISS');
assert.equal( assert.equal(
ambient.position(), ambient.position(),
point.position, point.pos,
'ISS getter reads the existing point cache', 'ISS getter reads the existing point cache',
); );
assert.equal( assert.equal(
@@ -359,16 +346,17 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
const trackedEntity = _trackIssForTest(); const trackedEntity = _trackIssForTest();
assert.ok(trackedEntity); 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( assert.equal(
viewer.entities.values.length, tracked.items.get('25544')?.pixelSize,
1, 14,
'runtime guard requires a real tracked entity', 'the tracked dot draws, as the follow camera frames it',
); );
assert.equal(trackedEntity.label, undefined); assert.equal(trackedEntity.label, undefined);
assert.ok(
trackedEntity.point,
'tracked dot remains on the entity for camera framing',
);
const trackedEntry = createTrackedOverlayEntry(trackedEntity); const trackedEntry = createTrackedOverlayEntry(trackedEntity);
assert.ok(trackedEntry); assert.ok(trackedEntry);
assert.equal(trackedEntry.id, 'satellites:25544'); assert.equal(trackedEntry.id, 'satellites:25544');
@@ -393,7 +381,8 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
_clearSatelliteLabelLifecycleForTest(); _clearSatelliteLabelLifecycleForTest();
cleaned = true; cleaned = true;
assert.equal(viewer.entities.values.length, 0); assert.equal(tracked.items.size, 0);
assert.ok(tracked.disposed);
assert.equal( assert.equal(
calls.filter( calls.filter(
([type, sourceId]) => ([type, sourceId]) =>
+2 -3
View File
@@ -18,11 +18,11 @@ const L2 =
function run(locale) { function run(locale) {
setLocale(locale); setLocale(locale);
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); 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 } } }; const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30); let nowMs = Date.UTC(2008, 8, 20, 12, 30);
const near = (metres) => ({ const near = (metres) => ({
get position() { get pos() {
const tracked = _trackedFrameCartesianForTest(); const tracked = _trackedFrameCartesianForTest();
return new Cesium.Cartesian3(tracked.x + metres, tracked.y, tracked.z); return new Cesium.Cartesian3(tracked.x + metres, tracked.y, tracked.z);
}, },
@@ -42,7 +42,6 @@ function run(locale) {
}); });
_runSatellitePreRenderForTest(); _runSatellitePreRenderForTest();
nowMs += 2000; nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest(); _runSatellitePreRenderForTest();
const details = readEntityRecord(entity)?.labelModel.details; const details = readEntityRecord(entity)?.labelModel.details;
setLocale('en'); setLocale('en');
+32 -1
View File
@@ -4,7 +4,7 @@
* east-north-up frame at a point, rotation about an axis, and the offset a * east-north-up frame at a point, rotation about an axis, and the offset a
* heading, pitch and range puts an eye at. * heading, pitch and range puts an eye at.
*/ */
import { geodeticSurfaceNormal } from './ellipsoid.js'; import { WGS84, geodeticSurfaceNormal } from './ellipsoid.js';
import { import {
EPSILON14, EPSILON14,
PI_OVER_TWO, PI_OVER_TWO,
@@ -113,3 +113,34 @@ export function offsetFromHeadingPitchRange(heading, pitch, range) {
); );
return scale(negate(offset), range); return scale(negate(offset), range);
} }
/** The range the default renderer frames a sphere of no size from. */
const MINIMUM_FIT_RANGE_M = 100;
/**
* Where the eye stands to follow a target, as the default renderer framed
* an entity it started following with no view of its own: looking at the
* centre of `sphere`, heading north, pitched down 45° (steeper far from the
* ground), at the range that fits the sphere in view (100 m for one of no
* size), within the camera's zoom limits. Returned as the eye's offset from
* the centre, east-north-up there; `at` is where the target stands.
* @param {{radius: number}} sphere
* @param {{x: number, y: number, z: number}} at
* @param {{fovy?: number, aspectRatio?: number, minDistance?: number,
* maxDistance?: number}} view The camera's field of view and zoom limits.
*/
export function followOffsetFitting(sphere, at, view = {}) {
const fovy = Number.isFinite(view.fovy) ? view.fovy : Math.PI / 3;
const aspect = Number.isFinite(view.aspectRatio) ? view.aspectRatio : 1;
const tanPhi = Math.tan(fovy / 2);
const tanTheta = aspect * tanPhi;
let range =
sphere.radius === 0
? MINIMUM_FIT_RANGE_M
: Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi);
const { minDistance = 0, maxDistance = Infinity } = view;
range = Math.min(Math.max(range, minDistance), maxDistance);
const factor =
2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x);
return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range);
}
+1 -3
View File
@@ -63,9 +63,7 @@ export function createLifecycle({
const now = Date.now(); const now = Date.now();
// "Did the camera move" uses the same quantization as the fleet // "Did the camera move" uses the same quantization as the fleet
// rotation pass's cameraPoseSignature (render/cesium/iconOrientation; // rotation pass's cameraPoseSignature (render/cesium/iconOrientation;
// keep the two in step), read from the camera port's pose, rather than // keep the two in step), read from the camera port's pose.
// camera.changed, whose granularity is globally degraded by other layers
// mutating camera.percentageChanged.
const poseSig = cameraMotionSignature(layerState.viewer); const poseSig = cameraMotionSignature(layerState.viewer);
if (poseSig !== layerState.lastCameraPoseSig) { if (poseSig !== layerState.lastCameraPoseSig) {
layerState.lastCameraPoseSig = poseSig; layerState.lastCameraPoseSig = poseSig;
+2 -6
View File
@@ -20,8 +20,6 @@ export function createLifecycle({
const camera = cameraOf(viewer); const camera = cameraOf(viewer);
layerState.moveEndRemove = camera.on('moveEnd', cameraChanged); layerState.moveEndRemove = camera.on('moveEnd', cameraChanged);
// Measured for this listener alone; off, a load is never scheduled. // Measured for this listener alone; off, a load is never scheduled.
// The sensitivity claim in enable() is for raw camera listeners
// elsewhere, which this layer has always made finer while on.
layerState.changedRemove = camera.on('changed', cameraChanged, { layerState.changedRemove = camera.on('changed', cameraChanged, {
threshold: CAMERA_CHANGED_THRESHOLD, threshold: CAMERA_CHANGED_THRESHOLD,
}); });
@@ -48,9 +46,8 @@ export function createLifecycle({
}); });
parts.namedMarkers?.enable(); parts.namedMarkers?.enable();
parts.namedMarkers?.sync(layerState.records || []); parts.namedMarkers?.sync(layerState.records || []);
parts.rendering.claimCameraChanges?.();
registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id)); registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id));
layerState.dataSource.show = true; parts.rendering.setShown(true);
// DataLayerManager invokes update() immediately after enable(), which owns // DataLayerManager invokes update() immediately after enable(), which owns
// the first fetch. Avoid racing it with a second aborting request here. // the first fetch. Avoid racing it with a second aborting request here.
}, },
@@ -59,7 +56,6 @@ export function createLifecycle({
layerState.enabled = false; layerState.enabled = false;
services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID); services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
parts.namedMarkers?.hide(); parts.namedMarkers?.hide();
parts.rendering.releaseCameraChanges?.();
layerState.contextAnchor = null; layerState.contextAnchor = null;
layerState.contextPosition = null; layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' }; layerState.coverage = { kind: 'viewport' };
@@ -71,7 +67,7 @@ export function createLifecycle({
layerState.abort?.abort(); layerState.abort?.abort();
layerState.abort = null; layerState.abort = null;
layerState.loading = false; layerState.loading = false;
if (layerState.dataSource) layerState.dataSource.show = false; parts.rendering.setShown(false);
clearSelectedEntityContextForLayer(LAYER_ID); clearSelectedEntityContextForLayer(LAYER_ID);
layerState.selectedId = null; layerState.selectedId = null;
parts.rendering.clearSelectionFill?.(); parts.rendering.clearSelectionFill?.();
+10 -4
View File
@@ -25,9 +25,9 @@ for (const source of [
viewer, viewer,
records: source ? [{ id: 'base', sources: [source] }] : [], records: source ? [{ id: 'base', sources: [source] }] : [],
recordById: new Map(), recordById: new Map(),
dataSource: { show: false },
}; };
let markersVisible = false; let markersVisible = false;
let drawnShown = false;
const parts = { const parts = {
namedMarkers: { namedMarkers: {
enable: () => { enable: () => {
@@ -38,7 +38,13 @@ for (const source of [
markersVisible = false; markersVisible = false;
}, },
}, },
rendering: { attach: noop, detach: noop }, rendering: {
attach: noop,
detach: noop,
setShown: (shown) => {
drawnShown = shown;
},
},
viewport: { clearUnavailableRetry: noop }, viewport: { clearUnavailableRetry: noop },
ingestion: { setInstallationStatus: noop }, ingestion: { setInstallationStatus: noop },
}; };
@@ -61,12 +67,12 @@ for (const source of [
try { try {
for (let cycle = 0; cycle < 2; cycle++) { for (let cycle = 0; cycle < 2; cycle++) {
lifecycle.enable(); lifecycle.enable();
assert.equal(state.dataSource.show, true); assert.equal(drawnShown, true);
assert.equal(markersVisible, true); assert.equal(markersVisible, true);
// No renderRecords or successful fetch occurs between toggles. // No renderRecords or successful fetch occurs between toggles.
assert.equal(visibleCredits.size, expected); assert.equal(visibleCredits.size, expected);
lifecycle.disable(); lifecycle.disable();
assert.equal(state.dataSource.show, false); assert.equal(drawnShown, false);
assert.equal(markersVisible, false); assert.equal(markersVisible, false);
assert.equal(visibleCredits.size, 0); assert.equal(visibleCredits.size, 0);
} }
-9
View File
@@ -1,9 +0,0 @@
import { createEntityStore } from '../../data/entityRecords.js';
/**
* What the installations layer last drew for a retained marker entity, so an
* unchanged record leaves it alone: `heightM` (surface height) and `selected`.
* Selection fills and outlines record the installation they belong to as
* `recordId`, which a pick on them resolves through.
*/
export const installationMarkers = createEntityStore();
@@ -26,7 +26,7 @@ function setup(t) {
bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(state.viewer) }); bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(state.viewer) });
const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } }; const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } };
let loads = 0; let loads = 0;
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() { state.dataSource = { show: false }; }, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } }; const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() {}, setShown() {}, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } };
const ctx = { state, services, parts, source: {}, overlayHost }; const ctx = { state, services, parts, source: {}, overlayHost };
parts.namedMarkers = createNamedMarkers(ctx); parts.namedMarkers = createNamedMarkers(ctx);
const lifecycle = createLifecycle(ctx).methods; const lifecycle = createLifecycle(ctx).methods;
+2 -3
View File
@@ -25,9 +25,8 @@ test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and
const parts = { const parts = {
selection: { installInteraction() {} }, selection: { installInteraction() {} },
rendering: { rendering: {
attach() { attach() {},
state.dataSource = { show: false }; setShown() {},
},
detach() {}, detach() {},
clearRendered() {}, clearRendered() {},
}, },
+339 -169
View File
@@ -1,22 +1,38 @@
import { installationClassLabel, installationTitle } from './classLabel.js'; import { installationClassLabel, installationTitle } from './classLabel.js';
import * as Cesium from 'cesium';
// Still Cesium for its entities, so this layer loads the unbound camera
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { t } from '../../i18n/index.js'; import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { entityFollowTarget } from '../../data/followed.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { followOffsetFitting } from '../../geo/frames.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { heightsOf } from '../../queries/heights.js';
import { import {
CAMERA_CHANGED_THRESHOLD, drawOf,
LAYER_ID, findCamera,
MAX_RENDERED, findGlobe,
COLOR_BY_CLASS, findQuery,
} from './policy.js'; } from '../../render/rendererOf.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { entityRecord } from '../../data/entityRecords.js';
import { installationMarkers } from './markerState.js';
let instances = 0;
const DOT_OUTLINE = Object.freeze([0, 0, 0, 0.8]);
const SELECTED_DOT = Object.freeze([1, 1, 1, 1]);
/** A record's footprint polygons, each its rings of `[lon, lat]`. */
const footprintsOf = (record) =>
record.footprints || (record.footprint ? [[record.footprint]] : []);
/** A record's outline polylines of `[lon, lat]`. */
const outlinesOf = (record) =>
record.outlineLines || (record.footprint ? [record.footprint] : []);
/**
* The installations layer's drawing: a draw-port point set of site dots, a
* point set of the selected site's dot (so selecting one restyles no other
* dot), a line set of their ground outlines and a shape set of the selected
* site's footprint fill, on the viewer's renderer (`drawOf`).
*/
export function createRendering({ export function createRendering({
state: layerState, state: layerState,
services, services,
@@ -33,27 +49,48 @@ export function createRendering({
const { governorRequestRender } = services.render; const { governorRequestRender } = services.render;
const { warmFireAnchorFloors } = services.anchors; const { warmFireAnchorFloors } = services.anchors;
/** A record's class colour, for the entities. */ /** A record's class colour with alpha `alpha`, as the draw port takes it. */
function colorFor(record) { function colorFor(record, alpha = null) {
const [r, g, b, a] = parts.model.colorFor(record); const [r, g, b, a] = parts.model.colorFor(record);
return new Cesium.Color(r, g, b, a); return [r, g, b, alpha ?? a];
} }
/** /**
* The layer's entities. They stay entities: the camera can follow a site * Make the layer's draw sets, hidden until the layer is enabled, and
* (double-click), and the tracked card reads what it shows from them. * follow a site on a double-click.
*/ */
function attach(viewer) { function attach(viewer) {
layerState.dataSource = new Cesium.CustomDataSource( const draw = drawOf(viewer);
'military-installations', selectedDotKey = null;
); const prefix = `${LAYER_ID}:${++instances}`;
viewer.dataSources.add(layerState.dataSource); layerState.sets = {
dots: draw.points({ id: `${prefix}:dots`, show: false }),
selected: draw.points({ id: `${prefix}:selected`, show: false }),
outlines: draw.lines({ id: `${prefix}:outlines`, show: false }),
fills: draw.shapes({ id: `${prefix}:fills`, show: false }),
};
} }
function detach(viewer) { function detach() {
if (layerState.dataSource && viewer) stopFollow();
viewer.dataSources.remove(layerState.dataSource, true); if (layerState.sets)
layerState.dataSource = null; for (const set of Object.values(layerState.sets)) set.dispose();
layerState.sets = null;
}
/** Show or hide everything the layer draws. */
function setShown(shown) {
if (!layerState.sets) return;
for (const set of Object.values(layerState.sets)) set.show = shown;
if (!shown) stopFollow();
}
/** Whether `setId` is one of this layer's sets. */
function ownsSet(setId) {
return Boolean(
layerState.sets &&
Object.values(layerState.sets).some((set) => set.id === setId),
);
} }
/** /**
@@ -75,8 +112,7 @@ export function createRendering({
const selectedFillIds = []; const selectedFillIds = [];
function clearSelectionFill() { function clearSelectionFill() {
for (const id of selectedFillIds) if (selectedFillIds.length) layerState.sets?.fills.remove(selectedFillIds);
layerState.dataSource?.entities.removeById(id);
selectedFillIds.length = 0; selectedFillIds.length = 0;
selectedFillKey = null; selectedFillKey = null;
} }
@@ -84,68 +120,63 @@ export function createRendering({
/** Ground geometry classifies the active surface; no height/extrusion plane. */ /** Ground geometry classifies the active surface; no height/extrusion plane. */
function syncSelectionFill() { function syncSelectionFill() {
const record = const record =
layerState.enabled && layerState.recordById.get(layerState.selectedId); layerState.enabled &&
layerState.sets &&
layerState.recordById.get(layerState.selectedId);
if (!record) { if (!record) {
clearSelectionFill(); clearSelectionFill();
return; return;
} }
const classificationType = // Tiles alone while the globe surface is hidden, as under photoreal.
layerState.viewer.scene.globe?.show === false const clampTo =
? Cesium.ClassificationType.CESIUM_3D_TILE findGlobe(layerState.viewer)?.isGlobeVisible?.() === false
: Cesium.ClassificationType.BOTH; ? 'tiles'
const key = `${record.id}|${renderKey(record)}|${classificationType}`; : 'both';
const key = `${record.id}|${renderKey(record)}|${clampTo}`;
if (key === selectedFillKey) return; if (key === selectedFillKey) return;
clearSelectionFill(); clearSelectionFill();
selectedFillKey = key; selectedFillKey = key;
const footprints = const fill = colorFor(record, 0.22);
record.footprints || (record.footprint ? [[record.footprint]] : []); const meta = { installationId: record.id };
const material = new Cesium.ColorMaterialProperty( const items = footprintsOf(record).map((rings, i) => ({
colorFor(record).withAlpha(0.22), id: `${record.id}:selected-fill:${i}`,
); geometry: {
for (let i = 0; i < footprints.length; i++) { kind: 'polygon',
const rings = footprints[i]; rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))),
const positions = (ring) => },
ring.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat)); fill,
const fill = layerState.dataSource.entities.add({ height: 'clampGround',
id: `${record.id}:selected-fill:${i}`, clampTo,
polygon: { meta,
hierarchy: new Cesium.PolygonHierarchy( }));
positions(rings[0]), if (items.length) layerState.sets.fills.upsert(items);
rings for (const item of items) selectedFillIds.push(item.id);
.slice(1)
.map((ring) => new Cesium.PolygonHierarchy(positions(ring))),
),
material,
classificationType,
},
});
installationMarkers.write(fill).recordId = record.id;
selectedFillIds.push(fill.id);
}
governorRequestRender('installation-selection-fill'); governorRequestRender('installation-selection-fill');
} }
function clearRendered() { function clearRendered() {
clearSelectionFill(); clearSelectionFill();
if (layerState.dataSource?.entities) stopFollow();
layerState.dataSource.entities.removeAll(); if (layerState.sets) {
layerState.sets.dots.clear();
layerState.sets.selected.clear();
layerState.sets.outlines.clear();
}
selectedDotKey = null;
layerState.renderedKeys.clear(); layerState.renderedKeys.clear();
removeEntityContextsForLayer(LAYER_ID); removeEntityContextsForLayer(LAYER_ID);
} }
/** /**
* Geometry identity of one rendered record. Records whose key is unchanged * Geometry identity of one rendered record. Records whose key is unchanged
* keep their Cesium entities across refreshes: ground-clamped outlines and * keep their drawn items across refreshes, only restyled or moved in
* classification fills rebuild asynchronously, so recreating them on every * place, so an unchanged site never blinks.
* reload made unchanged sites blink.
* @param {object} record Installation record. * @param {object} record Installation record.
* @returns {string} Stable key for the record's drawn geometry. * @returns {string} Stable key for the record's drawn geometry.
*/ */
function renderKey(record) { function renderKey(record) {
const footprints = const footprints = footprintsOf(record);
record.footprints || (record.footprint ? [[record.footprint]] : []); const outlines = outlinesOf(record);
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
let points = 0; let points = 0;
for (const rings of footprints) for (const rings of footprints)
for (const ring of rings) points += ring.length; for (const ring of rings) points += ring.length;
@@ -162,22 +193,84 @@ export function createRendering({
].join('|'); ].join('|');
} }
function removeRecordEntities(id) { /**
const entities = layerState.dataSource.entities; * A site's dot. The selected site's is hidden here and drawn larger, in
for (const entityId of layerState.renderedKeys.get(id)?.entityIds || []) * white, by the selected set (`selectedDotItem`): a clamped dot is
entities.removeById(entityId); * restyled only by drawing it again, so its own set never changes look.
*/
function dotItem(record, rendered) {
return {
id: record.id,
pos: {
lon: record.longitude,
lat: record.latitude,
height: rendered.heightM,
},
height: 'clampGround',
show: !record.namedArea && !rendered.selected,
pixelSize: 9,
color: colorFor(record),
outlineColor: DOT_OUTLINE,
outlineWidth: 1,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: rendered.carrier,
};
}
/** The selected site's dot, as its own set draws it. */
function selectedDotItem(record, rendered) {
return {
...dotItem(record, rendered),
show: true,
pixelSize: 13,
color: SELECTED_DOT,
};
}
/** What the selected set draws now (site, place, height), or null. */
let selectedDotKey = null;
/** Draw the selected site's dot, when it has one shown. */
function syncSelectedDot() {
const sets = layerState.sets;
if (!sets) return;
const rendered = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null;
const record = rendered
? layerState.recordById.get(layerState.selectedId)
: null;
const key =
record && rendered.selected && !record.namedArea
? [record.id, record.longitude, record.latitude, rendered.heightM].join(
'|',
)
: null;
if (key === selectedDotKey) return;
selectedDotKey = key;
if (key) sets.selected.set([selectedDotItem(record, rendered)]);
else sets.selected.clear();
}
/** Stop drawing a record's dot and outlines, and following it. */
function removeRecordItems(id, dotIds, outlineIds) {
const rendered = layerState.renderedKeys.get(id);
if (!rendered) return;
dotIds.push(id);
outlineIds.push(...rendered.outlineIds);
if (follow?.recordId === id) stopFollow();
layerState.renderedKeys.delete(id); layerState.renderedKeys.delete(id);
} }
/** /**
* The records that get entities this paint: the nearest `MAX_RENDERED`, plus * The records that get drawn this paint: the nearest `MAX_RENDERED`, plus
* the selected one when it falls outside that window. * the selected one when it falls outside that window.
* *
* Context navigation walks the FULL nearby cohort, which is not bounded by the * Context navigation walks the FULL nearby cohort, which is not bounded by the
* render cap, so selecting item 701+ used to produce no entity at all — the * render cap, so selecting item 701+ used to produce no marker at all — the
* camera flew, `getById` returned null, and the selection was silently dropped * camera flew, the lookup returned null, and the selection was silently dropped
* on the floor, leaving the Context subject stale so NEXT offered the same * on the floor, leaving the Context subject stale so NEXT offered the same
* installation forever. One extra entity keeps every cohort item selectable * installation forever. One extra marker keeps every cohort item selectable
* and the cohort count honest. * and the cohort count honest.
* @returns {Array<object>} Records to render this paint. * @returns {Array<object>} Records to render this paint.
*/ */
@@ -218,7 +311,7 @@ export function createRendering({
} }
} }
// Post-moveEnd debounced fetches commit after the camera settles; the // Post-moveEnd debounced fetches commit after the camera settles; the
// rebuilt entities need one frame in idle mode. (perf wave 2 fix) // rebuilt markers need one frame in idle mode. (perf wave 2 fix)
governorRequestRender('installations-render'); governorRequestRender('installations-render');
if ( if (
layerState.records.some((r) => layerState.records.some((r) =>
@@ -237,81 +330,74 @@ export function createRendering({
const keys = new Map( const keys = new Map(
records.map((record) => [record.id, renderKey(record)]), records.map((record) => [record.id, renderKey(record)]),
); );
const entities = layerState.dataSource.entities; const removedDots = [];
entities.suspendEvents(); const removedOutlines = [];
for (const [id, rendered] of [...layerState.renderedKeys]) for (const [id, rendered] of [...layerState.renderedKeys])
if (keys.get(id) !== rendered.key) removeRecordEntities(id); if (keys.get(id) !== rendered.key)
removeRecordItems(id, removedDots, removedOutlines);
const dots = [];
const outlines = [];
for (const record of records) { for (const record of records) {
const color = colorFor(record);
const surfaceHeightM = installationSurfaceHeightM(record); const surfaceHeightM = installationSurfaceHeightM(record);
const displayPosition = Cesium.Cartesian3.fromDegrees( const selectedRecord = record.id === layerState.selectedId;
const retained = layerState.renderedKeys.get(record.id);
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
let changed = false;
if (retained.heightM !== surfaceHeightM) {
retained.heightM = surfaceHeightM;
const displayPosition = fromDegrees(
record.longitude,
record.latitude,
surfaceHeightM,
);
entityRecord(retained.carrier).displayPosition = () =>
displayPosition;
changed = true;
}
if (retained.selected !== selectedRecord) {
retained.selected = selectedRecord;
changed = true;
}
if (changed) dots.push(dotItem(record, retained));
continue;
}
const displayPosition = fromDegrees(
record.longitude, record.longitude,
record.latitude, record.latitude,
surfaceHeightM, surfaceHeightM,
); );
const selectedRecord = record.id === layerState.selectedId; // What the dot's pick carries and the shared selection, the tracked
const retained = layerState.renderedKeys.has(record.id) // card and a follow read this site through.
? entities.getById(record.id) const carrier = { id: record.id, installationId: record.id };
: null; const rendered = {
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
const marker = installationMarkers.write(retained);
if (marker.heightM !== surfaceHeightM) {
marker.heightM = surfaceHeightM;
retained.position = displayPosition;
entityRecord(retained).displayPosition = () => displayPosition;
}
if (marker.selected !== selectedRecord) {
marker.selected = selectedRecord;
retained.point.pixelSize = selectedRecord ? 13 : 9;
retained.point.color = selectedRecord ? Cesium.Color.WHITE : color;
}
continue;
}
const entityIds = [record.id];
layerState.renderedKeys.set(record.id, {
key: keys.get(record.id), key: keys.get(record.id),
entityIds, outlineIds: [],
}); carrier,
const entity = layerState.dataSource.entities.add({
id: record.id,
position: displayPosition,
point: {
show: !record.namedArea,
pixelSize: record.id === layerState.selectedId ? 13 : 9,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
color:
record.id === layerState.selectedId ? Cesium.Color.WHITE : color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.8),
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
for (let i = 0; i < outlines.length; i++) {
const outline = layerState.dataSource.entities.add({
id: `${record.id}:outline:${i}`,
polyline: {
positions: outlines[i].map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
),
width: 2,
material: color.withAlpha(0.85),
clampToGround: true,
classificationType: Cesium.ClassificationType.BOTH,
},
});
installationMarkers.write(outline).recordId = record.id;
entityIds.push(outline.id);
}
Object.assign(installationMarkers.write(entity), {
heightM: surfaceHeightM, heightM: surfaceHeightM,
selected: selectedRecord, selected: selectedRecord,
}); };
entityRecord(entity).trackedId = `installations:${record.id}`; layerState.renderedKeys.set(record.id, rendered);
entityRecord(entity).displayPosition = () => displayPosition; dots.push(dotItem(record, rendered));
entityRecord(entity).labelModel = { const outlineColor = colorFor(record, 0.85);
const outlineMeta = { installationId: record.id };
const lines = outlinesOf(record);
for (let i = 0; i < lines.length; i++) {
const id = `${record.id}:outline:${i}`;
outlines.push({
id,
positions: lines[i].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color: outlineColor },
meta: outlineMeta,
});
rendered.outlineIds.push(id);
}
entityRecord(carrier).trackedId = `installations:${record.id}`;
entityRecord(carrier).displayPosition = () => displayPosition;
entityRecord(carrier).labelModel = {
title: installationTitle(record.name) || t('MAPPED INSTALLATION'), title: installationTitle(record.name) || t('MAPPED INSTALLATION'),
details: [ details: [
installationClassLabel(record.class), installationClassLabel(record.class),
@@ -319,7 +405,7 @@ export function createRendering({
], ],
accent: COLOR_BY_CLASS[record.class] || '#9ca6b0', accent: COLOR_BY_CLASS[record.class] || '#9ca6b0',
}; };
registerEntityContext(entity, { registerEntityContext(carrier, {
id: record.id, id: record.id,
layerId: LAYER_ID, layerId: LAYER_ID,
layerName: layerName:
@@ -340,19 +426,116 @@ export function createRendering({
}, },
}); });
} }
entities.resumeEvents(); const sets = layerState.sets;
const selectedEntity = layerState.selectedId if (removedDots.length) sets.dots.remove(removedDots);
? layerState.dataSource.entities.getById(layerState.selectedId) if (removedOutlines.length) sets.outlines.remove(removedOutlines);
if (dots.length) sets.dots.upsert(dots);
if (outlines.length) sets.outlines.upsert(outlines);
syncSelectedDot();
const selected = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null; : null;
if (selectedEntity && (claimSelection || migratedSelection)) if (selected && (claimSelection || migratedSelection))
selectEntityContext(selectedEntity); selectEntityContext(selected.carrier);
else if (!selectedEntity) layerState.selectedId = null; else if (!selected) layerState.selectedId = null;
// Re-register rebuilt geometry and migrate aliases before pruning old context. // Re-register rebuilt geometry and migrate aliases before pruning old context.
removeEntityContextsForLayer(LAYER_ID, { retainIds: new Set(keys.keys()) }); removeEntityContextsForLayer(LAYER_ID, { retainIds: new Set(keys.keys()) });
parts.namedMarkers?.sync(layerState.records); parts.namedMarkers?.sync(layerState.records);
syncSelectionFill(); syncSelectionFill();
} }
/** The follow a double-click started, while the camera keeps it. */
let follow = null;
/**
* Follow the site whose dot is under `position`, as the default renderer
* followed the site's entity on a double-click: by the site's display
* position, framed as that renderer framed an entity it started
* following. A double-click on an outline or the selected fill, which had
* no position to follow, zooms to it at once instead.
* @param {{x: number, y: number}} position Canvas pixels.
*/
function followAt(position) {
const viewer = layerState.viewer;
if (!layerState.enabled || !layerState.sets) return;
const query = findQuery(viewer);
const hit = query?.pick(position.x, position.y);
if (!hit || !ownsSet(hit.set)) return;
const camera = findCamera(viewer);
if (!camera) return;
const recordId = hit.meta?.installationId;
const record = layerState.recordById.get(recordId);
if (!record) return;
try {
if (
hit.set !== layerState.sets.dots.id &&
hit.set !== layerState.sets.selected.id
) {
const points = partPoints(record, hit.id);
if (!points.length) return;
// Following nothing then, as that zoom stopped any follow first.
if (camera.followed) camera.follow(null);
camera.flyToBounds(sphereFromPoints(points), { durationS: 0 });
return;
}
const rendered = layerState.renderedKeys.get(recordId);
if (!rendered) return;
const { carrier } = rendered;
const shown = readEntityRecord(carrier)?.displayPosition?.();
if (!shown) return;
// Centred where the dot is drawn, on the surface under it when its
// height is loaded (the cached floor may not be yet), and held there
// as the stock follow held the dot's bounding sphere.
const surface = heightsOf(viewer).now({
lon: record.longitude,
lat: record.latitude,
});
const at = Number.isFinite(surface)
? fromDegrees(record.longitude, record.latitude, surface)
: shown;
const pose = camera.pose?.();
const target = entityFollowTarget(carrier, {
key: `installations:${record.id}`,
position: () => at,
frame: 'enu',
viewFrom: followOffsetFitting({ center: at, radius: 0 }, at, {
fovy: pose?.fovy,
aspectRatio: pose?.aspectRatio,
minDistance: camera.controls?.minDistance,
maxDistance: camera.controls?.maxDistance,
}),
});
camera.follow(target);
follow = { target, recordId };
} catch (error) {
// A camera that cannot follow leaves the view where it is, as a
// viewer without entity tracking did on a double-click.
console.warn(`${LAYER_ID}: cannot follow`, error);
}
}
/** The ground points of a record's outline or fill item `itemId`. */
function partPoints(record, itemId) {
const outline = /:outline:(\d+)$/.exec(itemId);
if (outline) {
const line = outlinesOf(record)[Number(outline[1])] || [];
return line.map(([lon, lat]) => fromDegrees(lon, lat));
}
const fill = /:selected-fill:(\d+)$/.exec(itemId);
if (fill) {
const rings = footprintsOf(record)[Number(fill[1])] || [];
return rings.flat().map(([lon, lat]) => fromDegrees(lon, lat));
}
return [];
}
/** Stop a follow this layer started, if the camera still keeps it. */
function stopFollow() {
const camera = follow && findCamera(layerState.viewer);
if (follow && camera?.followed === follow.target) camera.follow(null);
follow = null;
}
/** /**
* Second paint for floors that missed the bounded pre-render deadline. * Second paint for floors that missed the bounded pre-render deadline.
* *
@@ -383,7 +566,7 @@ export function createRendering({
.map((record) => ({ lat: record.latitude, lon: record.longitude })); .map((record) => ({ lat: record.latitude, lon: record.longitude }));
if (!cold.length) return; if (!cold.length) return;
warmFireAnchorFloors(cold).then(() => { warmFireAnchorFloors(cold).then(() => {
if (!layerState.enabled || !layerState.dataSource) return; if (!layerState.enabled || !layerState.sets) return;
if ( if (
!cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null) !cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null)
) )
@@ -391,26 +574,13 @@ export function createRendering({
renderRecords(); renderRecords();
}); });
} }
/**
* While the layer is on, the Cesium camera reports changes at the layer's
* threshold to its own `changed` listeners too (the camera port measures
* each listener's threshold itself).
*/
function claimCameraChanges() {
claimCameraSensitivity(
layerState.viewer.camera,
LAYER_ID,
CAMERA_CHANGED_THRESHOLD,
);
}
function releaseCameraChanges() {
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
}
return { return {
attach, attach,
detach, detach,
claimCameraChanges, setShown,
releaseCameraChanges, ownsSet,
followAt,
stopFollow,
installationSurfaceHeightM, installationSurfaceHeightM,
clearSelectionFill, clearSelectionFill,
syncSelectionFill, syncSelectionFill,
+21 -10
View File
@@ -1,6 +1,5 @@
import { inputFor } from '../../input/dispatcher.js'; import { inputFor } from '../../input/dispatcher.js';
import { LAYER_ID } from './policy.js'; import { LAYER_ID } from './policy.js';
import { installationMarkers } from './markerState.js';
export function createSelection({ export function createSelection({
state: layerState, state: layerState,
@@ -11,6 +10,7 @@ export function createSelection({
const { clearSelectedEntityContextForLayer } = services.context; const { clearSelectedEntityContextForLayer } = services.context;
let removeContextListeners = null; let removeContextListeners = null;
let removeDoubleClick = null;
function syncContextSelection(event) { function syncContextSelection(event) {
if (!layerState.enabled) return; if (!layerState.enabled) return;
@@ -30,10 +30,10 @@ export function createSelection({
function selectRecord(id) { function selectRecord(id) {
const record = layerState.recordById.get(id); const record = layerState.recordById.get(id);
if (!record || !layerState.dataSource) return false; if (!record || !layerState.sets) return false;
layerState.selectedId = id; layerState.selectedId = id;
parts.rendering.renderRecords({ claimSelection: true }); parts.rendering.renderRecords({ claimSelection: true });
// renderRecords drops selectedId when the record produced no entity. // renderRecords drops selectedId when the record produced no marker.
return layerState.selectedId === id; return layerState.selectedId === id;
} }
@@ -50,17 +50,17 @@ export function createSelection({
for (const event of events) for (const event of events)
globalThis.window?.removeEventListener?.(event, syncContextSelection); globalThis.window?.removeEventListener?.(event, syncContextSelection);
}; };
layerState.clickSubscription = inputFor(viewer).onClick((event) => { const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return; if (!layerState.enabled) return;
// A named marker is a draw item; site markers are still entities. // A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit; const hit = event.drawHit;
const target = event.pick?.id;
const id = const id =
(hit?.set === parts.namedMarkers?.setId hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId ? hit.meta?.installationId
: null) || : null;
installationMarkers.read(target)?.recordId ||
(typeof target?.id === 'string' ? target.id : null);
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) { if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id); selectRecord(id);
} else if (layerState.selectedId) { } else if (layerState.selectedId) {
@@ -72,6 +72,15 @@ export function createSelection({
parts.rendering.renderRecords(); parts.rendering.renderRecords();
} }
}); });
// Follow a site on a double-click, as the renderer's own double-click
// followed the site's entity.
removeDoubleClick =
input.onPointer?.('dblclick', (event) => {
// The renderer's own double-click follow, off while a tool holds it
// or on a renderer without one.
if (input.stockEnabled?.('dblclickFollow') !== true) return;
parts.rendering.followAt(event.position);
}) ?? null;
} }
return { return {
selectRecord, selectRecord,
@@ -79,6 +88,8 @@ export function createSelection({
destroy() { destroy() {
removeContextListeners?.(); removeContextListeners?.();
removeContextListeners = null; removeContextListeners = null;
removeDoubleClick?.();
removeDoubleClick = null;
}, },
}; };
} }
+157 -6
View File
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js'; import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs'; import { fakeInput } from '../../input/testDoubles.mjs';
import { inputFor } from '../../input/dispatcher.js';
function harness(t) { function harness(t) {
const previousWindow = globalThis.window; const previousWindow = globalThis.window;
@@ -37,9 +38,18 @@ function harness(t) {
records: [record], records: [record],
recordById: new Map([[record.id, record]]), recordById: new Map([[record.id, record]]),
renderedKeys: new Map(), renderedKeys: new Map(),
dataSource: new Cesium.CustomDataSource(),
viewer: { viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) }, camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) },
// The viewer's stock double-click follow, which the site follow
// stands in for.
screenSpaceEventHandler: {
getInputAction: (type) =>
type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
? () => {}
: undefined,
setInputAction() {},
removeInputAction() {},
},
scene: { scene: {
globe: { show: false }, globe: { show: false },
canvas: Object.assign(new EventTarget(), { canvas: Object.assign(new EventTarget(), {
@@ -52,7 +62,7 @@ function harness(t) {
}, },
}; };
let picked; let picked;
const { draw } = bindFakeCesiumScene(state.viewer); const { draw, camera, query } = bindFakeCesiumScene(state.viewer);
const input = fakeInput(state.viewer); const input = fakeInput(state.viewer);
t.mock.method( t.mock.method(
Cesium.SceneTransforms, Cesium.SceneTransforms,
@@ -85,6 +95,7 @@ function harness(t) {
}, },
}; };
parts.rendering = createRendering(ctx); parts.rendering = createRendering(ctx);
parts.rendering.attach(state.viewer);
parts.namedMarkers = createNamedMarkers(ctx); parts.namedMarkers = createNamedMarkers(ctx);
const selection = createSelection(ctx); const selection = createSelection(ctx);
selection.installInteraction(state.viewer); selection.installInteraction(state.viewer);
@@ -93,6 +104,7 @@ function harness(t) {
state.clickSubscription(); state.clickSubscription();
parts.namedMarkers.destroy(); parts.namedMarkers.destroy();
parts.rendering.clearRendered(); parts.rendering.clearRendered();
parts.rendering.detach();
input.destroy(); input.destroy();
if (previousWindow === undefined) delete globalThis.window; if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow; else globalThis.window = previousWindow;
@@ -103,10 +115,7 @@ function harness(t) {
assert.equal(state.selectedId, selected ? record.id : null); assert.equal(state.selectedId, selected ? record.id : null);
assert.equal(labels[0].selected, selected); assert.equal(labels[0].selected, selected);
assert.equal(labels[0].variant, selected ? 'selected' : 'card'); assert.equal(labels[0].variant, selected ? 'selected' : 'card');
assert.equal( assert.equal(state.sets.fills.size(), selected ? 1 : 0);
state.dataSource.entities.values.filter((e) => e.polygon).length,
selected ? 1 : 0,
);
}; };
assert.equal(selection.selectRecord(record.id), true); assert.equal(selection.selectRecord(record.id), true);
assertSelected(true); assertSelected(true);
@@ -115,6 +124,9 @@ function harness(t) {
selection, selection,
assertSelected, assertSelected,
draw, draw,
camera,
query,
input,
parts, parts,
/** Click on what `pick` names, as the scene would pick it. */ /** Click on what `pick` names, as the scene would pick it. */
click(value) { click(value) {
@@ -186,3 +198,142 @@ test('a click on a named marker point selects its site; again releases it', (t)
h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } }); h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } });
h.assertSelected(false); h.assertSelected(false);
}); });
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords();
const selectedNow = () => h.state.selectedId === 'base';
assert.equal(selectedNow(), false);
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
assert.equal(dot.show, true);
assert.equal(dot.height, 'clampGround');
assert.equal(dot.pixelSize, 9);
assert.equal(dot.disableDepthTest, Infinity);
// The dot carries the site's shared context record, for point-and-ask.
assert.equal(context.getContextStore().entities.get('base').entity, dot.meta);
h.click({ id: { set: dots.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), true);
assert.equal(context.getSelectedEntityContext().id, 'base');
// Drawn larger and white by the selected set, hidden in its own.
assert.equal(h.draw.set(dots.id).items.get('base').show, false);
assert.equal(h.draw.set(dots.id).items.get('base').pixelSize, 9);
const selectedSet = h.draw.set(h.state.sets.selected.id);
const selected = selectedSet.items.get('base');
assert.equal(selected.pixelSize, 13);
assert.deepEqual(selected.color, [1, 1, 1, 1]);
assert.equal(selected.meta, dot.meta);
// A click on the selected dot clears it.
h.click({ id: { set: selectedSet.spec.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), false);
assert.equal(selectedSet.items.size, 0);
assert.equal(h.draw.set(dots.id).items.get('base').show, true);
const outlines = h.state.sets.outlines;
const outline = h.draw.set(outlines.id).items.get('base:outline:0');
assert.equal(outline.mode, 'draped');
assert.equal(outline.clampTo, 'both');
h.click({ id: { set: outlines.id, id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), true);
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
test('a double-click follows a site dot where it is drawn and zooms to its outline', (t) => {
const h = harness(t);
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords({ claimSelection: true });
h.state.enabled = true;
const follows = [];
const flights = [];
let followed = null;
Object.assign(h.camera, {
follow(target) {
follows.push(target);
followed = target;
},
flyToBounds(sphere, options) {
flights.push({ sphere, options });
},
controls: { minDistance: 1, maxDistance: 1e9 },
});
Object.defineProperty(h.camera, 'followed', { get: () => followed });
let hit = null;
h.query.pick = () => hit;
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, 0, 'nothing of the layer under it');
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
const target = follows.at(-1);
assert.equal(target.key, 'installations:base');
assert.equal(target.frame, 'enu');
// The tracked card reads the site through the target's entity.
assert.equal(target.entity, dot.meta);
assert.equal(target.labelModel.title, 'Base');
const at = target.position(0);
assert.ok(Math.abs(at.x - 6378137) < 1e-6 && Math.abs(at.y) < 1e-6);
// 100 m from it, north up, pitched down 45 degrees.
const range = Math.hypot(
target.viewFrom.x,
target.viewFrom.y,
target.viewFrom.z,
);
assert.ok(Math.abs(range - 100) < 1e-6);
assert.ok(Math.abs(target.viewFrom.x) < 1e-9);
assert.ok(Math.abs(target.viewFrom.y + target.viewFrom.z) < 1e-6);
// On the surface under the dot once its height is loaded, before the
// cached floor has it, and held there.
h.query.sampleHeightNow = () => 2400;
h.input.dblclick({ x: 640, y: 400 });
const raised = follows.at(-1).position(0);
assert.ok(Math.abs(raised.x - 6380537) < 1e-6);
h.query.sampleHeightNow = () => null;
h.input.dblclick({ x: 640, y: 400 });
assert.ok(Math.abs(follows.at(-1).position(0).x - 6378137) < 1e-6);
const outlines = h.state.sets.outlines;
hit = {
set: outlines.id,
id: 'base:outline:0',
meta: { installationId: 'base' },
surface: false,
};
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed, null, 'a zoom stops the follow');
assert.equal(flights.length, 1);
assert.equal(flights[0].options.durationS, 0);
// The follow stops when the layer hides.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed?.key, 'installations:base');
h.parts.rendering.setShown(false);
assert.equal(followed, null);
// Another layer's item under the cursor neither follows nor zooms.
h.parts.rendering.setShown(true);
const before = follows.length;
hit = { set: 'another:1', id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
assert.equal(flights.length, 1);
// With the stock double-click follow turned off, nothing follows.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
const release = inputFor(h.state.viewer).suppressStockClicks();
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
release();
});
+28 -22
View File
@@ -1,54 +1,59 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as C from 'cesium';
import { createRendering } from './rendering.js'; import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js'; import { createLifecycle } from './lifecycle.js';
import { installationMarkers } from './markerState.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness() { function harness() {
const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]]; const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]];
const record = { id: 'base', latitude: 30, longitude: -97, name: 'Base', class: 'base', footprints: [[ring, ring.map(([x,y]) => [x+0.001,y+0.001])], [ring]] }; const record = { id: 'base', latitude: 30, longitude: -97, name: 'Base', class: 'base', footprints: [[ring, ring.map(([x,y]) => [x+0.001,y+0.001])], [ring]] };
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), dataSource: new C.CustomDataSource(), viewer: { scene: { globe: { show: false } }, camera: {} } }; let globeVisible = false;
const viewer = { scene: {}, camera: {} };
const { draw } = bindFakeDraw(viewer, { globe: { isGlobeVisible: () => globeVisible } });
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), viewer };
let listener, removed = 0; let listener, removed = 0;
const noop = () => {}; const noop = () => {};
const services = { ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {}, render: { governorRequestRender: noop }, context: { removeEntityContextsForLayer: noop, clearSelectedEntityContextForLayer: noop }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, maps: { subscribeMapStack(cb) { listener = cb; return () => { listener = null; removed++; }; } } }; const services = { ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {}, render: { governorRequestRender: noop }, context: { removeEntityContextsForLayer: noop, clearSelectedEntityContextForLayer: noop }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, maps: { subscribeMapStack(cb) { listener = cb; return () => { listener = null; removed++; }; } } };
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1], installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } }; const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1], installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } };
parts.rendering = createRendering({ state, services, parts }); parts.rendering = createRendering({ state, services, parts });
parts.rendering.attach(viewer);
const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods; const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods;
return { state, record, parts, lifecycle, changeSurface: () => listener(), removed: () => removed }; const fills = () => [...draw.set(state.sets.fills.id).items.values()];
return { state, record, parts, lifecycle, draw, fills, showGlobe: (shown) => { globeVisible = shown; }, changeSurface: () => listener(), removed: () => removed };
} }
test('selected multipart footprints classify Google tiles with one constant translucent material and holes', () => { test('selected multipart footprints drape on Google tiles with one constant translucent colour and holes', () => {
const h = harness(), render = h.parts.rendering; const h = harness(), render = h.parts.rendering;
render.syncSelectionFill(); render.syncSelectionFill();
const fills = h.state.dataSource.entities.values.slice(); const fills = h.fills();
assert.equal(fills.length, 2); assert.equal(fills.length, 2);
for (const fill of fills) { for (const fill of fills) {
assert.equal(installationMarkers.read(fill)?.recordId, 'base'); assert.equal(fill.meta.installationId, 'base');
assert.equal(fill.polygon.classificationType.getValue(), C.ClassificationType.CESIUM_3D_TILE); assert.equal(fill.clampTo, 'tiles');
assert.equal(fill.polygon.height, undefined); assert.equal(fill.height, 'clampGround');
assert.equal(fill.polygon.extrudedHeight, undefined); assert.equal(fill.extrudeHeight, undefined);
assert.equal(fill.polygon.material.isConstant, true); assert.deepEqual(fill.fill, [1, 165 / 255, 0, 0.22]);
assert.equal(fill.polygon.material.color.getValue().alpha, 0.22);
} }
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1); assert.equal(fills[0].geometry.rings.length, 2, 'the hole is a second ring');
assert.equal(fills[0].polygon.material, fills[1].polygon.material); assert.equal(fills[0].fill, fills[1].fill);
const writes = h.draw.set(h.state.sets.fills.id).writes;
for (let i = 0; i < 100; i++) render.syncSelectionFill(); for (let i = 0; i < 100; i++) render.syncSelectionFill();
assert.deepEqual(h.state.dataSource.entities.values, fills, 'repaints retain ground geometry'); assert.equal(h.draw.set(h.state.sets.fills.id).writes, writes, 'repaints retain ground geometry');
assert.deepEqual(h.fills(), fills);
h.state.selectedId = null; render.syncSelectionFill(); h.state.selectedId = null; render.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0); assert.equal(h.fills().length, 0);
}); });
test('surface changes reclassify selected geometry and disable tears down fills and subscription', () => { test('surface changes reclassify selected geometry and disable tears down fills and subscription', () => {
const h = harness(); const h = harness();
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill(); h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
h.state.viewer.scene.globe.show = true; h.changeSurface(); h.showGlobe(true); h.changeSurface();
assert.ok(h.state.dataSource.entities.values.every(e => e.polygon.classificationType.getValue() === C.ClassificationType.BOTH)); assert.ok(h.fills().every((fill) => fill.clampTo === 'both'));
h.lifecycle.disable(); h.lifecycle.disable();
assert.equal(h.state.dataSource.entities.values.length, 0); assert.equal(h.fills().length, 0);
assert.equal(h.removed(), 1); assert.equal(h.removed(), 1);
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill(); h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0, 'reenabling cannot revive a stale selection'); assert.equal(h.fills().length, 0, 'reenabling cannot revive a stale selection');
h.lifecycle.disable(); h.lifecycle.disable();
}); });
@@ -61,15 +66,16 @@ test('geometry rebuild and canonical alias migration preserve shared selection b
const h = harness(); const h = harness();
const services = { context, render: { governorRequestRender() {} }, ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {} }; const services = { context, render: { governorRequestRender() {} }, ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {} };
const rendering = createRendering({ state: h.state, services, parts: h.parts }); const rendering = createRendering({ state: h.state, services, parts: h.parts });
rendering.attach(h.state.viewer);
const cleared = []; const cleared = [];
window.addEventListener('gev:entity-selection-cleared', e => { cleared.push(e.detail); h.state.selectedId = null; }); window.addEventListener('gev:entity-selection-cleared', e => { cleared.push(e.detail); h.state.selectedId = null; });
rendering.renderRecords({ claimSelection: true }); rendering.renderRecords({ claimSelection: true });
const oldEntity = context.getSelectedEntityContext().entity; const oldCarrier = context.getSelectedEntityContext().entity;
h.record.latitude += 0.001; h.record.latitude += 0.001;
rendering.renderRecords(); rendering.renderRecords();
assert.equal(h.state.selectedId, 'base'); assert.equal(h.state.selectedId, 'base');
assert.equal(context.getSelectedEntityContext().id, 'base'); assert.equal(context.getSelectedEntityContext().id, 'base');
assert.notEqual(context.getSelectedEntityContext().entity, oldEntity); assert.notEqual(context.getSelectedEntityContext().entity, oldCarrier);
const replacement = { ...h.record, id: 'canonical', aliasIds: ['base'] }; const replacement = { ...h.record, id: 'canonical', aliasIds: ['base'] };
h.state.records = [replacement]; h.state.recordById = new Map([['canonical', replacement]]); h.state.records = [replacement]; h.state.recordById = new Map([['canonical', replacement]]);
rendering.renderRecords(); rendering.renderRecords();
+6 -2
View File
@@ -3,7 +3,8 @@ export function createState({ services }) {
Object.assign(state, { Object.assign(state, {
viewer: null, viewer: null,
dataSource: null, /** The layer's draw sets (`dots`, `outlines`, `fills`) while attached. */
sets: null,
enabled: false, enabled: false,
records: [], records: [],
recordById: new Map(), recordById: new Map(),
@@ -32,7 +33,10 @@ export function createState({ services }) {
contextPosition: null, contextPosition: null,
/** Coverage of the last successful load: viewport, or radius around a subject. */ /** Coverage of the last successful load: viewport, or radius around a subject. */
coverage: { kind: 'viewport' }, coverage: { kind: 'viewport' },
/** Per-record geometry keys of the rendered entities, for in-place updates. */ /**
* What each drawn record last drew: its geometry key, outline item ids,
* context carrier, height and selection, for in-place updates.
*/
renderedKeys: new Map(), renderedKeys: new Map(),
}); });
return state; return state;
+10 -11
View File
@@ -21,7 +21,7 @@ export function createInteraction({
// Cross-layer untrack (H2, mirror of flights): if ANOTHER layer (flights, // Cross-layer untrack (H2, mirror of flights): if ANOTHER layer (flights,
// military, …) grabs the follow-camera, drop our tracking so the orbit ring / // military, …) grabs the follow-camera, drop our tracking so the orbit ring /
// tracked entity don't orphan — without touching viewer.trackedEntity (the // tracked dot don't orphan — without touching viewer.trackedEntity (the
// new owner controls it). Guarded so our OWN switch (viewer.trackedEntity // new owner controls it). Guarded so our OWN switch (viewer.trackedEntity
// briefly undefined mid-_trackSatellite) doesn't self-clear. // briefly undefined mid-_trackSatellite) doesn't self-clear.
if (!layerState._trackedEntityChangedRemove) { if (!layerState._trackedEntityChangedRemove) {
@@ -46,18 +46,17 @@ export function createInteraction({
layerState._clickSubscription = inputFor(viewer).onClick((event) => { layerState._clickSubscription = inputFor(viewer).onClick((event) => {
if (!layerState._enabled) return; if (!layerState._enabled) return;
const picked = event.pick; const picked = event.pick;
const hit = event.drawHit;
if (picked) { // Clicking the tracked satellite's own dot — ignore
// Clicking tracked entity itself — ignore if (parts.rendering._hitIsTracked(hit)) return;
if (parts.rendering._pickIsTrackedEntity(picked)) return;
// Check if it's a satellite point (id is NORAD catalog number) // A satellite dot (its item id is the NORAD catalog number)
const noradId = parts.rendering._pickedPointId(picked); const noradId = parts.rendering._hitPointId(hit);
if (noradId !== null && layerState._catalog.has(noradId)) { if (noradId !== null && layerState._catalog.has(noradId)) {
parts.tracking._cancelPendingTrackingRestore(); parts.tracking._cancelPendingTrackingRestore();
parts.tracking._trackSatellite(noradId, { origin: 'user' }); parts.tracking._trackSatellite(noradId, { origin: 'user' });
return; return;
}
} }
// A pick that belongs to a sibling layer (plane, vessel, station, CCTV // A pick that belongs to a sibling layer (plane, vessel, station, CCTV
+3 -3
View File
@@ -13,7 +13,7 @@ export function createLifecycle({
/** Run the shared per-frame tick before each frame draws. */ /** Run the shared per-frame tick before each frame draws. */
function onEachFrame(frame) { function onEachFrame(frame) {
return frame.on('preRender', () => parts.rendering._preRenderTick()); return frame.on('preRender', (t) => parts.rendering._preRenderTick(t));
} }
const methods = { const methods = {
@@ -54,7 +54,7 @@ export function createLifecycle({
layerState._denseError = null; layerState._denseError = null;
layerState._catalogRevision++; layerState._catalogRevision++;
// The collection the satellite dots draw in // The sets the satellite dots, the tracked dot and the rings draw in
parts.rendering._attach(viewer); parts.rendering._attach(viewer);
parts.interaction._installClickHandler(viewer); parts.interaction._installClickHandler(viewer);
@@ -141,7 +141,7 @@ export function createLifecycle({
} }
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID); layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false); layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false);
// The dots' collection and the orbit rings go (and are destroyed) // The dots', tracked dot's and rings' sets are disposed of
parts.rendering._detach(viewer); parts.rendering._detach(viewer);
layerState._points.clear(); layerState._points.clear();
layerState._detectionObjects.clear(); layerState._detectionObjects.clear();
+246 -62
View File
@@ -13,6 +13,9 @@ import {
TRACKED_ORBIT_COLOR, TRACKED_ORBIT_COLOR,
} from './policy.js'; } from './policy.js';
import { createRendering } from './rendering.js'; import { createRendering } from './rendering.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { gstime } from 'satellite.js';
import * as focusDeemphasis from '../../data/focusDeemphasis.js';
const rgba = (color) => [color.red, color.green, color.blue, color.alpha]; const rgba = (color) => [color.red, color.green, color.blue, color.alpha];
@@ -44,9 +47,9 @@ test('point styles keep the colours the dots were drawn in', () => {
test('positions read back from the drawn dots match the Cesium geodetic conversion', () => { test('positions read back from the drawn dots match the Cesium geodetic conversion', () => {
const position = Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000); const position = Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000);
const point = { position, show: true }; const point = { pos: position, show: true };
_setSatelliteLabelLifecycleStateForTest({ _setSatelliteLabelLifecycleStateForTest({
viewer: { scene: { frameState: { frameNumber: 1 } } }, viewer: {},
satrec: null, satrec: null,
point, point,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -68,7 +71,7 @@ test('positions read back from the drawn dots match the Cesium geodetic conversi
} }
}); });
test('only the rendering part drives Cesium', () => { test('no part of the layer drives Cesium', () => {
const offList = [ const offList = [
'catalog', 'catalog',
'controls', 'controls',
@@ -114,6 +117,13 @@ test('only the rendering part drives Cesium', () => {
for (const pattern of forbidden) for (const pattern of forbidden)
assert.doesNotMatch(source, pattern, `${name}.js: ${pattern}`); assert.doesNotMatch(source, pattern, `${name}.js: ${pattern}`);
} }
// The rendering part owns the handles, and draws through the draw port.
const rendering = readFileSync(
new URL('./rendering.js', import.meta.url),
'utf8',
);
for (const pattern of forbidden.slice(0, 7))
assert.doesNotMatch(rendering, pattern, `rendering.js: ${pattern}`);
// The patterns themselves still catch what they are for. // The patterns themselves still catch what they are for.
const caught = [ const caught = [
'layerState._trackedEntity.position.setValue(p)', 'layerState._trackedEntity.position.setValue(p)',
@@ -161,64 +171,238 @@ test('only the rendering part drives Cesium', () => {
); );
}); });
test('the rendering part draws the dots and rings in Cesium colours', () => { test('the rendering part draws the dots, the tracked dot and the rings through the draw port', () => {
const added = []; const viewer = {};
const state = { const { draw, unbind } = bindFakeDraw(viewer);
_points: new Map(), try {
_orbitPaths: new Map(), const state = {
_catalog: new Map([[25544, { satrec: {} }]]), _points: new Map(),
_pointCollection: { add: (options) => ({ ...options }) }, _orbitPaths: new Map(),
_viewer: { scene: { primitives: { add: (p) => added.push(p) } } }, _catalog: new Map([[25544, { satrec: {} }]]),
}; _viewer: viewer,
const path = [ _trackedNorad: null,
{ x: 7e6, y: 0, z: 0 }, _enabled: false,
{ x: 0, y: 7e6, z: 0 }, };
{ x: -7e6, y: 0, z: 0 }, const path = [
]; { x: 7e6, y: 0, z: 0 },
const rendering = createRendering({ { x: 0, y: 7e6, z: 0 },
state, { x: -7e6, y: 0, z: 0 },
services: { focus: {} }, ];
parts: { orbits: { computeOrbitPath: () => path } }, const rendering = createRendering({
}); state,
rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss); services: {
const point = state._points.get(25544); focus: {
assert.ok(point.position instanceof Cesium.Cartesian3); focusNowMs: (ms) => ms,
assert.deepEqual( getFocusTarget: () => null,
[point.position.x, point.position.y, point.position.z], focusPassIsNeeded: () => false,
[1, 2, 3], },
); },
assert.ok(point.color instanceof Cesium.Color); parts: {
assert.deepEqual( orbits: { computeOrbitPath: () => path },
rgba(point.color), tracking: { _getTrackedFramePosition: () => sampleFrame() },
rgba(Cesium.Color.fromCssColorString('#ff4444')), },
); });
assert.deepEqual( // The frame's own sample, taken after the tick's first part.
rgba(point.outlineColor), let sampleFrame = () => null;
rgba(Cesium.Color.WHITE.withAlpha(0.3)), rendering._attach(viewer);
); const points = draw.find('satellites:').spec.id;
assert.equal(point.pixelSize, 12); assert.match(points, /^satellites:\d+:points$/);
assert.equal(point.outlineWidth, 2); rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss);
assert.equal(point.id, 25544); const point = state._points.get(25544);
assert.ok( assert.deepEqual(point.pos, { x: 1, y: 2, z: 3 });
Cesium.NearFarScalar.equals( assert.equal(draw.set(points).items.size, 0, 'sent with the frame');
point.scaleByDistance, rendering._preRenderTick({ frame: 1 });
new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6), const drawn = draw.set(points).items.get('25544');
), assert.equal(drawn, point);
); assert.deepEqual(
[...drawn.color],
rgba(Cesium.Color.fromCssColorString('#ff4444')),
);
assert.deepEqual(
[...drawn.outlineColor],
rgba(Cesium.Color.WHITE.withAlpha(0.3)),
);
assert.equal(drawn.pixelSize, 12);
assert.equal(drawn.outlineWidth, 2);
assert.deepEqual(drawn.meta, { noradId: 25544 });
assert.deepEqual(
{ ...drawn.scaleByDistance },
{ near: 1e6, nearValue: 1.5, far: 2e7, farValue: 0.6 },
);
// Moves go out in one upsert a frame.
const writes = draw.set(points).writes;
rendering._movePoint(25544, { x: 4, y: 5, z: 6 });
rendering._movePoint(25544, { x: 7, y: 8, z: 9 });
rendering._preRenderTick({ frame: 2 });
assert.equal(draw.set(points).writes, writes + 1);
assert.deepEqual(draw.set(points).items.get('25544').pos, {
x: 7,
y: 8,
z: 9,
});
// A pick on a dot names its satellite; one on another set does not.
assert.equal(rendering._hitPointId({ set: points, id: '25544' }), 25544);
assert.equal(rendering._hitPointId({ set: 'other:1', id: '25544' }), null);
rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR); rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR);
assert.equal(added.length, 1); const rings = draw.sets.get(points.replace(':points', ':rings'));
const instance = added[0].geometryInstances; assert.equal(rings.spec.pickable, false, 'ring clicks fall through');
assert.deepEqual( const ring = rings.items.get('25544');
[...instance.attributes.color.value], assert.deepEqual(ring.style, { kind: 'solid', color: [1, 1, 0, 0.6] });
[255, 255, 0, Cesium.Color.floatToByte(0.6)], assert.deepEqual(ring.depthFailColor, [1, 1, 0, 0.35]);
); assert.equal(ring.widthPx, 2.5, 'the ISS ring is wider');
assert.ok( assert.equal(ring.mode, 'geodesic');
instance.geometry._positions.every((p) => p instanceof Cesium.Cartesian3), assert.deepEqual([...ring.positions.slice(0, 3)], [7e6, 0, 0]);
); // Turned with the Earth: by minus the GMST elapsed since its bake.
assert.ok( const path0 = state._orbitPaths.get(25544);
rendering const later = new Date(Date.now() + 600_000);
._rendererPositions(path) rendering._updateOrbitPathRotations(later);
.every((p, i) => p instanceof Cesium.Cartesian3 && p.x === path[i].x), const angle = -(gstime(later) - path0.gmstAtBake);
); const turned = rings.items.get('25544').positions;
assert.ok(Math.abs(turned[0] - 7e6 * Math.cos(angle)) < 1e-3);
assert.ok(Math.abs(turned[1] - 7e6 * Math.sin(angle)) < 1e-3);
rendering._hideOrbitPath(25544);
assert.equal(rings.items.size, 0);
// The tracked dot draws at the tracker's position, from the next frame.
state._trackedNorad = 25544;
state._enabled = true;
state._params = { showPoints: false, showOrbits: false };
let at = { x: 10, y: 20, z: 30 };
const carrier = rendering._addTrackedEntity({ position: () => at });
assert.deepEqual(carrier, { noradId: 25544 });
const tracked = draw.set(points.replace(':points', ':tracked'));
assert.equal(tracked.items.size, 0);
rendering._preRenderTick({ frame: 3 });
assert.deepEqual(tracked.items.get('25544').pos, at);
assert.equal(tracked.items.get('25544').pixelSize, 14);
assert.equal(tracked.items.get('25544').disableDepthTest, Infinity);
at = { x: 11, y: 21, z: 31 };
rendering._preRenderTick({ frame: 4 });
assert.deepEqual(tracked.items.get('25544').pos, at);
// When the follow camera has already sampled this frame's key, the dot
// draws at that sample, before the frame's own sample moves it on.
const framed = { x: 12, y: 22, z: 32 };
at = framed;
state._trackedFrameGeo = {};
state._trackedFrameNumber = 4;
sampleFrame = () => {
at = { x: 13, y: 23, z: 33 };
return at;
};
rendering._preRenderTick({ frame: 5 });
assert.deepEqual(tracked.items.get('25544').pos, framed);
// With no sample under the frame's key, it draws after the frame's own.
state._trackedFrameNumber = 3;
at = framed;
rendering._preRenderTick({ frame: 6 });
assert.deepEqual(tracked.items.get('25544').pos, { x: 13, y: 23, z: 33 });
assert.equal(
rendering._hitIsTracked({ set: tracked.spec.id, id: '25544' }),
true,
);
rendering._removeTrackedEntity(carrier);
assert.equal(tracked.items.size, 0);
rendering._detach(viewer);
assert.ok([...draw.sets.values()].every((set) => set.disposed));
} finally {
unbind();
}
});
test('the orbit frame matrix turns ECEF about Z by minus the GMST elapsed', () => {
const rendering = createRendering({
state: {},
services: { focus: {} },
parts: {},
});
const bake = new Date('2026-07-20T10:00:00Z');
const now = new Date('2026-07-20T10:10:00Z');
const m = rendering.orbitFrameModelMatrix(gstime(bake), now);
const angle = -(gstime(now) - gstime(bake));
assert.equal(m.length, 16);
assert.ok(Math.abs(m[0] - Math.cos(angle)) < 1e-12);
assert.ok(Math.abs(m[1] - Math.sin(angle)) < 1e-12);
assert.ok(Math.abs(m[4] + Math.sin(angle)) < 1e-12);
assert.equal(m[10], 1);
assert.equal(m[15], 1);
// Written in place into a matrix it is handed.
const into = new Cesium.Matrix4();
assert.equal(rendering.orbitFrameModelMatrix(gstime(bake), now, into), into);
assert.ok(Math.abs(into[0] - Math.cos(angle)) < 1e-12);
});
test('the focus pass projects every dot in one call and dims the dot under the focus', () => {
const viewer = {};
const calls = [];
const { unbind } = bindFakeDraw(viewer, {
camera: { pose: () => ({ position: { x: 0, y: 0, z: 0 } }) },
query: {
// Screen x, y are the point's own x, y.
projectMany(source, out) {
calls.push(source.length / 3);
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
out[j] = source[i];
out[j + 1] = source[i + 1];
}
},
project: () => {
throw new Error('the pass projects in one batch');
},
},
});
try {
const target = {
screenRect: { left: 90, right: 110, top: 90, bottom: 110 },
cameraDistance: 1,
};
const state = {
_points: new Map(),
_orbitPaths: new Map(),
_catalog: new Map(),
_viewer: viewer,
_trackedNorad: null,
_enabled: true,
_params: { showPoints: true, showOrbits: false },
_activeFocusCount: 0,
_lastFocusUpdate: -Infinity,
};
const rendering = createRendering({
state,
services: {
focus: {
...focusDeemphasis,
focusNowMs: (ms) => ms,
getFocusTarget: () => target,
focusPassIsNeeded: () => true,
},
},
parts: {
controls: { _pointStyleFor: () => ({ color: [1, 1, 1, 1] }) },
tracking: { _getTrackedFramePosition: () => null },
},
});
rendering._attach(viewer);
const style = { ...POINT_STYLES.iss, color: [1, 1, 1, 1] };
rendering._addPoint(1, { x: 100, y: 100, z: 0 }, style);
rendering._addPoint(2, { x: 100, y: 100, z: 0 }, style);
rendering._addPoint(3, { x: 500, y: 500, z: 0 }, style);
rendering._addPoint(4, { x: 100, y: 100, z: 0 }, style);
state._points.get(2).show = false;
state._trackedNorad = 4;
for (let now = 0; now <= 5000; now += 100) rendering._updatePointFocus(now);
assert.ok(calls.length > 0);
assert.ok(
calls.every((n) => n === 4),
'one call over every dot',
);
const alpha = (id) => state._points.get(id).color[3];
assert.ok(alpha(1) < 1, 'the dot under the focus dims');
assert.equal(alpha(2), 1, 'a hidden dot is not dimmed');
assert.equal(alpha(3), 1, 'a dot away from the focus is not dimmed');
assert.equal(alpha(4), 1, 'the tracked dot is not dimmed');
rendering._detach(viewer);
} finally {
unbind();
}
}); });
+416 -251
View File
@@ -1,39 +1,55 @@
import * as Cesium from 'cesium'; import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
// The camera and frame ports over a viewer with no renderer bound, for the import { fromDegreesInto } from '../../geo/ellipsoid.js';
// tracking and lifecycle parts that follow and tick through them. import { distance } from '../../geo/vector.js';
import '../../render/cesium/camera.js';
import '../../render/cesium/frame.js';
import { toCartesian } from '../../render/cesium/common.js';
import { toColor as cesiumColor } from '../../render/cesium/draw.js';
import { gstime } from 'satellite.js'; import { gstime } from 'satellite.js';
import { ISS_NORAD, POSITION_UPDATE_MS, RING_ROTATION_MS } from './policy.js'; import { ISS_NORAD, POSITION_UPDATE_MS, RING_ROTATION_MS } from './policy.js';
/** /**
* The satellites layer's Cesium side: the point collection and its point * The satellites layer's drawing, through the renderer contract's draw port:
* primitives, the baked orbit-ring primitives, the tracked entity the follow * a points set of the satellite dots, a points set of the tracked
* camera and the tracked card read, and the per-frame tick that moves them. * satellite's dot, and a lines set of the orbit rings, with the per-frame
* The other parts hand it render-contract values (ECEF `{x, y, z}`, colours * tick that moves them. The other parts hand it render-contract values
* as `[r, g, b, a]`) and never touch these objects themselves. * (ECEF `{x, y, z}`, colours as `[r, g, b, a]`).
*
* `layerState._points` keeps each satellite's dot as the point item it is
* drawn from (NORAD id → item): its `pos` is moved in place, so a reader
* holding it sees where the dot is now, as one holding a point primitive's
* position did. Writes are kept and sent to the set once per frame, at the
* end of the tick, so a catalog of thousands moves in one upsert.
*/ */
/** Points shrink with distance as they always have. */ /** Points shrink with distance as they always have. */
const POINT_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6); const POINT_SCALE_BY_DISTANCE = Object.freeze({
near: 1e6,
nearValue: 1.5,
far: 2e7,
farValue: 0.6,
});
/** Each policy style once in Cesium's colours (styles are module constants). */ /**
const cesiumStyles = new WeakMap(); * The tracked satellite's dot: 14 px yellow with a white outline, drawn
function cesiumStyleOf(style) { * over everything.
let converted = cesiumStyles.get(style); */
if (!converted) { const TRACKED_DOT = Object.freeze({
converted = { pixelSize: 14,
pixelSize: style.pixelSize, color: Object.freeze([1, 1, 0, 1]),
color: cesiumColor(style.color), outlineColor: Object.freeze([1, 1, 1, 1]),
outlineColor: cesiumColor(style.outlineColor), outlineWidth: 2,
outlineWidth: style.outlineWidth, disableDepthTest: Number.POSITIVE_INFINITY,
}; });
cesiumStyles.set(style, converted);
} /** An orbit ring's colour when none is given (cyan). */
return converted; const DEFAULT_RING_COLOR = Object.freeze([0, 1, 1, 1]);
}
/** Rings: this alpha in front of the globe, the dimmer one behind it. */
const RING_ALPHA = 0.6;
const RING_BEHIND_ALPHA = 0.35;
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** Layer instances so far: set ids unique to each. */
let instances = 0;
export function createRendering({ export function createRendering({
state: layerState, state: layerState,
@@ -51,96 +67,182 @@ export function createRendering({
publishFocusTargetAt, publishFocusTargetAt,
} = services.focus; } = services.focus;
const scratchFocusScreen = new Cesium.Cartesian2();
const scratchRingRotation = new Cesium.Matrix3();
// The tracked satellite's per-frame ECEF sample (WS-D2), shared with the // The tracked satellite's per-frame ECEF sample (WS-D2), shared with the
// tracked entity, the follow camera and the tracked card. Tracking writes // tracked dot, the follow camera and the tracked card. Tracking writes its
// its x/y/z; it stays one Cesium value for the readers that take it. // x/y/z in place.
layerState._trackedFrameCartesian = new Cesium.Cartesian3(); layerState._trackedFrameCartesian = { x: 0, y: 0, z: 0 };
/** The draw sets, while attached: `{points, tracked, rings}`. */
let sets = null;
/** Dots changed since the last write to the set, by NORAD id. */
const dirty = new Set();
/** Dots removed since the last write to the set, by NORAD id. */
const gone = new Set();
/** Whether every dot was removed since the last write. */
let cleared = false;
/** Whether the satellite dots are shown. */
let pointsShown = true;
/**
* The tracked dot: its item and how its position is read (the tracker's
* callback, read as the follow camera reads it).
*/
let trackedDot = null;
let trackedDrawnThisTick = false;
/** The frame the tick last ran in: the tracked sample's cache key. */
let renderedFrame = -1;
/** /**
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST * Build the rigid ECEF transform that keeps an orbit path baked at one GMST
* aligned with live SGP4 positions propagated at another epoch. * aligned with live SGP4 positions propagated at another epoch: a column-
* major 4×4 rotation about Z.
* @param {number} gmstAtBake GMST used when the path positions were baked. * @param {number} gmstAtBake GMST used when the path positions were baked.
* @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed. * @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed.
* @param {Cesium.Matrix4} [result] Optional matrix to update in place. * @param {ArrayLike<number>} [result] A 16-element matrix to update in place.
* @returns {Cesium.Matrix4} Z-rotation from bake-time ECEF to current ECEF. * @returns {ArrayLike<number>} Z-rotation from bake-time ECEF to current ECEF.
*/ */
function orbitFrameModelMatrix( function orbitFrameModelMatrix(gmstAtBake, nowDate, result = new Array(16)) {
gmstAtBake, const angle = -(gstime(nowDate) - gmstAtBake);
nowDate, const c = Math.cos(angle);
result = new Cesium.Matrix4(), const s = Math.sin(angle);
) { result[0] = c;
const deltaGmst = gstime(nowDate) - gmstAtBake; result[1] = s;
const rotation = Cesium.Matrix3.fromRotationZ( result[2] = 0;
-deltaGmst, result[3] = 0;
scratchRingRotation, result[4] = -s;
); result[5] = c;
return Cesium.Matrix4.fromRotationTranslation( result[6] = 0;
rotation, result[7] = 0;
Cesium.Cartesian3.ZERO, result[8] = 0;
result, result[9] = 0;
); result[10] = 1;
result[11] = 0;
result[12] = 0;
result[13] = 0;
result[14] = 0;
result[15] = 1;
return result;
} }
/** ECEF `{x, y, z}` positions as the renderer's own. */ /** ECEF `{x, y, z}` positions as the renderer's own: plain copies. */
function _rendererPositions(positions) { function _rendererPositions(positions) {
return positions.map(toCartesian); return positions.map((p) => ({ x: p.x, y: p.y, z: p.z }));
} }
/** The scene's rendered-frame number, the tracked sample's cache key. */ /** The frame the tick last ran in, the tracked sample's cache key. */
function _drawnFrameNumber() { function _drawnFrameNumber() {
return layerState._viewer?.scene?.frameState?.frameNumber ?? -1; return renderedFrame;
} }
/** Add the point collection the satellite dots draw in. */ /** Make the sets the dots, the tracked dot and the rings draw in. */
function _attach(viewer) { function _attach(viewer) {
layerState._pointCollection = new Cesium.PointPrimitiveCollection(); _attachTo(drawOf(viewer));
viewer.scene.primitives.add(layerState._pointCollection);
} }
/** Remove the point collection and every orbit ring from `viewer`. */ /** Make the layer's sets on `draw`, a draw port. */
function _attachTo(draw) {
if (sets) _detach();
const prefix = `satellites:${++instances}`;
pointsShown = true;
sets = {
points: draw.points({ id: `${prefix}:points`, show: pointsShown }),
tracked: draw.points({ id: `${prefix}:tracked` }),
// Ring clicks fall through to the satellites and the deselect.
rings: draw.lines({ id: `${prefix}:rings`, pickable: false }),
};
layerState._sets = sets;
dirty.clear();
gone.clear();
cleared = false;
// Dots kept while detached draw once attached.
for (const noradId of layerState._points.keys()) dirty.add(noradId);
}
/** Dispose of the sets; the dots and rings go with them. */
function _detach(viewer) { function _detach(viewer) {
if (layerState._pointCollection) { if (!sets) return;
viewer.scene.primitives.remove(layerState._pointCollection); sets.points.dispose();
layerState._pointCollection = null; sets.tracked.dispose();
} sets.rings.dispose();
// Orbit ring primitives are removed (and destroyed) here sets = null;
for (const path of layerState._orbitPaths.values()) { layerState._sets = null;
viewer.scene.primitives.remove(path.primitive); trackedDot = null;
} dirty.clear();
gone.clear();
cleared = false;
} }
/** Whether there is a point collection to draw satellites in. */ /** Whether there is a set to draw satellites in. */
function _hasPointCollection() { function _hasPointCollection() {
return Boolean(layerState._pointCollection); return Boolean(sets);
} }
/** Whether the satellite dots are shown. */ /** Whether the satellite dots are shown. */
function _pointsShown() { function _pointsShown() {
return Boolean(layerState._pointCollection?.show); return Boolean(sets) && pointsShown;
} }
function _setPointsShown(show) { function _setPointsShown(show) {
if (layerState._pointCollection) layerState._pointCollection.show = show; if (!sets) return;
pointsShown = show;
sets.points.show = show;
} }
/** Show or hide every ring. */
function _setOrbitPathsShown(show) { function _setOrbitPathsShown(show) {
for (const path of layerState._orbitPaths.values()) const changed = [];
path.primitive.show = show; for (const path of layerState._orbitPaths.values()) {
path.item.show = show;
changed.push(path.item);
}
if (sets && changed.length) sets.rings.upsert(changed);
} }
function _setOrbitPathShown(noradId, show) { function _setOrbitPathShown(noradId, show) {
const path = layerState._orbitPaths.get(noradId); const path = layerState._orbitPaths.get(noradId);
if (path) path.primitive.show = show; if (!path) return;
path.item.show = show;
sets?.rings.upsert([path.item]);
} }
/** Remove every orbit ring from `viewer`'s scene. */ /** Remove every orbit ring. */
function _clearOrbitPaths(viewer) { function _clearOrbitPaths() {
for (const path of layerState._orbitPaths.values()) const ids = [...layerState._orbitPaths.values()].map(
viewer.scene.primitives.remove(path.primitive); (path) => path.item.id,
);
layerState._orbitPaths.clear(); layerState._orbitPaths.clear();
if (sets && ids.length) sets.rings.remove(ids);
}
/** Note a dot's change, sent at the end of the frame's tick. */
function _markDirty(noradId) {
gone.delete(noradId);
dirty.add(noradId);
}
/** Send the dots changed since the last frame to the points set. */
function _flushPoints() {
if (!sets) return;
if (cleared) {
cleared = false;
gone.clear();
dirty.clear();
sets.points.set([...layerState._points.values()]);
return;
}
if (gone.size) {
sets.points.remove([...gone].map(String));
gone.clear();
}
if (dirty.size) {
const items = [];
for (const noradId of dirty) {
const item = layerState._points.get(noradId);
if (item) items.push(item);
}
dirty.clear();
if (items.length) sets.points.upsert(items);
}
} }
/** /**
@@ -150,104 +252,125 @@ export function createRendering({
* @param {object} style A `POINT_STYLES` entry. * @param {object} style A `POINT_STYLES` entry.
*/ */
function _addPoint(noradId, position, style) { function _addPoint(noradId, position, style) {
const look = cesiumStyleOf(style); layerState._points.set(noradId, {
const point = layerState._pointCollection.add({ id: String(noradId),
position: toCartesian(position), pos: { x: position.x, y: position.y, z: position.z },
pixelSize: look.pixelSize, pixelSize: style.pixelSize,
color: look.color, color: style.color,
outlineColor: look.outlineColor, outlineColor: style.outlineColor,
outlineWidth: look.outlineWidth, outlineWidth: style.outlineWidth,
scaleByDistance: POINT_SCALE_BY_DISTANCE, scaleByDistance: POINT_SCALE_BY_DISTANCE,
id: noradId, disableDepthTest: 0,
show: true,
meta: { noradId },
}); });
layerState._points.set(noradId, point); _markDirty(noradId);
} }
/** Move a drawn dot to ECEF `position`; false when it has none. */ /** Move a drawn dot to ECEF `position`; false when it has none. */
function _movePoint(noradId, position) { function _movePoint(noradId, position) {
const point = layerState._points.get(noradId); const point = layerState._points.get(noradId);
if (!point) return false; if (!point) return false;
point.position = position; // primitive setter clones point.pos.x = position.x;
point.pos.y = position.y;
point.pos.z = position.z;
_markDirty(noradId);
return true; return true;
} }
function _removePoint(noradId) { function _removePoint(noradId) {
const point = layerState._points.get(noradId); if (!layerState._points.delete(noradId)) return;
if (point && layerState._pointCollection) dirty.delete(noradId);
layerState._pointCollection.remove(point); if (!cleared) gone.add(noradId);
layerState._points.delete(noradId);
} }
/** Remove every dot. */ /** Remove every dot. */
function _clearPoints() { function _clearPoints() {
layerState._pointCollection.removeAll();
layerState._points.clear(); layerState._points.clear();
dirty.clear();
gone.clear();
cleared = true;
} }
/** Where a dot is drawn (ECEF), or null. */ /** Where a dot is drawn (ECEF), or null. */
function _pointPosition(noradId) { function _pointPosition(noradId) {
return layerState._points.get(noradId)?.position || null; return layerState._points.get(noradId)?.pos || null;
} }
/** Hide a dot while the tracked entity draws it. */ /** Hide a dot while the tracked dot draws it. */
function _hidePoint(noradId) { function _hidePoint(noradId) {
const point = layerState._points.get(noradId); const point = layerState._points.get(noradId);
if (point) point.show = false; if (!point) return;
point.show = false;
_markDirty(noradId);
} }
/** Show a dot again in its group's style (WS-D3). */ /** Show a dot again in its group's style (WS-D3). */
function _restorePoint(noradId, style) { function _restorePoint(noradId, style) {
const point = layerState._points.get(noradId); const point = layerState._points.get(noradId);
if (!point) return; if (!point) return;
const look = cesiumStyleOf(style);
point.show = true; point.show = true;
point.pixelSize = look.pixelSize; point.pixelSize = style.pixelSize;
point.color = look.color; point.color = style.color;
point.outlineColor = look.outlineColor; point.outlineColor = style.outlineColor;
point.outlineWidth = look.outlineWidth; point.outlineWidth = style.outlineWidth;
point.disableDepthTestDistance = 0; point.disableDepthTest = 0;
_markDirty(noradId);
} }
/** /**
* Add the tracked satellite's entity: it owns a point graphic so the * Draw the tracked satellite's dot and make the carrier the follow target
* follow camera can resolve a bounding sphere (a label-only entity left * and the tracked card read (its entity record holds the card).
* the camera stranded), and the tracked card reads its entity record.
* @param {{position: () => object, viewFrom: {x: number, y: number, * @param {{position: () => object, viewFrom: {x: number, y: number,
* z: number}}} options `position` is evaluated every time it is read. * z: number}}} options `position` is read as the follow camera reads
* @returns {object} The entity. * it, once each frame before the tick moves the sample on.
* @returns {object} The carrier.
*/ */
function _addTrackedEntity({ position, viewFrom }) { function _addTrackedEntity({ position }) {
return layerState._viewer.entities.add({ const noradId = layerState._trackedNorad;
position: new Cesium.CallbackProperty(position, false), const carrier = { noradId };
viewFrom: toCartesian(viewFrom), trackedDot = {
point: { position,
pixelSize: 14, item: {
color: Cesium.Color.YELLOW, id: String(noradId),
outlineColor: Cesium.Color.WHITE, pos: { x: 0, y: 0, z: 0 },
outlineWidth: 2, ...TRACKED_DOT,
disableDepthTestDistance: Number.POSITIVE_INFINITY, meta: { noradId },
}, },
}); drawn: false,
};
// Drawn from the next frame's tick on, as the camera first frames it.
return carrier;
} }
function _removeTrackedEntity(entity) { function _removeTrackedEntity() {
layerState._viewer.entities.remove(entity); if (trackedDot?.drawn) sets?.tracked.clear();
trackedDot = null;
} }
/** Whether a scene pick is the tracked satellite's entity. */ /** Put the tracked dot where the tracker says it is now. */
function _pickIsTrackedEntity(picked) { function _drawTrackedDot() {
return picked?.id === layerState._trackedEntity; if (!trackedDot || !sets) return;
const at = trackedDot.position();
if (!at) return;
const pos = trackedDot.item.pos;
pos.x = at.x;
pos.y = at.y;
pos.z = at.z;
sets.tracked.upsert([trackedDot.item]);
trackedDot.drawn = true;
} }
/** /** Whether a click's draw hit is the tracked satellite's dot. */
* The NORAD id a scene pick's point primitive carries, or null. Any function _hitIsTracked(hit) {
* primitive with a numeric id answers; the caller checks the catalog. return Boolean(sets) && hit?.set === sets.tracked.id;
*/ }
function _pickedPointId(picked) {
const prim = picked?.primitive; /** The NORAD id of the satellite dot a click's draw hit is on, or null. */
if (!prim || prim.id == null) return null; function _hitPointId(hit) {
const noradId = Number(prim.id); if (!sets || hit?.set !== sets.points.id) return null;
return isNaN(noradId) ? null : noradId; const noradId = Number(hit.id);
return Number.isFinite(noradId) ? noradId : null;
} }
/** Publish the tracked satellite's focus rectangle from its cached position. */ /** Publish the tracked satellite's focus rectangle from its cached position. */
@@ -255,23 +378,27 @@ export function createRendering({
publishFocusTargetAt({ ...target, viewer: layerState._viewer }); publishFocusTargetAt({ ...target, viewer: layerState._viewer });
} }
/** A ring's positions rotated from its bake-time frame to `gmst`'s. */
function _ringPositions(path, gmst) {
const angle = -(gmst - path.gmstAtBake);
const c = Math.cos(angle);
const s = Math.sin(angle);
const base = path.base;
const out = new Float64Array(base.length * 3);
for (let i = 0; i < base.length; i++) {
const p = base[i];
out[i * 3] = c * p.x - s * p.y;
out[i * 3 + 1] = s * p.x + c * p.y;
out[i * 3 + 2] = p.z;
}
return out;
}
/** /**
* Show orbital path for a satellite. * Show orbital path for a satellite: the ring over one orbit, baked once
* * in ECEF at the current GMST, bright in front of the globe and dimmed
* RING FLICKER FIX: this is a one-instance Cesium.Primitive built * behind it (`depthFailColor`), and turned with the Earth each
* synchronously ONCE (asynchronous: false), then re-aligned to current GMST * `RING_ROTATION_MS` (`_updateOrbitPathRotations`).
* each tick via its modelMatrix. The previous Entity-polyline approach
* rebuilt geometry ASYNCHRONOUSLY on every positions assignment, which made
* both the selected ring and the ISS ring blink once per second while the
* rebuild was in flight. A rigid Z-rotation needs no rebuild at all.
*
* Why not a CallbackProperty entity (dynamic mode)? Verified in Cesium
* 1.138 source: the dynamic polyline updater renders through a shared
* PolylineCollection and applies only the fill material —
* `depthFailMaterial` is silently dropped, losing the dimmed behind-Earth
* segment. The Primitive keeps it via depthFailAppearance + the per-instance
* depthFailColor attribute (same mechanism the entity STATIC batch uses):
* bright where above the horizon, dimmed where behind the globe.
*/ */
function _showOrbitPath(noradId, color) { function _showOrbitPath(noradId, color) {
@@ -281,86 +408,64 @@ export function createRendering({
if (!sat || !layerState._viewer) return; if (!sat || !layerState._viewer) return;
const bakeDate = new Date(); const bakeDate = new Date();
const basePositions = _rendererPositions( const base = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
parts.orbits.computeOrbitPath(sat.satrec, bakeDate), if (base.length < 2) return;
);
if (basePositions.length < 2) return;
const pathColor = color ? cesiumColor(color) : Cesium.Color.CYAN; const pathColor = color || DEFAULT_RING_COLOR;
const path = {
const primitive = new Cesium.Primitive({ base,
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolylineGeometry({
positions: basePositions,
width: noradId === ISS_NORAD ? 2.5 : 2.0,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.6),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.35),
),
},
}),
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
depthFailAppearance: new Cesium.PolylineColorAppearance({
translucent: true,
}),
asynchronous: false, // build this frame — no async-rebuild blink window
allowPicking: false, // ring clicks fall through to satellites/deselect
});
layerState._viewer.scene.primitives.add(primitive);
layerState._orbitPaths.set(noradId, {
primitive,
// Same Date object as computeOrbitPath's internal fixedGmst → identical // Same Date object as computeOrbitPath's internal fixedGmst → identical
// GMST value (gstime is pure), so delta starts at exactly 0 and the // GMST value (gstime is pure), so the ring starts unturned.
// initial identity modelMatrix is correct until the first ring tick.
gmstAtBake: gstime(bakeDate), gmstAtBake: gstime(bakeDate),
}); item: null,
};
path.item = {
id: String(noradId),
positions: _ringPositions(path, path.gmstAtBake),
widthPx: noradId === ISS_NORAD ? 2.5 : 2.0,
// Along the ellipsoid between samples, as the ring always ran.
mode: 'geodesic',
style: { kind: 'solid', color: withAlpha(pathColor, RING_ALPHA) },
depthFailColor: withAlpha(pathColor, RING_BEHIND_ALPHA),
show: true,
};
layerState._orbitPaths.set(noradId, path);
sets?.rings.upsert([path.item]);
} }
/** /**
* Rotate every baked orbit ring from its bake-time ECEF snapshot to current * Turn every baked orbit ring from its bake-time ECEF snapshot to current
* GMST (WS-D1). The baked ring is an inertial-frame snapshot frozen at * GMST (WS-D1). The baked ring is an inertial-frame snapshot frozen at
* gmstAtBake; the live dot lives in true rotating-frame ECEF, so without this * gmstAtBake; the live dot lives in true rotating-frame ECEF, so without this
* the dot slides west off the ring at Earth-rotation rate (~0.25°/min). * the dot slides west off the ring at Earth-rotation rate (~0.25°/min).
* *
* Sign derivation: a point fixed in inertial space keeps its right ascension * Sign derivation: a point fixed in inertial space keeps its right ascension
* α, so its ECEF longitude λ = α − gmst DECREASES by ΔGMST as time advances * α, so its ECEF longitude λ = α − gmst DECREASES by ΔGMST as time advances
* (it drifts WEST). Cesium.Matrix3.fromRotationZ(θ) rotates +X toward +Y, * (it drifts WEST). A rotation about Z by θ INCREASES longitude by θ — so
* i.e. INCREASES longitude by θ — so we rotate the baked points by −ΔGMST. * the baked points are rotated by −ΔGMST. Mental check: ISS baked over
* Mental check: ISS baked over Austin at t0; 10 min later Austin has rotated * Austin at t0; 10 min later Austin has rotated east under the (inertial)
* east under the (inertial) ring, so the ring must sit further WEST in ECEF. * ring, so the ring must sit further WEST in ECEF.
* *
* Wraparound: gstime returns radians in [0, 2π), so the raw difference can be * Wraparound: gstime returns radians in [0, 2π), so the raw difference can be
* off from the continuous ΔGMST — but only by exact multiples of 2π, which a * off from the continuous ΔGMST — but only by exact multiples of 2π, which a
* rotation cannot distinguish. Tiny negative deltas right after bake are * rotation cannot distinguish. Tiny negative deltas right after bake are
* likewise harmless. No unwrapping needed. * likewise harmless. No unwrapping needed.
* *
* No SGP4 here — the rotation is applied as the ring primitive's modelMatrix * No SGP4 here: WGS84 is rotationally symmetric about Z, so rotating the
* (exact compensation; WGS84 is rotationally symmetric about Z, so rotating * baked curve rigidly equals rebaking from rotated points. A ring with a
* the baked curve rigidly equals rebaking from rotated points). modelMatrix * `depthFailColor` is built at once where it now runs, so it never blinks.
* updates are synchronous uniforms — no geometry rebuild, no flicker. Post-
* creation modelMatrix changes are supported for one-instance primitives in
* 3D mode, which these rings are. In-place mutation is safe: Primitive.update
* diffs modelMatrix against an internal clone.
* @param {Date} nowDate Epoch used for current GMST. * @param {Date} nowDate Epoch used for current GMST.
*/ */
function _updateOrbitPathRotations(nowDate) { function _updateOrbitPathRotations(nowDate) {
if (layerState._orbitPaths.size === 0) return; if (layerState._orbitPaths.size === 0) return;
const gmst = gstime(nowDate);
const changed = [];
for (const path of layerState._orbitPaths.values()) { for (const path of layerState._orbitPaths.values()) {
if (!path.primitive) continue; path.item.positions = _ringPositions(path, gmst);
orbitFrameModelMatrix( changed.push(path.item);
path.gmstAtBake,
nowDate,
path.primitive.modelMatrix,
);
} }
sets?.rings.upsert(changed);
} }
/** /**
@@ -369,15 +474,13 @@ export function createRendering({
function _hideOrbitPath(noradId) { function _hideOrbitPath(noradId) {
const path = layerState._orbitPaths.get(noradId); const path = layerState._orbitPaths.get(noradId);
if (path) { if (!path) return;
if (layerState._viewer) layerState._orbitPaths.delete(noradId);
layerState._viewer.scene.primitives.remove(path.primitive); // remove() destroys sets?.rings.remove([path.item.id]);
layerState._orbitPaths.delete(noradId);
}
} }
/** /**
* Propagate all CORE satellite positions and update point primitives. * Propagate all CORE satellite positions and update their dots.
* (~840 sats ≈ 1.6 ms/pass — fine at the 1s/200ms cadence.) Dense extras are * (~840 sats ≈ 1.6 ms/pass — fine at the 1s/200ms cadence.) Dense extras are
* excluded: they refresh on the round-robin budget in _propagateDenseChunk. * excluded: they refresh on the round-robin budget in _propagateDenseChunk.
*/ */
@@ -391,14 +494,10 @@ export function createRendering({
const pos = parts.orbits.propagatePosition(sat.satrec, now); const pos = parts.orbits.propagatePosition(sat.satrec, now);
if (!pos) continue; if (!pos) continue;
const cartesian = Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
const point = layerState._points.get(noradId); const point = layerState._points.get(noradId);
if (point) { if (point) {
point.position = cartesian; fromDegreesInto(pos.longitude, pos.latitude, pos.altitude, point.pos);
_markDirty(noradId);
updated++; updated++;
} }
} }
@@ -407,15 +506,43 @@ export function createRendering({
} }
/** /**
* Shared scene.preRender tick (single definition for init + enable): * Shared preRender tick (single definition for init + enable):
* - the tracked dot where the follow camera put it this frame,
* - core fleet propagation at 200ms-tracked / 1s-idle cadence, * - core fleet propagation at 200ms-tracked / 1s-idle cadence,
* - dense extras on a per-frame round-robin budget, * - dense extras on a per-frame round-robin budget,
* - tracked satellite's point primitive per frame (WS-D2), * - tracked satellite's dot sample per frame (WS-D2),
* - orbit ring GMST re-alignment every ~1s (WS-D1). * - orbit ring GMST re-alignment every ~1s (WS-D1),
* - the frame's dot changes sent to the points set.
* @param {{frame: number}} [t] The frame port's tick.
*/ */
function _preRenderTick() { function _preRenderTick(t) {
if (!layerState._enabled) return; if (layerState._enabled) _tick();
// The frame's sample is taken from here on (the tracked dot above was
// drawn from the last one, as the camera framed it).
renderedFrame = Number.isFinite(t?.frame) ? t.frame : renderedFrame + 1;
if (layerState._enabled) _tickAfterFrame();
_flushPoints();
}
/** The tick's part read before the frame's own sample is taken. */
function _tick() {
// The tracked dot draws at the sample the follow camera framed this frame.
// With no camera reading it this frame, it is drawn after the frame's own
// sample instead, so the tracked satellite is propagated once a frame.
trackedDrawnThisTick = false;
if (
layerState._trackedNorad !== null &&
layerState._trackedFrameGeo !== null &&
layerState._trackedFrameNumber === renderedFrame
) {
_drawTrackedDot();
trackedDrawnThisTick = true;
}
}
/** The tick's part that takes the frame's own sample. */
function _tickAfterFrame() {
const now = focusNowMs(Date.now()); const now = focusNowMs(Date.now());
const interval = layerState._trackedNorad ? 200 : POSITION_UPDATE_MS; const interval = layerState._trackedNorad ? 200 : POSITION_UPDATE_MS;
@@ -433,20 +560,20 @@ export function createRendering({
if (layerState._params.showPoints) parts.catalog._propagateDenseChunk(); if (layerState._params.showPoints) parts.catalog._propagateDenseChunk();
// Keep the tracked dot on the per-frame epoch shared with label + camera — // Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
// runs after _propagateAll so the per-frame sample wins over the 200ms one. // with label + camera — runs after _propagateAll so the per-frame sample
// wins over the 200ms one.
if (layerState._trackedNorad !== null) { if (layerState._trackedNorad !== null) {
const pos = parts.tracking._getTrackedFramePosition(); const pos = parts.tracking._getTrackedFramePosition();
const point = layerState._points.get(layerState._trackedNorad); if (pos && layerState._points.has(layerState._trackedNorad))
if (pos && point) { _movePoint(layerState._trackedNorad, layerState._trackedFrameCartesian);
point.position = layerState._trackedFrameCartesian; // primitive setter clones if (!trackedDrawnThisTick) _drawTrackedDot();
}
} }
_updatePointFocus(now); _updatePointFocus(now);
// Hidden standalone orbit primitives do not need GMST matrix writes while // Hidden standalone orbit rings do not need turning while Space Missions
// Space Missions draws the selected mission orbit itself. // draws the selected mission orbit itself.
if ( if (
layerState._params.showOrbits && layerState._params.showOrbits &&
now - layerState._lastRingRotation >= RING_ROTATION_MS now - layerState._lastRingRotation >= RING_ROTATION_MS
@@ -458,6 +585,12 @@ export function createRendering({
/** Focus alpha for satellite points, inside the existing shared preRender tick. */ /** Focus alpha for satellite points, inside the existing shared preRender tick. */
// The focus pass projects every dot in one call, into buffers kept between
// passes, so a pass over thousands of dots allocates nothing per dot.
let focusSource = new Float64Array(0);
let focusScreen = new Float32Array(0);
const focusOrder = [];
const focusScreenXY = { x: 0, y: 0 };
function _updatePointFocus(nowMs) { function _updatePointFocus(nowMs) {
const target = getFocusTarget(); const target = getFocusTarget();
if ( if (
@@ -467,28 +600,55 @@ export function createRendering({
return; return;
if (nowMs - layerState._lastFocusUpdate < 80) return; if (nowMs - layerState._lastFocusUpdate < 80) return;
layerState._lastFocusUpdate = nowMs; layerState._lastFocusUpdate = nowMs;
const scene = layerState._viewer.scene; const query = findQuery(layerState._viewer);
const camera = layerState._viewer.camera; const eye = findCamera(layerState._viewer)?.pose()?.position;
if (!query || !eye) return;
const count = layerState._points.size;
if (focusSource.length < count * 3) {
focusSource = new Float64Array(count * 3);
focusScreen = new Float32Array(count * 2);
}
focusOrder.length = 0;
for (const point of layerState._points.values()) {
const pos = point?.pos;
const i = focusOrder.length * 3;
focusSource[i] = pos ? pos.x : NaN;
focusSource[i + 1] = pos ? pos.y : NaN;
focusSource[i + 2] = pos ? pos.z : NaN;
focusOrder.push(pos);
}
query.projectMany(
focusSource.subarray(0, focusOrder.length * 3),
focusScreen,
);
// The pass asks in the points' own order, skipping some: a cursor finds
// each asked position in one sweep.
let cursor = 0;
const result = applySatellitePointFocusDeemphasis({ const result = applySatellitePointFocusDeemphasis({
points: layerState._points, points: layerState._points,
trackedId: layerState._trackedNorad, trackedId: layerState._trackedNorad,
target, target,
previousActiveCount: layerState._activeFocusCount, previousActiveCount: layerState._activeFocusCount,
nowMs, nowMs,
screenPositionFor: (position) => screenPositionFor: (position) => {
Cesium.SceneTransforms.worldToWindowCoordinates( while (cursor < focusOrder.length && focusOrder[cursor] !== position)
scene, cursor++;
position, if (cursor >= focusOrder.length) {
scratchFocusScreen, cursor = 0;
), return query.project(position);
cameraDistanceFor: (position) => }
Cesium.Cartesian3.distance(camera.positionWC, position), const x = focusScreen[cursor * 2];
const y = focusScreen[cursor * 2 + 1];
if (Number.isNaN(x) || Number.isNaN(y)) return null;
focusScreenXY.x = x;
focusScreenXY.y = y;
return focusScreenXY;
},
cameraDistanceFor: (position) => distance(eye, position),
baseColorFor: (noradId) => baseColorFor: (noradId) =>
cesiumStyleOf( parts.controls._pointStyleFor(
parts.controls._pointStyleFor( noradId,
noradId, layerState._catalog.get(noradId)?.group,
layerState._catalog.get(noradId)?.group,
),
).color, ).color,
}); });
layerState._activeFocusCount = result.activeCount; layerState._activeFocusCount = result.activeCount;
@@ -497,6 +657,8 @@ export function createRendering({
/** /**
* Apply the gated satellite-point focus pass through the production color path. * Apply the gated satellite-point focus pass through the production color path.
* @param {object} input * @param {object} input
* @param {Map<number, object>} input.points Point items by NORAD id; a
* written colour is sent to the set with the frame's other changes.
* @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}} * @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}}
*/ */
@@ -518,8 +680,8 @@ export function createRendering({
let transitioning = false; let transitioning = false;
let activeCount = 0; let activeCount = 0;
for (const [noradId, point] of points || []) { for (const [noradId, point] of points || []) {
if (noradId === trackedId || !point?.position) continue; if (noradId === trackedId || !point?.pos) continue;
const cameraDistance = cameraDistanceFor(point.position); const cameraDistance = cameraDistanceFor(point.pos);
const distanceScale = nearFarScalarValueAtDistance( const distanceScale = nearFarScalarValueAtDistance(
point.scaleByDistance, point.scaleByDistance,
cameraDistance, cameraDistance,
@@ -529,7 +691,7 @@ export function createRendering({
// Hidden points still release toward identity, preventing stale dim // Hidden points still release toward identity, preventing stale dim
// alpha if a catalog/presentation toggle later makes them visible. // alpha if a catalog/presentation toggle later makes them visible.
screenPosition: screenPosition:
point.show === false ? null : screenPositionFor(point.position), point.show === false ? null : screenPositionFor(point.pos),
cameraDistance, cameraDistance,
nowMs, nowMs,
target, target,
@@ -540,11 +702,12 @@ export function createRendering({
transitioning ||= focus.transitioning; transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1; if (focus.active) activeCount += 1;
const base = baseColorFor(noradId); const base = baseColorFor(noradId);
const alpha = base.alpha * focus.factor; const alpha = base[3] * focus.factor;
if (focusAlphaNeedsWrite(point.color?.alpha, alpha, params)) { if (focusAlphaNeedsWrite(point.color?.[3], alpha, params)) {
// Point stays continuously present at the non-zero emphasis floor; its // Point stays continuously present at the non-zero emphasis floor; its
// own alpha yields around the tracked target, independent of draw order. // own alpha yields around the tracked target, independent of draw order.
point.color = base.withAlpha(alpha); point.color = withAlpha(base, alpha);
if (points === layerState._points) _markDirty(noradId);
writes += 1; writes += 1;
} }
} }
@@ -555,6 +718,7 @@ export function createRendering({
_rendererPositions, _rendererPositions,
_drawnFrameNumber, _drawnFrameNumber,
_attach, _attach,
_attachTo,
_detach, _detach,
_hasPointCollection, _hasPointCollection,
_pointsShown, _pointsShown,
@@ -572,8 +736,8 @@ export function createRendering({
_addTrackedEntity, _addTrackedEntity,
_removeTrackedEntity, _removeTrackedEntity,
_publishTrackedFocus, _publishTrackedFocus,
_pickIsTrackedEntity, _hitIsTracked,
_pickedPointId, _hitPointId,
_showOrbitPath, _showOrbitPath,
_updateOrbitPathRotations, _updateOrbitPathRotations,
_hideOrbitPath, _hideOrbitPath,
@@ -581,5 +745,6 @@ export function createRendering({
_preRenderTick, _preRenderTick,
_updatePointFocus, _updatePointFocus,
applySatellitePointFocusDeemphasis, applySatellitePointFocusDeemphasis,
_flushPoints,
}; };
} }
+7 -3
View File
@@ -12,6 +12,7 @@ import { createTracking } from './tracking.js';
import { createRendering } from './rendering.js'; import { createRendering } from './rendering.js';
import { bindRenderer } from '../../render/rendererOf.js'; import { bindRenderer } from '../../render/rendererOf.js';
import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs'; import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { createCatalog } from './catalog.js'; import { createCatalog } from './catalog.js';
import { createLifecycle } from './lifecycle.js'; import { createLifecycle } from './lifecycle.js';
import { createInteraction } from './interaction.js'; import { createInteraction } from './interaction.js';
@@ -66,7 +67,7 @@ async function fixture(t) {
fetchImpl: (path, options) => fetchImpl: (path, options) =>
fetch(`http://127.0.0.1:${server.address().port}${path}`, options), fetch(`http://127.0.0.1:${server.address().port}${path}`, options),
}); });
// Application host services and native EventTargets; actual Cesium collections, // Application host services and native EventTargets; a fake draw port,
// input handler, events, SGP4, ingestion and lifecycle run without a WebGL scene. // input handler, events, SGP4, ingestion and lifecycle run without a WebGL scene.
const noop = () => {}; const noop = () => {};
const services = { const services = {
@@ -117,11 +118,14 @@ async function fixture(t) {
}, },
trackedEntityChanged: new Cesium.Event(), trackedEntityChanged: new Cesium.Event(),
}; };
const unbind = bindRenderer(viewer, { frame: fakeSceneFrame(viewer) }); const unbind = bindRenderer(viewer, {
frame: fakeSceneFrame(viewer),
draw: fakeDrawPort(),
});
await parts.lifecycle.methods.init(viewer); await parts.lifecycle.methods.init(viewer);
t.after(async () => { t.after(async () => {
unbind(); unbind();
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer); if (state._sets) parts.lifecycle.methods.destroy(viewer);
viewer.scene.primitives.destroy(); viewer.scene.primitives.destroy();
if (previousDocument === undefined) delete globalThis.document; if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument; else globalThis.document = previousDocument;
+6 -6
View File
@@ -15,18 +15,18 @@ export function createState({ services }) {
state._catalog = new Map(); state._catalog = new Map();
state._pointCollection = null; /** The draw sets (`{points, tracked, rings}`), owned by the rendering part. */
state._sets = null;
state._points = new Map(); state._points = new Map();
// noradId → point primitive // noradId → the point item its dot is drawn from (the rendering part's)
/** Stable lightweight records reused by the detection overlay between updates. */ /** Stable lightweight records reused by the detection overlay between updates. */
state._detectionObjects = new Map(); state._detectionObjects = new Map();
// noradId → { primitive, gmstAtBake }, owned by the rendering part: // noradId → { base, gmstAtBake, item }, owned by the rendering part: base
// primitive is a one-instance primitive holding the ring baked in ECEF // is the ring baked in ECEF at gmstAtBake; the preRender tick turns it to
// at gmstAtBake; the preRender tick re-aligns it to current GMST by updating // current GMST (rigid Z-rotation, WS-D1) into the line item drawn.
// its modelMatrix (rigid Z-rotation — no geometry rebuild, WS-D1).
state._orbitPaths = new Map(); state._orbitPaths = new Map();
+35 -17
View File
@@ -1,5 +1,23 @@
import { rendererOf } from '../../render/rendererOf.js';
import { ISS_NORAD, ISS_OVERLAY_SOURCE_ID } from './policy.js'; import { ISS_NORAD, ISS_OVERLAY_SOURCE_ID } from './policy.js';
/** A draw port that draws nothing, for seams that need sets but no renderer. */
const NO_DRAW = (() => {
const set = (spec) => ({
id: spec.id,
show: spec.show !== false,
set() {},
upsert() {},
remove() {},
clear() {},
setOptions() {},
size: () => 0,
on: () => () => {},
dispose() {},
});
return { points: set, lines: set, icons: set, shapes: set };
})();
export function createTesting({ state: layerState, services, parts, source }) { export function createTesting({ state: layerState, services, parts, source }) {
/** /**
* Seed a single tracked satellite so tests can invoke the exact production * Seed a single tracked satellite so tests can invoke the exact production
@@ -8,8 +26,8 @@ export function createTesting({ state: layerState, services, parts, source }) {
* @param {number} state.noradId * @param {number} state.noradId
* @param {string} state.name * @param {string} state.name
* @param {object} state.satrec * @param {object} state.satrec
* @param {object} state.entity * @param {object} state.entity The tracked carrier.
* @param {object} state.point * @param {object} state.point The satellite's point item (`pos` ECEF).
* @param {object} state.viewer * @param {object} state.viewer
* @param {() => (number|Date)} state.now * @param {() => (number|Date)} state.now
*/ */
@@ -97,9 +115,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
catalog = 'core', catalog = 'core',
showPoints = true, showPoints = true,
} = {}) { } = {}) {
layerState._viewer = { layerState._viewer = {};
scene: { primitives: { add: (p) => p, remove() {} } },
};
// Neutralize the shared world-overlay host: these tests exercise catalog and // Neutralize the shared world-overlay host: these tests exercise catalog and
// row-control logic, not the ISS callout. // row-control logic, not the ISS callout.
layerState._overlayHost = { layerState._overlayHost = {
@@ -107,12 +123,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
setVisible() {}, setVisible() {},
clearSource() {}, clearSource() {},
}; };
layerState._pointCollection = { parts.rendering._attachTo(NO_DRAW);
show: true,
add: (opts) => ({ ...opts }),
remove() {},
removeAll() {},
};
layerState._catalog = new Map(); layerState._catalog = new Map();
layerState._points = new Map(); layerState._points = new Map();
layerState._detectionObjects = new Map(); layerState._detectionObjects = new Map();
@@ -136,7 +147,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._overlayHost = layerState.DEFAULT_OVERLAY_HOST; layerState._overlayHost = layerState.DEFAULT_OVERLAY_HOST;
layerState._orbitPaths = new Map(); layerState._orbitPaths = new Map();
layerState._viewer = null; layerState._viewer = null;
layerState._pointCollection = null; parts.rendering._detach();
layerState._catalog = new Map(); layerState._catalog = new Map();
layerState._points = new Map(); layerState._points = new Map();
layerState._denseIds = []; layerState._denseIds = [];
@@ -176,17 +187,23 @@ export function createTesting({ state: layerState, services, parts, source }) {
[ [
ISS_NORAD, ISS_NORAD,
{ {
// A stand-in ring: shown, at the identity 4x4 (column-major). // A stand-in ring: shown, baked with no points.
primitive: { base: [],
show: true,
modelMatrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
},
gmstAtBake: 0, gmstAtBake: 0,
item: {
id: String(ISS_NORAD),
positions: new Float64Array(0),
show: true,
},
}, },
], ],
]); ]);
layerState._trackedNorad = null; layerState._trackedNorad = null;
layerState._trackedEntity = null; layerState._trackedEntity = null;
// Drawn through the viewer's renderer when it has one bound.
parts.rendering._detach();
const draw = rendererOf(viewer)?.draw;
if (draw) parts.rendering._attachTo(draw);
if (!preservePending) parts.tracking._cancelPendingTrackingRestore(); if (!preservePending) parts.tracking._cancelPendingTrackingRestore();
layerState._trackedFrameNumber = -1; layerState._trackedFrameNumber = -1;
layerState._trackedFrameGeo = null; layerState._trackedFrameGeo = null;
@@ -231,6 +248,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
function _clearSatelliteLabelLifecycleForTest() { function _clearSatelliteLabelLifecycleForTest() {
parts.tracking._clearTracking(); parts.tracking._clearTracking();
parts.rendering._detach();
layerState._enabled = false; layerState._enabled = false;
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID); layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false); layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false);
+9 -11
View File
@@ -90,7 +90,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
const clearedNorad = layerState._trackedNorad; const clearedNorad = layerState._trackedNorad;
clearFocusTarget('satellites', layerState._trackedNorad); clearFocusTarget('satellites', layerState._trackedNorad);
// Re-show the dot (hidden while the tracked entity rendered it) and // Re-show the dot (hidden while the tracked dot drew it) and
// restore the original group palette from the shared style table (WS-D3) // restore the original group palette from the shared style table (WS-D3)
parts.rendering._restorePoint( parts.rendering._restorePoint(
layerState._trackedNorad, layerState._trackedNorad,
@@ -104,7 +104,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedFrameNumber = -1; layerState._trackedFrameNumber = -1;
layerState._trackedFrameGeo = null; layerState._trackedFrameGeo = null;
// Remove tracked entity and orbit path (unless ISS — keep its path) // Remove the tracked dot and orbit path (unless ISS — keep its path)
if (layerState._trackedNorad !== ISS_NORAD) { if (layerState._trackedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(layerState._trackedNorad); parts.rendering._hideOrbitPath(layerState._trackedNorad);
} }
@@ -128,8 +128,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
/** /**
* Get the tracked satellite's geodetic position, propagated at most once per * Get the tracked satellite's geodetic position, propagated at most once per
* rendered frame (WS-D2). All tracked-satellite consumers (entity position * rendered frame (WS-D2). All tracked-satellite consumers (the tracked dot
* callback → camera, host model, point primitive, getTrackedInfo) share this * and follow camera, host model, the hidden dot, getTrackedInfo) share this
* single `new Date()` epoch per frame, so they can never diverge by the old * single `new Date()` epoch per frame, so they can never diverge by the old
* 200ms throttle. The matching ECEF position is left in * 200ms throttle. The matching ECEF position is left in
* `_trackedFrameCartesian`. SGP4 for one satellite per frame is cheap. * `_trackedFrameCartesian`. SGP4 for one satellite per frame is cheap.
@@ -405,16 +405,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedFrameGeo = null; layerState._trackedFrameGeo = null;
parts.labels._syncIssOverlay(); parts.labels._syncIssOverlay();
// Hide the dot — the tracked ENTITY renders it below. The entity must // Hide the dot — the tracked dot draws it, larger and over everything.
// own a point graphic so the tracking camera can resolve a bounding
// sphere and engage viewFrom (a label-only entity left the camera
// stranded; this mirrors the proven flights pattern).
parts.rendering._hidePoint(noradId); parts.rendering._hidePoint(noradId);
// Show orbital path // Show orbital path
parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR); parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR);
// Tracked entity position propagates per evaluation through the per-frame // The tracked position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame. // cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
// Falls back to the dot's 1s-throttled position if SGP4 fails. // Falls back to the dot's 1s-throttled position if SGP4 fails.
const trackedPosition = () => { const trackedPosition = () => {
@@ -457,8 +454,9 @@ export function createTracking({ state: layerState, services, parts, source }) {
selectTrackedSubjectContext(_contextSubjectMetadata(noradId, initialPos)); selectTrackedSubjectContext(_contextSubjectMetadata(noradId, initialPos));
layerState._contextRefreshedAtMs = Date.now(); layerState._contextRefreshedAtMs = Date.now();
// The renderer's own frame for a fast mover (autodetect), as the tracked entity // The renderer's own frame for a fast mover (autodetect), as the tracked
// had; no close-range rules at orbital distances. // entity had; no close-range rules at orbital distances. The carrier is
// what the tracked card reads (its entity record).
layerState._followTarget = entityFollowTarget(layerState._trackedEntity, { layerState._followTarget = entityFollowTarget(layerState._trackedEntity, {
position: trackedPosition, position: trackedPosition,
frame: 'autodetect', frame: 'autodetect',
+1 -1
View File
@@ -19,7 +19,7 @@ import { TRANSIT_POLL_MS } from './policy.js';
* and height maps, the in-flight requests, the manager handle and the overlay * and height maps, the in-flight requests, the manager handle and the overlay
* host all live on the instance this returns, and `destroy()` releases every * host all live on the instance this returns, and `destroy()` releases every
* shared registration it took (sprite collection, pick owner, render hold, * shared registration it took (sprite collection, pick owner, render hold,
* camera sensitivity). * camera listener).
* *
* @param {{services: object}} options * @param {{services: object}} options
* @returns {object} The data-layer module the manager registers. * @returns {object} The data-layer module the manager registers.
+6 -7
View File
@@ -5,8 +5,7 @@ import { TRANSIT_ENABLED_FEEDS } from '../../data/transitFeeds.js';
/** /**
* Init / enable / disable / update / destroy for one Transit layer instance. * Init / enable / disable / update / destroy for one Transit layer instance.
* Everything acquired here is released here — primitives, listeners, the sprite * Everything acquired here is released here — primitives, listeners, the sprite
* registration, the pick owner, the render hold, and the camera sensitivity * registration, the pick owner, the render hold, and the camera listener.
* this layer borrowed.
* @param {object} context * @param {object} context
* @returns {object} * @returns {object}
*/ */
@@ -139,7 +138,8 @@ export function createLifecycle({ state, services, parts }) {
registerPickOwner('transit', (pickedId) => state._vehicles.has(pickedId)); registerPickOwner('transit', (pickedId) => state._vehicles.has(pickedId));
if (!state._cameraChangedAttached) { if (!state._cameraChangedAttached) {
parts.rendering.watchCamera(viewer, parts.viewport.onCameraChanged); parts.rendering.watchCamera(viewer, parts.viewport.onCameraChanged);
state._cameraChangedAttached = true; // Attached only with a camera to listen to, so a later enable retries.
state._cameraChangedAttached = state._cameraChangedOff !== null;
} }
parts.rendering.startFrames(viewer); parts.rendering.startFrames(viewer);
parts.viewport.runProximityCheck(); parts.viewport.runProximityCheck();
@@ -169,10 +169,9 @@ export function createLifecycle({ state, services, parts }) {
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false); state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
parts.selection.removeClickHandler(); parts.selection.removeClickHandler();
unregisterPickOwner('transit'); unregisterPickOwner('transit');
if (state._cameraChangedAttached) { // Unconditional: whatever watching started, none of it outlives this.
parts.rendering.unwatchCamera(viewer, parts.viewport.onCameraChanged); parts.rendering.unwatchCamera();
state._cameraChangedAttached = false; state._cameraChangedAttached = false;
}
parts.rendering.stopFrames(); parts.rendering.stopFrames();
parts.ingestion.abortAllInFlight(); parts.ingestion.abortAllInFlight();
state._activeFeeds.clear(); state._activeFeeds.clear();
+71 -68
View File
@@ -28,11 +28,6 @@ const lat = (entry) =>
Cesium.Math.toDegrees( Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(entry.marker.position).latitude, Cesium.Cartographic.fromCartesian(entry.marker.position).latitude,
); );
import {
cameraSensitivityClaims,
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { import {
_resetRenderGovernorForTest, _resetRenderGovernorForTest,
getRenderGovernorDiagnostics, getRenderGovernorDiagnostics,
@@ -209,6 +204,8 @@ function harness(
const preRender = new Cesium.Event(); const preRender = new Cesium.Event();
const cameraChanged = new Cesium.Event(); const cameraChanged = new Cesium.Event();
const cameraListeners = new Set();
const preUpdates = new Set();
const viewer = { const viewer = {
camera: { camera: {
changed: cameraChanged, changed: cameraChanged,
@@ -317,7 +314,28 @@ function harness(
const unbindCamera = bindRenderer(viewer, { const unbindCamera = bindRenderer(viewer, {
draw, draw,
query: fakeSceneQuery(viewer), query: fakeSceneQuery(viewer),
// Only the tick the layer's camera listener waits on.
frame: {
on(phase, cb) {
if (phase !== 'preUpdate') return () => {};
preUpdates.add(cb);
return () => preUpdates.delete(cb);
},
requestRender() {},
},
camera: { camera: {
// `changed` listeners, each at its own threshold, fired by the fake
// camera's own event as a real camera move fires them.
on(event, cb, options = {}) {
if (event !== 'changed') return () => {};
const listener = { cb, threshold: options.threshold ?? 0.5 };
cameraListeners.add(listener);
const remove = cameraChanged.addEventListener(cb);
return () => {
cameraListeners.delete(listener);
remove();
};
},
pose() { pose() {
const carto = viewer.camera.positionCartographic; const carto = viewer.camera.positionCartographic;
return { return {
@@ -365,6 +383,16 @@ function harness(
layer, layer,
viewer, viewer,
draw, draw,
/** One frame tick, as the frame port's `preUpdate` hears it. */
tick() {
for (const cb of [...preUpdates]) cb({ frame: 0 });
},
/** Move the view rectangle without the camera reporting the move. */
moveQuietly(next) {
Object.assign(viewRect, next);
},
/** The thresholds of the camera port's `changed` listeners. */
cameraThresholds: () => [...cameraListeners].map((l) => l.threshold),
input, input,
primitives, primitives,
sprites, sprites,
@@ -878,63 +906,42 @@ test('the render hold follows real motion, and is released when everything settl
); );
assert.equal(app.viewer.scene.requestRenderMode, true); assert.equal(app.viewer.scene.requestRenderMode, true);
}); });
test('disable hands back the camera sensitivity it borrowed', async (t) => { test('the layer listens to the camera at its own fine threshold while enabled', async (t) => {
const app = harness(t); const app = harness(t);
assert.equal(app.viewer.camera.percentageChanged, 0.5); assert.deepEqual(app.cameraThresholds(), []);
app.layer.enable(app.viewer); app.layer.enable(app.viewer);
assert.equal( assert.deepEqual(
app.viewer.camera.percentageChanged, app.cameraThresholds(),
0.05, [0.05],
'the layer needs a finer camera trigger', 'the layer needs a finer camera trigger, as its own',
); );
app.layer.disable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.5, 'and gives it back');
});
test('disable leaves the fine camera trigger another layer asked for', async (t) => {
// The sequence that broke it: two layers ask for the SAME sensitivity, so
// the value on the camera cannot say who owns it. Transit used to compare
// the number, find its own 0.05 still there, and hand the coarse default
// back while Bikeshare was still driving off the fine one.
const app = harness(t);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
app.layer.enable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.05);
claimCameraSensitivity(app.viewer.camera, 'bikeshare', 0.05);
app.layer.disable(app.viewer);
assert.equal(
app.viewer.camera.percentageChanged,
0.05,
'bikeshare is still enabled, so the fine trigger stays',
);
assert.deepEqual(cameraSensitivityClaims(app.viewer.camera), ['bikeshare']);
releaseCameraSensitivity(app.viewer.camera, 'bikeshare');
assert.equal( assert.equal(
app.viewer.camera.percentageChanged, app.viewer.camera.percentageChanged,
0.5, 0.5,
'and the original returns once the last claim is gone', 'and leaves the camera every other listener shares as it was',
);
assert.deepEqual(cameraSensitivityClaims(app.viewer.camera), []);
});
test('a finer claim wins while it stands, and the coarser one survives it', async (t) => {
const app = harness(t);
app.layer.enable(app.viewer);
claimCameraSensitivity(app.viewer.camera, 'traffic', 0.01);
assert.equal(app.viewer.camera.percentageChanged, 0.01);
releaseCameraSensitivity(app.viewer.camera, 'traffic');
assert.equal(
app.viewer.camera.percentageChanged,
0.05,
'transit still needs its own trigger',
); );
app.layer.disable(app.viewer); app.layer.disable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.5); assert.deepEqual(app.cameraThresholds(), [], 'and stops on disable');
});
test('a move before the camera listener first measures is still looked at', async (t) => {
const app = harness(t);
app.layer.enable(app.viewer);
// The move lands before the listener's first tick, so it is the view the
// listener measures from and never reports.
app.moveQuietly({ west: -71.2, south: 10, east: -71.0, north: 10.2 });
app.tick();
assert.ok(app.state()._viewBounds.south > 40, 'not looked at yet');
app.tick();
assert.ok(
app.state()._viewBounds.south < 11,
'looked at once the first tick is past',
);
app.moveQuietly({ west: -71.2, south: 42.3, east: -71.0, north: 42.5 });
app.tick();
app.tick();
assert.ok(app.state()._viewBounds.south < 11, 'once, not every tick');
app.layer.disable(app.viewer);
}); });
test('destroy releases every shared registration this layer took', async (t) => { test('destroy releases every shared registration this layer took', async (t) => {
@@ -957,6 +964,7 @@ test('destroy releases every shared registration this layer took', async (t) =>
assert.equal(app.primitives.length, 2); assert.equal(app.primitives.length, 2);
app.layer.destroy(app.viewer); app.layer.destroy(app.viewer);
assert.deepEqual(app.cameraThresholds(), [], 'the camera listener goes');
assert.equal( assert.equal(
app.sprites.has('transit'), app.sprites.has('transit'),
false, false,
@@ -3617,7 +3625,7 @@ test('reject then selected history backfill cannot resurrect a 111 km displaceme
assert.equal(entry.track.resets, 0); assert.equal(entry.track.resets, 0);
}); });
test('the actual Transit lifecycle retains its sensitivity in every enable/disable order, Traffic and Bikeshare among them', async (t) => { test('the actual Transit lifecycle keeps exactly its own camera listener in every enable/disable order, Traffic and Bikeshare among them', async (t) => {
const { createLifecycle: trafficLifecycle } = const { createLifecycle: trafficLifecycle } =
await import('../traffic/lifecycle.js'); await import('../traffic/lifecycle.js');
const { createLifecycle: bikeLifecycle } = const { createLifecycle: bikeLifecycle } =
@@ -3696,6 +3704,7 @@ test('the actual Transit lifecycle retains its sensitivity in every enable/disab
}, },
transit: app.layer, transit: app.layer,
}; };
// Only transit listens on this viewer's camera port.
const claimants = new Set(['transit']); const claimants = new Set(['transit']);
const orders = [ const orders = [
['traffic', 'bikeshare', 'transit'], ['traffic', 'bikeshare', 'transit'],
@@ -3718,27 +3727,21 @@ test('the actual Transit lifecycle retains its sensitivity in every enable/disab
assert.equal(trafficCamera.listenerCount('changed'), 1); assert.equal(trafficCamera.listenerCount('changed'), 1);
assert.equal(trafficFrames.size, 1); assert.equal(trafficFrames.size, 1);
} }
assert.equal(
app.viewer.camera.percentageChanged,
active.size ? 0.05 : 0.5,
);
assert.deepEqual( assert.deepEqual(
new Set(cameraSensitivityClaims(app.viewer.camera)), app.cameraThresholds(),
active, active.has('transit') ? [0.05] : [],
); );
assert.equal(app.viewer.camera.percentageChanged, 0.5);
} }
for (const id of disable) { for (const id of disable) {
layers[id].disable(app.viewer); layers[id].disable(app.viewer);
active.delete(id); active.delete(id);
assert.equal( assert.deepEqual(
app.viewer.camera.percentageChanged, app.cameraThresholds(),
active.size ? 0.05 : 0.5, active.has('transit') ? [0.05] : [],
`${enable} / ${disable} after ${id}`, `${enable} / ${disable} after ${id}`,
); );
assert.deepEqual( assert.equal(app.viewer.camera.percentageChanged, 0.5);
new Set(cameraSensitivityClaims(app.viewer.camera)),
active,
);
} }
assert.equal(bikeCamera.listenerCount('changed'), 0); assert.equal(bikeCamera.listenerCount('changed'), 0);
assert.equal(trafficCamera.listenerCount('changed'), 0); assert.equal(trafficCamera.listenerCount('changed'), 0);
+1 -1
View File
@@ -35,7 +35,7 @@ export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 150_000;
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 150_000; export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 150_000;
/** Debounce (ms) for camera-change proximity checks. */ /** Debounce (ms) for camera-change proximity checks. */
export const CAMERA_DEBOUNCE_MS = 340; export const CAMERA_DEBOUNCE_MS = 340;
/** Camera sensitivity this layer asks for while it is enabled. */ /** The `changed` threshold this layer's camera listener asks for. */
export const CAMERA_PERCENTAGE_CHANGED = 0.05; export const CAMERA_PERCENTAGE_CHANGED = 0.05;
/** Extra coverage radius (km) granted to a feed that is already active, so it does not flap at the edge. */ /** Extra coverage radius (km) granted to a feed that is already active, so it does not flap at the edge. */
export const RANGE_SLACK_KM = 40; export const RANGE_SLACK_KM = 40;
+28 -23
View File
@@ -2,11 +2,9 @@ import * as Cesium from 'cesium';
// The Cesium camera factory: given a viewer of a caller's own, with no // The Cesium camera factory: given a viewer of a caller's own, with no
// renderer bound, the layer's camera reads find a camera port. // renderer bound, the layer's camera reads find a camera port.
import '../../render/cesium/camera.js'; import '../../render/cesium/camera.js';
import '../../render/cesium/frame.js';
import { webglContext } from '../../render/cesium/internals.js'; import { webglContext } from '../../render/cesium/internals.js';
import { import { findCamera, findFrame } from '../../render/rendererOf.js';
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { import {
cameraPoseSignature, cameraPoseSignature,
perspectiveProjectedRotation, perspectiveProjectedRotation,
@@ -122,32 +120,39 @@ export function createRendering({ state, services, parts }) {
} }
/** /**
* Listen for the camera moving, borrowing its change sensitivity through * Listen for the camera moving, at this layer's own threshold.
* the shared claim ledger.
* *
* `camera.changed` fires on a percentage of the view moving, and this layer * The camera port measures `changed` per listener, so this layer's finer
* needs a finer trigger than the default to notice it has entered a feed's * trigger (it needs to notice it has entered a feed's coverage) is its own
* coverage. It is a single shared number, so the claim is registered by name * and leaves every other listener's untouched.
* rather than written directly: comparing the VALUE on the way out could not
* tell this layer's 0.05 from anybody else's, and handing back the coarse
* default while Bikeshare was still relying on a fine one was exactly the
* bug that produced.
* @param {object} viewer * @param {object} viewer
* @param {() => void} onChanged * @param {() => void} onChanged
*/ */
function watchCamera(viewer, onChanged) { function watchCamera(viewer, onChanged) {
viewer.camera.changed.addEventListener(onChanged); unwatchCamera();
claimCameraSensitivity( state._cameraChangedOff =
viewer?.camera, findCamera(viewer)?.on('changed', onChanged, {
'transit', threshold: CAMERA_PERCENTAGE_CHANGED,
CAMERA_PERCENTAGE_CHANGED, }) ?? null;
); // A new listener measures from the view at the next tick, so a move made
// before that tick never reaches it: look again once that tick is past.
if (!state._cameraChangedOff) return;
let ticks = 0;
state._cameraFirstTickOff =
findFrame(viewer)?.on('preUpdate', () => {
if (++ticks < 2) return;
state._cameraFirstTickOff?.();
state._cameraFirstTickOff = null;
onChanged();
}) ?? null;
} }
/** Stop listening and give the claim up; the camera keeps anyone else's. */ /** Stop listening for the camera moving. */
function unwatchCamera(viewer, onChanged) { function unwatchCamera() {
viewer.camera.changed.removeEventListener(onChanged); state._cameraChangedOff?.();
releaseCameraSensitivity(viewer?.camera, 'transit'); state._cameraChangedOff = null;
state._cameraFirstTickOff?.();
state._cameraFirstTickOff = null;
} }
/** Run the per-frame glide before each render, once. */ /** Run the per-frame glide before each render, once. */
+4 -4
View File
@@ -36,12 +36,12 @@ export function createState({ services }) {
state._generation = 0; state._generation = 0;
state._cameraChangedAttached = false; state._cameraChangedAttached = false;
/** Removes the camera port listener; null when not listening. */
state._cameraChangedOff = null;
/** Removes the one-shot look after the camera listener's first tick. */
state._cameraFirstTickOff = null;
state._cameraDebounceTimer = null; state._cameraDebounceTimer = null;
state._altitudeGateOpen = false; state._altitudeGateOpen = false;
/** Camera sensitivity as we found it, so disable() can hand it back. */
state._priorPercentageChanged = null;
/** The value this layer actually wrote, for an identity-guarded restore. */
state._appliedPercentageChanged = null;
/** @type {(() => void)|null} */ /** @type {(() => void)|null} */
state._preRenderRemove = null; state._preRenderRemove = null;
+2
View File
@@ -1700,6 +1700,8 @@ export function createCesiumDraw({
}), }),
show: item.show !== false, show: item.show !== false,
asynchronous: false, asynchronous: false,
// A set that never picks keeps these out of the pick pass too.
allowPicking: record.spec.pickable !== false,
}); });
} }
+158
View File
@@ -1879,6 +1879,164 @@ test('the installations layer draws its named markers as outlined point primitiv
assert.equal(scene.added.includes(host), false); assert.equal(scene.added.includes(host), false);
}); });
test('the installations layer draws its site dots, outlines and selected dot on a viewer of its own', async () => {
const { createRendering } =
await import('../../layers/installations/rendering.js');
const scene = fakeScene();
const viewer = { scene };
const record = (id, lon) => ({
id,
name: `Site ${id}`,
class: 'base',
latitude: 30,
longitude: lon,
namedArea: false,
outlineLines: [
[
[lon, 30],
[lon + 0.01, 30],
],
],
});
const records = [record('a', -97), record('b', -98)];
const state = {
viewer,
enabled: true,
selectedId: null,
records,
recordById: new Map(records.map((r) => [r.id, r])),
renderedKeys: new Map(),
};
const noop = () => {};
const rendering = createRendering({
state,
services: {
ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 },
anchors: {},
render: { governorRequestRender: noop },
context: {
registerEntityContext: noop,
removeEntityContextsForLayer: noop,
selectEntityContext: noop,
getSelectedEntityContext: () =>
state.selectedId ? { id: state.selectedId } : null,
clearSelectedEntityContextForLayer: noop,
},
},
parts: {
model: {
colorFor: (r, alpha = 1) => [1, 165 / 255, 0, alpha],
installationSourceLabel: () => 'OpenStreetMap',
},
},
});
rendering.attach(viewer);
rendering.renderRecords();
const billboards = (setId) => {
const out = [];
const visit = (node) => {
for (let i = 0; i < (node?.length ?? 0); i += 1) {
const child = node.get(i);
if (child?.id?.set === setId) out.push(child);
else if (typeof child?.get === 'function') visit(child);
}
};
for (const host of scene.added)
if (host.id?.set === setId) out.push(host);
else visit(host);
return out;
};
const dotsId = state.sets.dots.id;
const dots = billboards(dotsId);
assert.equal(dots.length, 2);
assert.ok(dots.every((dot) => dot instanceof Cesium.Billboard));
assert.ok(
dots.every(
(dot) => dot.heightReference === Cesium.HeightReference.CLAMP_TO_GROUND,
),
);
assert.ok(dots.every((dot) => dot.id.meta?.installationId));
// Selecting a site hides its dot where it is and draws the selected one
// in its own set: no other dot is drawn again.
state.selectedId = 'b';
rendering.renderRecords();
const after = billboards(dotsId);
assert.equal(after.length, 2);
assert.ok(after.every((dot, i) => dot === dots[i]), 'the same billboards');
assert.equal(after.find((dot) => dot.id.id === 'b').show, false);
assert.equal(after.find((dot) => dot.id.id === 'a').show, true);
const [selected] = billboards(state.sets.selected.id);
assert.ok(selected instanceof Cesium.Billboard);
assert.equal(selected.id.id, 'b');
assert.equal(selected.id.meta, dots.find((dot) => dot.id.id === 'b').id.meta);
rendering.detach();
assert.equal(scene.added.length, 0, 'gone with the layer');
});
test('the satellites layer draws its dots as one point collection and its rings as depth-fail primitives out of picks', async () => {
const { createRendering } =
await import('../../layers/satellites/rendering.js');
const { POINT_STYLES, TRACKED_ORBIT_COLOR } =
await import('../../layers/satellites/policy.js');
const scene = fakeScene();
const viewer = { scene };
const state = {
_points: new Map(),
_orbitPaths: new Map(),
_catalog: new Map([[25544, { satrec: {} }]]),
_viewer: viewer,
_trackedNorad: null,
_enabled: false,
};
const ring = [
{ x: 7e6, y: 0, z: 0 },
{ x: 0, y: 7e6, z: 0 },
{ x: -7e6, y: 0, z: 0 },
];
const rendering = createRendering({
state,
services: { focus: {} },
parts: { orbits: { computeOrbitPath: () => ring } },
});
rendering._attach(viewer);
rendering._addPoint(25544, { x: 7e6, y: 0, z: 0 }, POINT_STYLES.iss);
rendering._addPoint(5, { x: 0, y: 7e6, z: 0 }, POINT_STYLES.visual);
rendering._preRenderTick({ frame: 1 });
const points = scene.added.find(
(host) => host instanceof Cesium.PointPrimitiveCollection,
);
assert.equal(points.length, 2);
const iss = points.get(0);
assert.equal(iss.id.id, '25544');
assert.deepEqual(iss.id.meta, { noradId: 25544 });
assert.equal(iss.pixelSize, 12);
assert.equal(iss.scaleByDistance.nearValue, 1.5);
assert.equal(iss.scaleByDistance.far, 2e7);
// Moved in place, both in one write.
rendering._movePoint(25544, { x: 6.9e6, y: 0, z: 0 });
rendering._movePoint(5, { x: 0, y: 6.9e6, z: 0 });
rendering._preRenderTick({ frame: 2 });
assert.equal(points.get(0), iss);
assert.equal(iss.position.x, 6.9e6);
withImageClasses(() =>
rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR),
);
const all = (host) =>
host instanceof Cesium.PrimitiveCollection
? Array.from({ length: host.length }, (_, i) => all(host.get(i))).flat()
: [host];
const primitive = scene.added
.flatMap(all)
.find(
(host) => host instanceof Cesium.Primitive && host.depthFailAppearance,
);
assert.ok(primitive, 'a ring with a dimmed part behind the globe');
assert.equal(primitive.allowPicking, false, 'ring clicks fall through');
rendering._detach(viewer);
assert.equal(scene.added.length, 0, 'gone with the layer');
});
test('the ALPR layer draws its badges as icons that follow the ground, restyled in place', async () => { test('the ALPR layer draws its badges as icons that follow the ground, restyled in place', async () => {
const { alprMarkers, createAlprMarkerSet } = const { alprMarkers, createAlprMarkerSet } =
await import('../../layers/alpr/markerState.js'); await import('../../layers/alpr/markerState.js');
-2
View File
@@ -8,9 +8,7 @@
"src/cyberSonarScene.js", "src/cyberSonarScene.js",
"src/data/geoImportPins.js", "src/data/geoImportPins.js",
"src/input/dispatcher.js", "src/input/dispatcher.js",
"src/layers/installations/rendering.js",
"src/layers/recentImagery/rendering.js", "src/layers/recentImagery/rendering.js",
"src/layers/satellites/rendering.js",
"src/layers/traffic/rendering.js", "src/layers/traffic/rendering.js",
"src/layers/transit/rendering.js", "src/layers/transit/rendering.js",
"src/layers/weather/shellRendering.js", "src/layers/weather/shellRendering.js",
+6
View File
@@ -95,6 +95,12 @@ const DRAW_FROM_CALLER = new Set([
// Its station dots, clusters and selected marker draw through `drawOf`; // Its station dots, clusters and selected marker draw through `drawOf`;
// it clusters them on screen through the camera and query ports. // it clusters them on screen through the camera and query ports.
'./layers/radio', './layers/radio',
// Its site dots, outlines and selected fill draw through `drawOf`; it
// follows a site and reads the globe through the camera and globe ports.
'./layers/installations',
// Its dots, tracked dot and orbit rings draw through `drawOf`; it follows,
// ticks, projects and reads the eye through the ports.
'./layers/satellites',
// Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which
// throws until then too. // throws until then too.
'./scenes', './scenes',
+18 -6
View File
@@ -186,9 +186,11 @@ test('distinct named bases separated by one seam quantization step retain separa
}); });
test('named A+B to B to A+B preserves canonical identity, parent title and selection', async () => { test('named A+B to B to A+B preserves canonical identity, parent title and selection', async () => {
const C = await import('cesium');
const { createRendering } = const { createRendering } =
await import('../layers/installations/rendering.js'); await import('../layers/installations/rendering.js');
const { bindFakeDraw } = await import('../testSupport/fakeDrawPort.mjs');
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const aliases = new Map(); const aliases = new Map();
const named = (n, footprint, areaM2) => const named = (n, footprint, areaM2) =>
record(String(n * 10 + 2), footprint, { record(String(n * 10 + 2), footprint, {
@@ -213,7 +215,7 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec
recordById: new Map(), recordById: new Map(),
selectedId: selected.id, selectedId: selected.id,
renderedKeys: new Map(), renderedKeys: new Map(),
dataSource: new C.CustomDataSource(), viewer,
}; };
const rendering = createRendering({ const rendering = createRendering({
state, state,
@@ -238,6 +240,10 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec
anchors: {}, anchors: {},
}, },
}); });
rendering.attach(viewer);
/** Whether the selected site's dot is drawn. */
const selectedDrawn = () =>
draw.set(state.sets.dots.id).items.has(state.selectedId);
for (const members of [[a, b], [b], [a, b]]) { for (const members of [[a, b], [b], [a, b]]) {
state.records = mergeMilitaryFragments(members, aliases); state.records = mergeMilitaryFragments(members, aliases);
state.recordById = new Map(state.records.map((r) => [r.id, r])); state.recordById = new Map(state.records.map((r) => [r.id, r]));
@@ -246,7 +252,7 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec
assert.deepEqual(state.records[0].memberNames, ['Site 2']); assert.deepEqual(state.records[0].memberNames, ['Site 2']);
rendering.renderRecords(); rendering.renderRecords();
assert.equal(state.selectedId, 'osm:military:w1'); assert.equal(state.selectedId, 'osm:military:w1');
assert.ok(state.dataSource.entities.getById(state.selectedId)); assert.ok(selectedDrawn());
} }
const [detail] = mergeMilitaryFragments([{ ...b, tileZoom: 12 }], aliases); const [detail] = mergeMilitaryFragments([{ ...b, tileZoom: 12 }], aliases);
assert.equal(detail.id, 'osm:military:w2'); assert.equal(detail.id, 'osm:military:w2');
@@ -258,9 +264,11 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec
}); });
test('cold names reconcile selection through enrichment, identical groups at another zoom and wide-point handoff', async () => { test('cold names reconcile selection through enrichment, identical groups at another zoom and wide-point handoff', async () => {
const C = await import('cesium');
const { createRendering } = const { createRendering } =
await import('../layers/installations/rendering.js'); await import('../layers/installations/rendering.js');
const { bindFakeDraw } = await import('../testSupport/fakeDrawPort.mjs');
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const { retainNamedHandoff } = const { retainNamedHandoff } =
await import('../layers/installations/ingestion.js'); await import('../layers/installations/ingestion.js');
const aliases = new Map(); const aliases = new Map();
@@ -292,7 +300,7 @@ test('cold names reconcile selection through enrichment, identical groups at ano
recordById: new Map(), recordById: new Map(),
selectedId: null, selectedId: null,
renderedKeys: new Map(), renderedKeys: new Map(),
dataSource: new C.CustomDataSource(), viewer,
}; };
const rendering = createRendering({ const rendering = createRendering({
state, state,
@@ -321,13 +329,17 @@ test('cold names reconcile selection through enrichment, identical groups at ano
anchors: {}, anchors: {},
}, },
}); });
rendering.attach(viewer);
/** Whether the selected site's dot is drawn. */
const selectedDrawn = () =>
draw.set(state.sets.dots.id).items.has(state.selectedId);
const publish = (records, claimSelection = false) => { const publish = (records, claimSelection = false) => {
state.records = records; state.records = records;
state.recordById = new Map(records.map((r) => [r.id, r])); state.recordById = new Map(records.map((r) => [r.id, r]));
rendering.renderRecords({ claimSelection }); rendering.renderRecords({ claimSelection });
assert.equal(state.selectedId, records[0].id); assert.equal(state.selectedId, records[0].id);
assert.equal(selected.id, records[0].id); assert.equal(selected.id, records[0].id);
assert.ok(state.dataSource.entities.getById(state.selectedId)); assert.ok(selectedDrawn());
assert.ok(contexts.has(selected.id)); assert.ok(contexts.has(selected.id));
}; };
const cold = mergeMilitaryFragments(unnamed, aliases); const cold = mergeMilitaryFragments(unnamed, aliases);