Draw Mapped Installations, Global Context and the infrastructure layers through one display each

- Mapped Installations: one display holds the single copy of the logic
  the Cesium and Navara renderers each had (renderable records, painting,
  the selection fill, floors, named markers, selection). Discs are point
  movers, outlines ground corridors and the selection fill a ground
  polygon. Cesium's behaviour wins where they drifted: named areas draw
  their outlines (Navara dropped them), discs sit under the moving
  contacts, and outlines and the fill pick their site.
- Global Context: the range ring is a halo and a core line on
  engine.lines and the awareness logic no longer imports Cesium. The
  animated pulse disc, which no primitive draws yet, sits behind one
  seam, render/pulseDisc.js, with a Cesium and a Navara backend.
- Datacenters and dams: one display on movers, lines and ground sets
  with Cesium's LOD, motion probe, floor sampling and card cohort;
  localGeojsonCore.js keeps only the engine-free card and record code
  (1381 to 329 lines).

Coupling: layer renderer lines fall from 1011/4832 to 351/3349
(Cesium/Navara), `viewer` lines from 1745 to 1591,
ScreenSpaceEventHandler files from 8 to 6, Navara ground passes from 5
to 4.
This commit is contained in:
German Khokhlov committed 2026-11-07 07:13:56 +04:00
1 parent e18f12d34c
commit 30c86a6001
61 files changed
+5510 -7104

No files matched your search

