Draw the local GeoJSON layers through the draw port and take them off the Cesium list

The data centre and dam layers (src/data/localGeojsonCore.js) no longer load
a Cesium GeoJSON data source. Each build is six draw sets: ground fills,
raised fills, draped lines, pins, stems and their tip dots. A walk changes
what moved or showed in place. Ground heights come from the heights query,
with the globe visibility getter deciding whether terrain is a floor. The
stems are sized from the camera pose, and clicks select and fly through the
input and camera ports. Point-and-ask reads a draw hit's meta as the
feature's context record (drawItemMeta in src/data/pickedContext.js).

The drawn parts keep the loader's ids and its reading of each feature:
simplestyle fill, stroke and marker colours, opacities, widths and marker
sizes; polygons with heights drawn at them and outlined; 3D points standing
their pin on the stem tip; ground edges along rhumb lines.

Differences: a marker-symbol draws the plain pin; named CSS colours fall
back to the layer colour; a raised polygon's outline is 1 px around its
outer ring only, and its fill is unlit; the layer no longer sets the
viewer's selectedEntity, so Cesium's stock double-click no longer follows
a feature; a caller's own Cesium viewer needs
gods-eye-view/render/cesium/unbound loaded first.
This commit is contained in:
Sameh Khamis committed 2026-11-07 21:49:15 -08:00
1 parent 333c9b39fe
commit b0ed9d7e90
14 files changed
+1547 -947

No files matched your search

