From b0ed9d7e900e2b0c3112de64d56dd22282c717bc Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 21:07:44 -0800 Subject: [PATCH] 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. --- docs/INFRASTRUCTURE-LAYERS.md | 21 +- scripts/package-boundaries.json | 5 +- src/data/infrastructure.test.mjs | 58 +- src/data/localGeojson.analyst.test.mjs | 48 +- src/data/localGeojson.test.mjs | 430 +++---- src/data/localGeojsonCore.js | 1365 ++++++++++++++--------- src/data/localGeojsonDraw.test.mjs | 278 +++++ src/data/localGeojsonLifecycle.test.mjs | 58 +- src/data/pickedContext.js | 18 +- src/data/pickedContext.test.mjs | 24 + src/data/sharedOsmDisplays.test.mjs | 7 +- src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 4 + src/testSupport/fakeGroundRenderer.mjs | 177 +++ 14 files changed, 1547 insertions(+), 947 deletions(-) create mode 100644 src/data/localGeojsonDraw.test.mjs create mode 100644 src/testSupport/fakeGroundRenderer.mjs 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|null} */ let _cachedFeatures = null; @@ -380,17 +601,17 @@ export function createLocalGeoJsonLayer( let _lodComputed = false; /** * Camera position the last LOD selection ran from — the reference the motion - * fallback measures travel against. Preallocated: the walk clones into it, + * fallback measures travel against. Preallocated: the walk copies into it, * so a moving camera allocates nothing per pass. Only meaningful while * `_lodComputed` is true. */ - const _lastLodCameraPos = new Cesium.Cartesian3(); + const _lastLodCameraPos = { x: 0, y: 0, z: 0 }; /** Last time the motion-fallback probe window opened (or a selection ran). */ let _lastLodProbeMs = Number.NEGATIVE_INFINITY; let _groundRetryTimer = null; /** Consecutive self-armed retries since the last grounding/camera motion. */ let _groundRetryArms = 0; - /** Last observed scene.sampleHeightSupported; null until the first walk. */ + /** Last observed height-sampling support; null until the first walk. */ let _lastGroundSampleCapability = null; /** @@ -400,19 +621,19 @@ export function createLocalGeoJsonLayer( * retry pass walks every record anyway. (perf rebase 2026-08-17) * * Two gates keep this from becoming an idle leak (review round 2): - * - CAPABILITY: without `scene.sampleHeightSupported` the sample can never - * succeed, so a timer here would re-arm on every requested frame, - * forever. Records simply stay at ellipsoid height — exactly the - * pre-perf keyless behavior. + * - CAPABILITY: without height sampling the sample can never succeed, so + * a timer here would re-arm on every requested frame, forever. Records + * simply stay at ellipsoid height — exactly the pre-perf keyless + * behavior. * - BUDGET: sampling can be supported and still keep failing (no sampleable * surface yet/ever). Give up after GROUND_SAMPLE_MAX_ARMED_RETRIES * consecutive arms; free camera-motion frames still retry. - * @param {Cesium.Viewer} viewer + * @param {object} viewer * @returns {void} */ function scheduleGroundRetryRender(viewer) { if (_groundRetryTimer || !_enabled) return; - if (!viewer?.scene?.sampleHeightSupported) return; + if (!heightsOf(viewer).supported().surface) return; if (_groundRetryArms >= GROUND_SAMPLE_MAX_ARMED_RETRIES) return; _groundRetryArms += 1; _groundRetryTimer = setTimeout(() => { @@ -434,25 +655,31 @@ export function createLocalGeoJsonLayer( host: overlayHost, }); + /** Let go of every set a build made. */ + function disposeSets(sets) { + for (const set of Object.values(sets)) { + try { + set.dispose(); + } catch { + /* its scene is already gone */ + } + } + } + /** - * Take the built entities out of the scene entirely. The parsed features - * stay cached, so the next enable() rebuilds without a fetch; what must not - * survive a disable is the per-frame visualizer walk and the entity memory. - * @param {object} viewer + * Take the built sets out of the scene entirely. The parsed features stay + * cached, so the next enable() rebuilds without a fetch; what must not + * survive a disable is what the sets draw and hold. */ - const releaseDataSource = (viewer) => { - if (!_dataSource) return; - const source = _dataSource; - _dataSource = null; + const releaseDrawn = () => { + if (!_drawn) return; + const drawn = _drawn; + _drawn = null; _stemRecords = []; _stemGeometryDirty = true; _lastVisibilityUpdate = Number.NEGATIVE_INFINITY; removeEntityContextsForLayer(id); - try { - viewer?.dataSources?.remove(source, true); - } catch { - /* already gone */ - } + disposeSets(drawn.sets); }; const disableLayer = (viewer) => { @@ -464,12 +691,9 @@ export function createLocalGeoJsonLayer( _lastLodBudgetLimit = 0; _lodComputed = false; _lastLodProbeMs = Number.NEGATIVE_INFINITY; - releaseDataSource(viewer); + releaseDrawn(); _overlayPublisher.hide(); clearSelectedEntityContextForLayer(id); - if (_ownEntities.has(viewer?.selectedEntity)) { - viewer.selectedEntity = undefined; - } if (_preRenderRemover) { _preRenderRemover(); _preRenderRemover = null; @@ -480,6 +704,226 @@ export function createLocalGeoJsonLayer( } }; + /** + * Build the sets for the parsed features: a fill for each polygon, a + * draped line for each line, a pin for each point, and a stem and its dot + * for each polygon and point. Hidden until the enable finishes, as the + * loader's data source was. + */ + function buildDrawn(viewer, features) { + const draw = drawOf(viewer); + const rgba = cssColor(color) ?? [1, 1, 1, 1]; + const fillColor = [rgba[0], rgba[1], rgba[2], FILL_ALPHA]; + // One image per marker colour and size, shared by the pins wearing it. + const pinImages = new Map(); + const pinFor = (marker) => { + const key = `${marker.color.join()}|${marker.size}`; + let image = pinImages.get(key); + if (!image) + pinImages.set(key, (image = pinImage(marker.color, marker.size))); + return image; + }; + const parts = localGeojsonParts(features); + const sets = {}; + const built = { sets, parts: new Map(), records: [], count: parts.length }; + try { + sets.fills = draw.shapes({ id: `${setPrefix}:fills`, show: false }); + // Raised polygons apart: a ground fill showing or hiding changes in + // place only in a set of ground fills. + sets.raised = draw.shapes({ id: `${setPrefix}:raised`, show: false }); + sets.lines = draw.lines({ id: `${setPrefix}:lines`, show: false }); + sets.pins = draw.icons({ id: `${setPrefix}:pins`, show: false }); + sets.stems = draw.lines({ id: `${setPrefix}:stems`, show: false }); + sets.dots = draw.points({ id: `${setPrefix}:dots`, show: false }); + + const fills = []; + const lines = []; + const pins = []; + for (const part of parts) { + if (part.kind === 'empty') continue; + const properties = unwrapProperties(part.feature.properties ?? {}); + // The object every item of this part carries as its `meta`: what a + // click or point-and-ask hit hands back, and the context carrier. + const carrier = { layerId: id, id: part.id, record: null }; + part.carrier = carrier; + built.parts.set(part.id, part); + // The feature's own simplestyle properties, as the loader read them. + const style = part.feature.properties; + if (part.kind === 'line') { + const positions = rhumbPositions(part.coordinates).map( + ({ lon, lat }) => fromDegrees(lon, lat, 0), + ); + part.flyTo = lonLatOf(part.coordinates[0]); + const stroke = strokeOf(style, rgba); + lines.push({ + id: part.id, + positions, + widthPx: stroke.widthPx, + mode: 'draped', + style: { kind: 'solid', color: stroke.color }, + meta: carrier, + }); + continue; + } + + let lon; + let lat; + if (part.kind === 'polygon') { + // Heights on the first position make the loader's polygon one of + // per-position heights, outlined, its edges straight between its + // positions; without, it lies on the ground along rhumb lines. + const raised = part.coordinates[0][0].length > 2; + part.raised = raised; + part.rings = part.coordinates.map((ring) => + raised + ? ring.map(([lon, lat, h]) => ({ + lon, + lat, + height: Number(h) || 0, + })) + : rhumbPositions(ring), + ); + part.fill = fillOf(style, fillColor); + // The stem stands on the centre of the outer ring's bounding + // sphere, carried to the surface. + const center = toLonLatH( + sphereFromPoints( + part.coordinates[0].map(([x, y, h]) => + fromDegrees(x, y, raised ? Number(h) || 0 : 0), + ), + ).center, + ); + lon = center.lon; + lat = center.lat; + } else { + lon = part.coordinates[0]; + lat = part.coordinates[1]; + part.pinClamped = part.coordinates.length <= 2; + part.pinPos = { lon, lat }; + const marker = markerOf(style, rgba); + part.pin = pinFor(marker); + part.pinSize = marker.size; + } + + const groundHeight = 0; // Ellipsoid surface until a scene sample lands + const base = fromDegrees(lon, lat, groundHeight); + const tip = fromDegrees(lon, lat, INITIAL_TIP_HEIGHT_M); + const recordId = part.id; + const priority = labelPriorityFromProperties(properties, id); + const record = { + id: recordId, + part, + carrier, + lon, + lat, + base, + tip, + nextTip: copy(tip), + groundHeight, + groundSampled: false, + lastGroundSampleMs: 0, + priority, + properties, + visible: true, + entry: labels + ? createLocalInfrastructureOverlayEntry({ + id: recordId, + layerId: id, + position: tip, + properties, + priority, + accent: color, + }) + : null, + }; + carrier.record = record; + // A context record is active while its feature shows. + Object.defineProperty(carrier, 'show', { + get: () => record.visible, + enumerable: true, + }); + registerEntityContext(carrier, { + id: `${id}:${recordId}`, + layerId: id, + layerName: name, + source, + label: featureLabelFromProperties(properties, id), + properties, + latitude: Number(lat.toFixed(6)), + longitude: Number(lon.toFixed(6)), + // The surface base voice targeting projects. Ground sampling + // re-grounds it in place, so this stays current. + targetPosition: base, + }); + built.records.push(record); + if (part.kind === 'polygon') fills.push(fillItem(record, rgba)); + else pins.push(pinItem(record)); + } + sets.fills.set(fills.filter((item) => item.height === 'clampGround')); + sets.raised.set(fills.filter((item) => item.height !== 'clampGround')); + sets.lines.set(lines); + sets.pins.set(pins); + sets.stems.set(built.records.map((record) => stemItem(record, rgba))); + sets.dots.set(built.records.map((record) => dotItem(record, rgba))); + } catch (error) { + disposeSets(sets); + throw error; + } + built.rgba = rgba; + return built; + } + + /** + * Write what a walk changed: the stems and dots that moved or showed or + * hid, the fills and pins that showed or hid (changed in place), and the + * pins standing on a tip that moved. + */ + function writeChanges(drawn, moved, shown) { + if (!moved.size && !shown.size) return; + const stems = new Set([...moved, ...shown]); + drawn.sets.stems.upsert( + [...stems].map((record) => stemItem(record, drawn.rgba)), + ); + drawn.sets.dots.upsert( + [...stems].map((record) => dotItem(record, drawn.rgba)), + ); + const fills = []; + const pins = []; + for (const record of stems) { + const { kind, pinClamped } = record.part; + if (!shown.has(record) && (kind !== 'point' || pinClamped)) continue; + if (kind === 'polygon') fills.push(fillItem(record, drawn.rgba)); + else pins.push(pinItem(record)); + } + const ground = fills.filter((item) => item.height === 'clampGround'); + const raised = fills.filter((item) => item.height !== 'clampGround'); + if (ground.length) drawn.sets.fills.upsert(ground); + if (raised.length) drawn.sets.raised.upsert(raised); + if (pins.length) drawn.sets.pins.upsert(pins); + } + + /** Fly to where a clicked part stands, holding camera input meanwhile. */ + function flyToPart(viewer, input, part) { + const target = part.carrier.record + ? { lon: part.carrier.record.lon, lat: part.carrier.record.lat } + : part.flyTo; + if (!target) return; + // Before the hold: with no camera, nothing would end it. + const camera = cameraOf(viewer); + // Hold camera input so the user's input doesn't cancel the flight. + // A hold, not a flag: the flight ending must not hand input back under + // a drag or the cockpit. + const releaseCamera = input.suspendCamera('local-geojson-flight'); + camera.flyTo( + { lon: target.lon, lat: target.lat, height: 5000 }, + { + durationS: 1.5, + onComplete: releaseCamera, + onCancel: releaseCamera, + }, + ); + } + return { id, name, @@ -539,14 +983,13 @@ export function createLocalGeoJsonLayer( for (let i = 0; i < _stemRecords.length; i++) { if (result.length >= limit) break; const record = _stemRecords[i]; - const carto = record.carto; result.push( mapAnalystRecord( { id: record.id, - lat: carto ? Cesium.Math.toDegrees(carto.latitude) : null, - lon: carto ? Cesium.Math.toDegrees(carto.longitude) : null, - properties: propertyObject(record.entity), + lat: record.lat, + lon: record.lon, + properties: record.properties, }, id, ), @@ -569,23 +1012,17 @@ export function createLocalGeoJsonLayer( _lastLodProbeMs = Number.NEGATIVE_INFINITY; _overlayPublisher.show(); - // 1. Initialize data source - if (!_dataSource) { + // 1. Build the sets + if (!_drawn) { if (!_loadPromise) _loadPromise = (async () => { _loadController = new AbortController(); - const baseColor = Cesium.Color.fromCssColorString(color); - // Fetch and parse JSON Lines (.geojsonl) into a FeatureCollection. - // The source is built into a local and committed to `_dataSource` - // only once setup finishes: a half-built source published early would - // make every later enable() skip this block, so the layer could never - // clear its error or retry. + // Fetch and parse JSON Lines (.geojsonl) into features. The sets + // are committed to `_drawn` only once setup finishes: a half-built + // one published early would make every later enable() skip this + // block, so the layer could never clear its error or retry. _error = null; - let loaded = null; - // Whether the scene has actually accepted `loaded` — the two rollback - // windows (before vs after the add settles) need different cleanup. - let addedToScene = false; try { let features = _cachedFeatures; if (!features) { @@ -604,178 +1041,18 @@ export function createLocalGeoJsonLayer( _cachedFeatures = features; } - const geojson = { - type: 'FeatureCollection', - features, - }; - - // Natively parse into entities and use it as our _dataSource - loaded = await Cesium.GeoJsonDataSource.load(geojson, { - clampToGround: true, - stroke: baseColor, - fill: baseColor.withAlpha(0.3), - strokeWidth: 2, - markerSize: 8, - markerColor: baseColor, - }); - - if (_destroyed) return; - loaded.name = name; - loaded.show = false; - // Cesium's DataSourceCollection.add() returns a promise and only - // inserts on a later microtask. Without this await, a throw during - // post-processing would roll back a source the scene had not - // accepted yet — and Cesium would then insert the "removed" source - // anyway, leaving an orphan the retry would double up on. Awaiting - // also routes an add() rejection into the error path below instead - // of leaving it uncaught with healthy-looking stats. - await viewer.dataSources.add(loaded); - addedToScene = true; - if (_destroyed) { - viewer.dataSources.remove(loaded, true); - return; - } - - // Convert parsed points into 3D stems or style polygons - const entities = loaded.entities.values; - _count = entities.length; - _stemRecords = []; + const built = buildDrawn(viewer, features); + _count = built.count; + _stemRecords = built.records; _stemGeometryDirty = true; - - for (let i = 0; i < entities.length; i++) { - const feature = entities[i]; - _ownEntities.add(feature); - - let pos = feature.position?.getValue(Cesium.JulianDate.now()); - - if (!pos) { - // It's a polygon or line - if (feature.polygon) { - feature.polygon.outline = true; - feature.polygon.outlineColor = baseColor; - - // Calculate center point for the stem - const hierarchy = feature.polygon.hierarchy?.getValue( - Cesium.JulianDate.now(), - ); - if ( - hierarchy && - hierarchy.positions && - hierarchy.positions.length > 0 - ) { - pos = Cesium.BoundingSphere.fromPoints( - hierarchy.positions, - ).center; - } - } - } - - if (!pos) continue; - - const carto = Cesium.Cartographic.fromCartesian(pos); - const groundHeight = 0; // Ellipsoid surface until a scene sample lands - const tipHeight = 2000; // Initial Stem height - - const base = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - groundHeight, - ); - const tip = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - tipHeight, - ); - const properties = propertyObject(feature); - const recordId = String(feature.id ?? i); - - registerEntityContext(feature, { - id: `${id}:${recordId}`, - layerId: id, - layerName: name, - source, - dataSource: loaded, - label: featureLabelFromProperties(properties, id), - properties, - latitude: Number( - Cesium.Math.toDegrees(carto.latitude).toFixed(6), - ), - longitude: Number( - Cesium.Math.toDegrees(carto.longitude).toFixed(6), - ), - // The surface base voice targeting projects. Ground sampling - // re-grounds it in place, so this stays current. - targetPosition: base, - }); - - // Constant properties are refreshed on the existing 450 ms source - // cadence. Cesium no longer evaluates 2-3 callbacks per entity on - // every frame, while the point/stem pick surface stays native. - feature.position = tip; - const stemPositionBuffers = [ - [base, tip], - [base, tip], - ]; - feature.polyline = new Cesium.PolylineGraphics({ - positions: stemPositionBuffers[0], - width: 3.5, - material: new Cesium.ColorMaterialProperty(baseColor), - }); - feature.point = new Cesium.PointGraphics({ - pixelSize: 10, - color: baseColor, - outlineColor: Cesium.Color.BLACK, - outlineWidth: 2, - // Never depth-cull the anchor against the photoreal mesh — - // globe-horizon culling is handled by the pre-render occluder. - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }); - - const priority = labelPriorityFromProperties(properties, id); - _stemRecords.push({ - id: recordId, - entity: feature, - carto, - base, - tip, - nextTip: Cesium.Cartesian3.clone(tip), - stemPositionBuffers, - stemPositionBufferIndex: 0, - groundHeight, - groundSampled: false, - lastGroundSampleMs: 0, - priority, - entry: labels - ? createLocalInfrastructureOverlayEntry({ - id: recordId, - layerId: id, - position: tip, - properties, - priority, - accent: color, - }) - : null, - }); - } // Setup finished — publish it. - _dataSource = loaded; + _drawn = built; _lastUpdate = Date.now(); } catch (e) { // The dataset ships with the build, so this is a broken install, // not a blip — it has to reach the chip, not just the console. + // `buildDrawn` let go of its own sets. if (!_destroyed) _error = localDatasetError(e); - // Roll the partial build back so a later enable() retries from - // scratch instead of inheriting a half-populated source. Only the - // post-add window has something in the scene to remove: a failure - // before (or inside) add() never reached the collection, and - // removing then would race Cesium's pending insert. - if (addedToScene) { - try { - viewer?.dataSources?.remove(loaded, true); - } catch { - /* already gone */ - } - } if (_destroyed) return; removeEntityContextsForLayer(id); _count = 0; @@ -784,67 +1061,18 @@ export function createLocalGeoJsonLayer( } if (_destroyed) return; - // 2. Install native global click handler + // 2. Install the click handler if (!_clickSubscription) { const input = inputFor(viewer); _clickSubscription = input.onClick((event) => { - if (!_enabled) return; - const picked = event.pick; - - if (picked && _ownEntities.has(picked.id)) { - const entity = picked.id; - viewer.selectedEntity = entity; - selectEntityContext(entity); - - // We zoom to the surface base of the stem or the center of the polygon - let targetPos = null; - - if (entity.polyline) { - // If it's a stem, fly to the base - const positions = entity.polyline.positions.getValue( - Cesium.JulianDate.now(), - ); - if (positions && positions.length > 0) { - targetPos = positions[0]; - } - } else if (entity.polygon && entity.polygon.hierarchy) { - // If it's a polygon, just fly to its center - const hierarchy = entity.polygon.hierarchy.getValue( - Cesium.JulianDate.now(), - ); - if (hierarchy && hierarchy.positions.length > 0) { - targetPos = Cesium.BoundingSphere.fromPoints( - hierarchy.positions, - ).center; - } - } - - if (targetPos) { - const carto = Cesium.Cartographic.fromCartesian(targetPos); - // Before the hold: with no camera, nothing would end it. - const camera = cameraOf(viewer); - - // Hold camera input so Cesium doesn't cancel the flight. - // A hold, not a flag: the flight ending must not hand input - // back under a drag or the cockpit. - const releaseCamera = input.suspendCamera( - 'local-geojson-flight', - ); - - camera.flyTo( - Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - 5000, - ), - { - durationS: 1.5, - onComplete: releaseCamera, - onCancel: releaseCamera, - }, - ); - } - } + if (!_enabled || !_drawn) return; + const hit = event.drawHit; + if (!hit || !hit.set.startsWith(`${setPrefix}:`)) return; + const part = _drawn.parts.get(hit.id); + if (!part) return; + selectEntityContext(part.carrier); + // To the surface base of the stem, or the line's start. + flyToPart(viewer, input, part); }); } })(); @@ -860,209 +1088,220 @@ export function createLocalGeoJsonLayer( if (_enabled && _count > 0 && osmDerived) showOsmCredit?.(viewer, id); // 3. Add an incredibly fast pre-render occluder to hide points behind the globe if (_enabled && !_preRenderRemover) { - _preRenderRemover = viewer.scene.preRender.addEventListener(() => { - if (!_enabled || !_dataSource) return; - const now = performance.now(); - if (now - _lastVisibilityUpdate < VISIBILITY_UPDATE_MS) return; - _lastVisibilityUpdate = now; + // With no renderer to run frames (a viewer with no renderer, before it has + // loaded the adapter's factories) there is nothing to walk: the + // build has already reported why. + _preRenderRemover = + findFrame(viewer)?.on('preRender', () => { + const drawn = _drawn; + if (!_enabled || !drawn) return; + const now = performance.now(); + if (now - _lastVisibilityUpdate < VISIBILITY_UPDATE_MS) return; + _lastVisibilityUpdate = now; - const cameraPos = viewer.camera.positionWC; - if (!cameraPos) return; + const pose = cameraOf(viewer).pose(); + const cameraPos = pose?.position; + if (!cameraPos) return; + const query = findQuery(viewer); + const inView = (position) => !query?.isOccluded(position); - // --- Globe-LOD motion fallback. --- - // `_stemGeometryDirty` is otherwise raised only by moveEnd, which a - // tracked-entity follow, Cockpit, route flight, or continuous orbit - // never emits. Left alone the selection stays pinned to the region - // the camera left: the walk below hides those records one by one as - // they pass behind the globe and admits nothing newly visible, so - // the layer bleeds down to sparse-or-empty until motion stops. - // Bounded: rate-limited to a probe window, and only when the camera - // has actually travelled since the last selection. - if (!_stemGeometryDirty && _lodComputed && _stemRecords.length > 0) { - const probe = shouldRecomputeInfraLod({ - nowMs: now, - lastProbeMs: _lastLodProbeMs, - movedSqM: Cesium.Cartesian3.distanceSquared( - cameraPos, - _lastLodCameraPos, - ), - cameraHeightM: viewer.camera.positionCartographic?.height, - }); - _lastLodProbeMs = probe.lastProbeMs; - // Re-selecting demands fresh stem geometry: a record admitted - // mid-motion has never had its tip sized for this camera. - if (probe.recompute) _stemGeometryDirty = true; - } + // --- Globe-LOD motion fallback. --- + // `_stemGeometryDirty` is otherwise raised only by moveEnd, which a + // tracked-entity follow, Cockpit, route flight, or continuous orbit + // never emits. Left alone the selection stays pinned to the region + // the camera left: the walk below hides those records one by one as + // they pass behind the globe and admits nothing newly visible, so + // the layer bleeds down to sparse-or-empty until motion stops. + // Bounded: rate-limited to a probe window, and only when the camera + // has actually travelled since the last selection. + if ( + !_stemGeometryDirty && + _lodComputed && + _stemRecords.length > 0 + ) { + const probe = shouldRecomputeInfraLod({ + nowMs: now, + lastProbeMs: _lastLodProbeMs, + movedSqM: distanceSquared(cameraPos, _lastLodCameraPos), + cameraHeightM: pose.height, + }); + _lastLodProbeMs = probe.lastProbeMs; + // Re-selecting demands fresh stem geometry: a record admitted + // mid-motion has never had its tip sized for this camera. + if (probe.recompute) _stemGeometryDirty = true; + } - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - cameraPos, - ); - const visibleOverlayRecords = []; - const refreshStemGeometry = _stemGeometryDirty; + const visibleOverlayRecords = []; + const refreshStemGeometry = _stemGeometryDirty; + // What this walk changes, written once at its end. + const moved = new Set(); + const shown = new Set(); - // A scene that cannot sample heights can never ground a record, so it - // must never arm a retry (the arm would re-arm on every requested - // frame, forever) and must not spend ANY per-record work trying. - // Read once per walk, not per record. - const canSampleGround = viewer.scene.sampleHeightSupported === true; - // Capability can arrive late (WebGL context restore, a tileset that - // finally supports sampling). A parked camera has no moveEnd to - // re-open a spent budget, so the false→true edge does it. - if (canSampleGround && _lastGroundSampleCapability === false) - _groundRetryArms = 0; - _lastGroundSampleCapability = canSampleGround; - let groundRetryPending = false; - let groundSampleProgress = false; + // A scene that cannot sample heights can never ground a record, so it + // must never arm a retry (the arm would re-arm on every requested + // frame, forever) and must not spend ANY per-record work trying. + // Read once per walk, not per record. + const canSampleGround = heightsOf(viewer).supported().surface; + // Capability can arrive late (a renderer bound after this layer + // started). A parked camera has no moveEnd to re-open a spent + // budget, so the false→true edge does it. + if (canSampleGround && _lastGroundSampleCapability === false) + _groundRetryArms = 0; + _lastGroundSampleCapability = canSampleGround; + let groundRetryPending = false; + let groundSampleProgress = false; + const sizing = { + pose, + canvasHeight: canvasOf(viewer)?.clientHeight || 1080, + ground: groundOf(viewer), + }; + + // --- Globe-LOD: recompute the active-stem set on camera moves. --- + // `_stemGeometryDirty` is set by moveEnd, the first enable, and the + // motion fallback above — exactly when the camera-height budget and + // per-record distances can have changed. Without this, all local + // infrastructure features run stem trig + set writes on every + // move; with it, only the ~80 (global) to ~420 (regional) + // budgeted records do. + // The horizon test is the same cheap one used below. + if (refreshStemGeometry && _stemRecords.length > 0) { + const candidates = new Array(_stemRecords.length); + for (let i = 0; i < _stemRecords.length; i++) { + const record = _stemRecords[i]; + candidates[i] = { + id: record.id, + priority: record.priority, + distanceM: distance(cameraPos, record.base), + inView: inView(record.base), + }; + } + const selection = selectInfraLod(candidates, { + cameraHeightM: pose.height, + incumbentIds: _activeLodIds, + }); + const grace = applyInfraEvictionGrace({ + selectedIds: selection.activeIds, + builtIds: [..._activeLodIds], + graceState: _lodGraceState, + nowMs: now, + activeLimit: selection.budget.activeLimit, + }); + _activeLodIds = new Set(grace.keepIds); + _lodGraceState = grace.graceState; + _lastLodBudgetLimit = selection.budget.activeLimit; + _lodComputed = true; + // Adopt this pass as the motion-fallback reference. Travel is + // measured from the last SELECTION, never the previous walk, so + // jitter around a parked camera never accumulates into a + // recompute while genuine slow travel eventually does. + Object.assign(_lastLodCameraPos, copy(cameraPos)); + _lastLodProbeMs = now; + } - // --- Globe-LOD: recompute the active-stem set on camera moves. --- - // `_stemGeometryDirty` is set by moveEnd, the first enable, and the - // motion fallback above — exactly when the camera-height budget and - // per-record distances can have changed. Without this, all local - // infrastructure features run stem trig + Cesium property writes on - // every move; with it, only the ~80 (global) to ~420 (regional) - // budgeted records do. - // The occluder test is the same cheap dot product used below. - if (refreshStemGeometry && _stemRecords.length > 0) { - const cameraHeightM = viewer.camera.positionCartographic?.height; - const candidates = new Array(_stemRecords.length); for (let i = 0; i < _stemRecords.length; i++) { const record = _stemRecords[i]; - candidates[i] = { - id: record.id, - priority: record.priority, - distanceM: Cesium.Cartesian3.distance(cameraPos, record.base), - inView: occluder.isPointVisible(record.base), - }; - } - const selection = selectInfraLod(candidates, { - cameraHeightM, - incumbentIds: _activeLodIds, - }); - const grace = applyInfraEvictionGrace({ - selectedIds: selection.activeIds, - builtIds: [..._activeLodIds], - graceState: _lodGraceState, - nowMs: now, - activeLimit: selection.budget.activeLimit, - }); - _activeLodIds = new Set(grace.keepIds); - _lodGraceState = grace.graceState; - _lastLodBudgetLimit = selection.budget.activeLimit; - _lodComputed = true; - // Adopt this pass as the motion-fallback reference. Travel is - // measured from the last SELECTION, never the previous walk, so - // jitter around a parked camera never accumulates into a - // recompute while genuine slow travel eventually does. - Cesium.Cartesian3.clone(cameraPos, _lastLodCameraPos); - _lastLodProbeMs = now; - } - - for (let i = 0; i < _stemRecords.length; i++) { - const record = _stemRecords[i]; - const isActive = !_lodComputed || _activeLodIds.has(record.id); - const isVisible = isActive && occluder.isPointVisible(record.base); - if (record.entity.show !== isVisible) - record.entity.show = isVisible; - - // Records outside the globe-LOD active set carry no visible stem, - // so skip every per-frame cost for them — geometry trig, the - // ground-sample GPU readback, overlay-label candidacy. They rejoin - // on the next camera move if the budget has room. - if (!isActive) continue; - - const wasGroundSampled = record.groundSampled; - const terrainFloorChanged = refreshLocalTerrainFloor( - viewer, - record, - ); - if (refreshStemGeometry || terrainFloorChanged) { - updateLocalStemGeometry(viewer, record, now); - } else if ( - canSampleGround && - !record.groundSampled && - now - record.lastGroundSampleMs >= GROUND_SAMPLE_RETRY_MS - ) { - // Capability first: without it the distance below is pure waste, - // once per ungrounded record per walk, forever. - const distance = Cesium.Cartesian3.distance( - viewer.camera.positionWC, - record.base, - ); - if ( - distance < GROUND_SAMPLE_MAX_DISTANCE_M && - sampleLocalGroundHeight(viewer, record, now) - ) { - updateLocalStemGeometry(viewer, record, now, distance); + const isActive = !_lodComputed || _activeLodIds.has(record.id); + const isVisible = isActive && inView(record.base); + if (record.visible !== isVisible) { + record.visible = isVisible; + shown.add(record); } - } - if (!wasGroundSampled && record.groundSampled) - groundSampleProgress = true; - // Still unsampled AND close enough for a retry to succeed: this - // layer has no hold and no periodic update, so under the idle - // governor the retry's preRender never arrives on a parked camera - // and the stem stays at ellipsoid height (buried/floating) until - // the user happens to move. Schedule the frame the retry needs. - // Gated on a sampleable scene and in-range records only, so a far - // camera (or a keyless scene) stays fully idle; the distance is - // only computed for still-unsampled stems. - if ( - canSampleGround && - !record.groundSampled && - !groundRetryPending && - Cesium.Cartesian3.distance( - viewer.camera.positionWC, - record.base, - ) < GROUND_SAMPLE_MAX_DISTANCE_M - ) { - groundRetryPending = true; - } - if (isVisible && record.entry) visibleOverlayRecords.push(record); - } - _stemGeometryDirty = false; - // Tiles ARE streaming in: real progress re-opens the give-up budget - // so the records still waiting get their own bounded run of retries. - if (groundSampleProgress) _groundRetryArms = 0; - if (groundRetryPending) scheduleGroundRetryRender(viewer); - const canvas = viewer.scene.canvas; - const cohort = selectLocalInfrastructureOverlayCohort( - visibleOverlayRecords, - { - maxEntries: labelMax, - gridPx: labelGridPx, - width: canvas.clientWidth || canvas.width || 0, - height: canvas.clientHeight || canvas.height || 0, - cohortLimit: LOCAL_OVERLAY_COHORT_LIMIT, - project: (record) => projectToWindow(viewer.scene, record.tip), - }, - ); - _overlayPublisher.publish(cohort); - }); + // Records outside the globe-LOD active set carry no visible stem, + // so skip every per-frame cost for them — geometry trig, the + // ground-sample GPU readback, overlay-label candidacy. They rejoin + // on the next camera move if the budget has room. + if (!isActive) continue; + + const wasGroundSampled = record.groundSampled; + const terrainFloorChanged = refreshLocalTerrainFloor( + sizing, + record, + ); + if (refreshStemGeometry || terrainFloorChanged) { + if (updateLocalStemGeometry(sizing, record, now)) + moved.add(record); + } else if ( + canSampleGround && + !record.groundSampled && + now - record.lastGroundSampleMs >= GROUND_SAMPLE_RETRY_MS + ) { + // Capability first: without it the distance below is pure waste, + // once per ungrounded record per walk, forever. + const away = distance(cameraPos, record.base); + if ( + away < GROUND_SAMPLE_MAX_DISTANCE_M && + sampleLocalGroundHeight(sizing, record, now) && + updateLocalStemGeometry(sizing, record, now, away) + ) + moved.add(record); + } + if (!wasGroundSampled && record.groundSampled) + groundSampleProgress = true; + // Still unsampled AND close enough for a retry to succeed: this + // layer has no hold and no periodic update, so under the idle + // governor the retry's preRender never arrives on a parked camera + // and the stem stays at ellipsoid height (buried/floating) until + // the user happens to move. Schedule the frame the retry needs. + // Gated on a sampleable scene and in-range records only, so a far + // camera (or a keyless scene) stays fully idle; the distance is + // only computed for still-unsampled stems. + if ( + canSampleGround && + !record.groundSampled && + !groundRetryPending && + distance(cameraPos, record.base) < GROUND_SAMPLE_MAX_DISTANCE_M + ) { + groundRetryPending = true; + } + if (isVisible && record.entry) visibleOverlayRecords.push(record); + } + _stemGeometryDirty = false; + writeChanges(drawn, moved, shown); + // Tiles ARE streaming in: real progress re-opens the give-up budget + // so the records still waiting get their own bounded run of retries. + if (groundSampleProgress) _groundRetryArms = 0; + if (groundRetryPending) scheduleGroundRetryRender(viewer); + + const canvas = canvasOf(viewer); + const cohort = selectLocalInfrastructureOverlayCohort( + visibleOverlayRecords, + { + maxEntries: labelMax, + gridPx: labelGridPx, + width: canvas?.clientWidth || canvas?.width || 0, + height: canvas?.clientHeight || canvas?.height || 0, + cohortLimit: LOCAL_OVERLAY_COHORT_LIMIT, + project: (record) => projectToWindow(viewer, record.tip), + }, + ); + _overlayPublisher.publish(cohort); + }) ?? null; } if (_enabled && !_cameraMoveEndRemover) { - _cameraMoveEndRemover = viewer.camera.moveEnd.addEventListener(() => { - if (!_enabled) return; - _stemGeometryDirty = true; - _lastVisibilityUpdate = Number.NEGATIVE_INFINITY; - // Real camera motion is a fresh situation (new tiles, new distances) - // and its frames are free, so it re-opens the retry budget that a - // parked camera may have spent. - _groundRetryArms = 0; - viewer.scene.requestRender?.(); - }); + _cameraMoveEndRemover = + findCamera(viewer)?.on('moveEnd', () => { + if (!_enabled) return; + _stemGeometryDirty = true; + _lastVisibilityUpdate = Number.NEGATIVE_INFINITY; + // Real camera motion is a fresh situation (new tiles, new distances) + // and its frames are free, so it re-opens the retry budget that a + // parked camera may have spent. + _groundRetryArms = 0; + findFrame(viewer)?.requestRender('local-geojson'); + }) ?? null; } // Honor a disable() that landed while we were awaiting the fetch/parse: - // disable() runs before _dataSource exists, so its release is a no-op — + // disable() runs before `_drawn` exists, so its release is a no-op — // release the finished build here instead of parking it hidden in the // scene (the parsed features stay cached for the next enable). if (!_enabled) { - releaseDataSource(viewer); + releaseDrawn(); return; } - if (_dataSource) _dataSource.show = true; - viewer.scene.requestRender?.(); + if (_drawn) for (const set of Object.values(_drawn.sets)) set.show = true; + findFrame(viewer)?.requestRender('local-geojson'); }, disable: disableLayer, @@ -1077,11 +1316,7 @@ export function createLocalGeoJsonLayer( removeEntityContextsForLayer(id); _clickSubscription?.(); _clickSubscription = null; - if (_dataSource && viewer) { - viewer.dataSources.remove(_dataSource, true); - } _overlayPublisher.destroy(); - _dataSource = null; _cachedFeatures = null; _stemRecords = []; _count = 0; @@ -1091,6 +1326,96 @@ export function createLocalGeoJsonLayer( }; } +/** + * A polygon's fill, showing as its record does: on the ground, or with + * per-position heights and outlined in the layer colour (`outline`), as + * the loader outlined every polygon. + */ +const fillItem = (record, outline) => + record.part.raised + ? { + id: record.id, + geometry: { + kind: 'polygon', + rings: record.part.rings, + perPositionHeight: true, + }, + fill: record.part.fill, + outline, + // The loader's outline was an outline geometry, whose width the + // default renderer clamps to what WebGL draws: 1 px on most + // browsers, whatever `stroke-width` says. + outlineWidth: 1, + height: 'absolute', + meta: record.carrier, + show: record.visible, + } + : { + id: record.id, + geometry: { kind: 'polygon', rings: record.part.rings }, + fill: record.part.fill, + height: 'clampGround', + meta: record.carrier, + show: record.visible, + }; + +/** A point's pin, in its own marker colour and size, showing as its record does. */ +const pinItem = (record) => ({ + id: record.id, + // A point with a height stands its pin on the stem's tip, as the loader's + // billboard rode its entity's position; one without lies on the ground. + ...(record.part.pinClamped + ? { pos: record.part.pinPos, height: 'clampGround' } + : { pos: copy(record.tip) }), + image: record.part.pin, + size: [record.part.pinSize, record.part.pinSize], + anchor: 'bottom', + meta: record.carrier, + show: record.visible, +}); + +/** A record's stem, from its base to its tip. */ +const stemItem = (record, color) => ({ + id: record.id, + positions: [copy(record.base), copy(record.tip)], + widthPx: STEM_WIDTH_PX, + mode: '3d', + style: { kind: 'solid', color }, + meta: record.carrier, + show: record.visible, +}); + +/** + * The dot on a record's tip, never depth-tested against the photoreal + * mesh: the walk's horizon test hides it behind the globe. + */ +const dotItem = (record, color) => ({ + id: record.id, + pos: copy(record.tip), + pixelSize: 10, + color, + outlineColor: BLACK, + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + meta: record.carrier, + show: record.visible, +}); + +/** + * What a walk asks of the ground under its records: heights now, and + * whether the globe is shown and its terrain has finished loading. + */ +function groundOf(viewer) { + const globe = findGlobe(viewer); + const heights = heightsOf(viewer); + return { + heights, + canSample: heights.supported().surface, + globeShown: globe?.isGlobeVisible?.() === true, + terrainSettled: () => globe?.isSettled('terrain') !== false, + }; +} + function compareLocalOverlayRecords(a, b) { return b.priority - a.priority || String(a.id).localeCompare(String(b.id)); } @@ -1108,21 +1433,18 @@ function insertLocalCellContender(contenders, record) { contenders.length = LOCAL_OVERLAY_CELL_SURPLUS; } -function refreshLocalTerrainFloor(viewer, record) { - const globe = viewer.scene.globe; - if (!record.groundSampled || !globe?.show || globe.tilesLoaded === false) +function refreshLocalTerrainFloor(sizing, record) { + const { ground } = sizing; + if (!record.groundSampled || !ground.globeShown || !ground.terrainSettled()) return false; if ( - Cesium.Cartesian3.distance(viewer.camera.positionWC, record.base) >= - GROUND_SAMPLE_MAX_DISTANCE_M + distance(sizing.pose.position, record.base) >= GROUND_SAMPLE_MAX_DISTANCE_M ) return false; // Camera motion can refine terrain after the first successful depth sample. // Reuse the loaded mesh on existing bounded walks; never arm a timer or do // another GPU readback just to maintain this floor. Keep roof elevations. - const height = heightsFor(viewer.scene).now(record.carto, { - against: 'terrain', - }); + const height = ground.heights.now(record, { against: 'terrain' }); if ( height === null || Math.abs(height) > GROUND_SAMPLE_MAX_ABS_HEIGHT_M || @@ -1133,23 +1455,23 @@ function refreshLocalTerrainFloor(viewer, record) { return true; } -function sampleLocalGroundHeight(viewer, record, now) { - if (record.groundSampled || !viewer.scene.sampleHeightSupported) return false; +function sampleLocalGroundHeight(sizing, record, now) { + const { ground } = sizing; + if (record.groundSampled || !ground.canSample) return false; if (now - record.lastGroundSampleMs < GROUND_SAMPLE_RETRY_MS) return false; record.lastGroundSampleMs = now; - const globe = viewer.scene.globe; - if (globe?.show && globe.tilesLoaded === false) return false; - const heights = heightsFor(viewer.scene); - // A miss is tiles not ready: retry on a later bounded update. - let sampled = heights.now(record.carto, { exclude: [record.entity] }); + if (ground.globeShown && !ground.terrainSettled()) return false; + // A miss is tiles not ready: retry on a later bounded update. The layer's + // own sets are not ground, so the sample sees through them. + let sampled = ground.heights.now(record); if (sampled === null || Math.abs(sampled) > GROUND_SAMPLE_MAX_ABS_HEIGHT_M) return false; // A coarse scene-depth sample can lie below the terrain already loaded by // the visible globe. Keep that terrain as a floor while allowing roofs and // valid below-sea-level elevations. Photoreal scenes hide the globe, so its // inactive terrain must not constrain their geometry. - const terrainHeight = globe?.show - ? heights.now(record.carto, { against: 'terrain' }) + const terrainHeight = ground.globeShown + ? ground.heights.now(record, { against: 'terrain' }) : null; if ( terrainHeight !== null && @@ -1164,50 +1486,38 @@ function sampleLocalGroundHeight(viewer, record, now) { function setLocalGroundHeight(record, height) { record.groundHeight = height; - Cesium.Cartesian3.fromRadians( - record.carto.longitude, - record.carto.latitude, - record.groundHeight, - Cesium.Ellipsoid.WGS84, - record.base, - ); + fromDegreesInto(record.lon, record.lat, record.groundHeight, record.base); } -function updateLocalStemGeometry(viewer, record, now, knownDistance = null) { - const distance = Number.isFinite(knownDistance) +/** + * Size a record's stem to the camera: its tip stands where the stem spans + * about 65 px on screen. False when the tip moved less than the epsilon, + * which leaves it where it was. + */ +function updateLocalStemGeometry(sizing, record, now, knownDistance = null) { + const away = Number.isFinite(knownDistance) ? knownDistance - : Cesium.Cartesian3.distance(viewer.camera.positionWC, record.base); - if (distance < GROUND_SAMPLE_MAX_DISTANCE_M) - sampleLocalGroundHeight(viewer, record, now); + : distance(sizing.pose.position, record.base); + if (away < GROUND_SAMPLE_MAX_DISTANCE_M) + sampleLocalGroundHeight(sizing, record, now); // Keep the intended screen-size scaling in close-up views too. A 5 km // minimum made a marker hundreds of metres tall beside a nearby building. - const effectiveDistance = Math.max(distance, 1); - const canvasHeight = viewer.scene.canvas.clientHeight || 1080; - const fov = viewer.camera.frustum.fov || Math.PI / 3; + const effectiveDistance = Math.max(away, 1); + const fov = wideFov(sizing.pose); const targetPx = 65; - const fovFactor = 2 * Math.tan(fov / 2) * (targetPx / canvasHeight); + const fovFactor = 2 * Math.tan(fov / 2) * (targetPx / sizing.canvasHeight); const tipHeight = record.groundHeight + effectiveDistance * fovFactor; - Cesium.Cartesian3.fromRadians( - record.carto.longitude, - record.carto.latitude, - tipHeight, - Cesium.Ellipsoid.WGS84, - record.nextTip, - ); + fromDegreesInto(record.lon, record.lat, tipHeight, record.nextTip); + // A base that moved moves the stem, whatever its tip does. + const baseMoved = record.drawnBaseHeight !== record.groundHeight; if ( - Cesium.Cartesian3.distanceSquared(record.tip, record.nextTip) <= - LOCAL_STEM_TIP_EPSILON_SQ + !baseMoved && + distanceSquared(record.tip, record.nextTip) <= LOCAL_STEM_TIP_EPSILON_SQ ) { return false; } - Cesium.Cartesian3.clone(record.nextTip, record.tip); - record.stemPositionBufferIndex = 1 - record.stemPositionBufferIndex; - const stemPositions = - record.stemPositionBuffers[record.stemPositionBufferIndex]; - stemPositions[0] = record.base; - stemPositions[1] = record.tip; - record.entity.position.setValue(record.tip); - record.entity.polyline.positions.setValue(stemPositions); + record.drawnBaseHeight = record.groundHeight; + Object.assign(record.tip, record.nextTip); return true; } @@ -1243,15 +1553,6 @@ function labelPriorityFromProperties(props, layerId) { return score; } -function propertyObject(entity) { - const source = entity?.properties; - const raw = - typeof source?.getValue === 'function' - ? source.getValue(Cesium.JulianDate.now()) - : source || {}; - return unwrapProperties(raw); -} - function unwrapProperties(value) { if (!value || typeof value !== 'object') return value; if (Array.isArray(value)) return value.map(unwrapProperties); @@ -1259,7 +1560,7 @@ function unwrapProperties(value) { for (const [key, entry] of Object.entries(value)) { out[key] = entry && typeof entry.getValue === 'function' - ? unwrapProperties(entry.getValue(Cesium.JulianDate.now())) + ? unwrapProperties(entry.getValue()) : unwrapProperties(entry); } return out; diff --git a/src/data/localGeojsonDraw.test.mjs b/src/data/localGeojsonDraw.test.mjs new file mode 100644 index 000000000..70d208384 --- /dev/null +++ b/src/data/localGeojsonDraw.test.mjs @@ -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, / { + 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`); +}); diff --git a/src/data/localGeojsonLifecycle.test.mjs b/src/data/localGeojsonLifecycle.test.mjs index 96b817599..40f19b19b 100644 --- a/src/data/localGeojsonLifecycle.test.mjs +++ b/src/data/localGeojsonLifecycle.test.mjs @@ -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); diff --git a/src/data/pickedContext.js b/src/data/pickedContext.js index fb79c3f3a..634867ba1 100644 --- a/src/data/pickedContext.js +++ b/src/data/pickedContext.js @@ -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; diff --git a/src/data/pickedContext.test.mjs b/src/data/pickedContext.test.mjs index a73984432..1d192cd38 100644 --- a/src/data/pickedContext.test.mjs +++ b/src/data/pickedContext.test.mjs @@ -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'); diff --git a/src/data/sharedOsmDisplays.test.mjs b/src/data/sharedOsmDisplays.test.mjs index 99a092997..38be4d28c 100644 --- a/src/data/sharedOsmDisplays.test.mjs +++ b/src/data/sharedOsmDisplays.test.mjs @@ -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); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index e5b775159..01d2ba903 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -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", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 9cdf2eb1e..a6829ec8d 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -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', ]); /** diff --git a/src/testSupport/fakeGroundRenderer.mjs b/src/testSupport/fakeGroundRenderer.mjs new file mode 100644 index 000000000..be38f790b --- /dev/null +++ b/src/testSupport/fakeGroundRenderer.mjs @@ -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; + }, + }; +}