From faded8a41824ed5e77c7df803a021f704cc64ec8 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Fri, 6 Nov 2026 23:00:14 -0800 Subject: [PATCH] Draw the installations layer's named markers through the renderer's ports The named-site dots are a draw-port point set with horizon culling instead of a raw point collection; their on-screen count tests the ellipsoid horizon and projects through the query port, and they follow the camera port's changed and moveEnd events and the frame port's preRender. Points that only change look (a selection) are restyled in place. Clicks on a dot read the draw hit; the item id is not the bare record id, so sibling layers' pick-owner checks still treat a dot click as nobody's. Code that only asks whether a click hit anything (the CCTV layer) now sees a dot click as a hit, as it already did for the site markers: a draw item's pick always resolves to its id. The named markers leave the Cesium allow-list. The site markers in rendering.js stay entities. --- scripts/package-boundaries.json | 1 + src/data/militaryInstallations.test.mjs | 11 +- src/layers/installations/namedMarkers.js | 188 ++++++++++++------ .../installations/namedMarkers.test.mjs | 29 ++- src/layers/installations/selection.js | 9 +- src/layers/installations/selection.test.mjs | 47 ++++- src/overlays/worldOverlay.test.mjs | 11 +- src/render/cesium/draw.test.mjs | 95 +++++++++ src/render/cesiumAllowList.json | 1 - src/testSupport/fakeCesiumScene.mjs | 100 +++++++--- 10 files changed, 377 insertions(+), 115 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index d5daae535..5b4eb3691 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2058,6 +2058,7 @@ "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/layers/installations/namedMarkers.js", + "src/geo/horizon.js", "src/data/infrastructureOverlayEntry.js", "src/i18n/index.js", "src/i18n/locale.js", diff --git a/src/data/militaryInstallations.test.mjs b/src/data/militaryInstallations.test.mjs index 9a37b2eed..db6fb65de 100644 --- a/src/data/militaryInstallations.test.mjs +++ b/src/data/militaryInstallations.test.mjs @@ -1,4 +1,5 @@ import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; @@ -198,7 +199,7 @@ test('real enabled installation entities carry no native label graphics', async }, }, }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); try { militaryInstallationsLayer.init(viewer); @@ -344,7 +345,7 @@ async function runInstallationLoad({ }, }, }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); const originalSetInputAction = Cesium.ScreenSpaceEventHandler.prototype.setInputAction; Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (action, type, modifier) { @@ -635,7 +636,7 @@ test('a floor that lands after the render deadline lifts the dots off the ellips }, }, }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); const heightOf = (entity) => Cesium.Cartographic.fromCartesian( entity.position.getValue(Cesium.JulianDate.now()), @@ -706,7 +707,7 @@ test('reports bounded installation requests as loading and clears on settlement' }, dataSources: { add(value) { return value; }, remove() { return true; } }, }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); try { militaryInstallationsLayer.init(viewer); @@ -771,7 +772,7 @@ test('zoom-out aborts an active installation request and returns non-loading gui }, dataSources: { add(value) { return value; }, remove() { return true; } }, }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); try { militaryInstallationsLayer.init(viewer); diff --git a/src/layers/installations/namedMarkers.js b/src/layers/installations/namedMarkers.js index 2face7983..7e1ada64c 100644 --- a/src/layers/installations/namedMarkers.js +++ b/src/layers/installations/namedMarkers.js @@ -1,55 +1,112 @@ import { installationClassLabel, installationTitle } from './classLabel.js'; -import * as Cesium from 'cesium'; import { MILITARY_LABEL_CAP, MILITARY_POINT_CAP, } from '../../data/militaryNames.js'; -import { LAYER_ID, COLOR_BY_CLASS } from './policy.js'; +import { fromDegrees } from '../../geo/index.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { + cameraOf, + drawOf, + findFrame, + findQuery, +} from '../../render/rendererOf.js'; +import { + CAMERA_CHANGED_THRESHOLD, + LAYER_ID, + COLOR_BY_CLASS, +} from './policy.js'; import { createInfrastructureOverlayEntry } from '../../data/infrastructureOverlayEntry.js'; +let instances = 0; + +/** + * A named marker's point item id. Not the bare record id: the shared pick + * registry resolves a draw item's pick to its item id, and a point click has + * never been this layer's for sibling layers' owner checks (a tracked + * aircraft is released by it, as by a click on empty map). The click handler + * reads the record id from the item's `meta`. + */ +export const namedPointId = (recordId) => `named:${recordId}`; + +const samePlace = (a, b) => + Boolean(a) && a.x === b.x && a.y === b.y && a.z === b.z; + /** Bounded point markers; the shared overlay owns text projection and decluttering. */ export function createNamedMarkers({ state, services, parts, overlayHost }) { + const setId = `${LAYER_ID}:${++instances}:names`; let points = null; let entries = []; const markers = new Map(); - const screen = new Cesium.Cartesian2(); - const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84); let shownPoints = 0; + /** Where each drawn point item is, by item id. */ + let drawn = new Map(); let ordered = []; - const viewMatrix = new Cesium.Matrix4(); + let lastPose = null; let width = 0, height = 0; let removeChanged = null, removeEnd = null, removeFrame = null; - function refresh() { + /** Whether the eye moved or the canvas resized since the last refresh. */ + function viewChanged(viewer, pose) { + const same = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z; + return ( + !lastPose || + !same(pose.position, lastPose.position) || + !same(pose.direction, lastPose.direction) || + !same(pose.up, lastPose.up) || + width !== viewer.scene.canvas.clientWidth || + height !== viewer.scene.canvas.clientHeight + ); + } + + // Reused projection buffers, grown to the marker count. + let worldXyz = new Float64Array(0); + let screenXy = new Float32Array(0); + + function refresh(pose = null) { const viewer = state.viewer; if (!state.enabled || !points) return; width = viewer.scene.canvas.clientWidth; height = viewer.scene.canvas.clientHeight; - if (viewer.camera.viewMatrix) - Cesium.Matrix4.clone(viewer.camera.viewMatrix, viewMatrix); - occluder.cameraPosition = viewer.camera.positionWC; - shownPoints = 0; + pose ??= cameraOf(viewer).pose(); + lastPose = { + position: { ...pose.position }, + direction: { ...pose.direction }, + up: { ...pose.up }, + }; + // The ellipsoid horizon from the eye, the test the draw set's own + // horizon cull makes, so the count agrees with what is drawn. + const horizon = horizonFrom(pose.position); + if (worldXyz.length < ordered.length * 3) { + worldXyz = new Float64Array(ordered.length * 3); + screenXy = new Float32Array(ordered.length * 2); + } + let shown = 0; for (let index = 0; index < ordered.length; index++) { const marker = ordered[index]; const point = marker.point; - point.show = marker.named && occluder.isPointVisible(point.position); + point.show = marker.named && horizon.isPointVisible(point.position); if (!point.show) continue; - const projected = Cesium.SceneTransforms.worldToWindowCoordinates( - viewer.scene, - point.position, - screen, - ); - if ( - projected && - screen.x >= 0 && - screen.y >= 0 && - screen.x < width && - screen.y < height - ) - shownPoints++; + worldXyz[shown * 3] = point.position.x; + worldXyz[shown * 3 + 1] = point.position.y; + worldXyz[shown * 3 + 2] = point.position.z; + shown++; + } + shownPoints = 0; + const query = findQuery(viewer); + if (!query || !shown) return; + query.projectMany( + worldXyz.subarray(0, shown * 3), + screenXy.subarray(0, shown * 2), + ); + for (let i = 0; i < shown; i++) { + const x = screenXy[i * 2]; + const y = screenXy[i * 2 + 1]; + // NaN, behind the eye, fails every test. + if (x >= 0 && y >= 0 && x < width && y < height) shownPoints++; } } @@ -71,20 +128,20 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { } function frame() { const viewer = state.viewer; - if ( - viewer?.camera.viewMatrix && - (!Cesium.Matrix4.equals(viewMatrix, viewer.camera.viewMatrix) || - width !== viewer.scene.canvas.clientWidth || - height !== viewer.scene.canvas.clientHeight) - ) - refresh(); + if (!viewer || !points) return; + const pose = cameraOf(viewer).pose(); + if (viewChanged(viewer, pose)) refresh(pose); } function enable() { const viewer = state.viewer; if (!viewer || removeChanged || removeEnd || removeFrame) return; - removeChanged = viewer.camera.changed?.addEventListener(cameraChanged); - removeEnd = viewer.camera.moveEnd?.addEventListener(cameraChanged); - removeFrame = viewer.scene.preRender?.addEventListener(frame); + const camera = cameraOf(viewer); + // The sensitivity this layer claims for raw camera listeners while on. + removeChanged = camera.on('changed', cameraChanged, { + threshold: CAMERA_CHANGED_THRESHOLD, + }); + removeEnd = camera.on('moveEnd', cameraChanged); + removeFrame = findFrame(viewer)?.on('preRender', frame) ?? null; if (points) points.show = true; publishLabels(); overlayHost.setVisible(LAYER_ID, true); @@ -101,14 +158,25 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { shownPoints = 0; } + /** The point item a marker draws. */ + function pointItem(marker, record) { + return { + id: namedPointId(marker.recordId), + pos: marker.point.position, + pixelSize: 7, + color: parts.model.colorFor(record), + outlineColor: [0, 0, 0, 1], + outlineWidth: 1, + disableDepthTest: Infinity, + show: marker.named, + meta: { installationId: marker.recordId }, + }; + } + function sync(records) { const viewer = state.viewer; - if (!viewer?.scene?.primitives) return; - if (!points) { - points = viewer.scene.primitives.add( - new Cesium.PointPrimitiveCollection(), - ); - } + if (!viewer?.scene) return; + points ??= drawOf(viewer).points({ id: setId, horizonCull: true }); points.show = state.enabled; const named = records .filter((r) => r.namedArea || r.id === state.selectedId) @@ -132,15 +200,12 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { marker.entry.id = record.id; markers.set(record.id, marker); } - for (const [id, marker] of markers) - if (!keep.has(id)) { - points.remove(marker.point); - markers.delete(id); - } + for (const id of markers.keys()) if (!keep.has(id)) markers.delete(id); ordered = []; entries = []; + const items = []; for (const record of named) { - const position = Cesium.Cartesian3.fromDegrees( + const position = fromDegrees( record.longitude, record.latitude, record.pointOnly @@ -151,17 +216,9 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { if (!marker) { marker = { recordId: record.id, - point: points.add({ - // The app's own pick payload. An object, not the bare record id, so the - // shared pick registry keeps treating a point click as it always has. - id: { installationId: record.id }, - position, - pixelSize: 7, - color: new Cesium.Color(...parts.model.colorFor(record)), - outlineColor: Cesium.Color.BLACK, - outlineWidth: 1, - disableDepthTestDistance: Infinity, - }), + // What `visit` hands out: the marker's id, position and whether + // it is on this side of the horizon. + point: { id: { installationId: record.id }, position, show: false }, entry: createInfrastructureOverlayEntry({ id: record.id, source: LAYER_ID, @@ -175,7 +232,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { } else { marker.point.position = position; } - marker.named = record.namedArea; + marker.named = Boolean(record.namedArea); marker.entry.variant = record.id === state.selectedId ? 'selected' : 'card'; marker.entry.selected = record.id === state.selectedId; @@ -190,13 +247,25 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { marker.entry.priority = record.areaM2 || 0; entries.push(marker.entry); ordered.push(marker); + items.push(pointItem(marker, record)); } + // Restyled points that keep their ids and places change in place; any + // other change draws the set anew. + if ( + items.length === drawn.size && + items.every((item) => samePlace(drawn.get(item.id), item.pos)) + ) + points.upsert(items); + else points.set(items); + drawn = new Map(items.map((item) => [item.id, { ...item.pos }])); if (state.enabled) publishLabels(); refresh(); services.render.governorRequestRender('installation-names'); } return { sync, + /** The draw set's id, for matching its click hits. */ + setId, visit(visitor) { for (let i = 0; i < ordered.length; i++) { const marker = ordered[i]; @@ -217,8 +286,9 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { destroy() { hide(); ordered = []; - if (points) state.viewer?.scene.primitives.remove(points); + points?.dispose(); points = null; + drawn = new Map(); entries = []; markers.clear(); }, diff --git a/src/layers/installations/namedMarkers.test.mjs b/src/layers/installations/namedMarkers.test.mjs index 0aac0f00f..91f48a887 100644 --- a/src/layers/installations/namedMarkers.test.mjs +++ b/src/layers/installations/namedMarkers.test.mjs @@ -1,9 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as C from 'cesium'; -import { createNamedMarkers } from './namedMarkers.js'; +import { createNamedMarkers, namedPointId } from './namedMarkers.js'; import { createLifecycle } from './lifecycle.js'; import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { fakeSceneFrame, fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs'; import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js'; function setup(t) { @@ -17,11 +19,11 @@ function setup(t) { setVisible(_id, value) { visible = value; }, }; let x = -100; - const projections = new Set(); - t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', (_scene, _point, scratch) => { projections.add(scratch); scratch.x = x; scratch.y = 300; return scratch; }); - const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), viewMatrix: C.Matrix4.clone(C.Matrix4.IDENTITY) }; + t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', () => new C.Cartesian2(x, 300)); + const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), directionWC: new C.Cartesian3(0, 0, -1) }; const state = { viewer: { camera, dataSources: { add() {}, remove() {} }, scene: { canvas: { clientWidth: 1280, clientHeight: 800 }, preRender: new C.Event(), primitives: { add: (p) => p, remove() {} } } }, enabled: true, contextAnchor: { latitude: 0, longitude: 0 } }; - bindFakeCesiumCamera(state.viewer); + const draw = fakeDrawPort(); + bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(state.viewer) }); const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } }; let loads = 0; const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() { state.dataSource = { show: false }; }, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } }; @@ -30,7 +32,8 @@ function setup(t) { const lifecycle = createLifecycle(ctx).methods; lifecycle.init(state.viewer); lifecycle.enable(); const records = [1, 2].map((n) => ({ id: `osm:military:w${n}`, name: `Site ${n}`, namedArea: true, areaM2: 100 / n, latitude: 0, longitude: 0, pointOnly: true })); - return { state, camera, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, projections, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads }; + const points = () => [...draw.sets.values()].find((set) => set.kind === 'points' && !set.disposed); + return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads }; } test('Contacts camera motion reprojects and declutters existing labels without source loads or primitive replacement', (t) => { @@ -45,10 +48,14 @@ test('Contacts camera motion reprojects and declutters existing labels without s assert.equal(h.visible, true); assert.equal(h.loads(), 0); assert.equal(h.publications(), 3); - assert.equal(h.projections.size, 1); - h.setX(1400); h.camera.viewMatrix[12] = 1; h.state.viewer.scene.preRender.raiseEvent(); + const items = [...h.points().items.values()]; + assert.deepEqual(items.map((item) => [item.id, item.pixelSize, item.outlineWidth, item.disableDepthTest, item.show]), h.records.map((r) => [namedPointId(r.id), 7, 1, Infinity, true])); + assert.equal(h.points().spec.horizonCull, true); + assert.equal(h.points().show, true); + h.setX(1400); h.camera.positionWC = C.Cartesian3.fromDegrees(0, 0, 1.1e6); h.state.viewer.scene.preRender.raiseEvent(); assert.equal(h.markers.stats().pointsOnScreen, 0, 'small pose changes refresh before render'); h.lifecycle.disable(); + assert.equal(h.points().show, false); assert.equal(h.camera.changed.numberOfListeners, 1, 'only the viewport listener remains'); assert.equal(h.state.viewer.scene.preRender.numberOfListeners, 0); assert.equal(h.labels.length, 0); @@ -85,7 +92,7 @@ test('wide named markers retain primitives until close polygons publish with the h.lifecycle.destroy(h.state.viewer); }); -test('canonical aliases transfer named marker ownership without replacing primitives', (t) => { +test('canonical aliases transfer named marker ownership without replacing markers or labels', (t) => { const h = setup(t); h.setX(600); const parent = h.records[1]; @@ -105,6 +112,7 @@ test('canonical aliases transfer named marker ownership without replacing primit assert.equal(point, originalPoint); assert.equal(currentLabel, label); assert.equal(point.id.installationId, record.id); + assert.deepEqual(h.points().items.get(namedPointId(record.id)).meta, { installationId: record.id }); assert.equal(currentLabel.id, record.id); }); } @@ -126,12 +134,11 @@ test('the bounded host cohort ranks wide points and polygon titles by area', (t) const first = h.labels[0]; const publications = h.publications(); for (let i = 0; i < 100; i++) { - h.camera.viewMatrix[12] += 0.01; + h.camera.positionWC = C.Cartesian3.fromDegrees(0, 0, 1e6 + i + 1); h.state.viewer.scene.preRender.raiseEvent(); } assert.equal(h.labels[0], first); assert.equal(h.publications(), publications, 'camera frames never rebuild host entries'); - assert.equal(h.projections.size, 1, 'point projection reuses scratch storage'); h.lifecycle.destroy(h.state.viewer); assert.equal(h.labels.length, 0); }); diff --git a/src/layers/installations/selection.js b/src/layers/installations/selection.js index 79563c17e..a7b4d1185 100644 --- a/src/layers/installations/selection.js +++ b/src/layers/installations/selection.js @@ -52,10 +52,13 @@ export function createSelection({ }; layerState.clickSubscription = inputFor(viewer).onClick((event) => { if (!layerState.enabled) return; - const picked = event.pick; - const target = picked?.id; + // A named marker is a draw item; site markers are still entities. + const hit = event.drawHit; + const target = event.pick?.id; const id = - target?.installationId || + (hit?.set === parts.namedMarkers?.setId + ? hit.meta?.installationId + : null) || installationMarkers.read(target)?.recordId || (typeof target?.id === 'string' ? target.id : null); if (id && layerState.recordById.has(id) && id !== layerState.selectedId) { diff --git a/src/layers/installations/selection.test.mjs b/src/layers/installations/selection.test.mjs index ab6de8d54..150424fca 100644 --- a/src/layers/installations/selection.test.mjs +++ b/src/layers/installations/selection.test.mjs @@ -4,7 +4,9 @@ import * as Cesium from 'cesium'; import * as context from '../../data/contextStore.js'; import { createSelection } from './selection.js'; import { createRendering } from './rendering.js'; -import { createNamedMarkers } from './namedMarkers.js'; +import { createNamedMarkers, namedPointId } from './namedMarkers.js'; +import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; +import { fakeInput } from '../../input/testDoubles.mjs'; function harness(t) { const previousWindow = globalThis.window; @@ -45,17 +47,17 @@ function harness(t) { clientHeight: 800, }), primitives: { add: (p) => p, remove() {} }, + pick: () => picked, }, }, }; + let picked; + const { draw } = bindFakeCesiumScene(state.viewer); + const input = fakeInput(state.viewer); t.mock.method( Cesium.SceneTransforms, 'worldToWindowCoordinates', - (_scene, _point, scratch) => { - scratch.x = 640; - scratch.y = 400; - return scratch; - }, + () => new Cesium.Cartesian2(640, 400), ); let labels = []; const services = { @@ -91,6 +93,7 @@ function harness(t) { state.clickSubscription(); parts.namedMarkers.destroy(); parts.rendering.clearRendered(); + input.destroy(); if (previousWindow === undefined) delete globalThis.window; else globalThis.window = previousWindow; if (previousDocument === undefined) delete globalThis.document; @@ -107,7 +110,18 @@ function harness(t) { }; assert.equal(selection.selectRecord(record.id), true); assertSelected(true); - return { state, selection, assertSelected }; + return { + state, + selection, + assertSelected, + draw, + parts, + /** Click on what `pick` names, as the scene would pick it. */ + click(value) { + picked = value; + input.tap({ x: 640, y: 400 }); + }, + }; } for (const layerId of ['flights', 'military', 'satellites']) { @@ -153,3 +167,22 @@ test('destroy removes all installation context listeners', (t) => { h.assertSelected(true); } }); + +test('a click on a named marker point selects its site; again releases it', (t) => { + const h = harness(t); + h.state.selectedId = null; + context.clearSelectedEntityContextForLayer('military-installations'); + h.parts.rendering.renderRecords(); + h.assertSelected(false); + const setId = h.parts.namedMarkers.setId; + const item = h.draw.set(setId).items.get(namedPointId('base')); + assert.deepEqual(item.meta, { installationId: 'base' }); + const pointPick = { id: { set: setId, id: item.id, meta: item.meta } }; + h.click(pointPick); + h.assertSelected(true); + h.click(pointPick); + h.assertSelected(false); + // Another set's item with the same meta is not this layer's point. + h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } }); + h.assertSelected(false); +}); diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index 908ea3d50..ec31b2038 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -1,4 +1,5 @@ import { createNamedMarkers } from '../layers/installations/namedMarkers.js'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; import { renderApplicationHtml } from '../testSupport/applicationHtml.mjs'; import { readStylesheet } from '../testSupport/readStylesheet.mjs'; import test from 'node:test'; @@ -2254,14 +2255,20 @@ test('installation titles share persistent card arbitration and retain a bounded env.viewer.camera.changed = new Cesium.Event(); t.mock.method(Cesium.Cartesian3, 'fromDegrees', (lon, lat) => new Cesium.Cartesian3(lon, lat, 0)); t.mock.method(Cesium.EllipsoidalOccluder.prototype, 'isPointVisible', () => true); - t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', (_scene, _point, scratch) => { + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', (_scene, _point, scratch = new Cesium.Cartesian2()) => { scratch.x = scratch.y = 100; return scratch; }); const state = { enabled: true, viewer: env.viewer, contextAnchor: {} }; + bindFakeCesiumScene(env.viewer); const markers = createNamedMarkers({ state, services: { render: { governorRequestRender() {} } }, parts: { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { installationSurfaceHeightM: () => 0 } }, - overlayHost: { setEntries: setOverlayEntries, clearSource: clearOverlaySource, + // The markers place titles in ECEF; this camera looks at degrees, as the + // mocked fromDegrees above makes them. + overlayHost: { setEntries: (id, entries, policy) => setOverlayEntries(id, entries.map((entry) => { + const { longitude, latitude } = Cesium.Cartographic.fromCartesian(entry.position); + return { ...entry, position: new Cesium.Cartesian3(Cesium.Math.toDegrees(longitude), Cesium.Math.toDegrees(latitude), 0) }; + }), policy), clearSource: clearOverlaySource, setVisible: setOverlaySourceVisible, getDiagnostics: getWorldOverlayDiagnostics }, }); initWorldOverlay(env.viewer); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 8b9ada587..2a7bc22ba 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1098,6 +1098,101 @@ test('the context layer draws its rim as an outlined ellipse on a viewer of its assert.equal(other.added.length, 0); }); +test('the installations layer draws its named markers as outlined point primitives on a viewer of its own', async () => { + const { createNamedMarkers, namedPointId } = + await import('../../layers/installations/namedMarkers.js'); + const scene = fakeScene(); + scene.canvas = { clientWidth: 800, clientHeight: 600 }; + const viewer = { scene }; + const state = { viewer, enabled: false, selectedId: null }; + const markers = createNamedMarkers({ + state, + services: { render: { governorRequestRender() {} } }, + parts: { + model: { colorFor: () => [1, 165 / 255, 0, 1] }, + rendering: { installationSurfaceHeightM: () => 40 }, + }, + overlayHost: { setEntries() {}, clearSource() {}, setVisible() {} }, + }); + const records = [ + { + id: 'a', + name: 'A', + namedArea: true, + areaM2: 2, + latitude: 30, + longitude: -97, + pointOnly: false, + }, + { + id: 'b', + name: 'B', + namedArea: true, + areaM2: 1, + latitude: 31, + longitude: -98, + pointOnly: true, + }, + ]; + markers.sync(records); + const host = scene.added.find((h) => h.get?.(0)?.id?.set === markers.setId); + assert.ok(host instanceof Cesium.PointPrimitiveCollection); + assert.equal(host.show, false, 'hidden while the layer is off'); + assert.equal(host.length, 2); + const a = host.get(0); + assert.equal(a.id.id, namedPointId('a')); + assert.deepEqual(a.id.meta, { installationId: 'a' }); + assert.equal(a.pixelSize, 7); + assert.equal(a.outlineWidth, 1); + assert.ok(Cesium.Color.equals(a.outlineColor, Cesium.Color.BLACK)); + assert.ok(Cesium.Color.equals(a.color, new Cesium.Color(1, 165 / 255, 0, 1))); + assert.equal(a.disableDepthTestDistance, Infinity); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + a.position, + Cesium.Cartesian3.fromDegrees(-97, 30, 40), + 0, + 1e-6, + ), + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + host.get(1).position, + Cesium.Cartesian3.fromDegrees(-98, 31, 0), + 0, + 1e-6, + ), + 'a point-only site sits on the ellipsoid', + ); + // Selecting a drawn site restyles nothing that moves: the points stay. + state.selectedId = 'b'; + markers.sync(records); + assert.equal(scene.added.includes(host), true); + assert.equal(host.get(0), a); + // A selected site that is not a named area draws no point. + state.selectedId = 'c'; + markers.sync([ + ...records, + { + id: 'c', + name: 'C', + areaM2: 3, + latitude: 32, + longitude: -99, + pointOnly: true, + }, + ]); + const rebuilt = scene.added.find( + (h) => h.get?.(0)?.id?.set === markers.setId, + ); + const c = [0, 1, 2] + .map((i) => rebuilt.get(i)) + .find((p) => p.id.id === namedPointId('c')); + assert.equal(c.show, false); + markers.destroy(); + assert.equal(scene.added.includes(host), false); +}); + /** Run `fn` with the image classes Cesium's materials test uniforms against. */ function withImageClasses(fn) { const names = [ diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index b5373b4c8..bc07c4b0f 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -72,7 +72,6 @@ "src/layers/flights/testing.js", "src/layers/flights/tracking.js", "src/layers/ghostMaps/index.js", - "src/layers/installations/namedMarkers.js", "src/layers/installations/rendering.js", "src/layers/launches/launchPad.js", "src/layers/launches/orbitRendering.js", diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs index de6cb2cdb..daa982a37 100644 --- a/src/testSupport/fakeCesiumScene.mjs +++ b/src/testSupport/fakeCesiumScene.mjs @@ -9,7 +9,7 @@ * `positionCartographic`; `viewRectangle()` from its * `computeViewRectangle()`, in degrees; events from its own `moveEnd`, * `moveStart` and `changed`. - * - query: `project` through `Cesium.SceneTransforms.worldToWindowCoordinates` + * - query: `project` (and `projectMany`) through `Cesium.SceneTransforms.worldToWindowCoordinates` * (which a test may stub), `isOccluded` against the ellipsoid's horizon * from the camera's `positionWC` (never occluded without one). * - frame: phases from the scene's own `preUpdate`, `preRender` and @@ -30,6 +30,75 @@ function listen(source, cb) { return () => source?.removeEventListener?.(cb); } +/** The double's camera: `viewer.camera`, else `viewer.scene.camera`. */ +const cameraOfDouble = (viewer) => + viewer.camera?.positionWC || !viewer.scene?.camera + ? viewer.camera + : viewer.scene.camera; + +/** + * The query port `bindFakeCesiumScene` binds, on its own, for a test that + * binds its other ports another way (`bindFakeCesiumCamera`'s `ports`). + * @param {object} viewer + */ +export function fakeSceneQuery(viewer) { + return { + project(position) { + // The position itself, so a stub can tell positions apart by identity. + const s = Cesium.SceneTransforms.worldToWindowCoordinates( + viewer.scene, + position, + ); + return s ? { x: s.x, y: s.y } : null; + }, + projectMany(source, out) { + for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) { + const s = this.project({ + x: source[i], + y: source[i + 1], + z: source[i + 2], + }); + out[j] = s ? s.x : Number.NaN; + out[j + 1] = s ? s.y : Number.NaN; + } + }, + isOccluded(position) { + const eye = cameraOfDouble(viewer)?.positionWC; + if (!eye) return false; + return !new Cesium.EllipsoidalOccluder( + Cesium.Ellipsoid.WGS84, + eye, + ).isPointVisible(toCartesian(position)); + }, + }; +} + +/** + * The frame port `bindFakeCesiumScene` binds, on its own, as + * `fakeSceneQuery` is. + * @param {object} viewer + */ +export function fakeSceneFrame(viewer) { + return { + on: (phase, cb) => listen(viewer.scene?.[phase], cb), + requestRender: () => viewer.scene?.requestRender?.(), + }; +} + +/** + * A fake draw port and the query and frame ports above, for + * `bindFakeCesiumCamera(viewer, fakeScenePorts(viewer))`. + * @param {object} viewer + * @returns {{draw: object, query: object, frame: object}} + */ +export function fakeScenePorts(viewer) { + return { + draw: fakeDrawPort(), + query: fakeSceneQuery(viewer), + frame: fakeSceneFrame(viewer), + }; +} + /** * Bind the ports to `viewer`. * @param {object} viewer @@ -37,10 +106,7 @@ function listen(source, cb) { * @returns {{draw: object, camera: object, query: object, frame: object, unbind: () => void}} */ export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) { - const cam = () => - viewer.camera?.positionWC || !viewer.scene?.camera - ? viewer.camera - : viewer.scene.camera; + const cam = () => cameraOfDouble(viewer); const camera = { pose() { const c = cam(); @@ -80,28 +146,8 @@ export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) { }, on: (event, cb) => listen(cam()?.[event], cb), }; - const query = { - project(position) { - // The position itself, so a stub can tell positions apart by identity. - const s = Cesium.SceneTransforms.worldToWindowCoordinates( - viewer.scene, - position, - ); - return s ? { x: s.x, y: s.y } : null; - }, - isOccluded(position) { - const eye = cam()?.positionWC; - if (!eye) return false; - return !new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - eye, - ).isPointVisible(toCartesian(position)); - }, - }; - const frame = { - on: (phase, cb) => listen(viewer.scene?.[phase], cb), - requestRender: () => viewer.scene?.requestRender?.(), - }; + const query = fakeSceneQuery(viewer); + const frame = fakeSceneFrame(viewer); const unbind = bindRenderer(viewer, { draw, camera, query, frame }); return { draw, camera, query, frame, unbind }; }