diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index fbe31383c..d6d955cd6 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2518,6 +2518,7 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", "src/geo/frames.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", @@ -2564,7 +2565,6 @@ "src/data/aircraftRecession.js", "src/data/motionModel.js", "src/layers/cctv/selection.js", - "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", @@ -3459,6 +3459,7 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", @@ -3471,7 +3472,6 @@ "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", - "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", @@ -4422,6 +4422,7 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", @@ -4435,7 +4436,6 @@ "src/layers/cctv/rendering.js", "src/render/cesium/iconOrientation.js", "src/layers/cctv/selection.js", - "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index 7e99fc1f3..84eb09f6c 100644 --- a/scripts/qa-cctv-v2.mjs +++ b/scripts/qa-cctv-v2.mjs @@ -263,32 +263,30 @@ function installRenderFramesHelper(page) { // In-page helper (stringified and re-defined inside each evaluate that needs // it, since functions can't cross the puppeteer boundary): serializes the -// 5 frustum polylines + plane position/orientation/dimensions for a camera -// into plain arrays of numbers, using only the camera's own clock time (no -// Cesium namespace needed — Property.getValue just needs *a* JulianDate, -// and the viewer's own clock.currentTime is a valid live instance of one). +// 5 frustum lines + plane position/orientation/dimensions for a camera +// into plain arrays of numbers, from what the layer reports it draws. const SERIALIZE_GEOM_SRC = ` function serializeGeom(camId) { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap']; const poly = {}; for (const role of roles) { - const ent = viewer.entities.getById('cctv-' + camId + '-' + role); - poly[role] = ent && ent.polyline - ? ent.polyline.positions.getValue(time).map((p) => [p.x, p.y, p.z]) + const line = drawn.coverage['cctv-' + camId + '-' + role]; + poly[role] = line?.positions + ? line.positions.map((p) => [p.x, p.y, p.z]) : null; } - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); + const quad = drawn.planes['cctv-' + camId + '-plane']; let plane = null; - if (planeEnt) { - const pos = planeEnt.position.getValue(time); - const orient = planeEnt.orientation.getValue(time); - const dims = planeEnt.plane.dimensions.getValue(time); + if (quad) { + const pos = quad.center; + const orient = quad.orientation; plane = { position: [pos.x, pos.y, pos.z], orientation: [orient.x, orient.y, orient.z, orient.w], - dimensions: [dims.x, dims.y], + dimensions: [quad.size[0], quad.size[1]], }; } return { poly, plane }; @@ -695,10 +693,9 @@ async function main() { const camera = dataManager.layers .get('cctv') .module.getUIState().activeCamera; - const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`); - const mount = ray?.polyline?.positions.getValue( - viewer.clock.currentTime, - )?.[0]; + const ray = dataManager.layers.get('cctv').module._cctvDrawnForTest() + .coverage[`cctv-${camera.id}-ray-tl`]; + const mount = ray?.positions?.[0]; const height = mount && viewer.scene.globe.ellipsoid.cartesianToCartographic(mount) @@ -849,8 +846,10 @@ async function main() { // source. Assert the migrated surface via the host diagnostics. const diag = window.__gevWorldOverlay?.getDiagnostics?.(); g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - g.planeShow = planeEnt ? planeEnt.show : null; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + g.planeShow = quad ? quad.show : null; return g; })(${JSON.stringify(activeId)})`); @@ -1212,26 +1211,22 @@ async function main() { console.log( 'Checking frame-loop health (placeholder -> frame swap, URL family)...', ); - // The plane's material.image is always defined (placeholder canvas from - // the moment the runtime is created, real frame content painted onto the + // The plane's image is always defined (placeholder canvas from the + // moment the runtime is created, real frame content painted onto the // same canvas/video reference once the fetch resolves) — assert it's // never null/undefined once the runtime exists, i.e. there's no gap where // the plane shows nothing. const materialInfo = await page.evaluate((camId) => { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - const mat = planeEnt?.plane?.material; - const image = mat?.image; - const resolved = - image && typeof image.getValue === 'function' - ? image.getValue(time) - : image; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + const source = quad?.source; + const resolved = source?.video || source?.canvas || source?.image; return { - hasMaterial: !!mat, + hasMaterial: !!source, hasImage: !!resolved, tagName: resolved?.tagName || null, - show: planeEnt?.show, + show: quad?.show, }; }, activeId); record( @@ -1665,14 +1660,12 @@ async function main() { 'Checking viewshed mode (coverage tri-state + color-coded volumes)...', ); const countVolumes = () => - page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - let n = 0; - for (let i = 0; i < prims.length; i++) { - if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) n += 1; - } - return n; - }); + page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().viewsheds.length, + ); const cBeforeViewshed = await readCounters(); const modeAfterSet = await page.evaluate(() => { @@ -1725,26 +1718,26 @@ async function main() { mod.setParams({ coverageMode: 'viewshed' }); }); await sleep(400); - await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - window.__qaViewshedRefs = []; - for (let i = 0; i < prims.length; i++) { - if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) - window.__qaViewshedRefs.push(prims.get(i)); - } - }); + // Volumes are draw-port mesh items: "no churn" is no volume written. + const drawnViewsheds = () => + page.evaluate(() => { + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); + return { ids: drawn.viewsheds, writes: drawn.viewshedWrites }; + }); + const viewshedsBefore = await drawnViewsheds(); await sleep(8000); - const viewshedIdle = await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - const now = []; - for (let i = 0; i < prims.length; i++) { - if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) now.push(prims.get(i)); - } - const before = window.__qaViewshedRefs || []; - const sameCount = now.length === before.length; - const sameIdentity = sameCount && before.every((p) => now.includes(p)); - return { sameCount, sameIdentity, count: now.length }; - }); + const viewshedsAfter = await drawnViewsheds(); + const viewshedIdle = (() => { + const sameCount = + viewshedsAfter.ids.length === viewshedsBefore.ids.length; + const sameIdentity = + sameCount && + viewshedsBefore.ids.every((id) => viewshedsAfter.ids.includes(id)) && + viewshedsAfter.writes === viewshedsBefore.writes; + return { sameCount, sameIdentity, count: viewshedsAfter.ids.length }; + })(); const cAfterViewshed = await readCounters(); const lateFloorSamples = cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight; diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index e5258360a..a3d6aca74 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -81,7 +81,7 @@ import { IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; -import { cctvPicks } from '../layers/cctv/pickState.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; const ASPECT = 16 / 9; @@ -277,15 +277,9 @@ test('default COVERAGE refresh materializes the active and visible camera frustu coverageEntities: [], projection: null, })); - const inserted = []; - const viewer = { - entities: { - add(entity) { - inserted.push(entity); - return entity; - }, - }, - }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + const inserted = () => draw.find('cctv:')?.items ?? new Map(); const activeRecord = records.at(-1); try { @@ -300,10 +294,16 @@ test('default COVERAGE refresh materializes the active and visible camera frustu (record) => record.coverageEntities.length > 0, ); assert.equal( - inserted.length, + inserted().size, 14 * 5, 'default COVERAGE ON builds the 14-camera visible cohort', ); + assert.ok( + [...inserted().keys()].every((id) => + /^cctv-cam-\d+-(ray-..|cap)$/.test(id), + ), + 'coverage lines keep the cctv-- ids', + ); assert.equal(materialized.length, 14); assert.equal( activeRecord.coverageEntities.length, @@ -319,7 +319,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu ...records[0], camera: { ...records[0].camera, id: 'projection-only' }, coverageEntities: [], - projection: { planeEntity: { show: false } }, + projection: { plane: { show: false } }, }; _setCctvCoverageStateForTest({ viewer, @@ -334,8 +334,15 @@ test('default COVERAGE refresh materializes the active and visible camera frustu projectionOnly.coverageEntities.every((entity) => entity.show), 'COVERAGE OFF keeps the active projection frustum materialized and visible', ); + assert.ok( + projectionOnly.coverageEntities.every( + (entity) => inserted().get(entity.id)?.show === true, + ), + 'and draws it', + ); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); @@ -348,7 +355,8 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ const idleVideo = record('idle-hls', 'hls'); const idleStill = record('idle-image', 'image'); const activeVideo = record('active-hls', 'hls'); - const viewer = { entities: { add: (entity) => entity } }; + const viewer = {}; + const { unbind } = bindFakeDraw(viewer); try { // Disabled keeps the active video camera from opening a real projection; @@ -376,6 +384,7 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ assert.equal(icons.scale(icons.row(idleVideo.camera.id)), 1); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); @@ -679,15 +688,15 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou activationDone: true, probeClampRangeM: 105, coverageEntities: [{ show: true }, { show: true }], - projection: { planeEntity: { show: true } }, - viewshedPrimitive: viewshedA, + projection: { plane: { show: true } }, + viewshedVolume: viewshedA, }, { camera: { id: 'b' }, activationDone: true, probeClampRangeM: 146, projection: null, - viewshedPrimitive: viewshedB, + viewshedVolume: viewshedB, }, ]; const destroyed = []; @@ -696,7 +705,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou records, (record) => { destroyed.push(record.camera.id); - record.viewshedPrimitive = null; + record.viewshedVolume = null; }, 'a', ); @@ -707,10 +716,10 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou ), [false, false], ); - assert.equal(records[0].projection.planeEntity.show, false); + assert.equal(records[0].projection.plane.show, false); assert.deepEqual(destroyed, ['a', 'b']); - assert.equal(records[0].viewshedPrimitive, null); - assert.equal(records[1].viewshedPrimitive, null); + assert.equal(records[0].viewshedVolume, null); + assert.equal(records[1].viewshedVolume, null); assert.deepEqual( records.map((record) => record.probeClampRangeM), [null, null], @@ -728,7 +737,8 @@ test('real active monitor plane owns one protected host label and no native labe setVisible: (...args) => calls.push(['visible', ...args]), clearSource: (...args) => calls.push(['clear', ...args]), }; - const viewer = { entities: new Cesium.EntityCollection() }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); const record = { camera: { ...UNCLAMPED_CAMERA, @@ -752,17 +762,23 @@ test('real active monitor plane owns one protected host label and no native labe }); refreshCoverageStyles(); + assert.ok(runtime.plane, 'runtime guard requires a real monitor plane'); + const planes = draw.find('cctv:') + ? [...draw.sets.values()].filter((set) => set.kind === 'quads') + : []; + assert.equal(planes.length, 1, 'the plane draws as a quad'); + const quad = planes[0].items.get(`cctv-${record.camera.id}-plane`); + assert.ok(quad, 'under its cctv--plane id'); + assert.equal(quad.alpha, 0.95); + assert.deepEqual(quad.size, [ + record.frustumGeometry.halfW * 2, + record.frustumGeometry.halfH * 2, + ]); + assert.ok(quad.outline, 'with its outline'); + assert.equal(quad.meta.cameraId, record.camera.id); assert.ok( - runtime.planeEntity, - 'runtime guard requires a real monitor-plane entity', - ); - assert.equal(runtime.planeEntity.label, undefined); - assert.ok( - runtime.planeEntity.plane, - 'monitor plane geometry remains native', - ); - assert.ok( - viewer.entities.values.every((entity) => entity.label === undefined), + [...draw.sets.values()].every((set) => set.kind !== 'labels'), + 'and no native label', ); const publication = calls.find( ([type, sourceId]) => @@ -778,7 +794,8 @@ test('real active monitor plane owns one protected host label and no native labe assert.equal(entry.position(), runtime.labelPosition); assert.equal(entry.protected, true); assert.equal(entry.paintLane, 'selected'); - assert.equal(runtime.planeEntity.show, true); + assert.equal(runtime.plane.show, true); + assert.equal(quad.show, true, 'shown once projected'); const cachedPosition = runtime.labelPosition; record.frustumPositions.label = Cesium.Cartesian3.add( @@ -806,7 +823,8 @@ test('real active monitor plane owns one protected host label and no native labe showProjection: false, }); refreshCoverageStyles(); - assert.equal(runtime.planeEntity.show, false); + assert.equal(runtime.plane.show, false); + assert.equal(planes[0].items.get(quad.id).show, false); assert.deepEqual(calls.slice(-2), [ ['clear', 'cctv-projection'], ['visible', 'cctv-projection', false], @@ -814,6 +832,7 @@ test('real active monitor plane owns one protected host label and no native labe } finally { _setCctvCoverageStateForTest({ enabled: false }); _setCctvOverlayHostForTest(); + unbind(); } }); @@ -1002,8 +1021,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat // ─── Empty-space deselection and stable null-active state ────────────────── function makeDeselectViewer() { - return { - entities: new Cesium.EntityCollection(), + const viewer = { isDestroyed: () => false, trackedEntity: { id: 'sibling-track-owner' }, camera: { @@ -1028,6 +1046,9 @@ function makeDeselectViewer() { requestRender() {}, }, }; + // The layer's lines and plane draw through this. + viewer.draw = bindFakeDraw(viewer).draw; + return viewer; } function makeDeselectRecord(id, index = 0) { @@ -1118,19 +1139,23 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and }); test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => { - const ownedCoverageEntity = { id: 'cctv-shared-id-cap' }; - cctvPicks.write(ownedCoverageEntity).cameraId = 'shared-id'; - const strayEntity = { id: 'cctv-shared-id-stray' }; - cctvPicks.write(strayEntity).cameraId = 'shared-id'; - const record = { - ...makeDeselectRecord('shared-id'), - coverageEntities: [ownedCoverageEntity], - }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + const record = makeDeselectRecord('shared-id'); _setCctvCoverageStateForTest({ + viewer, records: [record], activeCameraId: 'shared-id', }); try { + refreshCoverageStyles(); + const coverage = [...draw.sets.values()].find( + (set) => set.kind === 'lines' && set.spec.id.startsWith('cctv:'), + ); + assert.ok(coverage.items.has('cctv-shared-id-cap')); + const lineHit = (set, id) => ({ + id: { set, id, meta: { cameraId: 'shared-id' } }, + }); assert.equal( _extractPickedCameraIdForTest({ id: 'shared-id', @@ -1154,9 +1179,18 @@ test('CCTV camera extraction requires layer ownership, not a colliding sibling I 'a sibling Entity with the same canonical ID cannot activate CCTV', ); assert.equal( - _extractPickedCameraIdForTest({ id: ownedCoverageEntity }), + _extractPickedCameraIdForTest( + lineHit(coverage.spec.id, 'cctv-shared-id-cap'), + ), 'shared-id', - 'an exact stored CCTV coverage Entity retains activation ownership', + 'a coverage line the record draws retains activation ownership', + ); + assert.equal( + _extractPickedCameraIdForTest( + lineHit('sibling:1:lines', 'cctv-shared-id-cap'), + ), + null, + "a sibling set's item with a CCTV id and meta cannot activate CCTV", ); assert.equal( _extractPickedCameraIdForTest({ @@ -1169,12 +1203,15 @@ test('CCTV camera extraction requires layer ownership, not a colliding sibling I 'a sibling cannot impersonate CCTV by copying its property shape', ); assert.equal( - _extractPickedCameraIdForTest({ id: strayEntity }), + _extractPickedCameraIdForTest( + lineHit(coverage.spec.id, 'cctv-shared-id-stray'), + ), null, - 'a camera id alone is not ownership: the record must hold the entity', + 'a camera id alone is not ownership: the record must draw the item', ); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); @@ -1228,7 +1265,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose assert.equal(publications.at(-1).activeCameraId, null); assert.equal(publications.at(-1).activeCamera, null); assert.equal(publications.at(-1).enabled, true); - assert.equal(runtime.planeEntity.show, false); + assert.equal(runtime.plane.show, false); assert.equal(record.probeClampRangeM, null); assert.equal(record.activationDone, false); assert.deepEqual(viewer.camera.positionWC, pose.positionWC); diff --git a/src/layers/cctv/calibration.js b/src/layers/cctv/calibration.js index 2603c843b..874c4ca36 100644 --- a/src/layers/cctv/calibration.js +++ b/src/layers/cctv/calibration.js @@ -261,6 +261,8 @@ export function createCalibration({ // §9.1: touching range takes manual control — clear the activation clamp. if ('rangeScale' in patch) { record.probeClampRangeM = null; + // A probe still to answer no longer lands. + record.probeToken = (record.probeToken || 0) + 1; } const anchorMoved = calibrationPatchMovesAnchor(patch); if (options.transient === true && anchorMoved) { diff --git a/src/layers/cctv/drawSets.js b/src/layers/cctv/drawSets.js new file mode 100644 index 000000000..c199d1d83 --- /dev/null +++ b/src/layers/cctv/drawSets.js @@ -0,0 +1,188 @@ +/** + * @module layers/cctv/drawSets + * @description The CCTV layer's draw sets: the frustum wireframes + * (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the + * active camera's monitor plane (`plane`, a quad), made through the draw + * port of the viewer the layer is on. They are made when first drawn into + * and made again on another viewer. Item ids keep the layer's + * `cctv--` scheme the shared pick registry reads, and each + * line's and plane's `meta.cameraId` names its camera (volumes are never + * picked and carry none). + * + * Coverage lines and the plane are written from handles the layer keeps + * (a record's `coverageEntities`, a projection runtime's `plane`): plain + * objects the layer changes and then writes, only what changed reaching + * the set. + */ +import { drawOf } from '../../render/rendererOf.js'; + +/** Layer instances, for set ids unique to each. */ +let instances = 0; + +/** A line handle's item, or null for a handle that names no line yet. */ +function lineItemOf(handle) { + if (!handle?.id || !Array.isArray(handle.positions)) return null; + const color = handle.color; + return { + id: handle.id, + positions: handle.positions, + widthPx: handle.widthPx, + // As a polyline entity runs: along the ellipsoid between its positions. + mode: 'geodesic', + style: handle.dashed + ? { kind: 'dash', color, length: 16, pattern16: 255 } + : { kind: 'solid', color }, + depthFailColor: handle.depthFailColor ?? null, + meta: { cameraId: handle.cameraId }, + show: handle.show !== false, + }; +} + +/** What a line item draws, as a key: an unchanged key is not written. */ +const lineKey = (item) => + [ + item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'), + item.widthPx, + item.style.kind, + item.style.color.join(','), + item.depthFailColor ? item.depthFailColor.join(',') : '', + item.show, + ].join('|'); + +/** The plane handle's quad item. */ +function quadItemOf(plane) { + return { + id: plane.id, + center: plane.center, + orientation: plane.orientation, + size: plane.size, + source: plane.source, + alpha: plane.alpha, + outline: plane.outline, + meta: { cameraId: plane.cameraId }, + show: plane.show === true, + }; +} + +export function createDrawSets({ state: layerState }) { + /** The live sets and the viewer they draw on, or null. */ + let current = null; + /** Viewshed volumes written, ever (the QA harness checks for churn). */ + let volumeWrites = 0; + + /** The layer's sets on its viewer now, made if need be; null with none. */ + function sets() { + const viewer = layerState._viewer; + if (!viewer) return null; + if (current?.viewer === viewer) return current; + dispose(); + const draw = drawOf(viewer); + const n = ++instances; + current = { + viewer, + coverage: draw.lines({ id: `cctv:${n}:coverage` }), + viewshed: draw.meshes({ id: `cctv:${n}:viewshed`, pickable: false }), + plane: draw.quads({ id: `cctv:${n}:plane` }), + // What each line item was last written as, by id. + lineKeys: new Map(), + }; + return current; + } + + /** The live sets, without making them. */ + const live = () => + current && current.viewer === layerState._viewer ? current : null; + + /** Let the sets go (the layer leaves its viewer, or moves to another). */ + function dispose() { + if (!current) return; + for (const set of [current.coverage, current.viewshed, current.plane]) + try { + set.dispose(); + } catch { + // Its viewer went first. + } + current = null; + } + + /** The ids of the sets that draw the layer's lines and plane. */ + function pickableSetIds() { + const s = live(); + return s ? [s.coverage.id, s.plane.id] : []; + } + + /** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */ + function roleOfSet(setId) { + const s = live(); + if (!s) return null; + if (setId === s.coverage.id) return 'coverage'; + if (setId === s.plane.id) return 'plane'; + return null; + } + + /** Write line handles that changed since they were last written. */ + function writeLines(handles) { + if (!handles?.length) return; + const s = handles.some((h) => h?.id) ? sets() : null; + if (!s) return; + const changed = []; + for (const handle of handles) { + const item = lineItemOf(handle); + if (!item) continue; + const key = lineKey(item); + if (s.lineKeys.get(item.id) === key) continue; + s.lineKeys.set(item.id, key); + changed.push(item); + } + if (changed.length) s.coverage.upsert(changed); + } + + /** Take every line out. */ + function clearLines() { + const s = live(); + if (!s) return; + s.coverage.clear(); + s.lineKeys.clear(); + } + + /** Write the plane handle as it is now. */ + function writePlane(plane) { + if (!plane?.id) return; + sets()?.plane.upsert([quadItemOf(plane)]); + } + + /** Take a plane out. */ + function removePlane(plane) { + if (plane?.id) live()?.plane.remove([plane.id]); + } + + /** Write a viewshed volume. */ + function writeVolume(item) { + const s = sets(); + if (!s) return; + s.viewshed.upsert([item]); + volumeWrites += 1; + } + + /** Take a viewshed volume out. */ + function removeVolume(id) { + if (id) live()?.viewshed.remove([id]); + } + + /** How many viewshed volumes were written, for the QA harness. */ + const volumeWritesForTest = () => volumeWrites; + + return { + sets, + dispose, + pickableSetIds, + roleOfSet, + writeLines, + clearLines, + writePlane, + removePlane, + writeVolume, + removeVolume, + volumeWritesForTest, + }; +} diff --git a/src/layers/cctv/drawSets.test.mjs b/src/layers/cctv/drawSets.test.mjs new file mode 100644 index 000000000..d17dc92d1 --- /dev/null +++ b/src/layers/cctv/drawSets.test.mjs @@ -0,0 +1,110 @@ +// The CCTV layer's draw sets: lines written only as they change, dashed for +// an estimated bearing, the depth-fail colour passed as it is; the sets made +// again on another viewer and let go on dispose. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createDrawSets } from './drawSets.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; + +const line = (id, fields = {}) => ({ + id, + cameraId: 'cam', + role: 'edge', + positions: [ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ], + widthPx: 1.2, + color: [0.1, 0.2, 0.3, 0.4], + dashed: false, + depthFailColor: null, + show: true, + ...fields, +}); + +test('lines are written as they change, and drawn as their handles say', () => { + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + const drawSets = createDrawSets({ state: { _viewer: viewer } }); + try { + const a = line('cctv-cam-ray-tl'); + const b = line('cctv-cam-cap', { role: 'cap' }); + drawSets.writeLines([a, b]); + const coverage = draw.find('cctv:'); + assert.equal(coverage.kind, 'lines'); + assert.equal(coverage.writes, 1); + assert.deepEqual(coverage.items.get(a.id), { + id: a.id, + positions: a.positions, + widthPx: 1.2, + mode: 'geodesic', + style: { kind: 'solid', color: a.color }, + depthFailColor: null, + meta: { cameraId: 'cam' }, + show: true, + }); + + drawSets.writeLines([a, b]); + assert.equal(coverage.writes, 1, 'unchanged handles write nothing'); + + b.dashed = true; + b.depthFailColor = [1, 1, 1, 0.2]; + drawSets.writeLines([a, b]); + assert.equal(coverage.writes, 2); + const cap = coverage.items.get(b.id); + assert.deepEqual(cap.style, { + kind: 'dash', + color: b.color, + length: 16, + pattern16: 255, + }); + assert.deepEqual(cap.depthFailColor, [1, 1, 1, 0.2]); + + assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage'); + assert.equal(drawSets.roleOfSet('other:1:lines'), null); + + drawSets.clearLines(); + assert.equal(coverage.items.size, 0); + drawSets.writeLines([a]); + assert.ok(coverage.items.has(a.id), 'a cleared line is written again'); + } finally { + unbind(); + } +}); + +test('another viewer gets sets of its own; dispose lets them go', () => { + const first = {}; + const second = {}; + const one = bindFakeDraw(first); + const two = bindFakeDraw(second); + const state = { _viewer: first }; + const drawSets = createDrawSets({ state }); + try { + const a = line('cctv-cam-ray-tl'); + drawSets.writeLines([a]); + drawSets.writeVolume({ id: 'cctv-cam-viewshed' }); + const old = one.draw.find('cctv:'); + assert.equal(drawSets.volumeWritesForTest(), 1); + + state._viewer = second; + assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet'); + drawSets.writeLines([a]); + assert.ok(old.disposed, 'the old viewer’s sets are let go'); + const now = two.draw.find('cctv:'); + assert.ok(now.items.has(a.id), 'the line is written anew'); + const [coverage, plane] = drawSets.pickableSetIds(); + assert.equal(two.draw.set(coverage).kind, 'lines'); + assert.equal(two.draw.set(plane).kind, 'quads'); + assert.equal(drawSets.roleOfSet(plane), 'plane'); + + drawSets.dispose(); + assert.ok( + [...two.draw.sets.values()].every((set) => set.disposed), + 'every set is let go', + ); + assert.equal(drawSets.roleOfSet(coverage), null); + } finally { + one.unbind(); + two.unbind(); + } +}); diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 0c1812127..eb9cdeeef 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -106,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) { * Blits the latest projection canvas into the next of two alternating * offscreen buffer canvases and returns it (H5). * - * Two buffers are required because Cesium's Material image path re-uploads a - * canvas texture only when the uniform receives a NEW object reference — - * redrawing the same canvas in place is invisible to the GPU. Alternating + * Two buffers are required because the plane re-uploads a canvas texture + * only when it is given a NEW canvas — redrawing the same canvas in place + * is invisible to the GPU. Alternating * references forces a texture recreate, which at <=1Hz and 1080p is cheap. * * @param {Object} runtime - Projection runtime with `.canvas`. @@ -139,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) { * Pushes fresh pixels into the monitor plane material. Called every * projection tick. * - * Video feeds are skipped entirely — their HTMLVideoElement uniform is - * updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap + * Video feeds are skipped entirely — the renderer reads their + * HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap * the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS. * * @param {Object} record - Camera record with an initialized projection runtime. @@ -156,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) { ) return; - const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial); + const planeShowing = !!runtime.plane?.show; if (!planeShowing) return; // Only swap when the canvas content actually changed since the last swap. @@ -170,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) { if (!buffer) return; runtime.lastTextureSwapAt = now; runtime.lastSwappedCanvasStamp = runtime.canvasStamp; - runtime.planeMaterial.image = buffer; + parts.projection.setPlaneSource(runtime, { canvas: buffer }); } /** @@ -346,7 +346,7 @@ export function createFrames({ state: layerState, services, parts, source }) { // camera republished once in 5 minutes, an Austin one not at all. // Redrawing regardless bumped canvasStamp, which forced a buffer swap // and a fresh 1920x1080 texture upload; the plane renders its white - // base color (planeMaterial color = WHITE, alpha .95) for the frame or + // base color (white, alpha .95) for the frame or // two Cesium needs to rebind, which IS the periodic white flash from the // owner field tests (2026-07-04 and 2026-07-30). const fit = fitToProjection( diff --git a/src/layers/cctv/geometry.js b/src/layers/cctv/geometry.js index d596db5b5..fed671e45 100644 --- a/src/layers/cctv/geometry.js +++ b/src/layers/cctv/geometry.js @@ -314,30 +314,10 @@ export function createGeometry({ state: layerState, services, parts, source }) { record.position = positions.mount; record.camera.absoluteHeightM = geometry.mount.alt; parts.rendering.moveCameraIcon(record); + record.groundAltM = groundAltM; if (record.coverageEntities?.length >= 5) { - record.coverageEntities[0].polyline.positions = [ - positions.mount, - positions.tl, - ]; - record.coverageEntities[1].polyline.positions = [ - positions.mount, - positions.tr, - ]; - record.coverageEntities[2].polyline.positions = [ - positions.mount, - positions.br, - ]; - record.coverageEntities[3].polyline.positions = [ - positions.mount, - positions.bl, - ]; - record.coverageEntities[4].polyline.positions = [ - positions.tl, - positions.tr, - positions.br, - positions.bl, - positions.tl, - ]; + parts.rendering.placeCoverageLines(record.coverageEntities, positions); + parts.drawSets.writeLines(record.coverageEntities); } // A live viewshed volume tracks its wireframe: rebuild from the SAME fresh // positions (weld invariant). Only records currently showing a volume pay @@ -345,7 +325,7 @@ export function createGeometry({ state: layerState, services, parts, source }) { // Tint derives from the live active id, not the cached viewshedActiveTint — // during an activation switch this runs BEFORE refreshCoverageStyles, and // the cache is stale for exactly that window. - if (record.viewshedPrimitive) { + if (record.viewshedVolume) { parts.rendering.rebuildViewshedVolume( record, record.camera.id === layerState._activeCameraId, @@ -420,11 +400,9 @@ export function createGeometry({ state: layerState, services, parts, source }) { record.groundMeshSampleRequestCount = (record.groundMeshSampleRequestCount || 0) + 1; const eye = parts.model.eyePose(); - const excludeObjects = [...(record.coverageEntities || [])]; - if (record.projection?.planeEntity) - excludeObjects.push(record.projection.planeEntity); - sampleMeshFloorCells(layerState._viewer?.scene, [point], { - excludeObjects: excludeObjects.filter(Boolean), + // The layer's own lines and plane are not ground; named all the same. + sampleMeshFloorCells(layerState._viewer, [point], { + sets: parts.drawSets.pickableSetIds(), viewerLat: eye ? eye.lat : undefined, viewerLon: eye ? eye.lon : undefined, }); @@ -526,7 +504,7 @@ export function createGeometry({ state: layerState, services, parts, source }) { /** * §9.1 activation obstruction probe (LOCKED owner decision): on camera - * ACTIVATION only, fire ONE scene.pickFromRay along the frustum axis + * ACTIVATION only, cast ONE ray against the scene along the frustum axis * (mount → cap-center direction). If it hits the tiles closer than the pose * range, clamp the plane's effective range just short of the first hit so the * "big and dramatic" true end cap never clips into downtown buildings. @@ -535,28 +513,58 @@ export function createGeometry({ state: layerState, services, parts, source }) { * never per-frame (the zero-raycast invariant applies to steady state). The * per-camera range slider overrides the clamp: a user-set rangeScale skips the * probe entirely. Probe failure/miss keeps the unclamped range. + * + * The cast is made now, against the scene as it is, and answers a + * microtask later: the clamp then lands by rewriting the geometry from the + * ground it was last written at, before the next frame draws. A newer + * activation, or the camera's deactivation, drops an answer still to come. * @param {Object} record - Camera record being activated. + * @returns {Promise} Settled once the clamp (if any) has landed. */ function runActivationObstructionProbe(record) { record.probeClampRangeM = null; - if (!parts.rendering.canPickFromRay()) return; + const token = (record.probeToken = (record.probeToken || 0) + 1); + const viewer = layerState._viewer; + if (!parts.rendering.canPickFromRay()) return Promise.resolve(); const camera = record.camera; const rangeScale = parts.calibration.normalizeCalibration( camera.calibration, ).rangeScale; - if (Math.abs(rangeScale - 1) > 0.0001) return; // slider overrides the clamp + // The slider overrides the clamp. + if (Math.abs(rangeScale - 1) > 0.0001) return Promise.resolve(); try { const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM; const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt); const { dir } = frustumFrameEcef(camera, mountPos); - // The rendering part sees through everything the layer draws. - const hit = parts.rendering.obstructionHit(mountPos, dir); - if (!hit?.position) return; - const dist = distance(mountPos, hit.position); - record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist); + // The cast sees through everything the layer draws. + return Promise.resolve(parts.rendering.obstructionHit(mountPos, dir)) + .then((hit) => { + if (!hit || record.probeToken !== token) return; + if (record.camera.id !== layerState._activeCameraId) return; + // A layer torn down or re-initialised since (another viewer, or + // a new record for the same camera) is not the one it asked for. + if (layerState._viewer !== viewer) return; + if (layerState._recordById?.get(record.camera.id) !== record) return; + const dist = distance(mountPos, hit); + const clamp = activationProbeClampRange(camera.rangeM, dist); + if (!Number.isFinite(clamp)) return; + record.probeClampRangeM = clamp; + if (Number.isFinite(record.groundAltM)) + applyFrustumGeometry(record, record.groundAltM); + // The activation asked for the ground under the unclamped plane's + // footprint; the clamped plane's is asked for now, and the layer + // restyles and tells its listeners, as that answer will. + void parts.ground.resolveFootprintGround(record); + parts.rendering.refreshCoverageStyles(); + parts.presentation.notifyListeners(); + }) + .catch(() => { + // probe failure → keep the unclamped range + }); } catch { // probe failure → keep the unclamped range + return Promise.resolve(); } } @@ -569,6 +577,7 @@ export function createGeometry({ state: layerState, services, parts, source }) { */ function clearProbeClampOnDeactivation(record, rewriteGeometry) { + if (record) record.probeToken = (record.probeToken || 0) + 1; if (!record || !Number.isFinite(record.probeClampRangeM)) return false; record.probeClampRangeM = null; rewriteGeometry?.(record); diff --git a/src/layers/cctv/geometry.test.mjs b/src/layers/cctv/geometry.test.mjs index 7cd8962c0..9152183d5 100644 --- a/src/layers/cctv/geometry.test.mjs +++ b/src/layers/cctv/geometry.test.mjs @@ -92,3 +92,91 @@ test('the frustum axis and plane orientation match the renderer transforms exact assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]); } }); + +test('the activation probe clamps the range once its ray answers, unless the camera moved on', async () => { + const { createRendering } = await import('./rendering.js'); + const p = {}; + const state = { _activeCameraId: 'cam', _viewer: {} }; + const context = { + state, + services: { ground: {}, mesh: {}, focus: {} }, + parts: p, + }; + const written = []; + const footprints = []; + let restyles = 0; + let notices = 0; + let hitAtM = 80; + p.model = createModel(context); + p.geometry = createGeometry(context); + p.rendering = { + ...createRendering(context), + canPickFromRay: () => true, + refreshCoverageStyles: () => (restyles += 1), + // The first surface `hitAtM` metres along the axis. + obstructionHit: async (origin, direction) => ({ + x: origin.x + direction.x * hitAtM, + y: origin.y + direction.y * hitAtM, + z: origin.z + direction.z * hitAtM, + }), + }; + p.calibration = { normalizeCalibration: () => ({ rangeScale: 1 }) }; + p.ground = { + groundAltFor: () => 100, + resolveFootprintGround: async (r) => + footprints.push(p.geometry.footprintPose(r)), + }; + p.presentation = { notifyListeners: () => (notices += 1) }; + p.drawSets = { writeLines: (lines) => written.push(lines) }; + p.projection = { updatePlanePlacement() {} }; + const record = { + camera: { + id: 'cam', + lon: -97.74, + lat: 30.27, + headingDeg: 90, + pitchDeg: -10, + fovDeg: 60, + rangeM: 200, + mountHeightM: 8, + }, + coverageEntities: [], + }; + state._recordById = new Map([['cam', record]]); + p.geometry.applyFrustumGeometry(record, 100); + assert.equal(record.frustumGeometry.rangeM, 200, 'unclamped at first'); + + const landed = p.geometry.runActivationObstructionProbe(record); + assert.equal(record.probeClampRangeM, null, 'the answer is still to come'); + await landed; + const clamp = p.geometry.activationProbeClampRange(200, 80); + assert.ok(Math.abs(record.probeClampRangeM - clamp) < 1e-6); + assert.ok( + Math.abs(record.frustumGeometry.rangeM - clamp) < 1e-6, + 'the geometry is rewritten at the clamp, from the ground it had', + ); + assert.equal(record.frustumGeometry.mount.alt, 108); + assert.deepEqual( + footprints, + [p.geometry.footprintPose(record)], + "the clamped plane's footprint ground is asked for", + ); + assert.ok( + Math.abs(footprints[0].rangeM - clamp) < 1e-6, + 'at the clamped pose', + ); + assert.deepEqual([restyles, notices], [1, 1]); + + // A probe whose camera is deactivated before it answers lands nothing. + hitAtM = 50; + const stale = p.geometry.runActivationObstructionProbe(record); + p.geometry.clearProbeClampOnDeactivation(record, () => {}); + await stale; + assert.equal(record.probeClampRangeM, null); + + // Nor does one whose record a re-init replaced for the same camera. + const replaced = p.geometry.runActivationObstructionProbe(record); + state._recordById = new Map([['cam', { ...record }]]); + await replaced; + assert.equal(record.probeClampRangeM, null); +}); diff --git a/src/layers/cctv/index.js b/src/layers/cctv/index.js index 120b662b0..f8ff4d126 100644 --- a/src/layers/cctv/index.js +++ b/src/layers/cctv/index.js @@ -18,6 +18,7 @@ import { createHealth } from './health.js'; import { createControls } from './controls.js'; import { createIngestion } from './ingestion.js'; import { createState } from './state.js'; +import { createDrawSets } from './drawSets.js'; /** Construct one layer with its own scene state and supplied application services. */ export function createCctvLayer({ services, source }) { @@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) { const state = createState({ services }); const parts = {}; const context = { state, services, parts, source }; + parts.drawSets = createDrawSets(context); parts.calibration = createCalibration(context); parts.testing = createTesting(context); parts.projection = createProjection(context); diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index e8e0d7ae6..223cb0093 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -157,6 +157,9 @@ export function createLifecycle({ // Idempotent — also covers a re-init without a prior destroy(). parts.cards.teardownAmbientCards(); parts.projection.clearProjectionOverlay(); + // An activation probe still to answer lands on none of these records. + for (const record of layerState._records || []) + if (record) record.probeToken = (record.probeToken || 0) + 1; layerState._records = []; layerState._recordById = new Map(); layerState._viewRecords = []; @@ -317,7 +320,7 @@ export function createLifecycle({ viewshedColors: viewshedColors( cameraHue(hueIndexById.get(camera.id) ?? 0), ), - viewshedPrimitive: null, + viewshedVolume: null, viewshedActiveTint: false, }; layerState._records.push(record); @@ -582,6 +585,7 @@ export function createLifecycle({ parts.cards.teardownAmbientCards(); parts.geometry.destroyCoverageEntities(); parts.rendering.destroyCameraIcons(); + parts.drawSets.dispose(); clearRuntimeState(); layerState._viewer = null; layerState._enabled = false; diff --git a/src/layers/cctv/pickState.js b/src/layers/cctv/pickState.js deleted file mode 100644 index e24012d97..000000000 --- a/src/layers/cctv/pickState.js +++ /dev/null @@ -1,7 +0,0 @@ -import { createEntityStore } from '../../data/entityRecords.js'; - -/** - * The camera a picked coverage ray or projection plane belongs to: `cameraId` - * is the upstream camera id. Gizmo entities never get one. - */ -export const cctvPicks = createEntityStore(); diff --git a/src/layers/cctv/projection.js b/src/layers/cctv/projection.js index 3ff34407d..852a41395 100644 --- a/src/layers/cctv/projection.js +++ b/src/layers/cctv/projection.js @@ -1,16 +1,30 @@ import { attachCctvVideo } from './videoPlayback.js'; -import * as Cesium from 'cesium'; import { CCTV_PROJECTION_OVERLAY_SOURCE_ID, CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS, - PLANE_OUTLINE_COLOR as PLANE_OUTLINE_RGBA, + PLANE_OUTLINE_COLOR, PROJECTION_CANVAS_WIDTH, PROJECTION_CANVAS_HEIGHT, } from './policy.js'; -import { cctvPicks } from './pickState.js'; -import { toColor } from '../../render/cesium/draw.js'; -const PLANE_OUTLINE_COLOR = toColor(PLANE_OUTLINE_RGBA); +/** The monitor plane's alpha over its frame, as its image material had it. */ +const PLANE_ALPHA = 0.95; + +/** A plain white image, for a plane with no media (tests). */ +const WHITE_IMAGE = + 'data:image/svg+xml,' + + encodeURIComponent( + '' + + '', + ); + +/** Copy a position's coordinates into `out`. */ +function copyPosition(from, out) { + out.x = from.x; + out.y = from.y; + out.z = from.z; + return out; +} export function createProjection({ state: layerState, @@ -20,15 +34,9 @@ export function createProjection({ }) { const { holdContinuousRender, releaseContinuousRender } = services.render; - /** The monitor plane's orientation, as the Cesium quaternion its entity takes. */ - function planeOrientation(camera, capCenter) { - const q = parts.model.planeOrientationFor(camera, capCenter); - return new Cesium.Quaternion(q.x, q.y, q.z, q.w); - } - /** * Build the protected label associated with one active monitor plane. - * @param {{cameraId: string, name: string, position: Cesium.Cartesian3|Function}} input + * @param {{cameraId: string, name: string, position: object|Function}} input * @returns {Object} Shared-host presentation entry. */ @@ -56,7 +64,7 @@ export function createProjection({ } /** - * Re-derives the monitor plane entity's placement (position, orientation, + * Re-derives the monitor plane's placement (position, orientation, * dimensions) + label from the record's current frustum geometry, so the plane * always caps the wireframe exactly (corner rays terminate on its corners). * No-op when the record has no plane runtime (idle neighbors have no plane). @@ -65,7 +73,8 @@ export function createProjection({ function updatePlanePlacement(record) { const runtime = record?.projection; - if (!runtime?.planeEntity) return; + const plane = runtime?.plane; + if (!plane) return; const geometry = record.frustumGeometry || parts.geometry.computeFrustumGeometry( @@ -75,20 +84,32 @@ export function createProjection({ ); const positions = record.frustumPositions || parts.rendering.frustumCartesians(geometry); - runtime.planeEntity.position = positions.capCenter; - runtime.planeEntity.orientation = planeOrientation( - record.camera, + placePlane(plane, record.camera, geometry, positions); + if (runtime.labelPosition) + copyPosition(positions.label, runtime.labelPosition); + parts.drawSets.writePlane(plane); + } + + /** Pose a plane handle on the frustum's far cap. */ + function placePlane(plane, camera, geometry, positions) { + plane.center = positions.capCenter; + plane.orientation = parts.model.planeOrientationFor( + camera, positions.capCenter, ); - if (runtime.planeEntity.plane) { - runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2( - geometry.halfW * 2, - geometry.halfH * 2, - ); - } - if (runtime.labelPosition) { - Cesium.Cartesian3.clone(positions.label, runtime.labelPosition); - } + plane.size = [geometry.halfW * 2, geometry.halfH * 2]; + } + + /** + * Give the monitor plane another image: a canvas, or the video element. + * @param {Object} runtime - Projection runtime. + * @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source + */ + function setPlaneSource(runtime, source) { + runtime.planeSource = source; + if (!runtime.plane) return; + runtime.plane.source = source; + parts.drawSets.writePlane(runtime.plane); } /** @@ -112,7 +133,10 @@ export function createProjection({ function setPlaneVisible(runtime, visible) { if (!runtime) return; - if (runtime.planeEntity) runtime.planeEntity.show = !!visible; + if (runtime.plane && runtime.plane.show !== !!visible) { + runtime.plane.show = !!visible; + parts.drawSets.writePlane(runtime.plane); + } if (visible && runtime.overlayEntry && runtime.cameraId) { if (layerState._projectionOverlayOwnerId !== runtime.cameraId) { layerState._cctvOverlayHost.setEntries( @@ -131,40 +155,34 @@ export function createProjection({ } } - /** A plain white plane material, for a plane with no media (tests). */ - function plainPlaneMaterial() { - return new Cesium.ColorMaterialProperty(Cesium.Color.WHITE); + /** A plain white plane image, for a plane with no media (tests). */ + function plainPlaneSource() { + return { image: WHITE_IMAGE }; } - /** Create the native monitor plane plus its cached host-label presentation. */ + /** Create the monitor plane plus its cached host-label presentation. */ function createProjectionPlane(record, runtime, geometry, positions) { - runtime.labelPosition ||= new Cesium.Cartesian3(); - Cesium.Cartesian3.clone(positions.label, runtime.labelPosition); + runtime.labelPosition ||= { x: 0, y: 0, z: 0 }; + copyPosition(positions.label, runtime.labelPosition); runtime.cameraId = String(record.camera.id); runtime.overlayEntry = createCctvProjectionOverlayEntry({ cameraId: runtime.cameraId, name: record.camera.name, position: () => runtime.labelPosition, }); - runtime.planeEntity = layerState._viewer.entities.add({ + const plane = { id: `cctv-${record.camera.id}-plane`, + cameraId: record.camera.id, + source: runtime.planeSource || plainPlaneSource(), + alpha: PLANE_ALPHA, + outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 }, show: false, - position: positions.capCenter, - orientation: planeOrientation(record.camera, positions.capCenter), - plane: { - plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0), - dimensions: new Cesium.Cartesian2( - geometry.halfW * 2, - geometry.halfH * 2, - ), - material: runtime.planeMaterial, - outline: true, - outlineColor: PLANE_OUTLINE_COLOR, - }, - }); - cctvPicks.write(runtime.planeEntity).cameraId = record.camera.id; - return runtime.planeEntity; + }; + placePlane(plane, record.camera, geometry, positions); + runtime.plane = plane; + parts.drawSets.writePlane(plane); + return plane; } /** @@ -196,11 +214,11 @@ export function createProjection({ ctx, image: null, video: null, - planeEntity: null, + plane: null, cameraId: String(record.camera.id), - labelPosition: new Cesium.Cartesian3(), + labelPosition: { x: 0, y: 0, z: 0 }, overlayEntry: null, - planeMaterial: null, + planeSource: { canvas }, buffers: null, bufferIndex: 0, lastTextureSwapAt: 0, @@ -231,16 +249,17 @@ export function createProjection({ video.playsInline = true; video.crossOrigin = 'anonymous'; video.preload = 'auto'; - // Cesium sizes the video texture from the element's width/height - // attributes at first upload. Set them from the real stream dimensions - // and rebind on any resolution change (camera switch, adaptive source). + // The plane shows the video once it knows its size (the element's + // width/height follow the real stream dimensions); the renderer reads + // it at a new size on any later resolution change (camera switch, + // adaptive source). const bindVideoTexture = () => { - if (runtime.video !== video || !runtime.planeMaterial) return; + if (runtime.video !== video || runtime.disposed) return; if (!(video.videoWidth > 0 && video.videoHeight > 0)) return; video.width = video.videoWidth; video.height = video.videoHeight; - runtime.planeMaterial.image = runtime.canvas; - runtime.planeMaterial.image = video; + if (runtime.planeSource?.video !== video) + setPlaneSource(runtime, { video }); }; video.addEventListener('loadedmetadata', bindVideoTexture); video.addEventListener('resize', bindVideoTexture); @@ -265,7 +284,7 @@ export function createProjection({ runtime.imageLoading = false; runtime.imageReady = false; }; - runtime.planeMaterial.image = runtime.canvas; + setPlaneSource(runtime, { canvas: runtime.canvas }); parts.frames.refreshProjectionImage(record, true); parts.presentation.notifyListeners(); }, @@ -288,9 +307,8 @@ export function createProjection({ } // Monitor plane = the frustum's far cap: video feeds bind the video element - // directly (Cesium updates video-backed entity materials per frame); image - // feeds start on the placeholder canvas and switch to double-buffer swaps - // at <=1Hz. + // directly (the renderer reads it every frame); image feeds start on the + // placeholder canvas and switch to double-buffer swaps at <=1Hz. const geometry = record.frustumGeometry || parts.geometry.computeFrustumGeometry( @@ -300,11 +318,6 @@ export function createProjection({ ); const positions = record.frustumPositions || parts.rendering.frustumCartesians(geometry); - runtime.planeMaterial = new Cesium.ImageMaterialProperty({ - image: canvas, - transparent: true, - color: Cesium.Color.WHITE.withAlpha(0.95), - }); createProjectionPlane(record, runtime, geometry, positions); return runtime; @@ -349,15 +362,15 @@ export function createProjection({ runtime.video.removeAttribute('src'); runtime.video.load(); } - if (runtime.planeEntity && layerState._viewer) { - layerState._viewer.entities.remove(runtime.planeEntity); - runtime.planeEntity = null; + if (runtime.plane) { + parts.drawSets.removePlane(runtime.plane); + runtime.plane = null; } if (layerState._projectionOverlayOwnerId === runtime.cameraId) clearProjectionOverlay(); runtime.overlayEntry = null; runtime.labelPosition = null; - runtime.planeMaterial = null; + runtime.planeSource = null; } function startProjectionLoop() { @@ -439,7 +452,8 @@ export function createProjection({ updatePlanePlacement, clearProjectionOverlay, setPlaneVisible, - plainPlaneMaterial, + setPlaneSource, + plainPlaneSource, createProjectionPlane, createProjectionRuntime, ensureProjectionRuntime, diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index df06a8e5a..d7d58ec22 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -5,13 +5,13 @@ import { CAMERA_ICON, IDLE_CAMERA_COLOR as IDLE_CAMERA_RGBA, LIVE_CAMERA_COLOR as LIVE_CAMERA_RGBA, - ACTIVE_COVERAGE_CENTER as ACTIVE_COVERAGE_CENTER_RGBA, - IDLE_COVERAGE_CENTER_MUTED as IDLE_COVERAGE_CENTER_MUTED_RGBA, - ACTIVE_COVERAGE_CENTER_DEPTHFAIL as ACTIVE_COVERAGE_CENTER_DEPTHFAIL_RGBA, - ACTIVE_COVERAGE_EDGE as ACTIVE_COVERAGE_EDGE_RGBA, - IDLE_COVERAGE_EDGE_MUTED as IDLE_COVERAGE_EDGE_MUTED_RGBA, - ACTIVE_COVERAGE_EDGE_DEPTHFAIL as ACTIVE_COVERAGE_EDGE_DEPTHFAIL_RGBA, - IDLE_COVERAGE_COLOR as IDLE_COVERAGE_RGBA, + ACTIVE_COVERAGE_CENTER, + IDLE_COVERAGE_CENTER_MUTED, + ACTIVE_COVERAGE_CENTER_DEPTHFAIL, + ACTIVE_COVERAGE_EDGE, + IDLE_COVERAGE_EDGE_MUTED, + ACTIVE_COVERAGE_EDGE_DEPTHFAIL, + IDLE_COVERAGE_COLOR, VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, @@ -20,11 +20,13 @@ import { createIconSet } from '../../data/iconSet.js'; import { writeHoldSegment } from '../../data/iconSegment.js'; import { IconSetPrimitive } from '../../render/cesium/iconSetPrimitive.js'; import { iconAtlas } from '../../data/iconAtlas.js'; -import { cctvPicks } from './pickState.js'; import { horizonOccluder } from '../../render/cesium/iconOrientation.js'; import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js'; -import { entityRecord } from '../../data/entityRecords.js'; import { toColor } from '../../render/cesium/draw.js'; +import { drawHitOf } from '../../render/cesium/drawHit.js'; +import { findQuery } from '../../render/rendererOf.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { eastNorthUp } from '../../geo/frames.js'; // Loads the factory a viewer of a caller's own gets its camera port from, // which the rest of the layer reads the eye through. import '../../render/cesium/camera.js'; @@ -34,17 +36,9 @@ import '../../render/cesium/globe.js'; const ACTIVE_CAMERA_COLOR = toColor(ACTIVE_CAMERA_RGBA); const IDLE_CAMERA_COLOR = toColor(IDLE_CAMERA_RGBA); const LIVE_CAMERA_COLOR = toColor(LIVE_CAMERA_RGBA); -const ACTIVE_COVERAGE_CENTER = toColor(ACTIVE_COVERAGE_CENTER_RGBA); -const IDLE_COVERAGE_CENTER_MUTED = toColor(IDLE_COVERAGE_CENTER_MUTED_RGBA); -const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = toColor( - ACTIVE_COVERAGE_CENTER_DEPTHFAIL_RGBA, -); -const ACTIVE_COVERAGE_EDGE = toColor(ACTIVE_COVERAGE_EDGE_RGBA); -const IDLE_COVERAGE_EDGE_MUTED = toColor(IDLE_COVERAGE_EDGE_MUTED_RGBA); -const IDLE_COVERAGE_COLOR = toColor(IDLE_COVERAGE_RGBA); -const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = toColor( - ACTIVE_COVERAGE_EDGE_DEPTHFAIL_RGBA, -); + +/** An RGBA colour with another alpha. */ +const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha]; /** The camera icon's drawn size (px). */ const CAMERA_ICON_PX = 24; @@ -61,67 +55,37 @@ const CAMERA_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( ); /** - * Builds the translucent frustum-volume primitive for one camera. - * Synchronous (6 triangles — cheaper than the async geometry pipeline's - * bookkeeping), unlit flat color, both faces visible (the viewer is routinely - * inside or behind a cone), never pickable (clicks fall through to the - * billboard/wireframe/plane, whose pick semantics are established). - * @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData). - * @param {Cesium.Color} color - Per-camera fill color (already alpha'd). - * @returns {Cesium.Primitive} + * The translucent frustum volume of one camera, as a mesh item: the same 5 + * points the wireframe draws (frustumVolumeGeometryData), in the + * east-north-up frame at the mount. Unlit flat colour, both faces visible + * (the viewer is routinely inside or behind a cone); its set is never + * pickable (clicks fall through to the icon/wireframe/plane, whose pick + * semantics are established). + * @param {string} id - Item id. + * @param {Object} positions - frustumCartesians shape. + * @param {number[]} color - Per-camera fill colour (already alpha'd). */ -function createFrustumVolumePrimitive(positions, color) { +function frustumVolumeItem(id, positions, color) { const { positions: flat, indices } = frustumVolumeGeometryData(positions); - const geometry = new Cesium.Geometry({ - attributes: { - position: new Cesium.GeometryAttribute({ - componentDatatype: Cesium.ComponentDatatype.DOUBLE, - componentsPerAttribute: 3, - values: flat, - }), - }, - indices, - primitiveType: Cesium.PrimitiveType.TRIANGLES, - boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)), - }); - return new Cesium.Primitive({ - geometryInstances: new Cesium.GeometryInstance({ - geometry, - attributes: { - color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), - }, - }), - appearance: new Cesium.PerInstanceColorAppearance({ - flat: true, - translucent: true, - renderState: { - cull: { enabled: false }, - }, - }), - asynchronous: false, - allowPicking: false, - }); -} - -/** - * A record's viewshed colours as Cesium colours, made once per palette - * object: a record gets a new palette rather than having one changed in place. - */ -const viewshedCesium = new WeakMap(); -function viewshedCesiumColors(record) { - const colors = record.viewshedColors; - if (!colors) return null; - let cesium = viewshedCesium.get(colors); - if (!cesium) { - cesium = { - fill: toColor(colors.fill), - fillActive: toColor(colors.fillActive), - line: toColor(colors.line), - lineActive: toColor(colors.lineActive), - }; - viewshedCesium.set(colors, cesium); + const origin = positions.mount; + const frame = eastNorthUp(origin); + const local = new Float32Array(flat.length); + for (let i = 0; i < flat.length; i += 3) { + const dx = flat[i] - origin.x; + const dy = flat[i + 1] - origin.y; + const dz = flat[i + 2] - origin.z; + local[i] = dx * frame.x.x + dy * frame.x.y + dz * frame.x.z; + local[i + 1] = dx * frame.y.x + dy * frame.y.y + dz * frame.y.z; + local[i + 2] = dx * frame.z.x + dy * frame.z.y + dz * frame.z.z; } - return cesium; + return { + id, + origin: { x: origin.x, y: origin.y, z: origin.z }, + positions: local, + indices, + color, + flat: true, + }; } /** FNV-1a over a camera id: a stable, well-spread order for crowded cells. */ @@ -522,12 +486,18 @@ export function createRendering({ for (const record of Array.isArray(records) ? records : []) { if (record) { record.probeClampRangeM = null; + // A probe still to answer no longer lands. + record.probeToken = (record.probeToken || 0) + 1; if (record.camera?.id === activeCameraId) record.activationDone = false; } for (const entity of record?.coverageEntities || []) entity.show = false; - if (record?.viewshedPrimitive) destroyVolume?.(record); - if (record?.projection?.planeEntity) - record.projection.planeEntity.show = false; + parts.drawSets.writeLines(record?.coverageEntities); + if (record?.viewshedVolume) destroyVolume?.(record); + const plane = record?.projection?.plane; + if (plane?.show) { + plane.show = false; + parts.drawSets.writePlane(plane); + } } } @@ -594,10 +564,6 @@ export function createRendering({ // rather than rendering identically to a surveyed one (#639). Colors, // widths, and the active/idle emphasis are unchanged. const bearingEstimated = isHeadingEstimated(record.camera); - const lineMaterial = (color) => - bearingEstimated - ? new Cesium.PolylineDashMaterialProperty({ color }) - : color; for (const entity of record.coverageEntities || []) { // The frustum wireframe is part of the projection representation — // force it on for the active camera and let it read through geometry @@ -606,45 +572,43 @@ export function createRendering({ layerState._enabled && ((coverageOn && inVisibleSet) || planeShowing) ); - if (!entity.polyline) continue; + if (!entity.role) continue; // Viewshed mode swaps the cyan/green scheme for the camera's own hue so // adjacent cones read as distinct coverage claims (design §3b); the // active camera keeps its width/alpha emphasis in both schemes. - const hue = viewshedOn ? viewshedCesiumColors(record) : null; - if (entity._coverageRole === 'cap') { - entity.polyline.material = lineMaterial( - hue - ? isActive - ? hue.lineActive - : hue.line - : isActive - ? ACTIVE_COVERAGE_CENTER - : IDLE_COVERAGE_CENTER_MUTED, - ); - entity.polyline.width = isActive ? 2.2 : 1.0; - entity.polyline.depthFailMaterial = planeShowing + const hue = viewshedOn ? record.viewshedColors || null : null; + entity.dashed = bearingEstimated; + if (entity.role === 'cap') { + entity.color = hue + ? isActive + ? hue.lineActive + : hue.line + : isActive + ? ACTIVE_COVERAGE_CENTER + : IDLE_COVERAGE_CENTER_MUTED; + entity.widthPx = isActive ? 2.2 : 1.0; + entity.depthFailColor = planeShowing ? hue - ? hue.line.withAlpha(0.26) + ? withAlpha(hue.line, 0.26) : ACTIVE_COVERAGE_CENTER_DEPTHFAIL - : undefined; + : null; } else { - entity.polyline.material = lineMaterial( - hue - ? isActive - ? hue.lineActive - : hue.line.withAlpha(0.6) - : isActive - ? ACTIVE_COVERAGE_EDGE - : IDLE_COVERAGE_EDGE_MUTED, - ); - entity.polyline.width = isActive ? 1.8 : 0.9; - entity.polyline.depthFailMaterial = planeShowing + entity.color = hue + ? isActive + ? hue.lineActive + : withAlpha(hue.line, 0.6) + : isActive + ? ACTIVE_COVERAGE_EDGE + : IDLE_COVERAGE_EDGE_MUTED; + entity.widthPx = isActive ? 1.8 : 0.9; + entity.depthFailColor = planeShowing ? hue - ? hue.line.withAlpha(0.18) + ? withAlpha(hue.line, 0.18) : ACTIVE_COVERAGE_EDGE_DEPTHFAIL - : undefined; + : null; } } + parts.drawSets.writeLines(record.coverageEntities); // Viewshed volume lifecycle: exists iff enabled + viewshed mode + in the // visible set. Rebuild on active-tint flips (rare); otherwise leave the @@ -656,13 +620,10 @@ export function createRendering({ record.frustumPositions ); if (wantVolume) { - if ( - !record.viewshedPrimitive || - record.viewshedActiveTint !== isActive - ) { + if (!record.viewshedVolume || record.viewshedActiveTint !== isActive) { rebuildViewshedVolume(record, isActive); } - } else if (record.viewshedPrimitive) { + } else if (record.viewshedVolume) { destroyViewshedVolume(record); } @@ -716,17 +677,16 @@ export function createRendering({ } /** - * Converts a computeFrustumGeometry result into the Cartesian3 positions the - * entities consume. Fresh objects per call (geometry updates are rare — - * slider/save/activation — and entities must never share scratch objects). + * Converts a computeFrustumGeometry result into the ECEF positions the + * drawn items consume. Fresh objects per call (geometry updates are rare — + * slider/save/activation — and items must never share scratch objects). * @param {Object} geometry - Result of computeFrustumGeometry. - * @returns {{ mount: Cesium.Cartesian3, capCenter: Cesium.Cartesian3, - * tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, br: Cesium.Cartesian3, - * bl: Cesium.Cartesian3, label: Cesium.Cartesian3 }} + * @returns {{ mount: object, capCenter: object, tl: object, tr: object, + * br: object, bl: object, label: object }} ECEF points with x, y and z. */ function frustumCartesians(geometry) { - const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt); + const at = (p) => fromDegrees(p.lon, p.lat, p.alt); return { mount: at(geometry.mount), capCenter: at(geometry.capCenter), @@ -734,7 +694,7 @@ export function createRendering({ tr: at(geometry.corners.tr), br: at(geometry.corners.br), bl: at(geometry.corners.bl), - label: Cesium.Cartesian3.fromDegrees( + label: fromDegrees( geometry.topCenter.lon, geometry.topCenter.lat, geometry.topCenter.alt + 1.2, @@ -743,12 +703,13 @@ export function createRendering({ } /** - * Creates the five Cesium polyline entities that visualize a camera's pitched - * frustum: 4 corner rays (mount → far-plane corner) + the closed far-plane - * rectangle. Entity ids stay in the `cctv--` scheme (pick-owner - * regex depends on it): roles ray-tl / ray-tr / ray-br / ray-bl / cap. + * Creates the five lines that visualize a camera's pitched frustum: 4 + * corner rays (mount → far-plane corner) + the closed far-plane rectangle, + * as line handles the layer restyles and then writes to its coverage set. + * Item ids stay in the `cctv--` scheme (pick-owner regex depends + * on it): ray-tl / ray-tr / ray-br / ray-bl / cap. * @param {Object} record - Camera record. - * @returns {Cesium.Entity[]} Array of five coverage entities. + * @returns {Object[]} Array of five coverage line handles. */ function buildCoverageEntities(record) { @@ -771,76 +732,74 @@ export function createRendering({ moveCameraIcon(record); } - const addPolyline = (role, linePositions) => { - const entity = layerState._viewer.entities.add({ - id: `cctv-${camera.id}-${role}`, - polyline: { - positions: linePositions, - width: 1.2, - material: IDLE_COVERAGE_COLOR, - }, - }); - cctvPicks.write(entity).cameraId = camera.id; - return entity; - }; - + const line = (name, role) => ({ + id: `cctv-${camera.id}-${name}`, + cameraId: camera.id, + role, + positions: null, + widthPx: 1.2, + color: IDLE_COVERAGE_COLOR, + dashed: false, + depthFailColor: null, + show: true, + }); const entities = [ - addPolyline('ray-tl', [positions.mount, positions.tl]), - addPolyline('ray-tr', [positions.mount, positions.tr]), - addPolyline('ray-br', [positions.mount, positions.br]), - addPolyline('ray-bl', [positions.mount, positions.bl]), - addPolyline('cap', [ - positions.tl, - positions.tr, - positions.br, - positions.bl, - positions.tl, - ]), + line('ray-tl', 'edge'), + line('ray-tr', 'edge'), + line('ray-br', 'edge'), + line('ray-bl', 'edge'), + line('cap', 'cap'), ]; - - entities[0]._coverageRole = 'edge'; - entities[1]._coverageRole = 'edge'; - entities[2]._coverageRole = 'edge'; - entities[3]._coverageRole = 'edge'; - entities[4]._coverageRole = 'cap'; + placeCoverageLines(entities, positions); + parts.drawSets.writeLines(entities); return entities; } /** - * The activation obstruction probe's one ray pick against the scene: the - * first thing along the ray from `origin`, seeing through `exclude` (the - * layer's own entities). + * Put a camera's five coverage line handles on its frustum positions (not + * written: the caller writes them). + * @param {Object[]} entities - The record's coverage handles. + * @param {Object} positions - frustumCartesians shape. + */ + function placeCoverageLines(entities, positions) { + if (!(entities?.length >= 5)) return; + entities[0].positions = [positions.mount, positions.tl]; + entities[1].positions = [positions.mount, positions.tr]; + entities[2].positions = [positions.mount, positions.br]; + entities[3].positions = [positions.mount, positions.bl]; + entities[4].positions = [ + positions.tl, + positions.tr, + positions.br, + positions.bl, + positions.tl, + ]; + } + + /** + * The activation obstruction probe's one ray cast against the scene: the + * first surface along the ray from `origin`. The layer's own lines, plane + * and volumes are not ground, so the cast sees through them. * @param {{x: number, y: number, z: number}} origin - ECEF ray origin. * @param {{x: number, y: number, z: number}} direction - Unit ECEF direction. - * @returns {{position?: object}|undefined} Undefined as well when the - * scene cannot pick along a ray. + * @returns {Promise<{x: number, y: number, z: number}|null>} Null as well + * when the scene cannot cast rays. */ - function obstructionHit(origin, direction) { - const scene = layerState._viewer?.scene; - if (!scene || typeof scene.pickFromRay !== 'function') return undefined; - // Exclude everything the layer itself draws so the probe can only hit the - // world (3D tiles), not our own polylines/planes. Icons never draw into - // ray picks. - const exclude = [...layerState._coverageEntities]; - for (const runtime of layerState._projectionEntities) { - if (runtime?.planeEntity) exclude.push(runtime.planeEntity); - } - return scene.pickFromRay(new Cesium.Ray(origin, direction), exclude); + async function obstructionHit(origin, direction) { + const query = findQuery(layerState._viewer); + if (!query) return null; + return query.rayCast({ origin, direction }, { against: 'surface' }); } - /** Whether the scene can pick along a ray (the activation probe needs it). */ + /** Whether there is a query port to cast the activation probe through. */ function canPickFromRay() { - return typeof layerState._viewer?.scene?.pickFromRay === 'function'; + return typeof findQuery(layerState._viewer)?.rayCast === 'function'; } - /** Removes the layer's coverage entities from the scene. */ + /** Removes the layer's coverage lines from the scene. */ function removeCoverageEntities() { - const viewer = layerState._viewer; - if (!viewer) return; - for (const entity of layerState._coverageEntities) { - viewer.entities.remove(entity); - } + parts.drawSets.clearLines(); } /** @@ -853,25 +812,24 @@ export function createRendering({ function extractPickedCameraId(picked) { if (!picked) return null; - const entity = cctvPicks.read(picked.id) - ? picked.id - : cctvPicks.read(picked.primitive?.id) - ? picked.primitive.id - : null; - const value = cctvPicks.read(entity)?.cameraId; - if (value !== undefined) { + // A coverage line or monitor plane: an item of the layer's own sets + // that its record still draws. + const hit = drawHitOf(picked); + const role = hit ? parts.drawSets.roleOfSet(hit.set) : null; + if (role) { + const value = hit.meta?.cameraId; const record = typeof value === 'string' ? layerState._recordById.get(value) : null; - const ownsCoverageEntity = Boolean( - record?.coverageEntities?.includes(entity), - ); - const ownsProjectionEntity = - record?.projection?.planeEntity === entity || - layerState._projectionEntities.some( - (runtime) => - runtime?.cameraId === value && runtime.planeEntity === entity, - ); - if (record && (ownsCoverageEntity || ownsProjectionEntity)) return value; + if (!record) return null; + const owns = + role === 'coverage' + ? Boolean(record.coverageEntities?.some((h) => h?.id === hit.id)) + : record.projection?.plane?.id === hit.id || + layerState._projectionEntities.some( + (runtime) => + runtime?.cameraId === value && runtime.plane?.id === hit.id, + ); + return owns ? value : null; } // Camera icon row IDs are intentionally the upstream camera ID, so a @@ -934,10 +892,9 @@ export function createRendering({ function destroyViewshedVolume(record) { if (!record) return; - if (record.viewshedPrimitive && layerState._viewer) { - layerState._viewer.scene.primitives.remove(record.viewshedPrimitive); - } - record.viewshedPrimitive = null; + if (record.viewshedVolume) + parts.drawSets.removeVolume(record.viewshedVolume); + record.viewshedVolume = null; } /** @@ -952,23 +909,25 @@ export function createRendering({ */ function rebuildViewshedVolume(record, isActive) { - destroyViewshedVolume(record); if ( !layerState._viewer || !record?.frustumPositions || !record.viewshedColors - ) + ) { + destroyViewshedVolume(record); return; - const colors = viewshedCesiumColors(record); - const color = isActive ? colors.fillActive : colors.fill; - const primitive = createFrustumVolumePrimitive( - record.frustumPositions, - color, + } + const colors = record.viewshedColors; + const id = `cctv-${record.camera.id}-viewshed`; + // Replaced where it is: the volume draws in the frame its old one did. + parts.drawSets.writeVolume( + frustumVolumeItem( + id, + record.frustumPositions, + isActive ? colors.fillActive : colors.fill, + ), ); - // QA tag: the harness counts viewshed volumes by this record field. - entityRecord(primitive).viewshedCameraId = record.camera.id; - record.viewshedPrimitive = - layerState._viewer.scene.primitives.add(primitive); + record.viewshedVolume = id; record.viewshedActiveTint = !!isActive; } @@ -976,6 +935,7 @@ export function createRendering({ projectionTilesReady, frustumCartesians, buildCoverageEntities, + placeCoverageLines, obstructionHit, canPickFromRay, removeCoverageEntities, diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 523b55b42..37cf84d76 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -14,6 +14,7 @@ import { import { isVideoFeedType } from '../../sources/cctvTypes.js'; import * as Cesium from 'cesium'; import { createIconSet } from '../../data/iconSet.js'; +import { bindRenderer } from '../../render/rendererOf.js'; const FOCUS_FACTOR = 0.5; @@ -112,40 +113,45 @@ test('icons leave the scene they were added to, whichever viewer tears down', () assert.equal(state._icons, null); }); -test('the obstruction probe sees through the layer and needs a ray pick', () => { - const coverage = [{ id: 'cov' }]; - const plane = { id: 'plane' }; +test('the obstruction probe casts one ray through the query port', async () => { const calls = []; - const state = { - _viewer: { - scene: { - pickFromRay(ray, exclude) { - calls.push({ ray, exclude }); - return { position: { x: 1, y: 2, z: 3 } }; - }, + const viewer = {}; + const unbind = bindRenderer(viewer, { + query: { + rayCast: async (ray, options) => { + calls.push({ ray, options }); + return { x: 1, y: 2, z: 3 }; }, }, - _coverageEntities: coverage, - _projectionEntities: [{ planeEntity: plane }, null, {}], - }; + }); + const state = { _viewer: viewer }; const rendering = createRendering({ state, services: { focus: {} }, parts: {}, }); - assert.equal(rendering.canPickFromRay(), true); - const hit = rendering.obstructionHit( - { x: 0, y: 0, z: 0 }, - { x: 1, y: 0, z: 0 }, - ); - assert.deepEqual(hit.position, { x: 1, y: 2, z: 3 }); - assert.deepEqual(calls[0].exclude, [...coverage, plane]); - assert.ok(calls[0].ray instanceof Cesium.Ray); - state._viewer = { scene: {} }; + try { + assert.equal(rendering.canPickFromRay(), true); + const origin = { x: 0, y: 0, z: 0 }; + const direction = { x: 1, y: 0, z: 0 }; + assert.deepEqual(await rendering.obstructionHit(origin, direction), { + x: 1, + y: 2, + z: 3, + }); + // The layer's own sets are not ground: the cast sees through them + // without naming them. + assert.deepEqual(calls, [ + { ray: { origin, direction }, options: { against: 'surface' } }, + ]); + } finally { + unbind(); + } + state._viewer = {}; assert.equal(rendering.canPickFromRay(), false); assert.equal( - rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), - undefined, + await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), + null, ); }); diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 25e17afa7..b0822997f 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -103,12 +103,13 @@ export function createSelection({ layerState._geoQueue.splice(queueIdx, 1); layerState._geoQueue.unshift(record); } - // §9.1: one obstruction probe per activation, BEFORE the geometry pass so - // the range clamp lands in the same rewrite. A FIRST-EVER activation (no - // real ground sample yet) probes from the catalog-prior altitude — if that - // prior is off, the clamp is measured from a shifted origin, but a - // re-activation after the one-shot snap lands re-probes from real ground, - // so it self-corrects. + // §9.1: one obstruction probe per activation, cast before the geometry + // pass; its range clamp lands a microtask later, before the next frame, + // rewriting the geometry and asking again for the footprint ground. A + // FIRST-EVER activation (no real ground sample yet) probes from the + // catalog-prior altitude — if that prior is off, the clamp is measured + // from a shifted origin, but a re-activation after the one-shot snap + // lands re-probes from real ground, so it self-corrects. parts.geometry.runActivationObstructionProbe(record); // Coverage is activation-lazy even while the mode is OFF: the active // camera's projection representation must be ready without materializing diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index df446d17c..60f030d66 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -19,7 +19,7 @@ export function createTesting({ state: layerState, services, parts, source }) { /** * Create the production monitor-plane/host-label pair without media setup. - * @param {Object} viewer Cesium viewer seam. + * @param {Object} viewer Viewer whose renderer draws the plane. * @param {Object} record CCTV runtime record. * @returns {Object} Projection runtime. */ @@ -39,11 +39,11 @@ export function createTesting({ state: layerState, services, parts, source }) { record.frustumPositions = positions; const runtime = { cameraId: String(record.camera.id), - planeEntity: null, + plane: null, // createProjectionPlane gives it its label position. labelPosition: null, overlayEntry: null, - planeMaterial: parts.projection.plainPlaneMaterial(), + planeSource: parts.projection.plainPlaneSource(), }; parts.projection.createProjectionPlane( record, @@ -122,10 +122,29 @@ export function createTesting({ state: layerState, services, parts, source }) { if (record?.camera?.id) parts.rendering.addCameraIcon(record); } - /** What the layer draws now, for the QA harness: the gizmo's parts. */ + /** + * What the layer draws now, for the QA harness: the gizmo's parts, the + * coverage lines and monitor planes by item id, the viewshed volumes' + * ids, and how many volumes were ever written. + */ function _cctvDrawnForTest() { - return { gizmo: layerState._gizmo?.partsForTest() ?? {} }; + const coverage = {}; + for (const record of layerState._records) + for (const line of record.coverageEntities || []) + if (line?.id) coverage[line.id] = line; + const planes = {}; + for (const runtime of layerState._projectionEntities) + if (runtime?.plane) planes[runtime.plane.id] = runtime.plane; + return { + gizmo: layerState._gizmo?.partsForTest() ?? {}, + coverage, + planes, + viewsheds: layerState._records + .map((record) => record.viewshedVolume) + .filter(Boolean), + viewshedWrites: parts.drawSets.volumeWritesForTest(), + }; } /** The layer's icon set, for tests that read what the rows draw. */ diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 5decddb1e..935fbae09 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -10,7 +10,6 @@ "src/data/geoImportPins.js", "src/input/dispatcher.js", "src/input/sensorPick.js", - "src/layers/cctv/projection.js", "src/layers/cctv/rendering.js", "src/layers/firms/rendering.js", "src/layers/ghostMaps/index.js", diff --git a/src/render/viewerAccessAllowList.json b/src/render/viewerAccessAllowList.json index 7f1c7a6d5..b12722f05 100644 --- a/src/render/viewerAccessAllowList.json +++ b/src/render/viewerAccessAllowList.json @@ -9,7 +9,6 @@ "src/data/followed.js": 5, "src/data/pickRegistry.js": 3, "src/data/spriteOrder.js": 2, - "src/layers/cctv/geometry.js": 1, "src/layers/flights/motion.js": 1, "src/layers/military/motion.js": 1, "src/layers/streetLevel/view.js": 1, diff --git a/src/testSupport/fakeDrawPort.mjs b/src/testSupport/fakeDrawPort.mjs index 5bacf4d37..594b74f1c 100644 --- a/src/testSupport/fakeDrawPort.mjs +++ b/src/testSupport/fakeDrawPort.mjs @@ -83,6 +83,8 @@ export function fakeDrawPort() { lines: make('lines'), shapes: make('shapes'), models: make('models'), + quads: make('quads'), + meshes: make('meshes'), /** Fire a models set's `ready` for an item, as a load finishing does. */ ready(setId, id) { for (const cb of [...(sets.get(setId)?.ready ?? [])]) cb(id);