diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 5b4eb3691..84748c7e9 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2473,6 +2473,7 @@ "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", + "src/geo/horizon.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index d5f7739b5..0403b7c38 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -4,6 +4,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import alprCamerasLayer, { createAlprCamerasLayer, configureAlprSource, @@ -311,7 +312,7 @@ function cameraHarness(layer = alprCamerasLayer) { }, }); let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 }; - let source, click, picked; + let click, picked; const credits = new Set(); const viewer = { creditDisplay: { @@ -336,14 +337,9 @@ function cameraHarness(layer = alprCamerasLayer) { postRender: new Cesium.Event(), pick: () => picked, }, - dataSources: { - add: (value) => { - source = value; - }, - remove() {}, - }, }; - bindFakeCesiumCamera(viewer); + const ports = fakeScenePorts(viewer); + bindFakeCesiumCamera(viewer, ports); // The renderer's camera port relays moveEnd; the layer's own come on top. const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners; const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction; @@ -366,14 +362,22 @@ function cameraHarness(layer = alprCamerasLayer) { Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput; } layer.enable(); + const icons = () => { + const set = [...ports.draw.sets.values()].find( + (candidate) => candidate.kind === 'icons' && !candidate.disposed, + ); + return set && { ...set, id: set.spec.id }; + }; + const marker = (id) => + icons()?.items.has(id) + ? getContextStore().entities.get(id)?.entity + : undefined; return { viewer, + ports, portMoveEndListeners, requests, credits, - get source() { - return source; - }, setFetch(fn) { response = fn; }, @@ -386,9 +390,16 @@ function cameraHarness(layer = alprCamerasLayer) { advance(ms) { now += ms; }, + /** The layer's icon set, as the fake draw port holds it. */ + icons, + /** The icon drawn for a camera, or undefined. */ + icon: (id) => icons()?.items.get(id), + /** The drawn markers' carriers (their context entities), in draw order. */ + markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)), + marker, click(id) { - const entity = typeof id === 'string' ? source.entities.getById(id) : id; - picked = entity ? { id: entity } : undefined; + const item = typeof id === 'string' ? icons()?.items.get(id) : null; + picked = item ? { id: { set: icons().id, id: item.id } } : undefined; click({ position: new Cesium.Cartesian2() }); }, restore() { @@ -452,14 +463,14 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a ]), ); await alprCamerasLayer.update(); - const entities = h.source.entities.values; + const entities = h.markers(); assert.equal(alprCamerasLayer.name, 'ALPR Cameras'); assert.deepEqual( entities.map((entity) => readEntityRecord(entity)?.labelModel.title), ['ALPR-0042', 'ALPR-0043', 'ALPR-0044'], ); assert.equal( - new Set(entities.map((entity) => entity.billboard.image.getValue())).size, + new Set(entities.map((entity) => h.icon(entity.id).image)).size, 1, ); assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [ @@ -498,7 +509,7 @@ test('the camera label stays English data in a translated interface', async () = ]), ); await alprCamerasLayer.update(); - h.click(h.source.entities.values[0].id); + h.click(h.markers()[0].id); assert.equal(getSelectedEntityContext().label, 'ALPR camera'); assert.equal( shownEntityLabel(getSelectedEntityContext().label), @@ -535,10 +546,7 @@ test('clicking the selected camera or empty map deselects, including after refre h.expire(); await alprCamerasLayer.update(); assert.equal(getSelectedEntityContext(), null); - assert.equal( - h.source.entities.getById('alpr:42').billboard.width.getValue(), - 38, - ); + assert.equal(h.icon('alpr:42').size[0], 38); } } finally { h.restore(); @@ -594,10 +602,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n alprCamerasLayer.enable(); await alprCamerasLayer.update(); assert.equal(getSelectedEntityContext(), null); - assert.equal( - h.source.entities.getById('alpr:42').billboard.width.getValue(), - 38, - ); + assert.equal(h.icon('alpr:42').size[0], 38); } finally { h.restore(); } @@ -686,7 +691,7 @@ test('duplicate nodes render once with a count that agrees with the entity set', await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'ready'); assert.equal(alprCamerasLayer.getStats().count, 1); - assert.equal(h.source.entities.values.length, 1); + assert.equal(h.icons().items.size, 1); } finally { h.restore(); } @@ -702,7 +707,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); assert.equal(alprCamerasLayer.getStats().count, 0); assert.equal(getSelectedEntityContext(), null); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); assert.equal(h.requests.length, 1); } finally { h.restore(); @@ -762,7 +767,7 @@ test('nearby camera moves reuse the snapped query but count and register only in await alprCamerasLayer.update(); assert.equal(h.requests.length, 1); assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']); @@ -809,9 +814,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di try { let samples = 0; h.viewer.scene.sampleHeightSupported = true; - h.viewer.scene.sampleHeight = (point, excluded) => { + h.viewer.scene.sampleHeight = () => { samples += 1; - assert.equal(excluded[0].id, 'alpr:42'); return 187; }; h.setFetch(async () => @@ -823,7 +827,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di ); await alprCamerasLayer.update(); h.click('alpr:42'); - const entity = h.source.entities.getById('alpr:42'); + const entity = h.marker('alpr:42'); const anchor = Cesium.Cartographic.fromCartesian( readEntityRecord(entity)?.displayPosition(), ); @@ -871,6 +875,7 @@ test('a late network failure after disable cannot resurrect retries or an error }); test('two factories keep their requests, records and destruction independent', async () => { + const carriers = new Map(); const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, @@ -884,7 +889,9 @@ test('two factories keep their requests, records and destruction independent', a getSelectedEntityContext() { return null; }, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -930,11 +937,11 @@ test('two factories keep their requests, records and destruction independent', a await pending; assert.equal(first.getStats().count, 0); assert.equal(second.getStats().count, 1); - assert.equal(b.source.entities.values[0].id, 'directory:99'); + assert.deepEqual([...b.icons().items.keys()], ['directory:99']); assert.equal(second.source, 'Test camera directory'); assert.ok( readEntityRecord( - b.source.entities.values[0], + carriers.get('directory:99'), )?.labelModel.details.includes('Source: Test directory'), ); assert.equal( @@ -952,6 +959,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso // Ground clamping re-samples every marker whenever a photoreal tile streams // in; a whole-city view (about 1,000 cameras) stuttered while zooming. const floors = new Map([['30.2672', 150]]); + const carriers = new Map(); let resolveCalls = 0; let releaseResolve; const services = { @@ -972,7 +980,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso getSelectedEntityContext() { return null; }, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -993,38 +1003,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso const h = cameraHarness(layer); try { await layer.update(); - const known = h.source.entities.getById('directory:1'); - const unknown = h.source.entities.getById('directory:2'); - assert.equal( - known.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, - ); + const known = h.icon('directory:1'); + const unknown = () => h.icon('directory:2'); + const unknownCarrier = carriers.get('directory:2'); + assert.equal(known.height, 'absolute'); assert.ok( - Math.abs( - Cesium.Cartographic.fromCartesian(known.position.getValue()).height - - 151.5, - ) < 0.01, - ); - assert.equal( - unknown.billboard.heightReference.getValue(), - Cesium.HeightReference.CLAMP_TO_GROUND, + Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) < + 0.01, ); + assert.equal(unknown().height, 'clampGround'); assert.equal(resolveCalls, 1); + const writes = h.icons().writes; releaseResolve(); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal( - unknown.billboard.heightReference.getValue(), - Cesium.HeightReference.NONE, - ); + assert.equal(unknown().height, 'absolute'); assert.ok( Math.abs( - Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height - - 161.5, + Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5, ) < 0.01, ); + assert.equal(h.icons().writes, writes + 1, 'one write for the move'); assert.equal( - h.source.entities.getById('directory:2'), - unknown, + carriers.get('directory:2'), + unknownCarrier, 'placed in place, not rebuilt', ); } finally { @@ -1076,23 +1077,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec ); await alprCamerasLayer.update(); h.click('alpr:42'); - const entity = h.source.entities.getById('alpr:42'); - const position = entity.position, - line = entity.polyline; + const entity = h.marker('alpr:42'); + const icon = h.icon('alpr:42'); // Ground-clamped native wedges cost ~40 ms per frame for a downtown view; // bearings are painted by the overlay for the nearest cameras instead. - assert.equal(line, undefined); - assert.equal(entity.polygon, undefined); + assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry'); let selections = 0, - clears = 0, - collectionChanges = 0; + clears = 0; window.addEventListener('gev:entity-selected', () => selections++); window.addEventListener('gev:entity-selection-cleared', () => clears++); - h.source.entities.collectionChanged.addEventListener( - (_collection, added, removed) => { - collectionChanges += added.length + removed.length; - }, - ); + const writes = h.icons().writes; h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 }); await alprCamerasLayer.update(); h.expire(); @@ -1108,30 +1102,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec ]), ); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); - assert.equal(entity.position, position); - assert.equal(entity.polyline, line); + assert.equal(h.marker('alpr:42'), entity); + assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again'); assert.equal( getSelectedEntityContext().properties.operator, 'Updated directory', ); assert.equal(selections, 0); assert.equal(clears, 0); - assert.equal(collectionChanges, 0); + assert.equal(h.icons().writes, writes, 'no icon added or removed'); assert.equal(h.requests.length, 2, 'only expiry needs another request'); h.expire(); h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })])); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); - assert.equal( - entity.polyline, - undefined, - 'removed direction must not persist', - ); + assert.equal(h.marker('alpr:42'), entity); assert.ok( - Cesium.Cartesian3.equals( - entity.position.getValue(), + Cesium.Cartesian3.equalsEpsilon( + h.icon('alpr:42').pos, Cesium.Cartesian3.fromDegrees(-97.742, 30.2672), + 0, + 1e-6, ), ); } finally { @@ -1171,7 +1161,7 @@ test('moves inside a pending query do not restart it; moving to another city can resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })])); await second; assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); } finally { @@ -1189,12 +1179,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200); try { await alprCamerasLayer.update(); - const entity = h.source.entities.getById('alpr:42'); + const entity = h.marker('alpr:42'); h.click('alpr:42'); for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) { h.setBox(box); await alprCamerasLayer.update(); - assert.equal(h.source.entities.getById('alpr:42'), entity); + assert.equal(h.marker('alpr:42'), entity); assert.equal(getSelectedEntityContext().id, 'alpr:42'); assert.equal(h.requests.length, 1); } @@ -1205,7 +1195,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da ); await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); camera.pickEllipsoid = () => undefined; await alprCamerasLayer.update(); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); @@ -1400,7 +1390,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an requests[1].release(); await new Promise((done) => setTimeout(done, 0)); assert.equal(requests.length, 2, 'queued final cells are discarded'); - assert.equal(h.source.entities.values.length, 0); + assert.equal(h.icons().items.size, 0); layer.enable(); await layer.update(); assert.equal( @@ -1419,10 +1409,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an } }); -test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => { +test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => { let floor = 180; let listener; let removed = 0; + const carriers = new Map(); const records = Array.from({ length: 70 }, (_, i) => ({ id: `surface:${i}`, latitude: 30.2672 + i * 0.00001, @@ -1448,7 +1439,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc context: { clearSelectedEntityContextForLayer() {}, getSelectedEntityContext() {}, - registerEntityContext() {}, + registerEntityContext(entity, metadata) { + carriers.set(metadata.id, entity); + }, removeEntityContextsForLayer() {}, selectEntityContext() {}, }, @@ -1457,40 +1450,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc const h = cameraHarness(layer); try { await layer.update(); - const entities = [...h.source.entities.values]; + const entities = [...carriers.values()]; + // One marker under a canvas badge: its icon is the faint pick target. const saved = entities[1]; - alprMarkers.write(saved).nativeAppearance = { - position: saved.position, - heightReference: saved.billboard.heightReference, - }; - saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190); - alprMarkers.write(saved).pickPosition = saved.position; + Object.assign(alprMarkers.write(saved), { + canvasOwned: true, + canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190), + }); for (const next of [150, 120, null, 180]) { floor = next; - // Includes a provider switch with the same globe.show value. - h.viewer.scene.globe.show = next !== 180; listener({ detail: { status: 'ready' } }); for (const entity of entities) { - assert.equal(h.source.entities.getById(entity.id), entity); + const icon = h.icon(entity.id); assert.ok( Math.abs( - Cesium.Cartographic.fromCartesian(entity.position.getValue()) - .height - (next == null ? 0 : next + 1.5), + Cesium.Cartographic.fromCartesian(icon.pos).height - + (next == null ? 0 : next + 1.5), ) < 0.01, `${entity.id} refreshes at ${next}`, ); - assert.equal( - entity.billboard.heightReference.getValue(), - next == null - ? Cesium.HeightReference.CLAMP_TO_GROUND - : Cesium.HeightReference.NONE, - ); + assert.equal(icon.height, next == null ? 'clampGround' : 'absolute'); + assert.equal(icon.color, undefined, 'drawn as a badge'); assert.equal(alprMarkers.read(entity)?.canvasPosition, null); } assert.equal( - alprMarkers.read(saved)?.nativeAppearance, - null, - 'saved appearance restores at the new floor', + alprMarkers.read(saved)?.canvasOwned, + false, + 'the badge comes back at the new floor', ); } } finally { @@ -1503,7 +1489,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set const h = cameraHarness(); try { await alprCamerasLayer.update(); - const previous = h.source.entities.getById('alpr:42'); + const previous = h.marker('alpr:42'); const revision = alprCamerasLayer.getStats().renderRevision; let release; h.setFetch( @@ -1516,7 +1502,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set const pending = alprCamerasLayer.update(); await alprCamerasLayer.update(); assert.equal( - h.source.entities.getById('alpr:42'), + h.marker('alpr:42'), previous, 'do not show an intermediate filtered snapshot while the new query prepares', ); @@ -1526,7 +1512,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set await pending; assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1); assert.deepEqual( - h.source.entities.values.map((e) => e.id), + h.markers().map((e) => e.id), ['alpr:43'], ); } finally { diff --git a/src/layers/alpr/index.js b/src/layers/alpr/index.js index 61e6721bf..2e3015424 100644 --- a/src/layers/alpr/index.js +++ b/src/layers/alpr/index.js @@ -1,6 +1,6 @@ import { isFollowing } from '../../data/followed.js'; import { isUnavailableCapability } from '../../sources/capability.js'; -import * as Cesium from 'cesium'; +import { cameraOf, drawOf, findFrame } from '../../render/rendererOf.js'; import { LAYER_ID, REQUEST_DEBOUNCE_MS, @@ -15,8 +15,11 @@ import { alprCredit, } from './model.js'; import { createAlprPresentation } from './presentation.js'; +import { createAlprMarkerSet } from './markerState.js'; import { t, tn, msg } from '../../i18n/index.js'; +let instances = 0; + /** * Own one layer's requests, records, display and viewer subscriptions. * A source fetches a bounded box with an AbortSignal and resolves @@ -40,7 +43,8 @@ export function createAlprCamerasLayer({ source, services } = {}) { const state = { viewer: null, - dataSource: null, + /** The camera markers, drawn as one icon set. */ + markers: createAlprMarkerSet(), credit: null, creditTimer: null, creditPresented: false, @@ -184,9 +188,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { } renderRecords(); state.retrying = false; - setAlprStatus( - state.dataSource.entities.values.length ? 'ready' : 'empty', - ); + setAlprStatus(state.markers.size ? 'ready' : 'empty'); return; } // A move inside an in-flight query must not abort and restart that query. @@ -254,13 +256,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { // Stale and saturated are independent facts; a cached response that also // hit the cap must still warn about coverage, not just about freshness. renderRecords(); - setAlprStatus( - state.dataSource.entities.values.length - ? stale - ? 'stale' - : 'ready' - : 'empty', - ); + setAlprStatus(state.markers.size ? (stale ? 'stale' : 'ready') : 'empty'); } catch (error) { if ( error?.name === 'AbortError' || @@ -297,13 +293,17 @@ export function createAlprCamerasLayer({ source, services } = {}) { init(viewer) { if (state.viewer) throw new Error('ALPR layer is already initialized'); state.viewer = viewer; - state.dataSource = new Cesium.CustomDataSource('alpr-cameras'); + state.markers.attach( + drawOf(viewer).icons({ + id: `${LAYER_ID}:${++instances}:markers`, + show: state.enabled, + }), + ); state.credit = alprCredit(source.attribution); - viewer.dataSources.add(state.dataSource); - state.moveEndRemove = - viewer.camera.moveEnd.addEventListener(scheduleLoad); + state.moveEndRemove = cameraOf(viewer).on('moveEnd', scheduleLoad); state.postRenderRemove = - viewer.scene.postRender?.addEventListener(updateSelectedAnchor); + findFrame(viewer)?.on('postRender', () => updateSelectedAnchor()) ?? + null; initOverlay(); installInteraction(viewer); }, @@ -312,7 +312,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { state.enabled = true; state.creditPresented = false; registerPickOwner(LAYER_ID, (id) => state.recordById.has(id)); - state.dataSource.show = true; + state.markers.icons.show = true; // DataLayerManager calls update() right after enable(); it owns the first fetch. }, disable() { @@ -326,7 +326,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { state.pendingQueryBox = null; state.loading = false; state.retrying = false; - if (state.dataSource) state.dataSource.show = false; + if (state.markers.icons) state.markers.icons.show = false; clearSelection(); clearRendered(); setAlprStatus('idle'); @@ -345,9 +345,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { state.clickSubscription?.(); state.clickSubscription = null; clearRendered(); - if (state.dataSource && viewer) - viewer.dataSources.remove(state.dataSource, true); - state.dataSource = null; + state.markers.dispose(); state.credit = null; state.creditPresented = false; state.records = []; @@ -362,7 +360,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { state.viewer = null; }, getRowControls() { - const count = state.dataSource?.entities.values.length || 0; + const count = state.markers.size; return { chips: [ { @@ -422,21 +420,17 @@ export function createAlprCamerasLayer({ source, services } = {}) { }, getStats() { return { - count: state.dataSource?.entities.values.length || 0, + count: state.markers.size, countLabel: state.enabled && !state.noCoverage && state.status !== 'zoom-in' ? Number.isInteger(state.onScreen) ? tn( - state.dataSource?.entities.values.length || 0, + state.markers.size, '{count} nearby · {onScreen} on screen', '{count} nearby · {onScreen} on screen', { onScreen: state.onScreen }, ) - : tn( - state.dataSource?.entities.values.length || 0, - '{count} nearby', - '{count} nearby', - ) + : tn(state.markers.size, '{count} nearby', '{count} nearby') : '', noCoverage: Boolean(state.noCoverage), lastUpdate: state.lastUpdate, @@ -444,7 +438,7 @@ export function createAlprCamerasLayer({ source, services } = {}) { saturated: state.saturated || state.renderSaturated, renderRevision: state.renderRevision, onScreen: state.onScreen ?? null, - shown: state.dataSource?.entities.values.length || 0, + shown: state.markers.size, error: state.error, status: state.status, loading: state.loading, diff --git a/src/layers/alpr/markerState.js b/src/layers/alpr/markerState.js index 9acf0d973..85a06ae5f 100644 --- a/src/layers/alpr/markerState.js +++ b/src/layers/alpr/markerState.js @@ -1,14 +1,173 @@ /** * @module alpr/markerState - * @description The ALPR layer's own per-marker state, held in the app rather than on the - * Cesium entities it draws: + * @description The ALPR layer's markers: one icon per camera in a draw set, + * and the layer's own per-marker state, held in the layer. Each marker is a + * plain carrier object (`{ id, show }`) that the layer registers as the + * camera's context entity; its state lives in `alprMarkers`: * - `record`: the camera record the marker shows. - * - `clamped`: whether the marker sits on the surface rather than at its height. + * - `position`, `clamped`: where the badge is drawn natively, and whether it + * follows the ground there rather than sitting at its height. + * - `selected`: drawn with the selected badge. * - `canvasPosition`, `displayPosition`: the canvas anchor and the position the card reads. * - `wedge`: the direction wedge's positions, plain ECEF. - * - `nativeAppearance`, `pickPosition`: the native look saved while the canvas draws it. - * - `shown`, `surfaceCheckedFor`: the last visibility applied and the anchor last checked. + * - `canvasOwned`: the overlay canvas draws the badge; the icon stays as a + * faint pick target at the canvas anchor. + * - `shown`, `surfaceCheckedFor`: whether the icon shows and the anchor last checked. */ import { createEntityStore } from '../../data/entityRecords.js'; +import { + MARKER_ICON_SIZE, + MARKER_SCALE_BY_DISTANCE, + SELECTED_MARKER_ICON_SIZE, +} from './policy.js'; +import { MARKER_IMAGE, SELECTED_IMAGE } from './visuals.js'; export const alprMarkers = createEntityStore(); + +const [NEAR, NEAR_SCALE, FAR, FAR_SCALE] = MARKER_SCALE_BY_DISTANCE; +/** City-wide views hold hundreds of badges; they shrink with distance. */ +const SCALE_BY_DISTANCE = Object.freeze({ + near: NEAR, + nearValue: NEAR_SCALE, + far: FAR, + farValue: FAR_SCALE, +}); +/** Under the canvas badge: faint, but still picked. */ +const PICK_TARGET_COLOR = Object.freeze([1, 1, 1, 0.01]); + +/** + * Where a marker's icon is drawn: the canvas anchor while the canvas owns + * it, else its native position. + * @param {{id: string}} carrier + * @returns {import('../../render/contract/common').Ecef|null|undefined} + */ +export function alprIconPosition(carrier) { + const marker = alprMarkers.read(carrier); + if (!marker) return null; + return marker.canvasOwned && marker.canvasPosition + ? marker.canvasPosition + : marker.position; +} + +/** + * The icon a marker draws now. + * @param {{id: string}} carrier + * @returns {import('../../render/contract/draw').IconItem} + */ +export function alprIconItem(carrier) { + const marker = alprMarkers.read(carrier) ?? {}; + const canvas = Boolean(marker.canvasOwned && marker.canvasPosition); + const size = marker.selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE; + return { + id: carrier.id, + pos: canvas ? marker.canvasPosition : marker.position, + // Ground clamping is the placeholder until a marker's floor resolves. + height: !canvas && marker.clamped ? 'clampGround' : 'absolute', + image: marker.selected ? SELECTED_IMAGE : MARKER_IMAGE, + size: [size, size], + disableDepthTest: Number.POSITIVE_INFINITY, + show: marker.shown !== false, + ...(canvas + ? { color: PICK_TARGET_COLOR } + : { scaleByDistance: SCALE_BY_DISTANCE }), + }; +} + +/** What tells one drawn icon from another, so unchanged ones are not sent again. */ +function itemKey(item) { + const { pos } = item; + return [ + pos?.x, + pos?.y, + pos?.z, + item.height, + item.image, + item.size[0], + item.show, + item.color ? 'pick' : 'badge', + ].join('|'); +} + +/** + * The layer's markers, drawn as one icon set: carriers by camera id, and + * the writes to the set, batched until `flush`. + * @returns {object} + */ +export function createAlprMarkerSet() { + const carriers = new Map(); + /** The key of each icon last sent to the set, by id. */ + const sent = new Map(); + const dirty = new Set(); + let icons = null; + + function flush() { + if (!icons || !dirty.size) return; + const items = []; + for (const carrier of dirty) { + if (carriers.get(carrier.id) !== carrier) continue; + const item = alprIconItem(carrier); + if (!item.pos) continue; + const key = itemKey(item); + if (sent.get(carrier.id) === key) continue; + sent.set(carrier.id, key); + items.push(item); + } + dirty.clear(); + if (items.length) icons.upsert(items); + } + + return { + /** Draw the markers into `set`, an icon set made for them. */ + attach(set) { + icons = set; + }, + /** The icon set, while attached. */ + get icons() { + return icons; + }, + get size() { + return carriers.size; + }, + get(id) { + return carriers.get(id) ?? null; + }, + values() { + return carriers.values(); + }, + /** A new marker for `id`, drawn at the next `flush`. */ + add(id) { + const carrier = { id, show: true }; + carriers.set(id, carrier); + dirty.add(carrier); + return carrier; + }, + /** Remove the markers with these ids now. */ + remove(ids) { + const gone = []; + for (const id of ids) { + if (!carriers.delete(id)) continue; + sent.delete(id); + gone.push(id); + } + if (gone.length) icons?.remove(gone); + }, + /** Redraw `carrier` at the next `flush`, if how it draws changed. */ + changed(carrier) { + if (carrier) dirty.add(carrier); + }, + flush, + clear() { + carriers.clear(); + sent.clear(); + dirty.clear(); + icons?.clear(); + }, + dispose() { + carriers.clear(); + sent.clear(); + dirty.clear(); + icons?.dispose(); + icons = null; + }, + }; +} diff --git a/src/layers/alpr/overlay.js b/src/layers/alpr/overlay.js index 470a542c5..728d9fd8a 100644 --- a/src/layers/alpr/overlay.js +++ b/src/layers/alpr/overlay.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { MAX_CANVAS_FRUSTUMS, MARKER_ICON_SIZE, @@ -19,9 +18,18 @@ import { validAlprGroundHeight, } from './visuals.js'; import { alprMarkers } from './markerState.js'; -import { heightsFor } from '../../queries/heights.js'; +import { distance, fromDegrees, toLonLatH } from '../../geo/index.js'; +import { cameraOf, findQuery, rendererOf } from '../../render/rendererOf.js'; -/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */ +let lanes = 0; + +/** Within `epsilon` on every axis. */ +const near = (a, b, epsilon) => + Math.abs(a.x - b.x) <= epsilon && + Math.abs(a.y - b.y) <= epsilon && + Math.abs(a.z - b.z) <= epsilon; + +/** Per-layer presentation on a caller-owned overlay; the icon set remains the fallback. */ export function createAlprOverlay({ state, services, @@ -40,76 +48,55 @@ export function createAlprOverlay({ if (!destroyed && state.enabled) lane?.requestPaint(); }; - function nativeVisible(entity, visible) { - if (!entity) return; - canvasOwned(entity, !visible); - setShown(entity, visible); + const markers = state.markers; + + function nativeVisible(carrier, visible) { + if (!carrier) return; + canvasOwned(carrier, !visible); + setShown(carrier, visible); } - /** Swap a marker between its native look and a faint canvas pick target. */ - function canvasOwned(entity, owned) { - const visible = !owned; - const billboard = entity.billboard; - const marker = alprMarkers.write(entity); - // Keep a faint native pick target under the canvas badge so sibling layer - // handlers recognize ALPR ownership instead of treating the click as empty. - if (!visible && !marker.nativeAppearance) { - marker.nativeAppearance = { - position: entity.position, - heightReference: billboard.heightReference, - scaleByDistance: billboard.scaleByDistance, - color: billboard.color, - }; - entity.position = marker.canvasPosition; - marker.pickPosition = entity.position; - billboard.heightReference = Cesium.HeightReference.NONE; - billboard.scaleByDistance = undefined; - billboard.color = Cesium.Color.WHITE.withAlpha(0.01); - } else if (visible && marker.nativeAppearance) { - const saved = marker.nativeAppearance; - if (entity.position === marker.pickPosition) - entity.position = saved.position; - billboard.heightReference = saved.heightReference; - billboard.scaleByDistance = saved.scaleByDistance; - billboard.color = saved.color; - marker.nativeAppearance = null; - marker.pickPosition = null; - } + /** + * Swap a marker between its native look and a faint canvas pick target. + * The faint icon stays under the canvas badge, at its anchor, so sibling + * layer handlers recognize ALPR ownership instead of treating the click + * as empty. + */ + function canvasOwned(carrier, owned) { + const marker = alprMarkers.write(carrier); + if (Boolean(marker.canvasOwned) === owned) return; + marker.canvasOwned = owned; + markers.changed(carrier); } - // Assign only on change: each Entity property write mints a new property - // and raises definitionChanged, which paint used to do for every overlay - // camera on every frame. - function setShown(entity, visible) { - const marker = alprMarkers.write(entity); - if (marker.shown === visible) return; + // Changed only on change: the icon is sent again only when it draws + // differently. + function setShown(carrier, visible) { + const marker = alprMarkers.write(carrier); + if ((marker.shown ?? true) === visible) return; marker.shown = visible; - entity.billboard.show = visible; - if (entity.polyline) entity.polyline.show = visible; - if (entity.polygon) entity.polygon.show = visible; + markers.changed(carrier); } function resetAnchors() { - for (const entity of state.dataSource.entities.values) { - const marker = alprMarkers.write(entity); + for (const carrier of markers.values()) { + const marker = alprMarkers.write(carrier); marker.canvasPosition = null; marker.wedge = null; marker.displayPosition = null; - nativeVisible(entity, true); + nativeVisible(carrier, true); } + markers.flush(); state.lastAnchorSampleAt = 0; retryUntil = Date.now() + 15000; requestPaint(); } - function anchorFor(record, entity, budget) { - const cached = alprMarkers.read(entity)?.canvasPosition; + function anchorFor(record, carrier, budget) { + const cached = alprMarkers.read(carrier)?.canvasPosition; if (cached) return cached; - const scene = state.viewer.scene; - const location = Cesium.Cartographic.fromDegrees( - record.longitude, - record.latitude, - ); + const query = findQuery(state.viewer); + const point = { lon: record.longitude, lat: record.latitude }; // A floor-placed marker anchors where its native badge sits; only a // marker still waiting for its floor samples the rendered surface, and // each paint samples a few at most (each sample is a depth render). @@ -119,17 +106,17 @@ export function createAlprOverlay({ record.longitude, ); if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M; - else if (scene.sampleHeightSupported) { + else if (query) { if (budget.samples <= 0) return null; budget.samples -= 1; // A miss is tiles still streaming. - height = heightsFor(scene).now(location, { exclude: [entity] }); + height = query.sampleHeightNow(point, { exclude: [markers.icons?.id] }); } - if (!validAlprGroundHeight(height) && scene.globe.show) - height = heightsFor(scene).now(location, { against: 'terrain' }); + if (!validAlprGroundHeight(height)) + height = query?.sampleHeightNow(point, { against: 'terrain' }); if (!validAlprGroundHeight(height)) return null; - setAnchor(record, entity, height); - return alprMarkers.read(entity)?.canvasPosition; + setAnchor(record, carrier, height); + return alprMarkers.read(carrier)?.canvasPosition; } function floorHeightAt(latitude, longitude) { @@ -137,24 +124,23 @@ export function createAlprOverlay({ return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null; } - function setAnchor(record, entity, height) { - const marker = alprMarkers.write(entity); - marker.canvasPosition = Cesium.Cartesian3.fromDegrees( + function setAnchor(record, carrier, height) { + const marker = alprMarkers.write(carrier); + marker.canvasPosition = fromDegrees( record.longitude, record.latitude, height, ); marker.wedge = directionWedgePositions(record, height, floorHeightAt); + if (marker.canvasOwned) markers.changed(carrier); } /** Whether the visible photoreal tiles (or globe) have finished streaming. */ - function surfaceSettled(scene) { - if (scene.globe?.show) return scene.globe.tilesLoaded !== false; - for (let i = 0; i < (scene.primitives?.length || 0); i++) { - const primitive = scene.primitives.get(i); - if (primitive?.show && primitive.tilesLoaded === false) return false; - } - return true; + function surfaceSettled() { + const globe = rendererOf(state.viewer)?.globe; + // A viewer with no renderer of its own cannot say; its samples are + // still checked against the floor. + return !globe || (globe.isSettled('terrain') && globe.isSettled('tiles')); } /** @@ -165,47 +151,34 @@ export function createAlprOverlay({ * samples far outside the floor prior (a roof or a streaming tile) are * rejected. Returns whether anchors remain to check. */ - function refineAnchors(budget) { - const camera = state.viewer.camera; - const scene = state.viewer.scene; + function refineAnchors(budget, pose) { const still = lastCamera && - camera.positionWC && - Cesium.Cartesian3.equalsEpsilon( - camera.positionWC, - lastCamera.position, - 0, - 0.05, - ) && - Cesium.Cartesian3.equalsEpsilon( - camera.directionWC, - lastCamera.direction, - 0, - 1e-6, - ); - if (camera.positionWC && camera.directionWC) - lastCamera = { - position: Cesium.Cartesian3.clone(camera.positionWC), - direction: Cesium.Cartesian3.clone(camera.directionWC), - }; - if (!scene.sampleHeightSupported) return false; + near(pose.position, lastCamera.position, 0.05) && + near(pose.direction, lastCamera.direction, 1e-6); + lastCamera = { + position: { ...pose.position }, + direction: { ...pose.direction }, + }; + const query = findQuery(state.viewer); + if (!query) return false; let pending = false; for (const record of records) { - const entity = state.dataSource.entities.getById(record.id); - const marker = alprMarkers.read(entity); + const carrier = markers.get(record.id); + const marker = alprMarkers.read(carrier); const anchor = marker?.canvasPosition; if (!anchor || marker.surfaceCheckedFor === anchor) continue; - if (!still || !surfaceSettled(scene) || budget.samples <= 0) { + if (!still || !surfaceSettled() || budget.samples <= 0) { pending = true; continue; } budget.samples -= 1; // A miss is tiles still streaming. - const sample = heightsFor(scene).now( + const sample = query.sampleHeightNow( { lon: record.longitude, lat: record.latitude }, - { exclude: [entity] }, + { exclude: [markers.icons?.id] }, ); - const current = Cesium.Cartographic.fromCartesian(anchor).height; + const current = toLonLatH(anchor)?.height; const floor = services.groundFloor.cachedGroundFloor( record.latitude, record.longitude, @@ -216,10 +189,10 @@ export function createAlprOverlay({ (sample >= floor - SURFACE_BELOW_FLOOR_M && sample <= floor + SURFACE_ABOVE_FLOOR_M)); if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1) - setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M); + setAnchor(record, carrier, sample + MARKER_FLOOR_LIFT_M); // setAnchor rewrote the same record, so this is the new anchor. marker.surfaceCheckedFor = marker.canvasPosition; - if (entity.id === state.selectedId) + if (carrier.id === state.selectedId) marker.displayPosition = marker.canvasPosition; } return pending; @@ -231,9 +204,11 @@ export function createAlprOverlay({ let unresolved = false; const painted = []; const budget = { samples: ANCHOR_SAMPLES_PER_PAINT }; + const pose = cameraOf(state.viewer).pose(); + const query = findQuery(state.viewer); for (const record of records) { - const entity = state.dataSource.entities.getById(record.id); - if (!entity) continue; + const carrier = markers.get(record.id); + if (!carrier) continue; const selected = record.id === state.selectedId; const image = images[selected ? 1 : 0]; if ( @@ -241,45 +216,35 @@ export function createAlprOverlay({ !image.naturalWidth || (selected && !images[2]?.naturalWidth) ) { - nativeVisible(entity, true); + nativeVisible(carrier, true); continue; } - const anchor = anchorFor(record, entity, budget); + const anchor = anchorFor(record, carrier, budget); if (!anchor) { - nativeVisible(entity, true); + nativeVisible(carrier, true); unresolved = true; continue; } - canvasOwned(entity, true); + canvasOwned(carrier, true); if (occluder && !occluder.isPointVisible(anchor)) { - setShown(entity, false); + setShown(carrier, false); continue; } - const scene = state.viewer.scene; - const origin = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - anchor, - ); + const origin = query?.project(anchor); if (!origin) { - setShown(entity, false); + setShown(carrier, false); continue; } const alpha = services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1; if (!(alpha > 0)) { - setShown(entity, false); + setShown(carrier, false); continue; } - const wedge = alprMarkers.read(entity)?.wedge; + const wedge = alprMarkers.read(carrier)?.wedge; if (wedge) { - const left = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - wedge[1], - ); - const right = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - wedge[2], - ); + const left = query.project(wedge[1]); + const right = query.project(wedge[2]); if (left && right) { ctx.save(); ctx.globalAlpha *= alpha; @@ -293,21 +258,19 @@ export function createAlprOverlay({ origin.y < -60 || origin.y > height + 60 ) { - setShown(entity, false); + setShown(carrier, false); continue; } - setShown(entity, true); + setShown(carrier, true); painted.push({ record, origin, selected, image, alpha, - scale: markerScale( - Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor), - ), + scale: markerScale(distance(pose.position, anchor)), }); - if (selected) alprMarkers.write(entity).displayPosition = anchor; + if (selected) alprMarkers.write(carrier).displayPosition = anchor; } // Paint all glyphs after the wedges so one camera's cone cannot wash out another. for (const { record, origin, selected, image, alpha, scale } of painted) { @@ -333,9 +296,11 @@ export function createAlprOverlay({ ctx.restore(); hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 }); } - const refining = refineAnchors({ - samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT), - }); + const refining = refineAnchors( + { samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT) }, + pose, + ); + markers.flush(); if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) { retryTimer = setTimeout(() => { retryTimer = null; @@ -356,7 +321,7 @@ export function createAlprOverlay({ if (!services.overlays?.registerPaintLane || typeof Image === 'undefined') return; lane = services.overlays.registerPaintLane('selected', paint, { - id: `alpr-${Cesium.createGuid()}`, + id: `alpr-${++lanes}`, active: false, }); images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => { @@ -369,9 +334,8 @@ export function createAlprOverlay({ }, sync(visible) { if (!lane) return; - for (const record of records) - nativeVisible(state.dataSource.entities.getById(record.id), true); - const position = state.viewer.camera.positionWC; + const previous = records; + const position = cameraOf(state.viewer).pose().position; records = visible .filter( (record) => @@ -381,13 +345,10 @@ export function createAlprOverlay({ .map((record) => ({ record, distance: position - ? Cesium.Cartesian3.distanceSquared( + ? distance( position, - Cesium.Cartesian3.fromDegrees( - record.longitude, - record.latitude, - ), - ) + fromDegrees(record.longitude, record.latitude), + ) ** 2 : 0, })) .sort((a, b) => a.distance - b.distance) @@ -398,6 +359,11 @@ export function createAlprOverlay({ if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop(); records.push(selected); } + // Cameras that leave the cohort go native; those that stay keep the + // canvas until the next paint, so their icons are not written twice. + const kept = new Set(records.map((record) => record.id)); + for (const record of previous) + if (!kept.has(record.id)) nativeVisible(markers.get(record.id), true); hits = []; retryUntil = Date.now() + 15000; lane.setActive(state.enabled && records.length > 0); @@ -419,8 +385,8 @@ export function createAlprOverlay({ clear() { clearTimeout(retryTimer); retryTimer = null; - for (const record of records) - nativeVisible(state.dataSource?.entities.getById(record.id), true); + for (const record of records) nativeVisible(markers.get(record.id), true); + markers.flush(); records = []; hits = []; lane?.setActive(false); diff --git a/src/layers/alpr/overlay.test.mjs b/src/layers/alpr/overlay.test.mjs index a0ba15e2d..5eee04c7f 100644 --- a/src/layers/alpr/overlay.test.mjs +++ b/src/layers/alpr/overlay.test.mjs @@ -8,7 +8,9 @@ import { alprLabelDetails, markerScale, } from './visuals.js'; -import { alprMarkers } from './markerState.js'; +import { alprMarkers, createAlprMarkerSet } from './markerState.js'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; function harness(t, count = 2, { floor = null } = {}) { const previousImage = globalThis.Image; @@ -24,23 +26,29 @@ function harness(t, count = 2, { floor = null } = {}) { longitude: -97, directionDeg: 90, })); - const entities = new Cesium.EntityCollection(); + const drawPort = fakeDrawPort(); + const markers = createAlprMarkerSet(); + markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' })); + const iconSet = drawPort.set('alpr-cameras:test:markers'); for (const record of records) - entities.add({ - id: record.id, - billboard: { image: 'fallback', show: true }, - polyline: { show: true }, - polygon: { show: true }, + Object.assign(alprMarkers.write(markers.add(record.id)), { + record, + position: Cesium.Cartesian3.fromDegrees( + record.longitude, + record.latitude, + ), }); + markers.flush(); const state = { enabled: true, selectedId: null, - dataSource: { entities }, + markers, viewer: { camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500) }, scene: { globe: { show: true, getHeight: () => 150 } }, }, }; + const { unbind } = bindFakeCesiumScene(state.viewer, { draw: drawPort }); let paint, mapListener, active, @@ -81,6 +89,7 @@ function harness(t, count = 2, { floor = null } = {}) { if (previousImage === undefined) delete globalThis.Image; else globalThis.Image = previousImage; Cesium.SceneTransforms.worldToWindowCoordinates = project; + unbind(); }); const draw = []; const ctx = { @@ -104,7 +113,11 @@ function harness(t, count = 2, { floor = null } = {}) { state, records, overlay, - entities, + markers, + iconSet, + /** A marker's carrier, and the icon last sent for it. */ + carrier: (id) => markers.get(id), + icon: (id) => iconSet.items.get(id), draw, paint: (occluder) => paint({ ctx, width: 800, height: 600, occluder }), mapChanged() { @@ -132,21 +145,19 @@ test('a selected camera without a bearing gets its badge and brackets, never a f assert.ok(h.draw[0].endsWith('alpr-marker-selected.png')); assert.ok(h.draw[1].endsWith('alpr-marker-selected-brackets.png')); assert.equal(h.overlay.pick({ x: 100, y: 100 }), 'camera:0'); - assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true); - assert.equal( - h.entities.getById('camera:0').billboard.color.getValue().alpha, - 0.01, - ); + assert.equal(h.icon('camera:0').show, true); + assert.equal(h.icon('camera:0').color[3], 0.01, 'a faint pick target'); assert.equal(directionWedgePositions(h.records[0]), null); }); test('the overlay bounds its cohort and promotes selection while leaving farther cameras native', (t) => { - const h = harness(t, 70); + // Floor anchors, so every camera anchors in one paint. + const h = harness(t, 70, { floor: 150 }); h.state.selectedId = 'camera:69'; h.overlay.sync(h.records); h.paint(); - const hidden = h.entities.values.filter( - (e) => alprMarkers.read(e)?.nativeAppearance, + const hidden = [...h.markers.values()].filter( + (carrier) => alprMarkers.read(carrier)?.canvasOwned, ); assert.equal(hidden.length, 64); assert.ok(hidden.some((e) => e.id === 'camera:69')); @@ -163,24 +174,25 @@ test('surface changes invalidate cached anchors, and disable/disposal release pa const h = harness(t, 1); h.overlay.sync(h.records); h.paint(); - const entity = h.entities.getById('camera:0'); - const first = alprMarkers.read(entity)?.canvasPosition; + const carrier = h.carrier('camera:0'); + const first = alprMarkers.read(carrier)?.canvasPosition; h.paint(); assert.equal( - alprMarkers.read(entity)?.canvasPosition, + alprMarkers.read(carrier)?.canvasPosition, first, 'stable anchor across frames', ); h.state.viewer.scene.globe.show = false; h.mapChanged(); - assert.equal(alprMarkers.read(entity)?.canvasPosition, null); + assert.equal(alprMarkers.read(carrier)?.canvasPosition, null); h.state.enabled = false; h.overlay.clear(); assert.equal(h.active, false); assert.equal(h.overlay.pick({ x: 100, y: 100 }), null); - assert.equal(entity.billboard.show.getValue(), true); - assert.equal(entity.billboard.color, undefined); - assert.equal(entity.position, undefined); + const icon = h.icon('camera:0'); + assert.equal(icon.show, true); + assert.equal(icon.color, undefined, 'the native badge again'); + assert.equal(icon.pos, alprMarkers.read(carrier).position); h.overlay.destroy(); assert.equal(h.removed, 1); }); @@ -190,7 +202,8 @@ test('an unresolved surface preserves the native marker; the horizon removes ove h.state.viewer.scene.globe.getHeight = () => -15000; h.overlay.sync(h.records); h.paint(); - assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true); + assert.equal(h.icon('camera:0').show, true); + assert.equal(h.icon('camera:0').color, undefined); assert.equal(h.draw.length, 0); h.state.viewer.scene.globe.getHeight = () => 150; h.paint({ isPointVisible: () => false }); @@ -198,18 +211,37 @@ test('an unresolved surface preserves the native marker; the horizon removes ove assert.equal(h.draw.length, 0); }); -test('repeated paints of a still view never rewrite marker properties', (t) => { - // Each Entity write raises definitionChanged; paint used to hide then show - // every overlay camera's native marker on every frame. +test('repeated paints of a still view never rewrite markers', (t) => { + // Paint used to hide then show every overlay camera's native marker on + // every frame. const h = harness(t, 3); h.overlay.sync(h.records); h.paint(); - let changes = 0; - for (const entity of h.entities.values) - entity.definitionChanged.addEventListener(() => changes++); + h.paint(); + const writes = h.iconSet.writes; for (let i = 0; i < 5; i++) h.paint(); - assert.equal(changes, 0); - assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true); + assert.equal(h.iconSet.writes, writes); + assert.equal(h.icon('camera:0').show, true); +}); + +test('a resync hands back only the cameras that leave the overlay', (t) => { + const h = harness(t, 2, { floor: 150 }); + h.overlay.sync(h.records); + h.paint(); + assert.equal(h.icon('camera:0').color[3], 0.01); + assert.equal(h.icon('camera:1').color[3], 0.01); + const writes = h.iconSet.writes; + h.overlay.sync([h.records[0]]); + h.markers.flush(); + assert.equal(h.icon('camera:1').color, undefined, 'native again'); + assert.equal(h.icon('camera:0').color[3], 0.01, 'still under the canvas'); + assert.equal( + h.iconSet.writes, + writes + 1, + 'one write, for the camera that left', + ); + h.paint(); + assert.equal(h.iconSet.writes, writes + 1, 'the next paint writes nothing'); }); test('adapter labels never claim a custom source is public OSM data', () => { @@ -263,7 +295,7 @@ test('a still view replaces floor anchors with the rendered surface, within the h.paint(); const height = (id) => Cesium.Cartographic.fromCartesian( - alprMarkers.read(h.entities.getById(id))?.canvasPosition, + alprMarkers.read(h.carrier(id))?.canvasPosition, ).height; assert.equal( samples, diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index b31ff6e91..a0ed50649 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -1,34 +1,35 @@ import { isFollowing } from '../../data/followed.js'; -import * as Cesium from 'cesium'; import { inputFor } from '../../input/dispatcher.js'; +import { distance, fromDegrees, toLonLatH } from '../../geo/index.js'; import { LAYER_ID, MAX_VIEWPORT_DEGREES, MAX_RENDERED, ALPR_COLOR, ALPR_SELECTED_COLOR, - MARKER_ICON_SIZE, SELECTED_MARKER_ICON_SIZE, CREDIT_DISPLAY_MS, MARKER_FLOOR_LIFT_M, - MARKER_SCALE_BY_DISTANCE, } from './policy.js'; import { boxContains } from './model.js'; import { msg } from '../../i18n/index.js'; import { createAlprFloorResolver } from './floors.js'; import { createAlprOverlay } from './overlay.js'; import { - MARKER_IMAGE, - SELECTED_IMAGE, alprDisplayId, alprLabelDetails, validAlprGroundHeight, } from './visuals.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; -import { alprMarkers } from './markerState.js'; -import { heightsFor } from '../../queries/heights.js'; -import { cameraOf } from '../../render/cesium/camera.js'; -import { findCredits } from '../../render/rendererOf.js'; +import { alprIconPosition, alprMarkers } from './markerState.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { cameraOf, findCredits, findQuery } from '../../render/rendererOf.js'; + +/** A `#rrggbb` colour as `rgb(r,g,b)`, the form the readout card has always had. */ +function cssRgb(hex) { + const n = Number.parseInt(hex.slice(1), 16); + return `rgb(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255})`; +} export function createAlprPresentation({ state, services, source }) { const { governorRequestRender } = services.render; @@ -41,6 +42,7 @@ export function createAlprPresentation({ state, services, source }) { } = services.context; const { cachedGroundFloor } = services.groundFloor; + const markers = state.markers; const overlay = createAlprOverlay({ state, services, @@ -48,11 +50,35 @@ export function createAlprPresentation({ state, services, source }) { }); let visibleRecords = []; let selectionStartedAt = 0; - /** Markers still clamped while their floor cell resolves (id -> entity). */ + /** Markers still clamped while their floor cell resolves (id -> carrier). */ const clampedMarkers = new Map(); let floorResolve = null; const floors = createAlprFloorResolver(services.groundFloor); + /** Heights under a camera now, through the renderer's query port. */ + function heightNow(record, against) { + const query = findQuery(state.viewer); + if (!query) return null; + const point = { lon: record.longitude, lat: record.latitude }; + // A miss is tiles still streaming. The markers are no ground: the + // height sees through them. + return against === 'terrain' + ? query.sampleHeightNow(point, { against: 'terrain' }) + : query.sampleHeightNow(point, { exclude: [markers.icons?.id] }); + } + + /** + * The ground under a camera: the rendered surface, else the terrain, + * else the cached floor; null when none is plausible. + */ + function groundHeight(record) { + let height = heightNow(record); + if (!validAlprGroundHeight(height)) height = heightNow(record, 'terrain'); + if (!validAlprGroundHeight(height)) + height = cachedGroundFloor(record.latitude, record.longitude); + return validAlprGroundHeight(height) ? height : null; + } + /** * Marker placement from the cached ground floor (validated mesh or DEM, the * ellipsoidal datum every layer shares). Ground clamping on photoreal tiles @@ -60,14 +86,14 @@ export function createAlprPresentation({ state, services, source }) { * whole-city view stutter while zooming, so it is only the placeholder for * a cell that has not resolved yet. * @param {{latitude:number, longitude:number}} record Camera. - * @returns {{position: Cesium.Cartesian3, clamped: boolean}} Placement. + * @returns {{position: {x:number, y:number, z:number}, clamped: boolean}} Placement. */ function markerPlacement(record) { const floor = cachedGroundFloor(record.latitude, record.longitude); const clamped = !validAlprGroundHeight(floor); return { clamped, - position: Cesium.Cartesian3.fromDegrees( + position: fromDegrees( record.longitude, record.latitude, clamped ? 0 : floor + MARKER_FLOOR_LIFT_M, @@ -136,25 +162,18 @@ export function createAlprPresentation({ state, services, source }) { * @returns {number|null} Count, or null without a scene to project into. */ function countOnScreen() { - const scene = state.viewer?.scene; - const canvas = scene?.canvas; + const canvas = state.viewer?.scene?.canvas; const width = canvas?.clientWidth || canvas?.width; const height = canvas?.clientHeight || canvas?.height; - const camera = state.viewer?.camera; - if (!scene || !width || !height || !camera?.positionWC) return null; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - camera.positionWC, - ); + const query = findQuery(state.viewer); + if (!query || !width || !height) return null; let count = 0; try { - for (const entity of state.dataSource.entities.values) { - const position = entity.position?.getValue?.(Cesium.JulianDate.now()); - if (!position || !occluder.isPointVisible(position)) continue; - const point = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - ); + const horizon = horizonFrom(cameraOf(state.viewer).pose().position); + for (const carrier of markers.values()) { + const position = alprIconPosition(carrier); + if (!position || !horizon.isPointVisible(position)) continue; + const point = query.project(position); if ( point && point.x >= 0 && @@ -171,33 +190,26 @@ export function createAlprPresentation({ state, services, source }) { return count; } - /** Write a marker position, respecting the overlay's pick-target swap. */ - function setMarkerPosition(entity, position, clamped) { - const heightReference = clamped - ? Cesium.HeightReference.CLAMP_TO_GROUND - : Cesium.HeightReference.NONE; - const saved = alprMarkers.read(entity)?.nativeAppearance; - if (saved) { - saved.position = position; - saved.heightReference = heightReference; - } else { - entity.position = position; - entity.billboard.heightReference = heightReference; - } - alprMarkers.write(entity).clamped = clamped; + /** Write a marker's native placement; the canvas anchor is left alone. */ + function setMarkerPosition(carrier, position, clamped) { + const marker = alprMarkers.write(carrier); + marker.position = position; + marker.clamped = clamped; + markers.changed(carrier); } - /** Refresh all native placements, including the appearances held by the canvas. */ + /** Refresh all native placements, including those under canvas badges. */ function refreshMarkerPlacements() { - if (!state.enabled || !state.dataSource) return; + if (!state.enabled || !markers.icons) return; clampedMarkers.clear(); - for (const entity of state.dataSource.entities.values) { + for (const carrier of markers.values()) { const { position, clamped } = markerPlacement( - alprMarkers.read(entity)?.record, + alprMarkers.read(carrier)?.record, ); - setMarkerPosition(entity, position, clamped); - if (clamped) clampedMarkers.set(entity.id, entity); + setMarkerPosition(carrier, position, clamped); + if (clamped) clampedMarkers.set(carrier.id, carrier); } + markers.flush(); resolveClampedFloors(); governorRequestRender('alpr-surface'); } @@ -210,8 +222,8 @@ export function createAlprPresentation({ state, services, source }) { const batch = [...clampedMarkers.values()]; const request = Promise.resolve( floors.resolve( - batch.map((entity) => { - const { record } = alprMarkers.read(entity); + batch.map((carrier) => { + const { record } = alprMarkers.read(carrier); return { lat: record.latitude, lon: record.longitude }; }), ), @@ -220,65 +232,55 @@ export function createAlprPresentation({ state, services, source }) { .then(() => { if (floorResolve !== request) return; floorResolve = null; - if (!state.enabled || !state.dataSource) return; + if (!state.enabled || !markers.icons) return; let moved = false; - for (const entity of batch) { - if (clampedMarkers.get(entity.id) !== entity) continue; - clampedMarkers.delete(entity.id); + for (const carrier of batch) { + if (clampedMarkers.get(carrier.id) !== carrier) continue; + clampedMarkers.delete(carrier.id); const { position, clamped } = markerPlacement( - alprMarkers.read(entity)?.record, + alprMarkers.read(carrier)?.record, ); if (clamped) continue; - setMarkerPosition(entity, position, false); + setMarkerPosition(carrier, position, false); moved = true; } + markers.flush(); if (moved) governorRequestRender('alpr-floor'); // Cells that never resolved stay clamped; later renders retry them. }); floorResolve = request; } - function updateAppearance(entity, selected) { - const color = Cesium.Color.fromCssColorString( - selected ? ALPR_SELECTED_COLOR : ALPR_COLOR, - ); - entity.billboard.image = selected ? SELECTED_IMAGE : MARKER_IMAGE; - entity.billboard.width = entity.billboard.height = selected - ? SELECTED_MARKER_ICON_SIZE - : MARKER_ICON_SIZE; - const labelModel = readEntityRecord(entity)?.labelModel; + function updateAppearance(carrier, selected) { + alprMarkers.write(carrier).selected = selected; + markers.changed(carrier); + const labelModel = readEntityRecord(carrier)?.labelModel; if (labelModel) { - labelModel.accent = color.toCssColorString(); + labelModel.accent = cssRgb(selected ? ALPR_SELECTED_COLOR : ALPR_COLOR); labelModel.leaderAnimationStartedAt = selected ? selectionStartedAt : 0; } } - function markerColor() { - return Cesium.Color.fromCssColorString(ALPR_COLOR); - } - // The horizon rectangle is unstable during low-angle orbits and can exclude // the ground point in the center of the screen. Bound nearby coverage around // that point instead; the camera-to-ground range keeps zoom-out queries capped. function viewportBox(viewer) { - const camera = viewer?.camera; - const canvas = viewer?.scene.canvas; - if (typeof camera?.pickEllipsoid === 'function' && canvas) { + const query = findQuery(viewer); + const canvas = viewer?.scene?.canvas; + if (typeof query?.pickEllipsoid === 'function' && canvas) { const width = canvas.clientWidth || canvas.width; const height = canvas.clientHeight || canvas.height; if (!width || !height) return null; - const focus = camera.pickEllipsoid( - new Cesium.Cartesian2(width / 2, height / 2), - viewer.scene.globe.ellipsoid, - ); + const focus = query.pickEllipsoid(width / 2, height / 2); if (!focus) return null; - const location = Cesium.Cartographic.fromCartesian(focus); - const range = Cesium.Cartesian3.distance(camera.positionWC, focus); + const location = toLonLatH(focus); + if (!location) return null; + const range = distance(cameraOf(viewer).pose().position, focus); const radius = Math.max(1000, 2 * range); - const latitude = Cesium.Math.toDegrees(location.latitude); - const longitude = Cesium.Math.toDegrees(location.longitude); + const latitude = location.lat; + const longitude = location.lon; const latSpan = radius / 111000; - const lonSpan = latSpan / Math.cos(location.latitude); + const lonSpan = latSpan / Math.cos((latitude * Math.PI) / 180); if ( !Number.isFinite(latSpan + lonSpan) || 2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES || @@ -294,14 +296,9 @@ export function createAlprPresentation({ state, services, source }) { }; } // Rectangle-only viewers retain the same bounded-area contract. - const rectangle = viewer?.camera?.computeViewRectangle( - viewer.scene.globe.ellipsoid, - ); + const rectangle = viewer ? cameraOf(viewer).viewRectangle() : null; if (!rectangle) return null; - const south = Cesium.Math.toDegrees(rectangle.south); - const north = Cesium.Math.toDegrees(rectangle.north); - const west = Cesium.Math.toDegrees(rectangle.west); - const east = Cesium.Math.toDegrees(rectangle.east); + const { south, north, west, east } = rectangle; if ( !Number.isFinite(south + north + west + east) || east <= west || @@ -319,7 +316,7 @@ export function createAlprPresentation({ state, services, source }) { overlay.clear(); visibleRecords = []; clampedMarkers.clear(); - if (state.dataSource?.entities) state.dataSource.entities.removeAll(); + markers.clear(); removeEntityContextsForLayer(LAYER_ID); } @@ -369,62 +366,45 @@ export function createAlprPresentation({ state, services, source }) { governorRequestRender('alpr-render'); const visibleIds = new Set(visible.map((record) => record.id)); let changed = false; - state.dataSource.entities.suspendEvents(); - for (const entity of [...state.dataSource.entities.values]) { - if (!visibleIds.has(entity.id)) { - state.dataSource.entities.remove(entity); - clampedMarkers.delete(entity.id); - changed = true; - } + const gone = []; + for (const carrier of markers.values()) + if (!visibleIds.has(carrier.id)) gone.push(carrier.id); + if (gone.length) { + markers.remove(gone); + for (const id of gone) clampedMarkers.delete(id); + changed = true; } removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds }); for (const record of visible) { - const existing = state.dataSource.entities.getById(record.id); + const existing = markers.get(record.id); if (alprMarkers.read(existing)?.record === record) { updateAppearance(existing, record.id === state.selectedId); continue; } - const color = markerColor(); const selected = record.id === state.selectedId; const { position, clamped } = markerPlacement(record); // Direction wedges are painted by the overlay for the nearest cameras. // Native ground-clamped wedges (a ground polyline plus a classification // polygon per camera) cost ~40 ms per frame for 200 downtown cameras on - // photoreal tiles, so markers stay billboards only. - const entityDef = { - id: record.id, - position, - billboard: { - image: selected ? SELECTED_IMAGE : MARKER_IMAGE, - width: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE, - height: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE, - heightReference: clamped - ? Cesium.HeightReference.CLAMP_TO_GROUND - : Cesium.HeightReference.NONE, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - // City-wide views hold hundreds of badges; let them shrink. - scaleByDistance: new Cesium.NearFarScalar( - ...MARKER_SCALE_BY_DISTANCE, - ), - }, - }; - let entity = existing; - // Keep the Cesium entity and its ground-clamping subscription while its - // geometry is unchanged. Updating metadata must not rebuild the marker. - const previous = alprMarkers.read(entity)?.record; - if (!entity) { - entity = state.dataSource.entities.add(entityDef); + // photoreal tiles, so markers stay icons only. + let carrier = existing; + // Keep the marker and its icon while its geometry is unchanged. + // Updating metadata must not rebuild the marker. + const previous = alprMarkers.read(carrier)?.record; + if (!carrier) { + carrier = markers.add(record.id); changed = true; } - const marker = alprMarkers.write(entity); + const marker = alprMarkers.write(carrier); if (!existing) { + marker.position = position; marker.clamped = clamped; } else { if ( previous.latitude !== record.latitude || previous.longitude !== record.longitude ) { - setMarkerPosition(entity, position, clamped); + setMarkerPosition(carrier, position, clamped); marker.canvasPosition = null; marker.displayPosition = null; } @@ -438,16 +418,16 @@ export function createAlprPresentation({ state, services, source }) { } } marker.record = record; - entityRecord(entity).trackedId = record.id; + entityRecord(carrier).trackedId = record.id; // The mapped camera datum has no elevation; it is not the clamped marker's // visual anchor. Only the selected marker samples the rendered surface, - // at most once per second, through Cesium's public height APIs. + // at most once per second, through the renderer's height queries. marker.displayPosition ??= null; - entityRecord(entity).displayPosition = () => marker.displayPosition; - entityRecord(entity).labelModel = { + entityRecord(carrier).displayPosition = () => marker.displayPosition; + entityRecord(carrier).labelModel = { title: alprDisplayId(record), details: alprLabelDetails(record, source), - accent: color.toCssColorString(), + accent: cssRgb(ALPR_COLOR), cardStyle: 'tactical', selected: true, leaderStyle: 'elbow', @@ -457,11 +437,12 @@ export function createAlprPresentation({ state, services, source }) { anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2, anchorRadiusScale: null, }; - updateAppearance(entity, selected); - registerEntityContext(entity, { + updateAppearance(carrier, selected); + registerEntityContext(carrier, { id: record.id, layerId: LAYER_ID, - dataSource: state.dataSource, + // Hidden with the layer: the context store reads its `show`. + dataSource: markers.icons, layerName: 'ALPR Cameras', source: source.attribution?.description || source.label || 'Camera source', @@ -481,64 +462,46 @@ export function createAlprPresentation({ state, services, source }) { }, }); } - state.dataSource.entities.resumeEvents(); if (changed) state.renderRevision += 1; state.onScreen = countOnScreen(); - for (const entity of state.dataSource.entities.values) - if (alprMarkers.read(entity)?.clamped) - clampedMarkers.set(entity.id, entity); + for (const carrier of markers.values()) + if (alprMarkers.read(carrier)?.clamped) + clampedMarkers.set(carrier.id, carrier); resolveClampedFloors(); - const selectedEntity = state.selectedId - ? state.dataSource.entities.getById(state.selectedId) + const selectedCarrier = state.selectedId + ? markers.get(state.selectedId) : null; - if (!selectedEntity) state.selectedId = null; + if (!selectedCarrier) state.selectedId = null; updateSelectedAnchor(); overlay.sync(visible); - if (selectedEntity) services.overlays?.refreshReadout?.(selectedEntity); + markers.flush(); + if (selectedCarrier) services.overlays?.refreshReadout?.(selectedCarrier); // Keep the on-map credit tied to displayed data, not loading or zoom prompts. if (visible.length) presentOnMapCredit(); else hideOnMapCredit(); } function focusNearest() { - const camera = state.viewer?.camera; - if (!state.enabled || !camera?.positionWC || isFollowing(state.viewer)) + if (!state.enabled || !state.viewer || isFollowing(state.viewer)) return false; + const port = cameraOf(state.viewer); + const eye = port.pose().position; let nearest = null, - distance = Infinity; - for (const entity of state.dataSource.entities.values) { - const position = entity.position.getValue(Cesium.JulianDate.now()); - const candidate = Cesium.Cartesian3.distanceSquared( - camera.positionWC, - position, - ); - if (candidate < distance) { - nearest = entity; - distance = candidate; + best = Infinity; + for (const carrier of markers.values()) { + const position = alprIconPosition(carrier); + if (!position) continue; + const candidate = distance(eye, position); + if (candidate < best) { + nearest = carrier; + best = candidate; } } if (!nearest) return false; const record = state.recordById.get(nearest.id); - const location = Cesium.Cartographic.fromDegrees( - record.longitude, - record.latitude, - ); - const heights = heightsFor(state.viewer.scene); - // A miss is tiles still streaming. - let height = state.viewer.scene.sampleHeightSupported - ? heights.now(location, { exclude: [nearest] }) - : null; - if (!validAlprGroundHeight(height) && state.viewer.scene.globe.show) - height = heights.now(location, { against: 'terrain' }); - if (!validAlprGroundHeight(height)) - height = cachedGroundFloor(record.latitude, record.longitude); - const center = Cesium.Cartesian3.fromDegrees( - record.longitude, - record.latitude, - validAlprGroundHeight(height) ? height : 0, - ); + const height = groundHeight(record); + const center = fromDegrees(record.longitude, record.latitude, height ?? 0); if (!selectRecord(nearest.id)) return false; - const port = cameraOf(state.viewer); port.flyToBounds( { center, radius: 30 }, { @@ -555,29 +518,29 @@ export function createAlprPresentation({ state, services, source }) { } function selectRecord(id) { - const entity = state.dataSource?.entities.getById(id); - if (!entity || !state.recordById.has(id)) return false; + const carrier = markers.get(id); + if (!carrier || !state.recordById.has(id)) return false; clearSelection(); state.selectedId = id; selectionStartedAt = globalThis.performance?.now?.() ?? Date.now(); - updateAppearance(entity, true); + updateAppearance(carrier, true); state.lastAnchorSampleAt = 0; - selectEntityContext(entity); + selectEntityContext(carrier); updateSelectedAnchor(); overlay.sync(visibleRecords); + markers.flush(); governorRequestRender('alpr-selection'); return true; } function clearSelection() { - const entity = state.selectedId - ? state.dataSource?.entities.getById(state.selectedId) - : null; + const carrier = state.selectedId ? markers.get(state.selectedId) : null; const record = state.recordById.get(state.selectedId); - if (entity && record) updateAppearance(entity, false); + if (carrier && record) updateAppearance(carrier, false); state.selectedId = null; selectionStartedAt = 0; overlay.sync(visibleRecords); + markers.flush(); clearSelectedEntityContextForLayer(LAYER_ID); governorRequestRender('alpr-selection'); } @@ -589,39 +552,22 @@ export function createAlprPresentation({ state, services, source }) { clearSelection(); return; } - const entity = state.dataSource?.entities.getById(state.selectedId); + const carrier = markers.get(state.selectedId); const record = state.recordById.get(state.selectedId); - const marker = alprMarkers.read(entity); + const marker = alprMarkers.read(carrier); if (marker?.canvasPosition) { marker.displayPosition = marker.canvasPosition; return; } - if (!entity || !record || Date.now() - state.lastAnchorSampleAt < 1000) + if (!carrier || !record || Date.now() - state.lastAnchorSampleAt < 1000) return; state.lastAnchorSampleAt = Date.now(); - const scene = state.viewer.scene; - const location = Cesium.Cartographic.fromDegrees( - record.longitude, - record.latitude, - ); - const heights = heightsFor(scene); - // A miss is tiles still streaming. - let height = scene.sampleHeightSupported - ? heights.now(location, { exclude: [entity] }) - : null; - if (!validAlprGroundHeight(height) && scene.globe.show) - height = heights.now(location, { against: 'terrain' }); - if (!validAlprGroundHeight(height)) - height = cachedGroundFloor(record.latitude, record.longitude); - if (!validAlprGroundHeight(height)) return; - const next = Cesium.Cartesian3.fromDegrees( - record.longitude, - record.latitude, - height, - ); + const height = groundHeight(record); + if (height === null) return; + const next = fromDegrees(record.longitude, record.latitude, height); const shown = marker?.displayPosition; - if (!shown || Cesium.Cartesian3.distance(next, shown) > 0.1) { - alprMarkers.write(entity).displayPosition = next; + if (!shown || distance(next, shown) > 0.1) { + alprMarkers.write(carrier).displayPosition = next; governorRequestRender('alpr-anchor'); } } @@ -631,10 +577,10 @@ export function createAlprPresentation({ state, services, source }) { state.clickSubscription = inputFor(viewer).onClick((event) => { if (!state.enabled) return; // The painted overlay answers first; the scene is picked only if not. - const pickedId = event.pick?.id?.id; + const hit = event.drawHit; const id = overlay.pick(event.screenPosition) || - (typeof pickedId === 'string' ? pickedId : null); + (hit && hit.set === markers.icons?.id ? hit.id : null); if ( id && state.recordById.has(id) && @@ -647,7 +593,6 @@ export function createAlprPresentation({ state, services, source }) { return { initOverlay: () => overlay.init(), destroyOverlay: () => overlay.destroy(), - markerColor, viewportBox, clearRendered, hideOnMapCredit, diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 2a7bc22ba..0e592d6f9 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1193,6 +1193,88 @@ test('the installations layer draws its named markers as outlined point primitiv assert.equal(scene.added.includes(host), false); }); +test('the ALPR layer draws its badges as icons that follow the ground, restyled in place', async () => { + const { alprMarkers, createAlprMarkerSet } = + await import('../../layers/alpr/markerState.js'); + const { MARKER_IMAGE, SELECTED_IMAGE } = + await import('../../layers/alpr/visuals.js'); + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const markers = createAlprMarkerSet(); + markers.attach(part.port.icons({ id: 'alpr-cameras:1:markers' })); + const place = (id, lon, clamped) => { + const carrier = markers.add(id); + Object.assign(alprMarkers.write(carrier), { + position: Cesium.Cartesian3.fromDegrees(lon, 30, clamped ? 0 : 150), + clamped, + }); + return carrier; + }; + const a = place('alpr:a', -97, true); + place('alpr:b', -97.01, false); + markers.flush(); + const [host] = scene.added; + assert.ok(host instanceof Cesium.BillboardCollection); + assert.equal(host.length, 2); + const badge = host.get(0); + assert.equal(badge.id.id, 'alpr:a'); + assert.equal(badge.id.set, 'alpr-cameras:1:markers'); + assert.equal(badge.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND); + assert.equal( + host.get(1).heightReference, + Cesium.HeightReference.NONE, + 'a marker on its floor sits at its height', + ); + assert.equal(badge.image, MARKER_IMAGE); + assert.equal(badge.width, 38); + assert.equal(badge.disableDepthTestDistance, Infinity); + assert.ok( + Cesium.NearFarScalar.equals( + badge.scaleByDistance, + new Cesium.NearFarScalar(500, 1.15, 40000, 0.45), + ), + ); + + // Selection swaps the image on the same billboard: no blink. + alprMarkers.write(a).selected = true; + markers.changed(a); + markers.flush(); + assert.equal(scene.added[0], host); + assert.equal(host.get(0), badge); + assert.equal(badge.image, SELECTED_IMAGE); + assert.equal(badge.width, 60); + + // Under a canvas badge: a faint pick target at the canvas anchor. + const anchor = Cesium.Cartesian3.fromDegrees(-97, 30, 172); + Object.assign(alprMarkers.write(a), { + canvasOwned: true, + canvasPosition: anchor, + }); + markers.changed(a); + markers.flush(); + assert.equal(host.get(0), badge, 'still the same billboard'); + assert.equal(badge.color.alpha, 0.01); + assert.equal(badge.heightReference, Cesium.HeightReference.NONE); + assert.equal(badge.scaleByDistance, undefined); + assert.ok(Cesium.Cartesian3.equalsEpsilon(badge.position, anchor, 0, 1e-6)); + + // A marker that arrives later joins the same collection. + place('alpr:c', -97.02, false); + markers.flush(); + assert.equal(scene.added[0], host, 'appended, not rebuilt'); + assert.equal(host.get(0), badge); + assert.equal(host.length, 3); + + markers.remove(['alpr:b']); + assert.equal(scene.added[0], host); + assert.equal(host.length, 2); + markers.dispose(); + assert.equal(scene.added.length, 0); +}); + /** 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 bc07c4b0f..9149c5cf8 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -40,9 +40,6 @@ "src/input/dispatcher.js", "src/input/sensorPick.js", "src/layers/airQuality/index.js", - "src/layers/alpr/index.js", - "src/layers/alpr/overlay.js", - "src/layers/alpr/presentation.js", "src/layers/cctv/cards.js", "src/layers/cctv/geometry.js", "src/layers/cctv/geometryQueue.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 15b9991f4..d046bed70 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -77,6 +77,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/perimeters', './layers/awareness', './layers/submarine-cables', + './layers/alpr', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs index daa982a37..f0ab932f3 100644 --- a/src/testSupport/fakeCesiumScene.mjs +++ b/src/testSupport/fakeCesiumScene.mjs @@ -9,7 +9,9 @@ * `positionCartographic`; `viewRectangle()` from its * `computeViewRectangle()`, in degrees; events from its own `moveEnd`, * `moveStart` and `changed`. - * - query: `project` (and `projectMany`) through `Cesium.SceneTransforms.worldToWindowCoordinates` + * - query: `sampleHeightNow` through the scene's height service; + * `pickEllipsoid` through the double camera's, when it has one; `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 @@ -18,6 +20,7 @@ */ import * as Cesium from 'cesium'; import { bindRenderer } from '../render/rendererOf.js'; +import { heightsFor } from '../queries/heights.js'; import { fakeDrawPort } from './fakeDrawPort.mjs'; const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z); @@ -51,6 +54,15 @@ export function fakeSceneQuery(viewer) { ); return s ? { x: s.x, y: s.y } : null; }, + /** The double camera's own, when it has one. */ + get pickEllipsoid() { + const camera = cameraOfDouble(viewer); + if (typeof camera?.pickEllipsoid !== 'function') return undefined; + return (x, y) => { + const hit = camera.pickEllipsoid(new Cesium.Cartesian2(x, y)); + return hit ? plain(hit) : null; + }; + }, projectMany(source, out) { for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) { const s = this.project({ @@ -62,6 +74,16 @@ export function fakeSceneQuery(viewer) { out[j + 1] = s ? s.y : Number.NaN; } }, + // The scene's own height service, the surface only where the scene has + // depth support. Unlike the Cesium port it samples terrain without depth + // support too, and sees through nothing (`exclude` is ignored). + sampleHeightNow(point, { against = 'surface' } = {}) { + if (against === 'terrain') + return heightsFor(viewer.scene).now(point, { against: 'terrain' }); + return viewer.scene?.sampleHeightSupported + ? heightsFor(viewer.scene).now(point) + : null; + }, isOccluded(position) { const eye = cameraOfDouble(viewer)?.positionWC; if (!eye) return false;