diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md
index 31d3cb4cb..9a5590ec6 100644
--- a/docs/INFRASTRUCTURE-LAYERS.md
+++ b/docs/INFRASTRUCTURE-LAYERS.md
@@ -45,11 +45,24 @@ Callbacks must be ready before enable and remain usable through destruction.
Disable retains the loaded dataset for reuse and clears selection and listeners.
Concurrent enables share one load. Destroy is permanent, aborts pending fetches,
-discards late results, and clears the owned data source, context records, overlays,
+discards late results, and clears the owned draw sets, context records, overlays,
input handler and listeners. The layer never creates an application context store,
overlay host, viewer, or render scheduler. The consumer must resolve one compatible
Cesium installation shared with its viewer; it must not bundle separate copies.
+The layers draw, size their stems and fly the camera through the renderer's
+ports. A viewer the application has bound a renderer to needs nothing more; a
+Cesium viewer with no renderer bound loads
+`gods-eye-view/render/cesium/unbound` once first; until then the layer reports
+an error naming it, as it does for a dataset it cannot load.
+A selected feature is the context record its draw item carries as `meta`; the
+layer no longer sets the viewer's `selectedEntity`.
+Features keep their own simplestyle `fill`, `fill-opacity`, `stroke`,
+`stroke-opacity`, `stroke-width`, `marker-color` and `marker-size`, given as hex,
+`rgb()` or `hsl()` colours; a `marker-symbol` draws the plain pin. Polygons
+with heights are drawn at them, outlined; points with heights stand their pin
+on the stem's tip. Edges follow rhumb lines.
+
`gods-eye-view/infrastructure/geojson` exports the lower-level
`createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay
helpers. `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers.
@@ -57,6 +70,6 @@ Consumers use the package exports, which do not import standalone application
globals.
Dataset files and source/license notices remain under `src/data/local_data/`.
-Their input counts are 4,351 datacenter features and 704 dam features. Cesium may
-expand multipart geometries into multiple entities; entity and stem counts are
-different measurements. This change does not refresh or relicense the datasets.
+Their input counts are 4,351 datacenter features and 704 dam features. A multipart
+geometry draws as several parts, each with its own stem; part and stem counts are
+different measurements from feature counts. This change does not refresh or relicense the datasets.
diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json
index 81e471d3a..29d9dbad1 100644
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@ -53,7 +53,10 @@
"src/styles/styleStages.js",
"src/data/infrastructureOverlayEntry.js",
"src/sources/infrastructureData.js",
- "src/queries/heights.js"
+ "src/queries/heights.js",
+ "src/render/color.js",
+ "src/geo/sphere.js",
+ "src/geo/rhumb.js"
],
"external": ["cesium"]
},
diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs
index 97f27ad9d..359395501 100644
--- a/src/data/infrastructure.test.mjs
+++ b/src/data/infrastructure.test.mjs
@@ -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',
]);
diff --git a/src/data/localGeojson.analyst.test.mjs b/src/data/localGeojson.analyst.test.mjs
index ea7ede7a6..17d617930 100644
--- a/src/data/localGeojson.analyst.test.mjs
+++ b/src/data/localGeojson.analyst.test.mjs
@@ -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;
}
diff --git a/src/data/localGeojson.test.mjs b/src/data/localGeojson.test.mjs
index 20925d293..f1ae662e3 100644
--- a/src/data/localGeojson.test.mjs
+++ b/src/data/localGeojson.test.mjs
@@ -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');
});
diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js
index dcc257c0d..68b0d362c 100644
--- a/src/data/localGeojsonCore.js
+++ b/src/data/localGeojsonCore.js
@@ -1,5 +1,17 @@
-import * as Cesium from 'cesium';
-import { cameraOf } from '../render/cesium/camera.js';
+import {
+ cameraOf,
+ canvasOf,
+ drawOf,
+ findCamera,
+ findFrame,
+ findGlobe,
+ findQuery,
+} from '../render/rendererOf.js';
+import { cssColor } from '../render/color.js';
+import { fromDegrees, fromDegreesInto, toLonLatH } from '../geo/ellipsoid.js';
+import { sphereFromPoints } from '../geo/sphere.js';
+import { densifyRhumb } from '../geo/rhumb.js';
+import { heightsOf } from '../queries/heights.js';
import {
layerTitle,
mapAnalystRecord,
@@ -12,7 +24,6 @@ import {
applyInfraEvictionGrace,
shouldRecomputeInfraLod,
} from './localGeojsonLod.js';
-import { heightsFor } from '../render/cesium/heights.js';
const DEFAULT_LABEL_MAX = 900;
const DEFAULT_LABEL_GRID_PX = 132;
@@ -99,7 +110,8 @@ export function localInfrastructureOverlayCopy(properties, layerId) {
* @param {object} options
* @param {string} options.id Stable id within the source.
* @param {string} options.layerId Local layer id.
- * @param {Cesium.Cartesian3} options.position Current stem-tip position.
+ * @param {{x: number, y: number, z: number}} options.position Current stem-tip
+ * position, ECEF metres.
* @param {object} options.properties Unwrapped feature properties.
* @param {number} options.priority Source-owned importance score.
* @param {string} options.accent Source accent color.
@@ -290,11 +302,221 @@ export function localDatasetError(error) {
return message ? `dataset unavailable (${message})` : 'dataset unavailable';
}
+/** Layer instances made so far, so each draws under set ids of its own. */
+let layerInstances = 0;
+
+/** The stem's starting height above the ellipsoid, until the first walk sizes it. */
+const INITIAL_TIP_HEIGHT_M = 2000;
+/** A polygon's fill alpha, and the line widths, as the GeoJSON loader drew them. */
+const FILL_ALPHA = 0.3;
+const FEATURE_LINE_WIDTH_PX = 2;
+const STEM_WIDTH_PX = 3.5;
+const PIN_SIZE_PX = 8;
+const BLACK = Object.freeze([0, 0, 0, 1]);
+
+/** A colour channel as a CSS byte, as the default renderer writes one. */
+const cssByte = (value) => (value === 1 ? 255 : (value * 256) | 0);
+const cssRgba = ([r, g, b, a]) =>
+ `rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`;
+
/**
- * A minimal, rock-solid native implementation for loading local GeoJSON Data.
- * Draws 3D stems (polylines) attached to Point entities and ensures
- * standard scene.pick natively clicks them.
- * @param {object} options Dataset URL, identity, appearance and optional Cesium adapters.
+ * The pin a Point feature stands on: the GeoJSON loader's default marker,
+ * its pin path at `size` pixels, filled in `rgba` and outlined in that
+ * colour brightened by 0.6.
+ * @param {number[]} rgba
+ * @param {number} [size]
+ * @returns {{svg: string}}
+ */
+function pinImage(rgba, size = PIN_SIZE_PX) {
+ const brighter = [
+ 1 - (1 - rgba[0]) * 0.4,
+ 1 - (1 - rgba[1]) * 0.4,
+ 1 - (1 - rgba[2]) * 0.4,
+ rgba[3],
+ ];
+ return {
+ svg:
+ ``,
+ };
+}
+
+/** The GeoJSON loader's `marker-size` names, in pixels. */
+const MARKER_SIZES = Object.freeze({ small: 24, medium: 48, large: 64 });
+/**
+ * Ground edges are drawn along rhumb lines, split this finely (metres), as
+ * the default renderer splits a draped rhumb line.
+ */
+const RHUMB_GRANULARITY_M = 9999;
+
+/** `rgba` with alpha `alpha`. */
+const withAlpha = (rgba, alpha) => [rgba[0], rgba[1], rgba[2], alpha];
+
+/** Whether the loader took a property: present and not null. */
+const given = (value) => value !== undefined && value !== null;
+
+/**
+ * A feature's own stroke as the GeoJSON loader read it from its
+ * properties (`stroke`, `stroke-opacity`, `stroke-width`), over the
+ * layer's colour and width.
+ */
+function strokeOf(properties, rgba) {
+ let color = null;
+ let widthPx = FEATURE_LINE_WIDTH_PX;
+ if (properties) {
+ if (given(properties['stroke-width']))
+ widthPx = Number(properties['stroke-width']);
+ if (given(properties.stroke)) color = cssColor(properties.stroke);
+ const opacity = properties['stroke-opacity'];
+ if (given(opacity) && opacity !== 1)
+ color = withAlpha(color ?? rgba, Number(opacity));
+ }
+ return { color: color ?? rgba, widthPx };
+}
+
+/**
+ * A polygon's own fill as the GeoJSON loader read it (`fill` keeps the
+ * layer's fill alpha; `fill-opacity` sets the alpha).
+ */
+function fillOf(properties, fillColor) {
+ let fill = null;
+ if (properties) {
+ if (given(properties.fill)) {
+ const css = cssColor(properties.fill);
+ if (css) fill = withAlpha(css, fillColor[3]);
+ }
+ const opacity = properties['fill-opacity'];
+ if (given(opacity) && opacity !== fillColor[3])
+ fill = withAlpha(fill ?? fillColor, Number(opacity));
+ }
+ return fill ?? fillColor;
+}
+
+/**
+ * A point's own marker colour and size as the GeoJSON loader read them
+ * (`marker-color`, `marker-size`), over the layer's.
+ */
+function markerOf(properties, rgba) {
+ const color = given(properties?.['marker-color'])
+ ? cssColor(properties['marker-color'])
+ : null;
+ const size = MARKER_SIZES[properties?.['marker-size']] ?? PIN_SIZE_PX;
+ return { color: color ?? rgba, size };
+}
+
+/**
+ * Ground `coordinates` as `{lon, lat}` degrees along the rhumb lines
+ * between them, as the GeoJSON loader drew its draped edges.
+ */
+function rhumbPositions(coordinates) {
+ return densifyRhumb(
+ coordinates.map((c) => ({ lon: c[0] * RADIANS, lat: c[1] * RADIANS })),
+ RHUMB_GRANULARITY_M,
+ ).map(({ lon, lat }) => ({ lon: lon / RADIANS, lat: lat / RADIANS }));
+}
+const RADIANS = Math.PI / 180;
+
+/**
+ * The drawn parts of a feature collection, one per thing the GeoJSON loader
+ * made an entity of, in its order and under its ids: a polygon, line or
+ * point per part of a multi-geometry, the feature's id taking `_2`, `_3`…
+ * when repeated, and an empty part for a null geometry. A feature without
+ * an id gets one of its own. Throws as the loader does on a missing or
+ * unknown geometry.
+ * @param {object[]} features
+ * @returns {Array<{id: string, kind: 'polygon'|'line'|'point'|'empty',
+ * feature: object, coordinates?: any}>}
+ */
+export function localGeojsonParts(features) {
+ const parts = [];
+ const taken = new Set();
+ const idOf = (feature) => {
+ const base =
+ feature.id === undefined || feature.id === null
+ ? `local-part:${parts.length}`
+ : String(feature.id);
+ let id = base;
+ for (let i = 2; taken.has(id); i++) id = `${base}_${i}`;
+ return id;
+ };
+ const add = (feature, kind, coordinates) => {
+ const id = idOf(feature);
+ taken.add(id);
+ parts.push({ id, kind, feature, coordinates });
+ };
+ const polygon = (feature, rings) => {
+ if (rings.length === 0 || rings[0].length === 0) return;
+ add(feature, 'polygon', rings);
+ };
+ const geometry = (feature, shape) => {
+ switch (shape.type) {
+ case 'Point':
+ return add(feature, 'point', shape.coordinates);
+ case 'MultiPoint':
+ for (const point of shape.coordinates) add(feature, 'point', point);
+ return;
+ case 'LineString':
+ return add(feature, 'line', shape.coordinates);
+ case 'MultiLineString':
+ for (const line of shape.coordinates) add(feature, 'line', line);
+ return;
+ case 'Polygon':
+ return polygon(feature, shape.coordinates);
+ case 'MultiPolygon':
+ for (const rings of shape.coordinates) polygon(feature, rings);
+ return;
+ case 'GeometryCollection':
+ for (const inner of shape.geometries) geometry(feature, inner);
+ return;
+ default:
+ throw new Error(`Unknown geometry type: ${shape.type}`);
+ }
+ };
+ for (const feature of features) {
+ if (feature.geometry === null) {
+ add(feature, 'empty');
+ continue;
+ }
+ if (!feature.geometry) throw new Error('feature.geometry is required.');
+ geometry(feature, feature.geometry);
+ }
+ return parts;
+}
+
+const lonLatOf = (coordinates) => ({
+ lon: coordinates[0],
+ lat: coordinates[1],
+});
+const distance = (a, b) => Math.sqrt(distanceSquared(a, b));
+function distanceSquared(a, b) {
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ const dz = a.z - b.z;
+ return dx * dx + dy * dy + dz * dz;
+}
+const copy = (p) => ({ x: p.x, y: p.y, z: p.z });
+
+/**
+ * The horizontal field of view the stems are sized by: the wider of the
+ * two angles, as the default renderer's frustum states its field of view.
+ */
+function wideFov(pose) {
+ const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3;
+ const aspect = pose?.aspectRatio;
+ return Number.isFinite(aspect) && aspect > 1
+ ? 2 * Math.atan(Math.tan(fovy / 2) * aspect)
+ : fovy;
+}
+
+/**
+ * A layer drawing a bundled GeoJSON dataset through the renderer's draw
+ * port: polygons and lines on the ground, and on each polygon or point a
+ * 3D stem with a dot on its tip, sized to the camera and lifted onto the
+ * sampled surface. Clicking any of it selects the feature and flies there.
+ * @param {object} options Dataset URL, identity, appearance and optional adapters.
* @param {object} services Caller-owned operations; see docs/INFRASTRUCTURE-LAYERS.md.
* @returns {object} A fresh layer implementing init/enable/disable/update/destroy/getStats/getAnalystRecords.
* One live instance per layer id is allowed in a given viewer/context/overlay host.
@@ -313,8 +535,8 @@ export function createLocalGeoJsonLayer(
labelMax = DEFAULT_LABEL_MAX,
labelGridPx = DEFAULT_LABEL_GRID_PX,
inputFor = defaultInputFor,
- projectToWindow = (scene, position) =>
- Cesium.SceneTransforms.worldToWindowCoordinates(scene, position),
+ projectToWindow = (viewer, position) =>
+ findQuery(viewer)?.project(position) ?? null,
},
{
overlayHost,
@@ -327,9 +549,9 @@ export function createLocalGeoJsonLayer(
hideOsmCredit,
},
) {
- let _dataSource = null;
- // The entities this layer loaded, so its click and teardown recognise them.
- const _ownEntities = new WeakSet();
+ const setPrefix = `${id}:${++layerInstances}`;
+ /** What this layer draws while built: its sets and parts, or null. */
+ let _drawn = null;
let _enabled = false;
let _clickSubscription = null;
let _count = 0;
@@ -347,12 +569,11 @@ export function createLocalGeoJsonLayer(
let _loadController = null;
/**
* The parsed bundled dataset, kept across disable/enable so a re-enable
- * rebuilds entities without refetching. The Cesium entities themselves are
- * NOT kept: a hidden data source still costs every frame (DataSourceDisplay
- * walks every visualizer over every entity regardless of `show`), and the
- * ~11k entities of the three bundled layers hold hundreds of MB, so leaving
- * them parked after a toggle-off made the whole scene render ~2× slower for
- * the rest of the session (owner field test 2026-09-13).
+ * rebuilds its sets without refetching. The sets themselves are NOT kept:
+ * a hidden set still holds its primitives, and the ~11k features of the
+ * three bundled layers hold hundreds of MB, so leaving them parked after a
+ * toggle-off made the whole scene render ~2× slower for the rest of the
+ * session (owner field test 2026-09-13).
* @type {Array