+27 -31
View File
@@ -2,10 +2,10 @@ 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 { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
function services() {
const records = new Map();
@@ -119,7 +119,6 @@ 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();
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
@@ -130,19 +129,25 @@ test('two viewers use their supplied contexts and dispose independently', async
},
host,
);
// A click picks the feature's stem, as the renderer's pick names it.
const viewer = {
dataSources: sources,
scene: {
canvas: {},
preRender: new Cesium.Event(),
requestRender() {},
screenSpaceCameraController: { enableInputs: true },
pick: () => ({ id: sources.get(0).entities.values[0] }),
pick: () => {
const [stem] = fake.set('stems').items.values();
return {
id: {
set: fake.set('stems').spec.id,
id: stem.id,
meta: stem.meta,
},
};
},
},
camera: { moveEnd: new Cesium.Event(), flyTo() {} },
};
const fake = bindFakeGroundRenderer(viewer);
const input = fakeInput(viewer);
return { layer, viewer, click: () => input.click({ x: 0, y: 0 }) };
return { layer, viewer, fake, click: () => input.click({ x: 0, y: 0 }) };
});
t.after(() =>
instances.forEach(({ layer, viewer }) => layer.destroy(viewer)),
@@ -157,10 +162,16 @@ test('two viewers use their supplied contexts and dispose independently', async
instances[0].click();
assert.ok(hosts[0].selection());
assert.equal(hosts[1].selection(), undefined);
assert.deepEqual(
instances[0].fake.flights.map(({ destination }) => destination.height),
[5000],
'the click flies to the feature',
);
instances[0].layer.destroy(instances[0].viewer);
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[0].fake.liveSets().length, 0);
assert.equal(instances[1].fake.liveSets().length, 6);
});
test('consumer build includes only infrastructure code and resolves assets under a non-root base', async () => {
@@ -185,47 +196,32 @@ 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'));
// It draws through the renderer's ports: a viewer of the caller's own
// draws once the caller has loaded `./render/cesium/unbound`.
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
'aircraftRecession.js',
'camera.js',
'cameraControls.js',
'cameraInput.js',
'celestial.js',
'common.js',
'creditMarkup.js',
'credits.js',
'color.js',
'ctrlWheelZoom.js',
'dispatcher.js',
'draw.js',
'drawHit.js',
'drawModels.js',
'events.js',
'ellipsoid.js',
'follow.js',
'frame.js',
'gpuIcons.js',
'heights.js',
'horizon.js',
'iconAtlas.js',
'iconMotion.js',
'iconSegment.js',
'iconSet.js',
'iconSetPrimitive.js',
'infrastructure.js',
'infrastructureData.js',
'infrastructureOverlayEntry.js',
'input.js',
'inputOwnership.js',
'internals.js',
'julian.js',
'localGeojsonCore.js',
'localGeojsonLod.js',
'pickRegistry.js',
'polyline.js',
'query.js',
'rendererOf.js',
'rhumb.js',
'router.js',
'scenePick.js',
'sensorPick.js',
'sphere.js',
'styleStages.js',
'vector.js',
]);
+6 -42
View File
@@ -1,8 +1,8 @@
// Focused tests for the local-infrastructure analyst-record mapper and snapshot seam.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import {
createLocalGeoJsonLayer as createLayer,
mapAnalystRecord,
@@ -109,17 +109,6 @@ test('infra analyst record: output is JSON-safe (no Cesium types leak)', () => {
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;
@@ -149,36 +138,10 @@ test('infra getAnalystRecords: enabled layer snapshots loaded stems; disable ret
},
}),
});
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 viewer = {};
const fake = bindFakeGroundRenderer(viewer, {
eye: { lon: -97.695, lat: 30.205, height: 100_000 },
});
const layer = createLocalGeoJsonLayer({
id: 'local-dams',
url: '/runtime-dam.geojsonl',
@@ -227,6 +190,7 @@ test('infra getAnalystRecords: enabled layer snapshots loaded stems; disable ret
'destroy releases analyst records',
);
globalThis.fetch = originalFetch;
fake.unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
}
+133 -297
View File
@@ -1,7 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import * as Cesium from 'cesium';
import {
GROUND_SAMPLE_MAX_ARMED_RETRIES,
LOCAL_OVERLAY_COHORT_LIMIT,
@@ -24,6 +23,8 @@ import {
import { getContextStore } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
/** The catalog's services, with the overlay host each test supplies. */
const createLocalGeoJsonLayer = (options) =>
@@ -32,45 +33,18 @@ const createLocalGeoJsonLayer = (options) =>
overlayHost: options.overlayHost ?? localGeoJsonServices.overlayHost,
});
class MockLayerEvent {
constructor() {
this.listeners = new Set();
this.addCount = 0;
this.removeCount = 0;
}
addEventListener(listener) {
this.addCount++;
this.listeners.add(listener);
let active = true;
return () => {
if (!active) return;
active = false;
this.removeCount++;
this.listeners.delete(listener);
};
}
raise(...args) {
for (const listener of [...this.listeners]) listener(...args);
}
}
/**
* @param {object} [options]
* @param {boolean} [options.sampleHeightSupported] Scene height-sampling capability.
* @param {Function} [options.sampleHeight] Initial scene.sampleHeight behavior
* (default: throws like a scene whose tiles are not sampleable yet).
* @param {boolean} [options.sampleHeightSupported] The renderer's height-sampling capability.
* @param {Function} [options.sampleHeight] Initial surface height behavior
* (default: nothing loaded yet, a miss).
*/
async function createRealLocalLayerHarness({
sampleHeightSupported = false,
sampleHeight = () => { throw new Error('tiles not sampleable yet'); },
sampleHeight = () => null,
} = {}) {
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
const preRender = new MockLayerEvent();
const moveEnd = new MockLayerEvent();
const dataSources = [];
const hostCalls = [];
globalThis.fetch = async () => ({
ok: true,
@@ -91,42 +65,17 @@ async function createRealLocalLayerHarness({
}),
});
globalThis.window = { dispatchEvent() {} };
let sampleHeightImpl = sampleHeight;
const sampleCalls = { count: 0 };
const overlayHost = {
setVisible: (...args) => hostCalls.push(['visible', ...args]),
setEntries: (...args) => hostCalls.push(['entries', ...args]),
clearSource: (...args) => hostCalls.push(['clear', ...args]),
};
const viewer = {
selectedEntity: undefined,
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;
},
},
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97.695, 30.205, 100_000),
frustum: { fov: Math.PI / 3 },
moveEnd,
flyTo() {},
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
preRender,
sampleHeightSupported,
sampleHeight: (...args) => {
sampleCalls.count += 1;
return sampleHeightImpl(...args);
},
screenSpaceCameraController: { enableInputs: true },
pick() { return null; },
requestRender() {},
},
};
const viewer = {};
const fake = bindFakeGroundRenderer(viewer, {
sampleHeight: sampleHeightSupported,
surface: sampleHeight,
eye: { lon: -97.695, lat: 30.205, height: 100_000 },
});
const layer = createLocalGeoJsonLayer({
id: 'local-dams',
url: '/runtime-dam.geojsonl',
@@ -144,20 +93,26 @@ async function createRealLocalLayerHarness({
return {
layer,
viewer,
dataSources,
fake,
hostCalls,
preRender,
moveEnd,
sampleCalls,
/** Swap scene.sampleHeight mid-test (e.g. tiles finally arrive). */
setSampleHeight(next) { sampleHeightImpl = next; },
preRender: fake.preRender,
moveEnd: fake.moveEnd,
sampleCalls: fake.sampleCalls,
/** Swap the surface heights mid-test (e.g. tiles finally arrive). */
setSampleHeight(next) { fake.setSurface(next); },
cleanup() {
fake.unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
},
};
}
/** The eye moved by `dx` metres along ECEF x from where it is. */
function nudgeEye(env, from, dx) {
env.fake.setEyePosition({ x: from.x + dx, y: from.y, z: from.z });
}
test('local infrastructure card copy uses the owner-approved source fields', () => {
assert.deepEqual(localInfrastructureOverlayCopy({
tags: {
@@ -187,7 +142,7 @@ test('local infrastructure card copy uses the owner-approved source fields', ()
});
test('local infrastructure entries satisfy the shared presentation contract', () => {
const position = Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 2000);
const position = fromDegrees(-97.7, 30.2, 2000);
const entry = createLocalInfrastructureOverlayEntry({
id: 'dc-42',
layerId: 'local-datacenters',
@@ -337,9 +292,7 @@ test('slow parked frames do not keep republishing the same local overlay cohort'
assert.equal(publications().length, 1,
'unchanged publication invalidates the real host and requests another slow frame');
const camera = env.viewer.camera.positionWC;
env.viewer.camera.positionWC = Cesium.Cartesian3.add(camera,
new Cesium.Cartesian3(10_000, 0, 0), new Cesium.Cartesian3());
nudgeEye(env, env.fake.eyePosition(), 10_000);
env.moveEnd.raise();
env.preRender.raise();
assert.equal(publications().length, 2, 'changed stem positions must still reach the host');
@@ -381,102 +334,52 @@ test('real layer disable clears its published host entries and balances settle l
env.cleanup();
});
test('unchanged moveEnds do not redefine stem constants and real tip changes update once', async () => {
test('unchanged moveEnds do not rewrite the stem and real tip changes write it once', async () => {
const env = await createRealLocalLayerHarness();
env.preRender.raise();
const entity = env.dataSources[0].entities.values[0];
let positionSetCalls = 0;
let polylineSetCalls = 0;
let polylineDefinitionChanges = 0;
const stemArrays = [];
const initialStemArray = entity.polyline.positions.getValue();
const originalPositionSet = entity.position.setValue.bind(entity.position);
const originalPolylineSet = entity.polyline.positions.setValue.bind(entity.polyline.positions);
const removeDefinitionListener = entity.polyline.definitionChanged.addEventListener(
(_polyline, propertyName) => {
if (propertyName === 'positions') polylineDefinitionChanges++;
},
);
entity.position.setValue = (...args) => {
positionSetCalls++;
return originalPositionSet(...args);
};
entity.polyline.positions.setValue = (...args) => {
polylineSetCalls++;
stemArrays.push(args[0]);
return originalPolylineSet(...args);
};
const stems = env.fake.set('stems');
const dots = env.fake.set('dots');
const writes = () => [stems.writes, dots.writes];
const before = writes();
env.moveEnd.raise();
env.preRender.raise();
env.moveEnd.raise();
env.preRender.raise();
assert.equal(positionSetCalls, 0);
assert.equal(polylineSetCalls, 0);
assert.equal(polylineDefinitionChanges, 0);
assert.deepEqual(writes(), before, 'an unchanged camera writes nothing');
const camera = env.viewer.camera.positionWC;
env.viewer.camera.positionWC = Cesium.Cartesian3.add(
camera,
new Cesium.Cartesian3(LOCAL_STEM_TIP_EPSILON_M / 10, 0, 0),
new Cesium.Cartesian3(),
);
const camera = env.fake.eyePosition();
nudgeEye(env, camera, LOCAL_STEM_TIP_EPSILON_M / 10);
env.moveEnd.raise();
env.preRender.raise();
assert.equal(positionSetCalls, 0, 'sub-epsilon camera noise must not redefine the tip');
assert.equal(polylineSetCalls, 0);
assert.equal(polylineDefinitionChanges, 0, 'sub-epsilon jitter must not redefine the polyline');
assert.deepEqual(writes(), before, 'sub-epsilon camera noise must not move the tip');
env.viewer.camera.positionWC = Cesium.Cartesian3.add(
camera,
new Cesium.Cartesian3(10_000, 0, 0),
new Cesium.Cartesian3(),
);
env.moveEnd.raise();
env.preRender.raise();
assert.equal(positionSetCalls, 1);
assert.equal(polylineSetCalls, 1);
assert.equal(polylineDefinitionChanges, 1, 'one real tip change must emit one polyline notification');
env.viewer.camera.positionWC = Cesium.Cartesian3.add(
camera,
new Cesium.Cartesian3(20_000, 0, 0),
new Cesium.Cartesian3(),
);
env.moveEnd.raise();
env.preRender.raise();
assert.equal(positionSetCalls, 2);
assert.equal(polylineSetCalls, 2);
assert.equal(polylineDefinitionChanges, 2, 'each real tip change must emit exactly one notification');
env.viewer.camera.positionWC = Cesium.Cartesian3.add(
camera,
new Cesium.Cartesian3(30_000, 0, 0),
new Cesium.Cartesian3(),
);
env.moveEnd.raise();
env.preRender.raise();
assert.equal(positionSetCalls, 3);
assert.equal(polylineSetCalls, 3);
assert.equal(polylineDefinitionChanges, 3, 'third real tip change must emit exactly one notification');
assert.notEqual(stemArrays[0], initialStemArray, 'first real update must select the alternate buffer');
assert.equal(stemArrays[1], initialStemArray, 'second real update must return to the initial buffer');
assert.equal(stemArrays[2], stemArrays[0], 'consecutive real updates must alternate buffer identity');
assert.equal(
new Set([initialStemArray, ...stemArrays]).size,
2,
'steady-state updates must allocate no stem arrays beyond the two preallocated buffers',
);
removeDefinitionListener();
for (const [step, dx] of [[1, 10_000], [2, 20_000], [3, 30_000]]) {
nudgeEye(env, camera, dx);
env.moveEnd.raise();
env.preRender.raise();
assert.deepEqual(
writes(),
[before[0] + step, before[1] + step],
'each real tip change writes the stem and its dot exactly once',
);
}
const [stem] = stems.items.values();
const [dot] = dots.items.values();
assert.deepEqual(dot.pos, stem.positions[1], 'the dot stands on the stem tip');
env.layer.destroy(env.viewer);
env.cleanup();
});
test('a real enabled local layer has no native label graphics at runtime', async () => {
const env = await createRealLocalLayerHarness();
const entities = env.dataSources[0].entities.values;
assert.ok(entities.length > 0, 'runtime guard requires a populated real data source');
assert.ok(entities.every((entity) => entity.label === undefined));
const sets = env.fake.liveSets();
assert.ok(sets.length > 0, 'runtime guard requires populated sets');
assert.deepEqual(
sets.map((record) => record.kind).sort(),
['icons', 'lines', 'lines', 'points', 'shapes', 'shapes'],
'labels go through the overlay host, never a set of their own',
);
env.layer.destroy(env.viewer);
env.cleanup();
});
@@ -485,26 +388,22 @@ for (const [heightM, minStemM, maxStemM] of [[500, 45, 90], [10000, 1100, 1400]]
test(`local infrastructure keeps stems proportional at ${heightM} m`, async (t) => {
const env = await createRealLocalLayerHarness();
t.after(() => { env.layer.destroy(env.viewer); env.cleanup(); });
const entity = env.dataSources[0].entities.values[0];
const carto = Cesium.Cartographic.fromCartesian(targetPositionOf(entity));
env.viewer.camera.positionWC = Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, heightM);
env.preRender.raise(env.viewer.scene, Cesium.JulianDate.now());
const positions = entity.polyline.positions.getValue(Cesium.JulianDate.now());
const stemM = Cesium.Cartesian3.distance(positions[0], positions[1]);
const base = toLonLatH(targetPositionOf(env));
env.fake.setEye(base.lon, base.lat, heightM);
env.preRender.raise();
const [stem] = env.fake.set('stems').items.values();
const [from, to] = stem.positions;
const stemM = Math.hypot(to.x - from.x, to.y - from.y, to.z - from.z);
assert.ok(stemM >= minStemM && stemM <= maxStemM,
`a ${heightM} m close-up must not inherit a globe-sized stem: ${stemM.toFixed(1)} m`);
});
}
test('local infrastructure creates no native labels or per-frame geometry callbacks', () => {
test('local infrastructure draws through the renderer, with no per-frame geometry callbacks', () => {
const source = readFileSync(new URL('./localGeojsonCore.js', import.meta.url), 'utf8');
assert.doesNotMatch(source, /new Cesium\.LabelGraphics/);
assert.doesNotMatch(source, /new Cesium\.CallbackProperty/);
assert.match(source, /feature\.position = tip/);
assert.match(source, /record\.entity\.position\.setValue\(record\.tip\)/);
assert.match(source, /const stemPositionBuffers = \[\s*\[base, tip\],\s*\[base, tip\],?\s*\]/);
assert.match(source, /record\.entity\.polyline\.positions\.setValue\(stemPositions\)/);
assert.match(source, /viewer\.camera\.moveEnd\.addEventListener/);
assert.doesNotMatch(source, /from 'cesium'/);
assert.match(source, /findCamera\(viewer\)\?\.on\('moveEnd'/);
assert.match(source, /findFrame\(viewer\)\?\.on\('preRender'/);
assert.match(source, /if \(refreshStemGeometry \|\| terrainFloorChanged\)/);
assert.match(source, /now - _lastVisibilityUpdate < VISIBILITY_UPDATE_MS/);
});
@@ -516,15 +415,19 @@ test('local infrastructure creates no native labels or per-frame geometry callba
// empty one both reported {count: 0} and the manager painted a green ON chip.
/** Build the failing layer alone — the harness above owns the happy path. */
async function enableLayerWithFetch(fetchImpl, { dataSources, windowStub } = {}) {
async function enableLayerWithFetch(fetchImpl, { windowStub, failDraw = false } = {}) {
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
globalThis.window = windowStub || { dispatchEvent() {} };
const viewer = {
dataSources: dataSources || { add() {}, remove() { return true; } },
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1000), moveEnd: new MockLayerEvent() },
scene: { canvas: {}, preRender: new MockLayerEvent(), pick() { return null; } },
};
const viewer = {};
const fake = bindFakeGroundRenderer(viewer);
if (failDraw) {
const points = fake.draw.points;
fake.draw.points = () => {
fake.draw.points = points;
throw new Error('the renderer refused a set');
};
}
const layer = createLocalGeoJsonLayer({
id: 'local-dams',
url: '/missing.geojsonl',
@@ -544,10 +447,11 @@ async function enableLayerWithFetch(fetchImpl, { dataSources, windowStub } = {})
await enable();
const cleanup = () => {
layer.destroy(viewer);
fake.unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
};
return { layer, viewer, cleanup, enable };
return { layer, viewer, fake, cleanup, enable };
}
test('a bundled-dataset failure reduces to a short, honest reason', () => {
@@ -586,8 +490,6 @@ test('a corrupt dataset line reports malformed rather than parsing into nothing'
cleanup();
});
// Polygon, like the harness above: Cesium builds Point features through a
// canvas pin builder, which needs a DOM these tests do not have.
const ONE_POLYGON_FEATURE = JSON.stringify({
type: 'Feature',
id: 'dam-1',
@@ -604,31 +506,6 @@ const serveOnePolygon = async () => ({
text: async () => ONE_POLYGON_FEATURE,
});
/**
* Scene collection with Cesium's real timing: DataSourceCollection.add()
* returns a promise and inserts on a LATER microtask, so the source is not in
* the collection when add() returns. A synchronous mock hides exactly the bug
* this models.
*/
function asyncDataSources({ rejectAdd = false } = {}) {
const added = [];
return {
added,
add(dataSource) {
if (rejectAdd) return Promise.reject(new Error('scene rejected the data source'));
return Promise.resolve().then(() => {
added.push(dataSource);
return dataSource;
});
},
remove(dataSource) {
const index = added.indexOf(dataSource);
if (index >= 0) added.splice(index, 1);
return index >= 0;
},
};
}
/** A window whose context store throws once — an exception during post-processing. */
function windowThatFailsOnce() {
let armed = true;
@@ -646,14 +523,10 @@ function windowThatFailsOnce() {
};
}
test('a post-processing failure after the scene accepts the source rolls it back, and the retry does not double-add', async () => {
// The window between GeoJsonDataSource.load() and the end of entity
// post-processing. Publishing early made every later enable() skip the
// loader; rolling back before the add settled left Cesium to insert the
// "removed" source afterwards, which the retry would then double up on.
const scene = asyncDataSources();
const { layer, cleanup, enable } = await enableLayerWithFetch(serveOnePolygon, {
dataSources: scene,
test('a post-processing failure rolls the sets back, and the retry does not double them', async () => {
// Publishing early made every later enable() skip the loader; a failure
// after the sets were made must let go of them, or the retry doubles up.
const { layer, fake, cleanup, enable } = await enableLayerWithFetch(serveOnePolygon, {
windowStub: windowThatFailsOnce(),
});
@@ -662,29 +535,27 @@ test('a post-processing failure after the scene accepts the source rolls it back
assert.equal(failed.count, 0);
assert.equal(failed.lastUpdate, null);
assert.equal(layerFeedState(failed), 'unavailable');
assert.equal(scene.added.length, 0,
'rollback must remove the source the scene already accepted');
assert.equal(fake.liveSets().length, 0, 'rollback must dispose the sets it made');
await enable();
const retried = layer.getStats();
assert.equal(retried.error, null, 'the retry must clear the error, not skip the loader');
assert.equal(retried.count, 1);
assert.ok(Number.isFinite(retried.lastUpdate));
assert.equal(scene.added.length, 1, 'the retry must not leave two sources in the scene');
assert.equal(fake.liveSets().length, 6, 'the retry must not leave two builds drawn');
cleanup();
});
test('a rejected scene add surfaces as an error instead of healthy stats', async () => {
const scene = asyncDataSources({ rejectAdd: true });
const { layer, cleanup } = await enableLayerWithFetch(serveOnePolygon, {
dataSources: scene,
test('a set the renderer refuses surfaces as an error instead of healthy stats', async () => {
const { layer, fake, cleanup } = await enableLayerWithFetch(serveOnePolygon, {
failDraw: true,
});
const stats = layer.getStats();
assert.equal(stats.error, 'dataset unavailable (scene rejected the data source)');
assert.equal(stats.error, 'dataset unavailable (the renderer refused a set)');
assert.equal(stats.count, 0);
assert.equal(stats.lastUpdate, null);
assert.equal(layerFeedState(stats), 'unavailable');
assert.equal(scene.added.length, 0);
assert.equal(fake.liveSets().length, 0, 'the sets made before the refusal are let go');
cleanup();
});
@@ -711,7 +582,7 @@ test('a loaded dataset is distinguishable from a dead one', async () => {
/** Drop the camera to `altM` above the fixture dam so retries are in range. */
function setCameraAltitude(env, altM) {
env.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.695, 30.205, altM);
env.fake.setEye(-97.695, 30.205, altM);
}
function governorReasons() {
@@ -724,12 +595,12 @@ test('ground sampling waits for visible globe tiles before caching a height', as
});
const clock = installFakeClock(t);
t.after(() => { env.layer.destroy(env.viewer); env.cleanup(); });
env.viewer.scene.globe = { show: true, tilesLoaded: false, getHeight: () => 117 };
Object.assign(env.fake.globe, { show: true, tilesLoaded: false, terrain: () => 117 });
setCameraAltitude(env, 20_000);
env.preRender.raise();
assert.equal(env.sampleCalls.count, 0, 'streaming terrain must not become a permanent coarse sample');
assert.ok(Math.abs(baseHeightM(env)) < 0.01);
env.viewer.scene.globe.tilesLoaded = true;
env.fake.globe.tilesLoaded = true;
clock.advance(2_100);
env.preRender.raise();
assert.equal(env.sampleCalls.count, 1, 'the existing retry must sample the settled scene');
@@ -743,8 +614,7 @@ test('settled terrain refinement lifts an already sampled stem without another G
const clock = installFakeClock(t);
t.after(() => { env.layer.destroy(env.viewer); env.cleanup(); });
let terrain = 117;
const globe = { show: true, tilesLoaded: true, getHeight: () => terrain };
env.viewer.scene.globe = globe;
const globe = Object.assign(env.fake.globe, { show: true, tilesLoaded: true, terrain: () => terrain });
setCameraAltitude(env, 20_000);
env.preRender.raise();
assert.ok(Math.abs(baseHeightM(env) - 117) < 0.01);
@@ -783,7 +653,7 @@ for (const [terrainHeight, sampledHeight, expectedHeight, globeShown] of [
});
installFakeClock(t);
t.after(() => { env.layer.destroy(env.viewer); env.cleanup(); });
env.viewer.scene.globe = { show: globeShown, getHeight: () => terrainHeight };
Object.assign(env.fake.globe, { show: globeShown, terrain: () => terrainHeight });
setCameraAltitude(env, 20_000);
env.preRender.raise();
assert.ok(Math.abs(baseHeightM(env) - expectedHeight) < 0.01,
@@ -894,32 +764,29 @@ function runArmedRetryChain(env, t, clock, cycles) {
}
}
/** The stem base an entity registered for voice targeting. */
function targetPositionOf(entity) {
const contextId = readEntityRecord(entity)?.contextId;
/** The stem base the harness feature registered for voice targeting. */
function targetPositionOf(env) {
const [stem] = env.fake.set('stems').items.values();
const contextId = readEntityRecord(stem.meta)?.contextId;
return getContextStore().entities.get(contextId)?.targetPosition;
}
/** Height of the (mutated-in-place) stem base — 0 until a sample lands. */
function baseHeightM(env) {
const entity = env.dataSources[0].entities.values[0];
return Cesium.Cartographic.fromCartesian(targetPositionOf(entity)).height;
// To the millimetre: back from ECEF, a height of 0 reads ~1e-9.
return Math.round(toLonLatH(targetPositionOf(env)).height * 1000) / 1000 || 0;
}
/**
* Count Cartesian3.distance calls. The retry path costs one per ungrounded
* record per walk; on a scene that cannot sample, every one of them is waste
* (O(N) every 450 ms in a keyless scene that some other layer keeps awake).
* Count the eye reads a walk makes past its first. The retry path reads the
* eye's distance to each ungrounded record; on a scene that cannot sample,
* every one of them is waste (O(N) every 450 ms in a keyless scene that some
* other layer keeps awake). Counted as surface samples asked for, the only
* per-record retry work the renderer sees.
*/
function countDistanceCalls(t) {
const original = Cesium.Cartesian3.distance;
const calls = { count: 0 };
Cesium.Cartesian3.distance = (...args) => {
calls.count += 1;
return original(...args);
};
t.after(() => { Cesium.Cartesian3.distance = original; });
return calls;
function countRetryWork(env) {
const start = env.sampleCalls.count;
return { get count() { return env.sampleCalls.count - start; } };
}
test('a scene that cannot sample heights never arms a retry — not even once', async (t) => {
@@ -944,7 +811,7 @@ test('a scene that cannot sample heights never arms a retry — not even once',
// camera distance to size the stem), then measure the STEADY state.
env.preRender.raise();
clock.advance(2_100);
const distances = countDistanceCalls(t);
const distances = countRetryWork(env);
runArmedRetryChain(env, t, clock, 5);
assert.equal(governorScene.renders, 0, 'an unsampleable scene must ask for no frames at all');
@@ -978,7 +845,7 @@ test('a sampleable scene still measures the retry distance it needs', async (t)
setCameraAltitude(env, 20_000);
env.preRender.raise();
clock.advance(2_100);
const distances = countDistanceCalls(t);
const distances = countRetryWork(env);
runArmedRetryChain(env, t, clock, 5);
assert.ok(distances.count > 0, 'the retry path must still measure range when it can sample');
@@ -1007,11 +874,11 @@ test('capability arriving late re-opens a spent budget without camera motion', a
assert.equal(governorScene.renders, GROUND_SAMPLE_MAX_ARMED_RETRIES, 'budget spent');
// Context lost, then restored — with the camera never touched.
env.viewer.scene.sampleHeightSupported = false;
env.fake.capabilities.delete('sampleHeight');
runArmedRetryChain(env, t, clock, 2);
assert.equal(governorScene.renders, GROUND_SAMPLE_MAX_ARMED_RETRIES, 'no arming while unsupported');
env.viewer.scene.sampleHeightSupported = true;
env.fake.capabilities.add('sampleHeight');
runArmedRetryChain(env, t, clock, 3);
assert.equal(
governorScene.renders,
@@ -1110,14 +977,10 @@ test('after the cap a camera-motion frame still samples, and re-opens the budget
async function createMultiFeatureLodHarness({ featureCount = 150, cameraHeightM = 9_000_000 } = {}) {
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
const preRender = new MockLayerEvent();
const moveEnd = new MockLayerEvent();
const dataSources = [];
const centerLon = -97.7;
const centerLat = 30.2;
// Polygons, not Points: Cesium's GeoJsonDataSource builds a PinBuilder
// billboard for a Point, which needs a DOM canvas the node test env lacks.
// The layer takes the polygon's bounding-sphere centre as the stem anchor.
// Polygons: the layer takes the polygon's bounding-sphere centre as the
// stem anchor.
const lines = Array.from({ length: featureCount }, (_, i) => {
const lon = centerLon + (i % 12) * 0.02;
const lat = centerLat + Math.floor(i / 12) * 0.02;
@@ -1141,37 +1004,12 @@ async function createMultiFeatureLodHarness({ featureCount = 150, cameraHeightM
globalThis.fetch = async () => ({ ok: true, status: 200, text: async () => lines.join('\n') });
globalThis.window = { dispatchEvent() {} };
const setPos = (m) => {
const p = Cesium.Cartesian3.fromDegrees(centerLon, centerLat, m);
viewer.camera.positionWC = p;
viewer.camera.positionCartographic = Cesium.Cartographic.fromCartesian(p);
};
const viewer = {
selectedEntity: undefined,
dataSources: {
add(ds) { dataSources.push(ds); return ds; },
remove(ds) {
const i = dataSources.indexOf(ds);
if (i >= 0) dataSources.splice(i, 1);
return i >= 0;
},
},
camera: {
positionWC: null,
positionCartographic: null,
frustum: { fov: Math.PI / 3 },
moveEnd,
flyTo() {},
},
scene: {
canvas: { clientWidth: 1440, clientHeight: 900 },
preRender,
sampleHeightSupported: false,
screenSpaceCameraController: { enableInputs: true },
pick() { return null; },
requestRender() {},
},
};
const viewer = {};
const fake = bindFakeGroundRenderer(viewer, {
eye: { lon: centerLon, lat: centerLat, height: cameraHeightM },
canvas: { width: 1440, height: 900 },
});
const setPos = (m) => fake.setEye(centerLon, centerLat, m);
setPos(cameraHeightM);
const layer = createLocalGeoJsonLayer({
id: 'local-datacenters',
@@ -1190,14 +1028,20 @@ async function createMultiFeatureLodHarness({ featureCount = 150, cameraHeightM
return {
layer,
viewer,
dataSources,
preRender,
moveEnd,
fake,
preRender: fake.preRender,
moveEnd: fake.moveEnd,
setCameraHeight: setPos,
/** The stems drawn, by item. */
stems: () => [...fake.set('stems').items.values()],
shownIds() {
return this.stems().filter((stem) => stem.show !== false).map((stem) => stem.id);
},
shownCount() {
return dataSources[0].entities.values.filter((entity) => entity.show === true).length;
return this.shownIds().length;
},
cleanup() {
fake.unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
},
@@ -1214,15 +1058,13 @@ test('globe-LOD caps live stems at the camera-height budget and widens as you zo
// Full-earth framing: 150 in-view features, but the global band allows 80.
env.preRender.raise();
assert.equal(env.dataSources[0].entities.values.length, 150, 'all features are materialized');
assert.equal(env.stems().length, 150, 'all features are materialized');
assert.equal(env.shownCount(), INFRA_LOD_ACTIVE_MIN, 'only the global-band budget carries a stem');
// Named features (label priority ~1240) outrank anonymous nodes (~60), so
// every one of the 75 named features keeps a stem; the 5 remaining budget
// slots go to unnamed ones.
const shownIds = new Set(
env.dataSources[0].entities.values.filter((entity) => entity.show === true).map((entity) => entity.id),
);
const shownIds = new Set(env.shownIds());
const namedIds = Array.from({ length: 150 }, (_, i) => i).filter((i) => i % 2 === 0).map((i) => `dc-${i}`);
assert.ok(namedIds.every((id) => shownIds.has(id)), 'every named feature wins a stem before any unnamed one');
@@ -1244,19 +1086,13 @@ test('globe-LOD selection is stable between camera moves (no per-frame churn)',
});
env.preRender.raise();
const firstSet = env.dataSources[0].entities.values
.filter((entity) => entity.show === true)
.map((entity) => entity.id)
.sort();
const firstSet = env.shownIds().sort();
assert.equal(firstSet.length, INFRA_LOD_ACTIVE_MIN);
// A second walk with no intervening moveEnd must not re-select.
clock.advance(500);
env.preRender.raise();
const secondSet = env.dataSources[0].entities.values
.filter((entity) => entity.show === true)
.map((entity) => entity.id)
.sort();
const secondSet = env.shownIds().sort();
assert.deepEqual(secondSet, firstSet, 'the active set only changes on camera moves');
});
File diff suppressed because it is too large. Load diff
+278
View File
@@ -0,0 +1,278 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createLocalGeoJsonLayer,
localGeojsonParts,
} from './localGeojsonCore.js';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { getContextStore } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
const feature = (id, geometry, properties = { name: `Feature ${id}` }) => ({
type: 'Feature',
id,
properties,
geometry,
});
const square = (lon, lat, d = 0.01) => [
[
[lon, lat],
[lon + d, lat],
[lon + d, lat + d],
[lon, lat],
],
];
test('the drawn parts take the loader’s ids, one per part of a multi-geometry', () => {
const parts = localGeojsonParts([
feature('m', {
type: 'MultiPolygon',
coordinates: [square(0, 0), square(1, 1)],
}),
feature('m', { type: 'Point', coordinates: [2, 2] }),
feature('l', {
type: 'MultiLineString',
coordinates: [
[
[0, 0],
[1, 1],
],
],
}),
feature('n', null),
]);
assert.deepEqual(
parts.map((part) => [part.id, part.kind]),
[
['m', 'polygon'],
['m_2', 'polygon'],
['m_3', 'point'],
['l', 'line'],
['n', 'empty'],
],
);
assert.throws(
() => localGeojsonParts([{ type: 'Feature', id: 'x' }]),
/geometry is required/,
);
assert.throws(
() => localGeojsonParts([feature('x', { type: 'Blob', coordinates: [] })]),
/Unknown geometry type: Blob/,
);
});
async function enabledLayer(t, features) {
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
globalThis.window = { dispatchEvent() {} };
globalThis.fetch = async () => ({
ok: true,
status: 200,
text: async () => features.map((f) => JSON.stringify(f)).join('\n'),
});
const viewer = {};
const fake = bindFakeGroundRenderer(viewer, {
eye: { lon: 0.005, lat: 0.005, height: 50_000 },
});
let click = null;
const holds = [];
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
url: '/draw.geojsonl',
name: 'Dams',
color: '#0088ff',
projectToWindow: () => ({ x: 400, y: 300 }),
inputFor: () => ({
onClick: (handler) => {
click = handler;
return () => {
click = null;
};
},
suspendCamera: (reason) => {
holds.push(reason);
return () => holds.push(`release:${reason}`);
},
}),
},
{
...localGeoJsonServices,
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
},
);
try {
await layer.enable(viewer);
} finally {
globalThis.fetch = originalFetch;
}
t.after(() => {
layer.destroy(viewer);
fake.unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
});
return { layer, viewer, fake, holds, click: (event) => click?.(event) };
}
test('polygons fill the ground, lines drape, points stand on pins, all shown', async (t) => {
const env = await enabledLayer(t, [
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
feature('l', {
type: 'LineString',
coordinates: [
[0, 0],
[0.01, 0.01],
],
}),
feature('pt', { type: 'Point', coordinates: [0.002, 0.003] }),
]);
const fills = env.fake.set('fills');
const lines = env.fake.set('lines');
const pins = env.fake.set('pins');
for (const set of [fills, lines, pins, env.fake.set('stems')])
assert.notEqual(set.show, false, `${set.spec.id} shows once enabled`);
const fill = fills.items.get('p');
assert.equal(fill.height, 'clampGround');
assert.equal(fill.geometry.kind, 'polygon');
assert.equal(fill.show, true);
const line = lines.items.get('l');
assert.equal(line.widthPx, 2);
assert.equal(line.mode, 'draped');
const pin = pins.items.get('pt');
assert.deepEqual(pin.size, [8, 8]);
assert.match(pin.image.svg, /<svg/);
// A stem for the polygon and the point, none for the line.
assert.deepEqual([...env.fake.set('stems').items.keys()].sort(), ['p', 'pt']);
// Each item carries its feature's context record.
const record = getContextStore().entities.get(
readEntityRecord(fill.meta)?.contextId,
);
assert.equal(record?.label, 'Feature p');
});
test('a click on a drawn part selects its feature and flies above it', async (t) => {
const env = await enabledLayer(t, [
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
]);
const fills = env.fake.set('fills');
// Another layer's hit, or an id it never drew, is not its own.
env.click({ drawHit: { set: 'other:fills', id: 'p' } });
env.click({ drawHit: { set: fills.spec.id, id: 'nope' } });
assert.equal(env.fake.flights.length, 0);
env.click({ drawHit: { set: fills.spec.id, id: 'p' } });
assert.equal(env.fake.flights.length, 1);
const { destination, options } = env.fake.flights[0];
assert.equal(destination.height, 5000);
assert.ok(Math.abs(destination.lon - 0.005) < 0.01);
assert.equal(options.durationS, 1.5);
assert.deepEqual(env.holds, ['local-geojson-flight']);
options.onComplete();
assert.deepEqual(env.holds, [
'local-geojson-flight',
'release:local-geojson-flight',
]);
assert.equal(
getContextStore().selectedEntityId,
readEntityRecord(fills.items.get('p').meta)?.contextId,
'its feature is selected',
);
});
test('features keep their own simplestyle colours, widths and marker sizes', async (t) => {
const env = await enabledLayer(t, [
feature(
'p',
{ type: 'Polygon', coordinates: square(0, 0) },
{ fill: '#ff0000', 'fill-opacity': 0.5 },
),
feature(
'q',
{ type: 'Polygon', coordinates: square(0.02, 0) },
{ fill: '#00ff00' },
),
feature(
'l',
{
type: 'LineString',
coordinates: [
[0, 0],
[0.01, 0.01],
],
},
{ stroke: '#00ff00', 'stroke-opacity': 0.25, 'stroke-width': 5 },
),
// Null is no value, as the loader reads it.
feature(
'n',
{
type: 'LineString',
coordinates: [
[0, 0],
[0.01, 0],
],
},
{ stroke: null, 'stroke-opacity': null, 'stroke-width': null },
),
feature(
'pt',
{ type: 'Point', coordinates: [0.002, 0.003] },
{ 'marker-color': '#ffffff', 'marker-size': 'large' },
),
]);
assert.deepEqual(env.fake.set('fills').items.get('p').fill, [1, 0, 0, 0.5]);
// `fill` alone keeps the layer's fill alpha.
assert.deepEqual(env.fake.set('fills').items.get('q').fill, [0, 1, 0, 0.3]);
const line = env.fake.set('lines').items.get('l');
assert.equal(line.widthPx, 5);
assert.deepEqual(line.style.color, [0, 1, 0, 0.25]);
const plain = env.fake.set('lines').items.get('n');
assert.equal(plain.widthPx, 2);
assert.deepEqual(plain.style.color, [0, 136 / 255, 1, 1]);
const pin = env.fake.set('pins').items.get('pt');
assert.deepEqual(pin.size, [64, 64]);
assert.match(pin.image.svg, /fill="rgba\(255,255,255,1\)"/);
});
test('heights raise a polygon off the ground and stand a point’s pin on its tip', async (t) => {
const env = await enabledLayer(t, [
feature('p', {
type: 'Polygon',
coordinates: [
[
[0, 0, 100],
[0.01, 0, 100],
[0.01, 0.01, 100],
[0, 0, 100],
],
],
}),
feature('pt', { type: 'Point', coordinates: [0.002, 0.003, 50] }),
]);
assert.equal(env.fake.set('fills').items.size, 0, 'none on the ground');
const fill = env.fake.set('raised').items.get('p');
assert.equal(fill.height, 'absolute');
assert.equal(fill.geometry.perPositionHeight, true);
assert.equal(fill.geometry.rings[0][0].height, 100);
assert.deepEqual(fill.outline, [0, 136 / 255, 1, 1]);
const pin = env.fake.set('pins').items.get('pt');
assert.equal(pin.height, undefined, 'not clamped');
const dot = env.fake.set('dots').items.get('pt');
assert.deepEqual(pin.pos, dot.pos, 'the pin stands where the dot does');
});
test('long edges follow rhumb lines', async (t) => {
const env = await enabledLayer(t, [
feature('l', {
type: 'LineString',
coordinates: [
[0, 10],
[10, 20],
],
}),
]);
const { positions } = env.fake.set('lines').items.get('l');
// Split as the default renderer splits a draped rhumb line: under 10 km.
assert.ok(positions.length > 150, `${positions.length} points`);
});
+24 -34
View File
@@ -1,9 +1,9 @@
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';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
/** The catalog's services, with the overlay host each test supplies. */
const createLocalGeoJsonLayer = (options) =>
@@ -28,20 +28,21 @@ function harness(t) {
globalThis.window = { dispatchEvent() {} };
t.after(() => {
layer.destroy(viewer);
fake.unbind();
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 viewer = {};
const fake = bindFakeGroundRenderer(viewer);
// The builds drawn now: one per five live sets (fills, lines, pins,
// stems and dots).
const sources = {
get size() { return fake.liveSets().length / 6; },
get shown() { return fake.liveSets().every((set) => set.show); },
};
const listeners = {
get size() { return fake.preRender.listeners.size + fake.moveEnd.listeners.size; },
};
const create = () => createLocalGeoJsonLayer({
id: 'local-dams', name: 'Dams', color: '#0088ff', url: '/dams.geojsonl',
@@ -55,7 +56,7 @@ function harness(t) {
}),
});
const layer = create();
return { layer, create, viewer, sources, listeners, handlers: () => handlers };
return { layer, create, viewer, fake, sources, listeners, handlers: () => handlers };
}
test('destroy removes context records and permits a fresh replacement', async t => {
@@ -66,7 +67,7 @@ test('destroy removes context records and permits a fresh replacement', async t
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');
assert.equal(env.sources.size, 0, 'disable disposes the built sets');
env.layer.destroy(env.viewer);
assert.equal(getContextStore().entities.size, 0);
assert.equal(env.sources.size, 0);
@@ -81,7 +82,7 @@ test('destroy removes context records and permits a fresh replacement', async t
assert.equal(getContextStore().entities.size, 0);
});
for (const phase of ['fetch', 'text', 'parse', 'add']) {
for (const phase of ['fetch', 'text']) {
test(`destroy during ${phase} leaves no late objects or context records`, async t => {
const env = harness(t);
const entered = deferred();
@@ -94,17 +95,6 @@ for (const phase of ['fetch', 'text', 'parse', 'add']) {
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);
@@ -135,7 +125,7 @@ test('concurrent enable and disable/re-enable share one pending dataset load', a
assert.equal(env.sources.size, 1);
assert.equal(env.handlers(), 1);
assert.equal(env.listeners.size, 2);
assert.equal([...env.sources][0].show, true);
assert.equal(env.sources.shown, true);
});
test('disable during loading releases the completed source; re-enable rebuilds without refetching', async t => {
@@ -151,7 +141,7 @@ test('disable during loading releases the completed source; re-enable rebuilds w
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(env.sources.shown, true);
assert.equal(fetchMock.mock.callCount(), 1, 'the parsed dataset is cached across the toggle');
});
@@ -159,19 +149,19 @@ test('a toggle-off frees the entities and a toggle-on rebuilds them from the cac
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);
const first = env.fake.set('fills');
assert.equal(first.items.size, 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(env.sources.size, 0, 'no set stays drawn 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);
const second = env.fake.set('fills');
assert.notEqual(second, first, 're-enable builds fresh sets');
assert.equal(env.sources.shown, true);
assert.equal(second.items.size, 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);
+14 -4
View File
@@ -7,10 +7,11 @@ import { findPickOwner, resolvePickId } from './pickRegistry.js';
* layer, which record, and its display label.
*
* Two lanes, in order:
* 1. Context-store carriers. Entity-backed layers (infrastructure GeoJSON,
* selected vessels, fires, installations) write a `contextId` into the
* picked object's entity record, and the store record already carries the label and
* position voice uses everywhere else.
* 1. Context-store carriers. Entity-backed layers (selected vessels, fires,
* installations) write a `contextId` into the picked object's entity
* record, and layers drawing through the draw port (infrastructure
* GeoJSON) into a draw item's `meta`; the store record already carries
* the label and position voice uses everywhere else.
* 2. Pick owners. Primitive-backed layers (aircraft, satellites, vessels)
* register an ownership predicate in `pickRegistry`; the owning layer's
* `findByQuery` turns the pick id into a live descriptor.
@@ -46,12 +47,21 @@ export function pickedKindForLayer(layerId) {
return KIND_BY_LAYER[layerId] || 'feature';
}
/** A pick of a draw-set item (its id is `{set, id, meta}`): the item's `meta`. */
function drawItemMeta(picked) {
const id = picked?.id;
return id && typeof id.set === 'string' && typeof id.id === 'string'
? id.meta
: undefined;
}
function contextCarrierRecord(picked, dataManager) {
const store = getContextStore();
for (const carrier of [
picked?.id,
picked?.primitive?.id,
picked?.primitive,
drawItemMeta(picked),
]) {
const contextId = readEntityRecord(carrier)?.contextId;
if (!contextId) continue;
+24
View File
@@ -64,6 +64,30 @@ test('an entity-backed feature resolves through the context store', () => {
});
});
test('a draw-set item resolves through the context record its meta carries', () => {
const carrier = { show: true };
registerEntityContext(carrier, {
id: 'local-datacenters:8',
layerId: 'local-datacenters',
label: 'Data Center 8',
latitude: 30.3,
longitude: -97.5,
});
// A Cesium pick of a draw-set item: its id is the item's pick id.
const picked = { id: { set: 'local-datacenters#1:fills', id: '8', meta: carrier }, primitive: {} };
assert.deepEqual(resolvePickedContext(picked, { dataManager: manager() }), {
layerId: 'local-datacenters',
id: 'local-datacenters:8',
label: 'Data Center 8',
kind: 'feature',
lat: 30.3,
lon: -97.5,
});
// Hidden, it is not what the user points at.
carrier.show = false;
assert.equal(resolvePickedContext(picked, { dataManager: manager() }), null);
});
test('disabled layers, trails and empty picks never resolve', () => {
registerPickOwner('military', (id) => id === 'm1');
assert.equal(resolvePickedContext({ id: 'm1' }, { dataManager: manager() }), null, 'military is disabled');
+6 -1
View File
@@ -4,6 +4,7 @@ import * as C from 'cesium';
import { showOsmCredit, hideOsmCredit } from './dataCredits.js';
import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { createInfrastructureLayers } from './infrastructure.js';
import { createBhoteKoshiLocatorLayer } from './bhoteKoshiLocator.js';
@@ -40,7 +41,11 @@ 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);
// They draw through the renderer's ports: a fake one, with the credits.
const ground = bindFakeGroundRenderer({});
t.after(ground.unbind);
const { capabilities, canvas, draw, frame, camera, query, globe } = ground.renderer;
const v = viewer(t, { capabilities, canvas, draw, frame, camera, query, globe });
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);
-1
View File
@@ -15,7 +15,6 @@
"src/data/iconSegment.js",
"src/data/iconSet.js",
"src/data/iconSetPrimitive.js",
"src/data/localGeojsonCore.js",
"src/input/dispatcher.js",
"src/input/sensorPick.js",
"src/layers/cctv/projection.js",
+4
View File
@@ -96,6 +96,10 @@ const DRAW_FROM_CALLER = new Set([
// input still is), but none of their modules loads a factory.
'./layers/flights',
'./layers/military',
// Not wholly Cesium-free (its pointer input still is), but its layers
// draw, size and fly through the ports alone.
'./infrastructure',
'./infrastructure/geojson',
]);
/**
+177
View File
@@ -0,0 +1,177 @@
/**
* A renderer double for layers that draw on the ground and size what they
* draw to the camera: a fake draw port (`fakeDrawPort.mjs`), a frame port
* whose `preRender` the test raises, a camera whose eye the test moves and
* whose `moveEnd` it raises, a query port answering the ellipsoid's
* horizon and scripted heights, and a globe whose visibility and terrain
* loading the test sets. Bound to `viewer`, as the application binds its
* renderer, so `drawOf`, `cameraOf` and the rest find it.
*/
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from './fakeDrawPort.mjs';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
/** An event a test raises: listeners added, removed and counted. */
export class FakeEvent {
constructor() {
this.listeners = new Set();
this.addCount = 0;
this.removeCount = 0;
}
on(listener) {
this.addCount++;
this.listeners.add(listener);
let active = true;
return () => {
if (!active) return;
active = false;
this.removeCount++;
this.listeners.delete(listener);
};
}
raise(...args) {
for (const listener of [...this.listeners]) listener(...args);
}
}
const WGS84_RADII = { x: 6378137, y: 6378137, z: 6356752.3142451793 };
/**
* Whether the ellipsoid hides `point` from `eye`, by the horizon-plane test
* the default renderer's occluder makes.
*/
function occluded(eye, point) {
const scaled = (p) => ({
x: p.x / WGS84_RADII.x,
y: p.y / WGS84_RADII.y,
z: p.z / WGS84_RADII.z,
});
const v = scaled(eye);
const vhMagnitudeSquared = v.x * v.x + v.y * v.y + v.z * v.z - 1;
const t = scaled(point);
const vt = { x: t.x - v.x, y: t.y - v.y, z: t.z - v.z };
const vtDotVc = -(vt.x * v.x + vt.y * v.y + vt.z * v.z);
if (vhMagnitudeSquared < 0) return vtDotVc > 0;
return (
vtDotVc > vhMagnitudeSquared &&
(vtDotVc * vtDotVc) / (vt.x * vt.x + vt.y * vt.y + vt.z * vt.z) >
vhMagnitudeSquared
);
}
/**
* @param {object} viewer The scene object to bind it to.
* @param {object} [options]
* @param {boolean} [options.sampleHeight] The `sampleHeight` capability.
* @param {(point: {lon: number, lat: number}) => number|null} [options.surface]
* Surface heights; default: none loaded.
* @param {{lon: number, lat: number, height: number}} [options.eye]
* @param {{width: number, height: number}} [options.canvas]
*/
export function bindFakeGroundRenderer(
viewer,
{
sampleHeight = false,
surface = () => null,
eye = { lon: 0, lat: 0, height: 1000 },
canvas = { width: 800, height: 600 },
} = {},
) {
const draw = fakeDrawPort();
const preRender = new FakeEvent();
const moveEnd = new FakeEvent();
const capabilities = new Set(sampleHeight ? ['sampleHeight'] : []);
const flights = [];
const renders = [];
let position = fromDegrees(eye.lon, eye.lat, eye.height);
let surfaceHeight = surface;
const sampleCalls = { count: 0 };
/** The globe: shown, its terrain loaded, and the terrain's heights. */
const globe = {
show: true,
tilesLoaded: true,
terrain: () => null,
};
const element = {
clientWidth: canvas.width,
clientHeight: canvas.height,
width: canvas.width,
height: canvas.height,
};
const renderer = {
capabilities,
canvas: element,
draw,
frame: {
on: (phase, cb) => (phase === 'preRender' ? preRender.on(cb) : () => {}),
requestRender: (reason) => renders.push(reason),
},
camera: {
pose() {
const at = toLonLatH(position);
return {
...at,
position: { ...position },
fovy: Math.PI / 3,
aspectRatio: 1,
};
},
on: (event, cb) => (event === 'moveEnd' ? moveEnd.on(cb) : () => {}),
flyTo(destination, options) {
flights.push({ destination, options });
return { done: Promise.resolve('complete'), cancel() {} };
},
},
query: {
project: () => ({ x: canvas.width / 2, y: canvas.height / 2 }),
isOccluded: (point) => occluded(position, point),
sampleHeightNow(point, options = {}) {
if (options.against === 'terrain')
return globe.show ? globe.terrain(point) : null;
if (!capabilities.has('sampleHeight')) return null;
sampleCalls.count += 1;
return surfaceHeight(point);
},
},
globe: {
isGlobeVisible: () => globe.show,
isSettled: (kind) =>
kind !== 'terrain' || !globe.show || globe.tilesLoaded !== false,
},
};
const unbind = bindRenderer(viewer, renderer);
return {
renderer,
draw,
preRender,
moveEnd,
globe,
flights,
renders,
sampleCalls,
capabilities,
unbind,
/** The live set whose id ends with `:${role}`. */
set: (role) =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(`:${role}`),
),
/** Every set not yet disposed. */
liveSets: () =>
[...draw.sets.values()].filter((record) => !record.disposed),
/** Move the eye. */
setEye(lon, lat, height) {
position = fromDegrees(lon, lat, height);
},
setEyePosition(next) {
position = { ...next };
},
eyePosition: () => ({ ...position }),
/** Change what surface samples answer. */
setSurface(next) {
surfaceHeight = next;
},
};
}