+6 -3
View File
@@ -1,14 +1,17 @@
import { createLocalGeoJsonLayer } from './localGeojsonCore.js';
import { createInfrastructureSessionLayer } from '../layers/infrastructure/index.js';
import { INFRASTRUCTURE_DATA_URLS } from '../sources/infrastructureData.js';
/**
* Create fresh datacenter and dam layers without starting or loading them.
* @param {object} services Caller-owned context, overlay and render operations.
* @param {object} services Caller-owned context, overlay and credit operations.
* @param {(config: object, services: object) => object} [createLayer] One
* layer from its descriptor; by default a session layer that draws through
* the globe contract (src/layers/infrastructure).
* @returns {object[]} Datacenters then dams, with stable standalone identities.
*/
export function createInfrastructureLayers(
services,
createLayer = createLocalGeoJsonLayer,
createLayer = createInfrastructureSessionLayer,
) {
const datacentersUrl = INFRASTRUCTURE_DATA_URLS['local-datacenters'];
const damsUrl = INFRASTRUCTURE_DATA_URLS['local-dams'];
+54 -50
View File
@@ -2,9 +2,8 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import * as Cesium from 'cesium';
import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
function services() {
const records = new Map();
@@ -13,7 +12,7 @@ function services() {
return {
records,
credited,
showOsmCredit: (viewer) => credited.push(viewer),
showOsmCredit: (engine) => credited.push(engine),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
registerEntityContext(entity, metadata) {
records.set(metadata.id, { entity, ...metadata });
@@ -95,7 +94,7 @@ test('dataset URLs still name the complete bundled sources', () => {
}
});
test('two viewers use their supplied contexts and dispose independently', async (t) => {
test('two engines use their supplied contexts and dispose independently', async (t) => {
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
text: async () =>
@@ -118,57 +117,42 @@ test('two viewers use their supplied contexts and dispose independently', async
}));
const hosts = [services(), services()];
const instances = hosts.map((host) => {
const sources = new Cesium.DataSourceCollection();
let click;
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
name: 'Dams',
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
screenSpaceEventHandlerFactory: () => ({
setInputAction(fn) {
click = fn;
},
destroy() {},
}),
},
host,
);
const viewer = {
dataSources: sources,
scene: {
canvas: {},
preRender: new Cesium.Event(),
requestRender() {},
screenSpaceCameraController: { enableInputs: true },
pick: () => ({ id: sources.get(0).entities.values[0] }),
},
camera: { moveEnd: new Cesium.Event(), flyTo() {} },
};
return { layer, viewer, click: () => click({ position: {} }) };
const engine = createFakeEngine();
const [, layer] = createInfrastructureLayers(host);
layer.init(null, { engine });
return { layer, engine };
});
t.after(() =>
instances.forEach(({ layer, viewer }) => layer.destroy(viewer)),
instances.forEach(({ layer, engine }) => {
layer.destroy();
engine.destroy();
}),
);
await Promise.all(instances.map(({ layer, viewer }) => layer.enable(viewer)));
await Promise.all(instances.map(({ layer }) => layer.enable()));
assert.equal(hosts[0].records.size, 1);
assert.deepEqual(
hosts.map((host) => host.credited),
instances.map(({ viewer }) => [viewer]),
instances.map(({ engine }) => [engine]),
);
assert.equal(hosts[1].records.size, 1);
instances[0].click();
// A click on the first engine's footprint selects only its own record.
const { engine } = instances[0];
engine.camera.flyTo = () => {};
engine.fake.script('pick', {
id: 'local-dams:same-id',
owner: 'local-dams-footprints',
instance: 0,
});
engine.fake.input('click', { position: { x: 1, y: 1 } });
assert.ok(hosts[0].selection());
assert.equal(hosts[1].selection(), undefined);
instances[0].layer.destroy(instances[0].viewer);
instances[0].layer.destroy();
assert.equal(hosts[0].records.size, 0);
assert.equal(hosts[1].records.size, 1);
assert.equal(instances[1].viewer.dataSources.length, 1);
assert.equal(instances[1].engine.ground.list().length, 2);
});
test('consumer build includes only infrastructure code and resolves assets under a non-root base', async () => {
test('consumer build includes only infrastructure code and engine-free geometry, and resolves assets under a non-root base', async () => {
const { build } = await import('vite');
const { fileURLToPath } = await import('node:url');
const result = await build({
@@ -189,18 +173,38 @@ test('consumer build includes only infrastructure code and resolves assets under
});
const output = result.output;
const entry = output.find((item) => item.type === 'chunk' && item.isEntry);
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
'infrastructure.js',
'infrastructureData.js',
'infrastructureOverlayEntry.js',
'localGeojsonCore.js',
'localGeojsonLod.js',
const sources = Object.keys(entry.modules)
.filter((id) => id.endsWith('.js'))
.map((id) => id.slice(id.lastIndexOf('/src/') + 1));
assert.deepEqual(sources.sort(), [
'src/data/infrastructure.js',
'src/data/infrastructureOverlayEntry.js',
'src/data/localGeojsonCore.js',
'src/data/localGeojsonLod.js',
...[
'boundingSphere',
'cartesian2',
'cartesian3',
'cartographic',
'ellipsoid',
'ellipsoidGeodesic',
'julianDate',
'math',
'matrix4',
'quaternion',
'scaleToGeodeticSurface',
'simon1994',
].map((name) => `src/geo/${name}.js`),
'src/layers/infrastructure/index.js',
'src/layers/infrastructure/render/display.js',
'src/layers/shared/color.js',
'src/sources/infrastructureData.js',
'src/sources/requestDeadline.js',
]);
assert.deepEqual(
entry.imports,
['cesium'],
'the viewer supplies the same Cesium dependency',
[],
'the layers draw through the engine they are given',
);
for (const name of ['datacenters', 'dams']) {
const asset = output.find(
+8 -4
View File
@@ -115,16 +115,20 @@ test('every scene click handler consults ownership before it picks', () => {
// appear here too.
const guarded = [
['src/data/trackingClickGesture.js', 'onClick(click, gesture);'],
['src/data/localGeojsonCore.js', 'viewer.scene.pick(click.position)'],
[
'src/layers/infrastructure/render/display.js',
'const picked = event.picked;',
],
['src/data/cctvGizmo.js', 'pickGizmoPart(event.position)'],
// ALPR and bikeshare take the engine's click with its pick.
['src/layers/alpr/render/display.js', 'overlay.pick(position) ||'],
['src/layers/bikeshare/render/display.js', 'const picked = event.picked;'],
// FIRMS takes the engine dispatcher's click with its pick.
['src/layers/firms/selection.js', 'const picked = click.picked;'],
// Mapped Installations take the engine's click with its pick.
[
'src/layers/installations/render/cesium/selection.js',
'viewer.scene.pick(click.position)',
'src/layers/installations/render/display.js',
"const id = typeof picked?.id === 'string' ? picked.id : null;",
],
['src/layers/launches/render/display.js', '[ctx.picked, ...ctx.drilled]'],
[
@@ -170,7 +174,7 @@ test('ambient selection handlers never claim the pointer themselves', () => {
// moment a user clicked anything. Only tools claim.
for (const file of [
'src/data/trackingClickGesture.js',
'src/data/localGeojsonCore.js',
'src/layers/infrastructure/render/display.js',
'src/data/cctvGizmo.js',
'src/layers/vessels/selection.js',
'src/layers/satellites/interaction.js',
+4 -138
View File
@@ -1,19 +1,8 @@
// Focused tests for the local-infrastructure analyst-record mapper and snapshot seam.
// Focused tests for the local-infrastructure analyst-record mapper. The
// layer's snapshot is tested in src/layers/infrastructure/session.test.mjs.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import {
createLocalGeoJsonLayer as createLayer,
mapAnalystRecord,
} from './localGeojsonCore.js';
/** The catalog's services, with the overlay host each test supplies. */
const createLocalGeoJsonLayer = (options) =>
createLayer(options, {
...localGeoJsonServices,
overlayHost: options.overlayHost,
});
import { mapAnalystRecord } from './localGeojsonCore.js';
const DC_RAW = {
id: '1176042553',
@@ -95,7 +84,7 @@ test('infra analyst record: empty record yields nulls, never NaN/undefined', ()
}
});
test('infra analyst record: output is JSON-safe (no Cesium types leak)', () => {
test('infra analyst record: output is JSON-safe (no engine types leak)', () => {
const r = mapAnalystRecord(
{
...DAM_RAW,
@@ -108,126 +97,3 @@ test('infra analyst record: output is JSON-safe (no Cesium types leak)', () => {
assert.equal('entity' in r, false);
assert.equal('position' in r, false);
});
class MockLayerEvent {
constructor() {
this.listeners = new Set();
}
addEventListener(listener) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
}
test('infra getAnalystRecords: enabled layer snapshots loaded stems; disable returns []', async () => {
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
globalThis.window = { dispatchEvent() {} };
globalThis.fetch = async () => ({
ok: true,
status: 200,
text: async () =>
JSON.stringify({
type: 'Feature',
id: 'runtime-dam',
properties: {
name: 'Runtime Dam',
output: '12 MW',
tags: { associated_river: 'Test River', operator: 'Test Hydro' },
},
geometry: {
type: 'Polygon',
coordinates: [
[
[-97.7, 30.2],
[-97.69, 30.2],
[-97.69, 30.21],
[-97.7, 30.2],
],
],
},
}),
});
const viewer = {
selectedEntity: undefined,
dataSources: {
add(dataSource) {
return dataSource;
},
remove() {
return true;
},
},
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97.695, 30.205, 100_000),
frustum: { fov: Math.PI / 3 },
moveEnd: new MockLayerEvent(),
flyTo() {},
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
preRender: new MockLayerEvent(),
sampleHeightSupported: false,
sampleHeight() {
return undefined;
},
screenSpaceCameraController: { enableInputs: true },
pick() {
return null;
},
requestRender() {},
},
};
const layer = createLocalGeoJsonLayer({
id: 'local-dams',
url: '/runtime-dam.geojsonl',
name: 'Runtime Dams',
color: '#0088ff',
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
projectToWindow: () => ({ x: 400, y: 300 }),
screenSpaceEventHandlerFactory: () => ({
setInputAction() {},
destroy() {},
}),
});
try {
assert.deepEqual(
layer.getAnalystRecords(),
[],
'unenabled layer has no analyst records',
);
await layer.enable(viewer);
const rows = layer.getAnalystRecords();
assert.equal(rows.length, 1);
assert.equal(rows[0].id, 'Runtime Dam');
assert.equal(rows[0].name, 'Runtime Dam');
assert.equal(rows[0].operator, 'Test Hydro');
assert.equal(rows[0].river, 'Test River');
assert.equal(rows[0].output, '12 MW');
assert.ok(Number.isFinite(rows[0].lat) && Number.isFinite(rows[0].lon));
assert.deepEqual(JSON.parse(JSON.stringify(rows[0])), rows[0]);
assert.equal(
layer.getAnalystRecords(0).length,
1,
'non-finite/zero cap still returns at least one',
);
layer.disable(viewer);
assert.deepEqual(
layer.getAnalystRecords(),
[],
'disable keeps stems but analyst snapshot is empty',
);
} finally {
layer.destroy(viewer);
assert.deepEqual(
layer.getAnalystRecords(),
[],
'destroy releases analyst records',
);
globalThis.fetch = originalFetch;
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
}
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-175
View File
@@ -1,175 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { createLocalGeoJsonLayer as createLayer } from './localGeojsonCore.js';
import { getContextStore } from './contextStore.js';
/** The catalog's services, with the overlay host each test supplies. */
const createLocalGeoJsonLayer = (options) =>
createLayer(options, {
...localGeoJsonServices,
overlayHost: options.overlayHost,
});
const dataset = JSON.stringify({
type: 'Feature', id: 'dam', properties: { name: 'Test dam' },
geometry: { type: 'Polygon', coordinates: [[[0, 0], [0.01, 0], [0, 0.01], [0, 0]]] },
});
const response = () => ({ ok: true, text: async () => dataset });
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
function harness(t) {
const previousWindow = globalThis.window;
globalThis.window = { dispatchEvent() {} };
t.after(() => {
layer.destroy(viewer);
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
});
const sources = new Set();
const listeners = new Set();
const event = { addEventListener(fn) { listeners.add(fn); return () => listeners.delete(fn); } };
let handlers = 0;
const viewer = {
dataSources: {
async add(source) { sources.add(source); return source; },
remove(source) { return sources.delete(source); },
},
scene: { canvas: {}, preRender: event, requestRender() {} },
camera: { moveEnd: event },
};
const create = () => createLocalGeoJsonLayer({
id: 'local-dams', name: 'Dams', color: '#0088ff', url: '/dams.geojsonl',
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
screenSpaceEventHandlerFactory() {
handlers++;
return { setInputAction() {}, destroy() { handlers--; } };
},
});
const layer = create();
return { layer, create, viewer, sources, listeners, handlers: () => handlers };
}
test('destroy removes context records and permits a fresh replacement', async t => {
const env = harness(t);
t.mock.method(globalThis, 'fetch', async () => response());
await env.layer.enable(env.viewer);
const oldEntity = [...getContextStore().entities.values()][0].entity;
assert.equal(getContextStore().entities.size, 1);
env.layer.disable(env.viewer);
assert.equal(getContextStore().entities.size, 0, 'disable releases its records with the source');
assert.equal(env.sources.size, 0, 'disable removes the built source from the scene');
env.layer.destroy(env.viewer);
assert.equal(getContextStore().entities.size, 0);
assert.equal(env.sources.size, 0);
assert.equal(env.listeners.size, 0);
assert.equal(env.handlers(), 0);
const replacement = env.create();
await replacement.enable(env.viewer);
assert.equal(getContextStore().entities.size, 1);
assert.notEqual([...getContextStore().entities.values()][0].entity, oldEntity);
replacement.destroy(env.viewer);
await env.layer.enable(env.viewer);
assert.equal(getContextStore().entities.size, 0);
});
for (const phase of ['fetch', 'text', 'parse', 'add']) {
test(`destroy during ${phase} leaves no late objects or context records`, async t => {
const env = harness(t);
const entered = deferred();
const release = deferred();
const pause = async value => { entered.resolve(); await release.promise; return value; };
let signal;
t.mock.method(globalThis, 'fetch', async (_url, options) => {
signal = options.signal;
if (phase === 'fetch') return pause(response());
if (phase === 'text') return { ok: true, text: () => pause(dataset) };
return response();
});
if (phase === 'parse') {
const load = Cesium.GeoJsonDataSource.load;
t.mock.method(Cesium.GeoJsonDataSource, 'load', async (...args) => pause(await load(...args)));
}
if (phase === 'add') {
t.mock.method(env.viewer.dataSources, 'add', async source => {
await pause();
env.sources.add(source);
return source;
});
}
const loading = env.layer.enable(env.viewer);
await entered.promise;
env.layer.destroy(env.viewer);
assert.equal(signal.aborted, true);
release.resolve();
await loading;
assert.equal(env.sources.size, 0);
assert.equal(env.listeners.size, 0);
assert.equal(env.handlers(), 0);
assert.equal(getContextStore().entities.size, 0);
assert.deepEqual(env.layer.getStats(), { count: 0, lastUpdate: null, error: null });
});
}
test('concurrent enable and disable/re-enable share one pending dataset load', async t => {
const env = harness(t);
const release = deferred();
const fetchMock = t.mock.method(globalThis, 'fetch', async () => {
await release.promise;
return response();
});
const first = env.layer.enable(env.viewer);
env.layer.disable(env.viewer);
const second = env.layer.enable(env.viewer);
release.resolve();
await Promise.all([first, second]);
assert.equal(fetchMock.mock.callCount(), 1);
assert.equal(env.sources.size, 1);
assert.equal(env.handlers(), 1);
assert.equal(env.listeners.size, 2);
assert.equal([...env.sources][0].show, true);
});
test('disable during loading releases the completed source; re-enable rebuilds without refetching', async t => {
const env = harness(t);
const release = deferred();
const fetchMock = t.mock.method(globalThis, 'fetch', async () => { await release.promise; return response(); });
const loading = env.layer.enable(env.viewer);
env.layer.disable(env.viewer);
release.resolve();
await loading;
assert.equal(env.sources.size, 0, 'a build that finishes after disable() is released, not parked hidden');
assert.equal(env.listeners.size, 0);
assert.equal(getContextStore().entities.size, 0);
await env.layer.enable(env.viewer);
assert.equal(env.sources.size, 1);
assert.equal([...env.sources][0].show, true);
assert.equal(fetchMock.mock.callCount(), 1, 'the parsed dataset is cached across the toggle');
});
test('a toggle-off frees the entities and a toggle-on rebuilds them from the cached dataset', async t => {
const env = harness(t);
const fetchMock = t.mock.method(globalThis, 'fetch', async () => response());
await env.layer.enable(env.viewer);
const first = [...env.sources][0];
assert.equal(first.entities.values.length, 1);
assert.equal(getContextStore().entities.size, 1);
env.layer.disable(env.viewer);
assert.equal(env.sources.size, 0, 'no data source stays registered while the layer is off');
assert.equal(getContextStore().entities.size, 0);
assert.equal(env.layer.getLodDiagnostics().total, 0);
assert.equal(env.layer.getStats().count, 1, 'the row keeps reporting the dataset size');
await env.layer.enable(env.viewer);
const second = [...env.sources][0];
assert.notEqual(second, first, 're-enable builds a fresh source');
assert.equal(second.show, true);
assert.equal(second.entities.values.length, 1);
assert.equal(getContextStore().entities.size, 1);
assert.equal(fetchMock.mock.callCount(), 1, 'no second fetch for a bundled dataset');
assert.equal(env.layer.getLodDiagnostics().total, 1);
});
+6 -6
View File
@@ -3,16 +3,16 @@
* @module localGeojsonLod
*
* Pure selection policy for the bundled local-infrastructure layers
* (`local-datacenters`, `local-dams`, and any future `createLocalGeoJsonLayer`
* dataset). Cesium-specific projection, occlusion, and stem geometry stay in
* `localGeojsonCore.js`; this module turns the resulting in-view records into a
* (`local-datacenters`, `local-dams`). Projection, occlusion, and stem
* geometry stay in `src/layers/infrastructure/render/display.js`; this module
* turns the resulting in-view records into a
* bounded "active" set — the only records that layer should spend per-frame
* stem-geometry and ground-sample work on.
*
* The screen-space label overlay is already decluttered
* (LOCAL_OVERLAY_COHORT_LIMIT); this also bounds world-space stems and their
* geometry/ground-sampling work. It does not reduce the number of materialized
* entities. Submarine cables use their own renderer and are not changed here.
* records. Submarine cables use their own renderer and are not changed here.
* Performance must be measured against the current renderer, not inferred
* from the number of hidden stems.
*
@@ -297,7 +297,7 @@ export function applyInfraEvictionGrace({
* ------------------------------------------------------------------ */
/**
* Probe window for the motion fallback. `localGeojsonCore.js` marks its selection
* Probe window for the motion fallback. The infrastructure display marks its selection
* dirty on `moveEnd`, which covers drags, one-shot `setView`, and voice
* `flyTo` — but a tracked-entity follow camera, a Cockpit view, a route
* flight, or a continuous orbit never emits one. Without a fallback the
@@ -377,7 +377,7 @@ export function infraLodMotionEpsilonM(
* creeping camera probes on a fixed cadence instead of on every walk.
*
* Travel arrives SQUARED so the caller can hand over
* `Cesium.Cartesian3.distanceSquared` and spend no sqrt on a per-walk probe,
* `cartesian3.distanceSquared` and spend no sqrt on a per-walk probe,
* the same trade `createCableReferenceSweepGate` makes.
*
* @param {object} [input]
+28 -2
View File
@@ -47,6 +47,32 @@ import {
} from '../layers/awareness/panel.js';
import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js';
import { aircraftViewerRenderer } from '../testSupport/aircraftViewerRenderer.mjs';
import { registerLayerRenderers } from '../app/layers/renderers.js';
// The layer's view of a stub viewer (render/display.js's interface), drawn
// by nothing: these tests drive the layer's logic, not the ring. It reaches
// the layer through the renderer registry, under an engine kind of its own.
const VIEWER_ENGINE = 'awareness-viewer-test';
registerLayerRenderers(VIEWER_ENGINE, {
'military-awareness': ({ viewer }) => ({
container: viewer.container,
canvas: viewer.canvas,
get camera() {
return viewer.camera;
},
get trackedEntity() {
return viewer.trackedEntity;
},
cameraHeight: () => viewer.camera?.positionCartographic?.height ?? NaN,
onFrame: (run) => viewer.scene.preRender.addEventListener(run),
onFrameEnd: () => () => {},
frameContact: (center, radius, duration) =>
viewer.camera.flyToBoundingSphere({ center, radius }, { duration }),
createRim: () => ({ move() {}, setAlpha() {}, destroy() {} }),
createPulses: () => null,
}),
});
const viewerEngine = (viewer) => ({ kind: VIEWER_ENGINE, viewer });
const militaryAwarenessSource = readLayerSource(
new URL('./militaryAwareness.js', import.meta.url),
@@ -220,7 +246,7 @@ function installAwarenessRuntime({
...(subscribe ? { subscribe } : {}),
});
militaryAwarenessLayer.setParams({ passive: true });
militaryAwarenessLayer.init(viewer);
militaryAwarenessLayer.init(viewer, { engine: viewerEngine(viewer) });
const panelViews = [];
const unsubscribePanel = militaryAwarenessLayer.subscribePanel((view) =>
panelViews.push(view),
@@ -3747,7 +3773,7 @@ test('runtime listeners exist only while the awareness layer is enabled', () =>
try {
militaryAwarenessLayer.setParams({ passive: true });
militaryAwarenessLayer.init(viewer);
militaryAwarenessLayer.init(viewer, { engine: viewerEngine(viewer) });
assert.equal(
[...listeners.values()].reduce((count, set) => count + set.size, 0),
0,
+80 -163
View File
@@ -24,7 +24,39 @@ import {
installRenderGovernor,
} from '../renderGovernor.js';
import * as Cesium from 'cesium';
import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js';
import { getContextStore, registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
const LAYER_ID = 'military-installations';
/** A fake engine looking at `box` (degrees). */
function engineOver(box) {
const engine = createFakeEngine();
engine.fake.script('viewRectangle', () => box && {
south: Cesium.Math.toRadians(box.south),
west: Cesium.Math.toRadians(box.west),
north: Cesium.Math.toRadians(box.north),
east: Cesium.Math.toRadians(box.east),
});
return engine;
}
/** The context handles of the drawn sites, in drawing order. */
const drawnHandles = () =>
[...getContextStore().entities.values()]
.filter((record) => record.layerId === LAYER_ID)
.map((record) => record.entity);
/** The drawn disc size of a site: 13 px selected, 9 px otherwise. */
function discSize(engine, id) {
const drawn = (setId) => {
const set = engine.fake.moverSet(setId);
return set.store.pickIds.slice(0, set.store.count).includes(id);
};
if (drawn(`${LAYER_ID}-selected`)) return 13;
if (drawn(LAYER_ID)) return 9;
return null;
}
test('clicking a selected installation again or empty map clears it through refresh', async () => {
const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42,
@@ -37,7 +69,7 @@ test('clicking a selected installation again or empty map clears it through refr
assert.equal(getSelectedEntityContext(), null);
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(), null, 'refresh must not resurrect selection');
assert.equal(run.entities()[0].point.pixelSize.getValue(), 9);
assert.equal(run.discSize(run.entities()[0].id), 9);
}
} finally { run.restore(); }
});
@@ -55,7 +87,7 @@ test('background installation paints neither reopen Contacts nor resurrect a cle
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext(),null);
assert.equal(selected(),1,'an external clear must survive the next paint');
assert.equal(run.entities()[0].point.pixelSize.getValue(),9);
assert.equal(run.discSize(run.entities()[0].id),9);
} finally { run.restore(); }
});
@@ -87,8 +119,8 @@ test('switching sites keeps the new selection through refresh and disable clears
assert.equal(getSelectedEntityContext()?.id, 'osm:node:43');
await militaryInstallationsLayer.update();
assert.equal(getSelectedEntityContext()?.id, 'osm:node:43');
assert.equal(run.entities().find(e => e.id === 'osm:node:42').point.pixelSize.getValue(), 9);
assert.equal(run.entities().find(e => e.id === 'osm:node:43').point.pixelSize.getValue(), 13);
assert.equal(run.discSize('osm:node:42'), 9);
assert.equal(run.discSize('osm:node:43'), 13);
militaryInstallationsLayer.disable();
run.click('osm:node:42');
assert.equal(getSelectedEntityContext(), null, 'disabled layer ignores clicks');
@@ -134,10 +166,6 @@ test('real enabled installation entities carry no native label graphics', async
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
const originalFetch = globalThis.fetch;
const canvas = {
addEventListener() {},
removeEventListener() {},
};
globalThis.document = {
addEventListener() {},
removeEventListener() {},
@@ -163,49 +191,22 @@ test('real enabled installation entities carry no native label graphics', async
}),
};
};
const moveEndListeners = new Set();
const dataSources = [];
const viewer = {
camera: {
moveEnd: {
addEventListener(listener) {
moveEndListeners.add(listener);
return () => moveEndListeners.delete(listener);
},
},
computeViewRectangle() {
return {
south: Cesium.Math.toRadians(30),
west: Cesium.Math.toRadians(-98),
north: Cesium.Math.toRadians(31),
east: Cesium.Math.toRadians(-97),
};
},
},
scene: {
canvas,
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
pick() { return null; },
},
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
const engine = engineOver({ south: 30, west: -98, north: 31, east: -97 });
try {
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.init(null, { engine });
militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update();
const entities = dataSources[0].entities.values;
const entities = drawnHandles();
assert.ok(entities.length > 0, 'runtime guard requires rendered installation records');
assert.ok(entities.every((entity) => entity.label === undefined));
assert.ok(
engine.movers.list().every(({ kind }) => kind === 'point'),
'the titles are the shared overlay, not label primitives',
);
} finally {
militaryInstallationsLayer.destroy(viewer);
militaryInstallationsLayer.destroy();
engine.destroy();
globalThis.fetch = originalFetch;
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
@@ -305,68 +306,37 @@ async function runInstallationLoad({
if (!legacyPayload) payload.saturated = exact ? exactSaturated : saturated;
return { ok: true, status: 200, json: async () => payload };
};
const dataSources = [];
const cameraFlights = [];
let picked = null;
let clickAction;
const engine = engineOver(VIEWPORT);
// Enough of a viewer for the real render governor, so one-shot render
// requests are observable.
const viewer = {
camera: {
moveEnd: { addEventListener() { return () => {}; } },
flyToBoundingSphere(sphere, options) { cameraFlights.push({ sphere, options }); },
computeViewRectangle() {
return {
south: Cesium.Math.toRadians(VIEWPORT.south),
west: Cesium.Math.toRadians(VIEWPORT.west),
north: Cesium.Math.toRadians(VIEWPORT.north),
east: Cesium.Math.toRadians(VIEWPORT.east),
};
},
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
pick() { return picked; },
// Enough surface for the real render governor to drive this viewer, so
// one-shot render requests are observable.
requestRenderMode: false,
maximumRenderTimeChange: 0,
requestRender() {},
},
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
const originalSetInputAction = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (action, type, modifier) {
if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) clickAction = action;
return originalSetInputAction.call(this, action, type, modifier);
};
try { militaryInstallationsLayer.init(viewer); }
finally { Cesium.ScreenSpaceEventHandler.prototype.setInputAction = originalSetInputAction; }
militaryInstallationsLayer.init(null, { engine });
installRenderGovernor(viewer);
militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update();
return {
requests,
cameraFlights,
entities: () => dataSources[0]?.entities?.values || [],
engine,
entities: drawnHandles,
discSize: (id) => discSize(engine, id),
contextLabels: () => contextEvents,
stats: () => militaryInstallationsLayer.getStats(),
click(target) {
const entity = typeof target === 'string' ? dataSources[0].entities.getById(target) : target;
picked = entity ? { id: entity } : undefined;
clickAction({ position: { x: 0, y: 0 } });
engine.fake.script('pick', target ? { id: target } : undefined);
engine.fake.input('click', { position: { x: 0, y: 0 } });
engine.fake.unscript('pick');
},
renderRequests: () => getRenderGovernorDiagnostics().recentRequests.map((item) => item.reason),
restore() {
militaryInstallationsLayer.destroy(viewer);
militaryInstallationsLayer.destroy();
engine.destroy();
_resetRenderGovernorForTest();
globalThis.fetch = originalFetch;
if (originalDocument === undefined) delete globalThis.document;
@@ -603,44 +573,18 @@ test('a floor that lands after the render deadline lifts the dots off the ellips
}),
};
};
const dataSources = [];
const viewer = {
camera: {
moveEnd: { addEventListener() { return () => {}; } },
computeViewRectangle() {
return {
south: Cesium.Math.toRadians(44),
west: Cesium.Math.toRadians(-111),
north: Cesium.Math.toRadians(45),
east: Cesium.Math.toRadians(-110),
};
},
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
pick() { return null; },
},
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
const engine = engineOver({ south: 44, west: -111, north: 45, east: -110 });
const heightOf = (entity) => Cesium.Cartographic.fromCartesian(
entity.position.getValue(Cesium.JulianDate.now()),
entity.gevDisplayPosition(),
).height;
try {
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.init(null, { engine });
militaryInstallationsLayer.enable();
await militaryInstallationsLayer.update();
const buried = dataSources[0].entities.values[0];
const buried = drawnHandles()[0];
assert.ok(buried, 'the cold-floor pass still renders the record');
assert.ok(Math.abs(heightOf(buried)) < 1, 'a cold floor anchors at the ellipsoid, as before');
@@ -650,13 +594,14 @@ test('a floor that lands after the render deadline lifts the dots off the ellips
}
assert.equal(cachedGroundFloor(lat, lon), 2400, 'the late floor landed in the shared cache');
const lifted = dataSources[0].entities.values[0];
const lifted = drawnHandles()[0];
assert.ok(
Math.abs(heightOf(lifted) - 2401.5) < 0.5,
`re-render must lift the dot onto the resolved floor, got ${heightOf(lifted)}`,
);
} finally {
militaryInstallationsLayer.destroy(viewer);
militaryInstallationsLayer.destroy();
engine.destroy();
_resetFireAnchorsForTest();
setMeshFloorPreferred(true);
globalThis.fetch = originalFetch;
@@ -681,28 +626,10 @@ test('reports bounded installation requests as loading and clears on settlement'
}
return installationsResponse;
};
const viewer = {
camera: {
moveEnd: { addEventListener() { return () => {}; } },
computeViewRectangle() {
return {
south: Cesium.Math.toRadians(30),
west: Cesium.Math.toRadians(-98),
north: Cesium.Math.toRadians(31),
east: Cesium.Math.toRadians(-97),
};
},
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
pick() { return null; },
},
dataSources: { add(value) { return value; }, remove() { return true; } },
};
const engine = engineOver({ south: 30, west: -98, north: 31, east: -97 });
try {
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.init(null, { engine });
militaryInstallationsLayer.enable();
const update = militaryInstallationsLayer.update();
assert.equal(militaryInstallationsLayer.getStats().loading, true);
@@ -718,7 +645,8 @@ test('reports bounded installation requests as loading and clears on settlement'
await update;
assert.equal(militaryInstallationsLayer.getStats().loading, false);
} finally {
militaryInstallationsLayer.destroy(viewer);
militaryInstallationsLayer.destroy();
engine.destroy();
globalThis.fetch = originalFetch;
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
@@ -745,28 +673,16 @@ test('zoom-out aborts an active installation request and returns non-loading gui
}, { once: true });
});
};
const viewer = {
camera: {
moveEnd: { addEventListener() { return () => {}; } },
computeViewRectangle() {
return globalView ? null : {
south: Cesium.Math.toRadians(30),
west: Cesium.Math.toRadians(-98),
north: Cesium.Math.toRadians(31),
east: Cesium.Math.toRadians(-97),
};
},
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
pick() { return null; },
},
dataSources: { add(value) { return value; }, remove() { return true; } },
};
const engine = engineOver({ south: 30, west: -98, north: 31, east: -97 });
engine.fake.script('viewRectangle', () => globalView ? null : {
south: Cesium.Math.toRadians(30),
west: Cesium.Math.toRadians(-98),
north: Cesium.Math.toRadians(31),
east: Cesium.Math.toRadians(-97),
});
try {
militaryInstallationsLayer.init(viewer);
militaryInstallationsLayer.init(null, { engine });
militaryInstallationsLayer.enable();
const pending = militaryInstallationsLayer.update();
assert.equal(militaryInstallationsLayer.getStats().loading, true);
@@ -779,7 +695,8 @@ test('zoom-out aborts an active installation request and returns non-loading gui
assert.equal(militaryInstallationsLayer.getStats().error, null, 'guidance is not a fault');
assert.match(militaryInstallationsLayer.getStats().statusMessage, /zoom in/i);
} finally {
militaryInstallationsLayer.destroy(viewer);
militaryInstallationsLayer.destroy();
engine.destroy();
globalThis.fetch = originalFetch;
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
@@ -794,7 +711,7 @@ test('zoom-out aborts an active installation request and returns non-loading gui
// sat healthy — observed in the field as a layer stuck reporting unavailable
// while its own endpoint served hundreds of features. The backoff progression
// is a pure exported helper so it pins without booting the layer (the full
// layer needs a Cesium viewer and interaction handlers); the wiring is pinned
// layer needs a globe engine and interaction handlers); the wiring is pinned
// by source probes against the shipped file, the same technique the HUD datum
// tests use where a full boot is impractical.
import { installationRetryDelayMs } from './militaryInstallations.js';
+10 -6
View File
@@ -39,14 +39,18 @@ function assertCredit(v) {
assert.ok(v.credits.some((credit) => credit.showOnScreen && credit.html.includes('>© OpenStreetMap<')));
}
for (const index of [0, 1]) test(`${index ? 'dams' : 'datacenters'} introduce the shared OSM credit when data displays`, async (t) => {
const v = viewer(t);
const before = globalThis.window;
globalThis.window = { dispatchEvent: noop };
t.after(() => { if (before === undefined) delete globalThis.window; else globalThis.window = before; });
const engine = createFakeEngine();
t.mock.method(globalThis, 'fetch', async () => ({ ok: true, text: async () => JSON.stringify({ type: 'Feature', id: 'test', properties: { name: 'Site' }, geometry: { type: 'Polygon', coordinates: [[[0, 0], [0.01, 0], [0, 0.01], [0, 0]]] } }) }));
const layer = createInfrastructureLayers({ overlayHost, registerEntityContext: noop, selectEntityContext: noop, clearSelectedEntityContextForLayer: noop, removeEntityContextsForLayer: noop, governorRequestRender: noop, showOsmCredit, hideOsmCredit })[index];
await layer.enable(v);
const layer = createInfrastructureLayers({ overlayHost, registerEntityContext: noop, selectEntityContext: noop, clearSelectedEntityContextForLayer: noop, removeEntityContextsForLayer: noop, showOsmCredit, hideOsmCredit })[index];
layer.init(null, { engine });
await layer.enable();
assert.equal(layer.getStats().count, 1);
assertCredit(v);
layer.destroy(v);
assert.equal(v.credits.filter(c => c.showOnScreen).length, 0);
assert.ok(engine.fake.credits.some((credit) => credit.onScreen && credit.html.includes('>© OpenStreetMap<')));
layer.destroy();
assert.equal(engine.fake.credits.filter((credit) => credit.onScreen).length, 0);
});
test('Nepal locator introduces the shared OSM credit', async (t) => {
+3 -3
View File
@@ -284,11 +284,11 @@ test('tracking layers write gevLabelModel and expose only their cached display p
assert.ok(source.includes('.gevDisplayPosition ='), `${name} exposes a display-position cache`);
}
const installations = await readFile(
new URL('../layers/installations/render/cesium/rendering.js', import.meta.url),
new URL('../layers/installations/render/display.js', import.meta.url),
'utf8',
);
assert.ok(installations.includes('entity.gevLabelModel ='));
assert.ok(installations.includes('entity.gevDisplayPosition = () => displayPosition'));
assert.ok(installations.includes(' gevLabelModel: {'));
assert.ok(installations.includes('handle.gevDisplayPosition = () => handle.position'));
assert.match(sources['flights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.match(sources['militaryFlights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.ok(sources['satellites.js'].includes('gevDisplayPosition = _trackedDisplayCached'));