mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
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:
1 parent
333c9b39fe
commit
b0ed9d7e90
14 files changed
+1547
-947
No files matched your search
+133
-297
@@ -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');
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user