diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 981ebe787..72f7c1f94 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1063,6 +1063,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -1836,6 +1838,8 @@ "src/queries/heights.js", "src/render/cesium/effects.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -1927,6 +1931,8 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2022,6 +2028,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2091,6 +2099,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2178,6 +2188,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2383,6 +2395,8 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2504,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", @@ -2517,6 +2532,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2539,6 +2556,8 @@ "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/render/motion/iconBook.js", + "src/geo/frustum.js", "src/render/cesium/iconOrientation.js", "src/render/cesium/iconSetPrimitive.js", "src/data/iconSet.js", @@ -2548,7 +2567,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", @@ -2806,6 +2824,8 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -2984,6 +3004,8 @@ "src/render/cesium/credits.js", "src/render/cesium/tileRequests.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -3214,6 +3236,8 @@ "src/render/cesium/globe.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/quality.js", @@ -3437,6 +3461,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", @@ -3449,7 +3474,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", @@ -4221,6 +4245,8 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -4398,6 +4424,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", @@ -4411,7 +4438,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", @@ -4909,6 +4935,8 @@ "src/render/cesium/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -5586,6 +5614,8 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -5737,6 +5767,8 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", @@ -5996,6 +6028,8 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index d315d3163..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; @@ -1785,9 +1778,9 @@ async function main() { const gizmoStates = await page.evaluate((parts) => { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: true }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); @@ -1802,9 +1795,10 @@ async function main() { // stay frozen until release, with no transient sampleHeight calls. const eastDrag = await page.evaluate(() => { const viewer = window.__godsEyeView.viewer; - const e = viewer.entities.getById('cctv-gizmo-move-east'); + const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; + const e = mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east']; if (!e) return null; - const pts = e.polyline.positions.getValue(viewer.clock.currentTime); + const pts = e.positions; const scene = viewer.scene; const w = scene.canvas.clientWidth; const h = scene.canvas.clientHeight; @@ -2082,9 +2076,9 @@ async function main() { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: false }); mod.setParams({ calibration: { reset: true } }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index e5258360a..2ddbee7ca 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,21 +334,31 @@ 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(); } }); test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { const record = (id, feedType) => ({ camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, + // Every catalog record is placed as it is made, and drawn there. + position: { x: 6378137, y: 0, z: 0 }, coverageEntities: [], projection: null, }); 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; @@ -362,20 +372,15 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ }); refreshCoverageStyles(); const icons = _cctvIconsForTest(); - const color = (record) => icons.color(icons.row(record.camera.id)); - const bytes = (c) => - [c.red, c.green, c.blue, c.alpha].map(Cesium.Color.floatToByte); - const policyBytes = (rgba) => rgba.map(Cesium.Color.floatToByte); - assert.deepEqual(bytes(color(idleVideo)), policyBytes(LIVE_CAMERA_COLOR)); - assert.deepEqual(bytes(color(idleStill)), policyBytes(IDLE_CAMERA_COLOR)); - assert.deepEqual( - bytes(color(activeVideo)), - policyBytes(ACTIVE_CAMERA_COLOR), - ); - assert.equal(icons.scale(icons.row(activeVideo.camera.id)), 1.25); - assert.equal(icons.scale(icons.row(idleVideo.camera.id)), 1); + const color = (record) => icons.item(record.camera.id).color; + assert.deepEqual(color(idleVideo), LIVE_CAMERA_COLOR); + assert.deepEqual(color(idleStill), IDLE_CAMERA_COLOR); + assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR); + assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); + assert.equal(icons.item(idleVideo.camera.id).scale, 1); } finally { _setCctvCoverageStateForTest({ enabled: false }); + unbind(); } }); @@ -679,15 +684,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 +701,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 +712,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 +733,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 +758,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 +790,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 +819,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 +828,7 @@ test('real active monitor plane owns one protected host label and no native labe } finally { _setCctvCoverageStateForTest({ enabled: false }); _setCctvOverlayHostForTest(); + unbind(); } }); @@ -1002,8 +1017,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 +1042,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,63 +1135,86 @@ 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) => ({ + set, + id, + meta: { cameraId: 'shared-id' }, + surface: false, + }); assert.equal( _extractPickedCameraIdForTest({ + set: _cctvIconsForTest().setId, id: 'shared-id', - iconSet: _cctvIconsForTest(), - primitive: { id: 'shared-id' }, + surface: false, }), 'shared-id', ); assert.equal( _extractPickedCameraIdForTest({ + set: 'sibling:1:icons', id: 'shared-id', - iconSet: {}, - primitive: { id: 'shared-id' }, + surface: false, }), null, - 'a sibling primitive with the same canonical ID cannot activate CCTV', - ); - assert.equal( - _extractPickedCameraIdForTest({ id: { id: 'shared-id' } }), - null, - 'a sibling Entity with the same canonical ID cannot activate CCTV', - ); - assert.equal( - _extractPickedCameraIdForTest({ id: ownedCoverageEntity }), - 'shared-id', - 'an exact stored CCTV coverage Entity retains activation ownership', + "a sibling set's icon with the same canonical ID cannot activate CCTV", ); assert.equal( _extractPickedCameraIdForTest({ - id: { - id: 'sibling-entity', - properties: { cctvCameraId: 'shared-id' }, - }, + set: _cctvIconsForTest().setId, + id: 'not-a-camera', + surface: false, + }), + null, + 'an id the icon book does not draw is not a camera', + ); + assert.equal( + _extractPickedCameraIdForTest( + lineHit(coverage.spec.id, 'cctv-shared-id-cap'), + ), + 'shared-id', + '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({ + set: 'sibling:1:entities', + id: 'sibling-entity', + meta: { cctvCameraId: 'shared-id', cameraId: 'shared-id' }, + surface: false, }), null, '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 +1268,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/data/cctvGizmo.js b/src/data/cctvGizmo.js index 89789d691..0d9734932 100644 --- a/src/data/cctvGizmo.js +++ b/src/data/cctvGizmo.js @@ -8,7 +8,7 @@ * - Pure drag math (this top section): ray↔axis closest-point, ray↔plane * intersection with a grazing-angle guard, ring angles. All unit-tested * under node:test with zero scene dependencies. - * - createCalibrationGizmo (below): the entity + pointer-input + * - createCalibrationGizmo (below): the draw-set + pointer-input * controller that renders grab-able handles on the ACTIVE camera and turns * drags into calibration patches through a narrow callback interface. It * never touches the layer's records/stores directly. @@ -23,8 +23,10 @@ * throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query * invariant is untouched. */ -import * as Cesium from 'cesium'; import { inputFor } from '../input/dispatcher.js'; +import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js'; +import { eastNorthUp } from '../geo/frames.js'; +import { add, dot, scale, sub } from '../geo/vector.js'; // Grazing guard (spec §5): reject plane intersections when the view ray is // nearly parallel to the constraint plane — the hit point races to infinity @@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08; // Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²). const PARALLEL_EPS = 1e-6; -const scratchW = new Cesium.Cartesian3(); - /** * Parameter t (metres) along an axis line of the point on that axis closest * to a mouse ray. Both directions must be normalized. @@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3(); * t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin, * d = rayDir·w, e = axisDir·w. * - * @param {Cesium.Cartesian3} rayOrigin - * @param {Cesium.Cartesian3} rayDir - Unit. - * @param {Cesium.Cartesian3} axisOrigin - * @param {Cesium.Cartesian3} axisDir - Unit. + * Vectors are ECEF `{x, y, z}`. + * @param {{x: number, y: number, z: number}} rayOrigin + * @param {{x: number, y: number, z: number}} rayDir - Unit. + * @param {{x: number, y: number, z: number}} axisOrigin + * @param {{x: number, y: number, z: number}} axisDir - Unit. * @returns {number|null} Axis parameter in metres, or null when near-parallel. */ export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) { - const b = Cesium.Cartesian3.dot(rayDir, axisDir); + const b = dot(rayDir, axisDir); const denom = 1 - b * b; if (Math.abs(denom) < PARALLEL_EPS) return null; - const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW); - const d = Cesium.Cartesian3.dot(rayDir, w); - const e = Cesium.Cartesian3.dot(axisDir, w); + const w = sub(rayOrigin, axisOrigin); + const d = dot(rayDir, w); + const e = dot(axisDir, w); return (e - b * d) / denom; } /** * Intersects a mouse ray with a plane, refusing grazing configurations * (|rayDir·normal| < 0.08) and hits behind the ray origin. - * @param {Cesium.Cartesian3} rayOrigin - * @param {Cesium.Cartesian3} rayDir - Unit. - * @param {Cesium.Cartesian3} planeOrigin - * @param {Cesium.Cartesian3} planeNormal - Unit. - * @returns {Cesium.Cartesian3|null} Hit point (new instance), or null. + * @param {{x: number, y: number, z: number}} rayOrigin + * @param {{x: number, y: number, z: number}} rayDir - Unit. + * @param {{x: number, y: number, z: number}} planeOrigin + * @param {{x: number, y: number, z: number}} planeNormal - Unit. + * @returns {{x: number, y: number, z: number}|null} Hit point (new), or null. */ export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) { - const denom = Cesium.Cartesian3.dot(rayDir, planeNormal); + const denom = dot(rayDir, planeNormal); if (Math.abs(denom) < GRAZING_DOT_MIN) return null; - const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW); - const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom; + const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom; if (s < 0) return null; - const hit = Cesium.Cartesian3.multiplyByScalar( - rayDir, - s, - new Cesium.Cartesian3(), - ); - return Cesium.Cartesian3.add(rayOrigin, hit, hit); + return add(rayOrigin, scale(rayDir, s)); } /** * Angle (radians, atan2 convention) of a point around a ring center in the * plane spanned by two orthonormal basis vectors. - * @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane. - * @param {Cesium.Cartesian3} center - Ring center. - * @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0). - * @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°). + * @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane. + * @param {{x: number, y: number, z: number}} center - Ring center. + * @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0). + * @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°). * @returns {number} Angle in (−π, π]. */ export function ringAngle(hitPoint, center, basisA, basisB) { - const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW); - return Math.atan2( - Cesium.Cartesian3.dot(v, basisB), - Cesium.Cartesian3.dot(v, basisA), - ); + const v = sub(hitPoint, center); + return Math.atan2(dot(v, basisB), dot(v, basisA)); } /** @@ -117,8 +109,8 @@ export function signedAngleDelta(fromRad, toRad) { // Gizmo controller // --------------------------------------------------------------------------- -/** Entity id prefix for every gizmo part — the layer's pick-owner regex and - * click-to-select guard key off this. Gizmo entities NEVER get a camera id in +/** Item id prefix for every gizmo part — the layer's pick-owner regex and + * click-to-select guard key off this. Gizmo parts NEVER get a camera id in * the layer's pick store, so the layer's selection path ignores them. */ export const GIZMO_ID_PREFIX = 'cctv-gizmo-'; @@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6; const DRAG_THROTTLE_MS = 16; const HOVER_THROTTLE_MS = 120; -const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff'); -const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0'); -const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252'); -const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a'); -const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff'); -const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a'); +/** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */ +function rgba(hex, alpha = 1) { + const n = Number.parseInt(hex.slice(1), 16); + return [ + ((n >> 16) & 255) / 255, + ((n >> 8) & 255) / 255, + (n & 255) / 255, + alpha, + ]; +} + +const COLOR_RING_HEADING = '#35d8ff'; +const COLOR_RING_PITCH = '#ff5fd0'; +const COLOR_MOVE_EAST = '#ff5252'; +const COLOR_MOVE_NORTH = '#52ff7a'; +const COLOR_MOVE_UP = '#5b8cff'; +const COLOR_HANDLE = '#ffd97a'; +const HANDLE_OUTLINE = [0, 0, 0, 0.7]; const toRadians = (deg) => (deg * Math.PI) / 180; const toDeg = (rad) => (rad * 180) / Math.PI; /** * Local ENU unit axes at an ECEF position. - * @param {Cesium.Cartesian3} position - * @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}} + * @param {{x: number, y: number, z: number}} position + * @returns {{east: object, north: object, up: object}} */ function enuAxes(position) { - const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position); - const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3()); - return { - east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()), - north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()), - up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()), - }; + const frame = eastNorthUp(position); + return { east: frame.x, north: frame.y, up: frame.z }; } -/** a*sa + b*sb (fresh Cartesian3). */ +/** a*sa + b*sb. */ function combine2(a, sa, b, sb) { - const out = Cesium.Cartesian3.multiplyByScalar( - a, - sa, - new Cesium.Cartesian3(), - ); - const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3()); - return Cesium.Cartesian3.add(out, t, out); + return add(scale(a, sa), scale(b, sb)); } +/** The midpoint of two points. */ +const midpoint = (a, b) => scale(add(a, b), 0.5); + /** * View-frame unit vectors for a pose within a local ENU frame: horizontal * forward, viewer-right, and the full pitched view axis. @@ -192,25 +188,57 @@ function ringPositions(center, radius, basisA, basisB) { const positions = []; for (let i = 0; i <= RING_SEGMENTS; i++) { const angle = (i / RING_SEGMENTS) * 2 * Math.PI; - const offset = combine2( - basisA, - Math.cos(angle) * radius, - basisB, - Math.sin(angle) * radius, + positions.push( + add( + center, + combine2( + basisA, + Math.cos(angle) * radius, + basisB, + Math.sin(angle) * radius, + ), + ), ); - positions.push(Cesium.Cartesian3.add(center, offset, offset)); } return positions; } +/** The ring and arrow parts: their colour, width and whether an arrow. */ +const LINE_PARTS = Object.freeze([ + ['ring-heading', COLOR_RING_HEADING, 3, false], + ['ring-pitch', COLOR_RING_PITCH, 3, false], + ['move-east', COLOR_MOVE_EAST, 12, true], + ['move-north', COLOR_MOVE_NORTH, 12, true], + ['move-up', COLOR_MOVE_UP, 12, true], +]); +/** The point parts (an arrow's tip included): colour and first size. */ +const POINT_PARTS = Object.freeze([ + ['move-east', COLOR_MOVE_EAST, 14], + ['move-north', COLOR_MOVE_NORTH, 14], + ['move-up', COLOR_MOVE_UP, 14], + ['handle-range', COLOR_HANDLE, 13], + ['handle-fov-l', COLOR_HANDLE, 10], + ['handle-fov-r', COLOR_HANDLE, 10], +]); +/** Every part a pick can grab. */ +const PARTS = new Set([ + ...LINE_PARTS.map(([part]) => part), + ...POINT_PARTS.map(([part]) => part), +]); + +let gizmoInstances = 0; + /** * Creates the calibration gizmo controller (design §3c). Renders grab-able * handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags * into calibration patches through a narrow callback interface — the gizmo - * never touches layer records/stores directly. + * never touches layer records/stores directly. It draws through the + * renderer's draw port (a line set for the rings and arrows, a point set + * for the handles and arrow tips, each item `cctv-gizmo-`) and picks + * and casts rays through its query port. * * @param {Object} deps - * @param {Cesium.Viewer} deps.viewer + * @param {object} deps.viewer - The viewer whose renderer draws it. * @param {function(): Object|null} deps.getActiveRecord - Returns the record * the gizmo should attach to, or null to hide (layer decides: enabled + * calibration mode + active camera). @@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) { * end, for the PINNED drag record. * @returns {{setEnabled: function(boolean): void, refresh: function(): void, * destroy: function(): void, isDragging: function(): boolean, - * isEnabled: function(): boolean}} + * isEnabled: function(): boolean, partsForTest: function(): Object}} */ export function createCalibrationGizmo({ viewer, @@ -234,74 +262,70 @@ export function createCalibrationGizmo({ let hoveredId = null; let lastDragAt = 0; let lastHoverAt = 0; - const entities = new Map(); // part -> Entity + // Whether the parts are drawn now, and each point part's pixel size. + let shown = false; + const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size])); + // The parts' geometry as last drawn: ECEF line positions and point spots. + const linePositions = new Map(); + const pointPositions = new Map(); - const scene = viewer.scene; const input = inputFor(viewer); let releaseCamera = null; - /** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */ - function addEntity(part, options) { - const id = `${GIZMO_ID_PREFIX}${part}`; - const stale = viewer.entities.getById(id); - if (stale) viewer.entities.remove(stale); - const entity = viewer.entities.add({ id, show: false, ...options }); - entities.set(part, entity); - return entity; - } + const instance = ++gizmoInstances; + const draw = drawOf(viewer); + const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` }); + const points = draw.points({ id: `cctv-gizmo:${instance}:points` }); - function polylinePart(part, color, width, arrow = false) { - addEntity(part, { - ...(arrow - ? { - position: Cesium.Cartesian3.ZERO, - point: { - pixelSize: 14, - color, - outlineColor: Cesium.Color.BLACK.withAlpha(0.7), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - } - : {}), - polyline: { - positions: [], - width, - material: arrow - ? new Cesium.PolylineArrowMaterialProperty(color) - : color.withAlpha(0.9), + /** The rings and arrows as they now are. */ + function lineItems() { + const items = []; + for (const [part, color, widthPx, arrow] of LINE_PARTS) { + const positions = linePositions.get(part); + if (!positions) continue; + items.push({ + id: `${GIZMO_ID_PREFIX}${part}`, + positions, + widthPx, + mode: '3d', + style: arrow + ? { kind: 'arrow', color: rgba(color) } + : { kind: 'solid', color: rgba(color, 0.9) }, // Standard gizmo convention: parts behind geometry stay clearly // visible, just dimmed (a street-level mount buries half the heading // ring in sloped photogrammetry tiles — smoke-tested 2026-07-05). - depthFailMaterial: color.withAlpha(0.45), - }, - }); + depthFailColor: rgba(color, 0.45), + show: shown, + }); + } + return items; } - function pointPart(part, color, pixelSize) { - addEntity(part, { - position: Cesium.Cartesian3.ZERO, - point: { - pixelSize, - color, - outlineColor: Cesium.Color.BLACK.withAlpha(0.7), + /** The handles and arrow tips as they now are. */ + function pointItems() { + const items = []; + for (const [part, color] of POINT_PARTS) { + const pos = pointPositions.get(part); + if (!pos) continue; + items.push({ + id: `${GIZMO_ID_PREFIX}${part}`, + pos, + pixelSize: pointSizes.get(part), + color: rgba(color), + outlineColor: HANDLE_OUTLINE, outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + disableDepthTest: Number.POSITIVE_INFINITY, + show: shown, + }); + } + return items; } - polylinePart('ring-heading', COLOR_RING_HEADING, 3); - polylinePart('ring-pitch', COLOR_RING_PITCH, 3); - polylinePart('move-east', COLOR_MOVE_EAST, 12, true); - polylinePart('move-north', COLOR_MOVE_NORTH, 12, true); - polylinePart('move-up', COLOR_MOVE_UP, 12, true); - pointPart('handle-range', COLOR_HANDLE, 13); - pointPart('handle-fov-l', COLOR_HANDLE, 10); - pointPart('handle-fov-r', COLOR_HANDLE, 10); - function hideAll() { - for (const entity of entities.values()) entity.show = false; + if (!shown) return; + shown = false; + lines.upsert(lineItems()); + points.upsert(pointItems()); } /** Recomputes every handle's geometry from the active record's CURRENT pose @@ -329,69 +353,52 @@ export function createCalibrationGizmo({ ); const arrowLen = radius * ARROW_LENGTH_FACTOR; - entities.get('ring-heading').polyline.positions = ringPositions( - mount, - radius, - axes.north, - axes.east, + linePositions.set( + 'ring-heading', + ringPositions(mount, radius, axes.north, axes.east), ); - entities.get('ring-pitch').polyline.positions = ringPositions( - mount, - radius, - forwardHoriz, - axes.up, + linePositions.set( + 'ring-pitch', + ringPositions(mount, radius, forwardHoriz, axes.up), ); - const arrowTo = (dir) => [ - mount, - Cesium.Cartesian3.add( - mount, - Cesium.Cartesian3.multiplyByScalar( - dir, - arrowLen, - new Cesium.Cartesian3(), - ), - new Cesium.Cartesian3(), - ), - ]; - const eastArrow = arrowTo(axes.east); - const northArrow = arrowTo(axes.north); - const upArrow = arrowTo(axes.up); - entities.get('move-east').polyline.positions = eastArrow; - entities.get('move-east').position = eastArrow[1]; - entities.get('move-north').polyline.positions = northArrow; - entities.get('move-north').position = northArrow[1]; - entities.get('move-up').polyline.positions = upArrow; - entities.get('move-up').position = upArrow[1]; - entities.get('handle-range').position = positions.capCenter; - entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint( - positions.tl, - positions.bl, - new Cesium.Cartesian3(), - ); - entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint( - positions.tr, - positions.br, - new Cesium.Cartesian3(), - ); - for (const entity of entities.values()) entity.show = true; + const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))]; + for (const [part, dir] of [ + ['move-east', axes.east], + ['move-north', axes.north], + ['move-up', axes.up], + ]) { + const arrow = arrowTo(dir); + linePositions.set(part, arrow); + pointPositions.set(part, arrow[1]); + } + pointPositions.set('handle-range', positions.capCenter); + pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl)); + pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br)); + shown = true; + lines.upsert(lineItems()); + points.upsert(pointItems()); } - /** Extracts a gizmo part name from a pick result, or null. */ - function gizmoPartFrom(picked) { - const id = picked?.id?.id ?? picked?.id; + /** The gizmo part a pick hit is, or null. */ + function gizmoPartFrom(hit) { + if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null; + const id = hit.id; if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null; - return id.slice(GIZMO_ID_PREFIX.length); + const part = id.slice(GIZMO_ID_PREFIX.length); + return PARTS.has(part) ? part : null; } function pickGizmoPart(windowPosition) { + const query = findQuery(viewer); + if (!query || !windowPosition) return null; + const { x, y } = windowPosition; // Gizmo primitives render depth-test-free and should be the topmost pick. // Take the cheap single-result path first: a full drillPick can stall for // tens of seconds under software GL even when its first result is already // the gizmo. Retain drillPick for uncommon overlap/fallback cases. try { - const picked = scene.pick(windowPosition, 14, 14); - const part = gizmoPartFrom(picked); - if (part && entities.get(part)?.show) return part; + const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 })); + if (part && shown) return part; } catch (err) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug('[CCTV:gizmo] pick threw:', err?.message || err); @@ -400,7 +407,8 @@ export function createCalibrationGizmo({ let results = []; try { - results = scene.drillPick(windowPosition, 6, 14, 14) || []; + results = + query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || []; } catch (err) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err); @@ -410,52 +418,54 @@ export function createCalibrationGizmo({ if (typeof window !== 'undefined' && window.__gevGizmoDebug) { console.debug( '[CCTV:gizmo] drillPick @', - windowPosition?.x, - windowPosition?.y, + x, + y, '→', JSON.stringify( - results.map((r) => - String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name), + results.map((hit) => + hit.surface ? '(surface)' : `${hit.set}/${hit.id}`, ), ), ); } - for (const picked of results) { - const part = gizmoPartFrom(picked); - if (part && entities.get(part)?.show) return part; + for (const hit of results) { + const part = gizmoPartFrom(hit); + if (part && shown) return part; } return null; } function pickRay(windowPosition) { try { - return viewer.camera.getPickRay(windowPosition) || null; + return ( + findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null + ); } catch { return null; } } function setCursor(value) { - if (scene.canvas?.style) scene.canvas.style.cursor = value; + const style = canvasOf(viewer)?.style; + if (style) style.cursor = value; } function setHovered(part) { const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null; if (nextId === hoveredId) return; hoveredId = nextId; - // Hover feedback must NEVER touch polyline geometry: a width change makes - // Cesium rebuild the batched polyline primitive, and until the next render - // the part vanishes from the pick buffer — so the very hover that finds a - // ring makes the following LEFT_DOWN miss it (root-caused via the QA - // harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback - // only; point handles are PointPrimitives (live-updatable, no rebuild), so - // they keep the size bump. - for (const [name, entity] of entities.entries()) { - if (!entity.point) continue; + // Hover feedback must NEVER touch line geometry: a width change rebuilds + // the line, and until the next render the part vanishes from the pick + // buffer — so the very hover that finds a ring makes the following + // LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag, + // 2026-07-05). Rings/arrows get cursor feedback only; point handles + // (an arrow's tip included) change size in place, so they keep the size + // bump. + for (const [name] of POINT_PARTS) { const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`; - entity.point.pixelSize = - (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0); + pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0)); } + points.upsert(pointItems()); setCursor(hoveredId ? 'grab' : ''); } @@ -469,8 +479,8 @@ export function createCalibrationGizmo({ const ray = pickRay(windowPosition); if (!ray) return false; - const mount = Cesium.Cartesian3.clone(positions.mount); - const capCenter = Cesium.Cartesian3.clone(positions.capCenter); + const mount = { ...positions.mount }; + const capCenter = { ...positions.capCenter }; const axes = enuAxes(mount); const { forwardHoriz, right, view } = viewAxesFor( camera.headingDeg, @@ -595,12 +605,7 @@ export function createCalibrationGizmo({ if (part === 'handle-fov-l' || part === 'handle-fov-r') { const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view); if (!hit) return null; - const lateral = Math.abs( - Cesium.Cartesian3.dot( - Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()), - right, - ), - ); + const lateral = Math.abs(dot(sub(hit, capCenter), right)); const halfW = Math.max(0.5, lateral); const fovDeg = toDeg( 2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)), @@ -692,13 +697,22 @@ export function createCalibrationGizmo({ offDown(); offMove(); offUp(); - for (const entity of entities.values()) { - viewer.entities.remove(entity); - } - entities.clear(); + lines.dispose(); + points.dispose(); setCursor(''); }, isDragging: () => !!drag, isEnabled: () => enabled, + /** + * The parts as last drawn, by item id, for the QA harness: whether each + * shows, a line's `positions` and a point's `pos` (an arrow has both). + */ + partsForTest() { + const parts = {}; + for (const item of [...lineItems(), ...pointItems()]) + parts[item.id] = { ...parts[item.id], ...item }; + for (const item of lineItems()) parts[item.id].show = item.show; + return parts; + }, }; } diff --git a/src/data/cctvGizmo.test.mjs b/src/data/cctvGizmo.test.mjs index 6b6c80f76..200972499 100644 --- a/src/data/cctvGizmo.test.mjs +++ b/src/data/cctvGizmo.test.mjs @@ -12,7 +12,6 @@ // - the controller ends an open drag, and its camera hold, on the next press. import { test } from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import { GIZMO_ID_PREFIX, closestParamOnAxis, @@ -22,8 +21,11 @@ import { signedAngleDelta, } from './cctvGizmo.js'; import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { add, distance, negate, normalize, scale } from '../geo/vector.js'; -const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z); +const c3 = (x, y, z) => ({ x, y, z }); test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => { // Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5): @@ -40,10 +42,7 @@ test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => { // Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the // axis around x=10 (it reaches y=0 at x=10). - const dir = Cesium.Cartesian3.normalize( - c3(1, -1, 0), - new Cesium.Cartesian3(), - ); + const dir = normalize(c3(1, -1, 0)); const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0)); assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`); }); @@ -63,10 +62,7 @@ test('closestParamOnAxis: near-parallel ray/axis returns null', () => { closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), null, ); - const nearly = Cesium.Cartesian3.normalize( - c3(1, 1e-9, 0), - new Cesium.Cartesian3(), - ); + const nearly = normalize(c3(1, 1e-9, 0)); assert.equal( closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), null, @@ -81,25 +77,19 @@ test('rayPlaneIntersect: straight-on hit lands at the expected point', () => { c3(0, 0, 1), ); assert.ok(hit, 'expected a hit'); - assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9); + assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9); }); test('rayPlaneIntersect: oblique hit resolves correctly', () => { - const dir = Cesium.Cartesian3.normalize( - c3(1, 0, -1), - new Cesium.Cartesian3(), - ); + const dir = normalize(c3(1, 0, -1)); const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)); assert.ok(hit); - assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`); + assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`); }); test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => { // dir almost in-plane: z component 0.05 < 0.08 threshold. - const dir = Cesium.Cartesian3.normalize( - c3(1, 0, -0.05), - new Cesium.Cartesian3(), - ); + const dir = normalize(c3(1, 0, -0.05)); assert.equal( rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), null, @@ -136,60 +126,133 @@ test('signedAngleDelta: shortest-path wrap', () => { assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9); }); -test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => { +/** + * A viewer double drawing through a fake draw port, whose query port picks + * `picked` and casts the ray `ray` (a ray, + * or a function of the window position). + */ +function gizmoViewer(t, { picked, ray }) { const viewer = { - entities: { - byId: new Map(), - getById(id) { - return this.byId.get(id); - }, - add(options) { - this.byId.set(options.id, options); - return options; - }, - remove(entity) { - this.byId.delete(entity.id); - }, - }, scene: { canvas: { style: {} }, screenSpaceCameraController: { enableInputs: true }, - pick: () => ({ id: { id: `${GIZMO_ID_PREFIX}move-up` } }), - drillPick: () => [], }, }; - const mount = Cesium.Cartesian3.fromDegrees(0, 0, 10); - const east = new Cesium.Cartesian3(0, 1, 0); // east at lon 0, lat 0 - viewer.camera = { - getPickRay: () => ({ - origin: Cesium.Cartesian3.add( - mount, - Cesium.Cartesian3.multiplyByScalar(east, 100, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ), - direction: Cesium.Cartesian3.negate(east, new Cesium.Cartesian3()), + const queries = []; + const { draw, unbind } = bindFakeDraw(viewer, { + query: { + pick: (x, y, window) => (queries.push(['pick', window]), picked()), + drillPick: (x, y, options) => (queries.push(['drill', options]), []), + pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray), + }, + }); + t.after(unbind); + return { viewer, draw, queries }; +} + +const mount = fromDegrees(0, 0, 10); +const east = c3(0, 1, 0); // east at lon 0, lat 0 +const gizmoRecord = () => ({ + frustumPositions: { + mount, + capCenter: mount, + tl: mount, + tr: mount, + bl: mount, + br: mount, + }, + frustumGeometry: { rangeM: 50 }, + camera: { + headingDeg: 0, + pitchDeg: 0, + rangeM: 50, + calibration: {}, + basePose: {}, + }, +}); + +test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => { + const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null }); + const { input } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + const lines = draw.find('cctv-gizmo:'); + const points = [...draw.sets.values()].find( + (set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'), + ); + assert.equal(lines.kind, 'lines'); + assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST'); + gizmo.setEnabled(true); + assert.deepEqual( + [...lines.items.keys()], + ['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map( + (part) => GIZMO_ID_PREFIX + part, + ), + ); + assert.deepEqual( + [...points.items.keys()], + [ + 'move-east', + 'move-north', + 'move-up', + 'handle-range', + 'handle-fov-l', + 'handle-fov-r', + ].map((part) => GIZMO_ID_PREFIX + part), + ); + const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`); + assert.equal(ring.mode, '3d'); + assert.equal(ring.widthPx, 3); + assert.equal(ring.positions.length, 97, 'a closed 96-segment ring'); + assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12); + assert.ok(Math.abs(ring.depthFailColor[3] - 0.45) < 1e-12); + const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`); + assert.equal(arrow.style.kind, 'arrow'); + assert.equal(arrow.widthPx, 12); + // The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up. + assert.ok( + distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6, + ); + const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`); + assert.deepEqual(tip.pos, arrow.positions[1]); + assert.equal(tip.pixelSize, 14); + assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY); + assert.ok( + [...lines.items.values(), ...points.items.values()].every( + (item) => item.show, + ), + ); + gizmo.setEnabled(false); + assert.ok( + [...lines.items.values(), ...points.items.values()].every( + (item) => !item.show, + ), + 'hidden off ADJUST', + ); + gizmo.destroy(); + assert.equal(lines.disposed, true); + assert.equal(points.disposed, true); +}); + +test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => { + let lineSet = null; + const { viewer, draw, queries } = gizmoViewer(t, { + picked: () => ({ + set: lineSet, + id: `${GIZMO_ID_PREFIX}move-up`, + surface: false, }), - }; + ray: { origin: add(mount, scale(east, 100)), direction: negate(east) }, + }); const { input, handler } = fakeInput(viewer); t.after(() => input.destroy()); - const record = { - frustumPositions: { - mount, - capCenter: mount, - tl: mount, - tr: mount, - bl: mount, - br: mount, - }, - frustumGeometry: { rangeM: 50 }, - camera: { - headingDeg: 0, - pitchDeg: 0, - rangeM: 50, - calibration: {}, - basePose: {}, - }, - }; + const record = gizmoRecord(); const ended = []; const gizmo = createCalibrationGizmo({ viewer, @@ -198,11 +261,13 @@ test('a press after a release Cesium never reported ends the open drag and its c endPatch: (r) => ended.push(r), }); t.after(() => gizmo.destroy()); + lineSet = draw.find('cctv-gizmo:').spec.id; gizmo.setEnabled(true); const controller = viewer.scene.screenSpaceCameraController; handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); assert.equal(gizmo.isDragging(), true); + assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]); assert.equal(controller.enableInputs, false); // The release came with a modifier key held: Cesium raised no LEFT_UP. handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); @@ -211,3 +276,145 @@ test('a press after a release Cesium never reported ends the open drag and its c assert.equal(gizmo.isDragging(), false); assert.equal(controller.enableInputs, true, 'no hold was stranded'); }); + +test('a pick of another set or a stray id is no gizmo part', (t) => { + let picked = null; + const { viewer, draw } = gizmoViewer(t, { + picked: () => picked, + ray: { origin: add(mount, scale(east, 100)), direction: negate(east) }, + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + gizmo.setEnabled(true); + picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false }; + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), false, 'another set'); + handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } }); + picked = { + set: draw.find('cctv-gizmo:').spec.id, + id: `${GIZMO_ID_PREFIX}nothing`, + surface: false, + }; + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), false, 'no such part'); +}); + +test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => { + const up = c3(1, 0, 0); // up at lon 0, lat 0 + let lineSet = null; + const { viewer, draw } = gizmoViewer(t, { + picked: () => ({ + set: lineSet, + id: `${GIZMO_ID_PREFIX}move-east`, + surface: false, + }), + // Straight down onto the east axis, `x` metres east of the mount. + ray: (x) => ({ + origin: add(add(mount, scale(east, x)), scale(up, 100)), + direction: negate(up), + }), + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + record.camera.calibration = { offsetEastM: 2 }; + const patches = []; + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch: (patch, pinned) => patches.push([patch, pinned]), + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + lineSet = draw.find('cctv-gizmo:').spec.id; + gizmo.setEnabled(true); + + handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); + assert.equal(gizmo.isDragging(), true); + assert.equal(viewer.scene.canvas.style.cursor, 'grabbing'); + handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, { + startPosition: { x: 5, y: 5 }, + endPosition: { x: 12, y: 5 }, + }); + assert.equal(patches.length, 1); + const [patch, pinned] = patches[0]; + assert.equal(pinned, record, 'patched on the record dragged'); + assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`); + handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } }); + assert.equal(gizmo.isDragging(), false); +}); + +test('hovering a handle grows it and shows the grab cursor', (t) => { + let pointSet = null; + let over = true; + const { viewer, draw } = gizmoViewer(t, { + picked: () => + over + ? { + set: pointSet, + id: `${GIZMO_ID_PREFIX}handle-range`, + surface: false, + } + : null, + ray: null, + }); + const { input, handler } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + const points = [...draw.sets.values()].find( + (set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'), + ); + pointSet = points.spec.id; + gizmo.setEnabled(true); + const size = () => + points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize; + assert.equal(size(), 13); + handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, { + startPosition: { x: 5, y: 5 }, + endPosition: { x: 6, y: 5 }, + }); + assert.equal(size(), 17); + assert.equal(viewer.scene.canvas.style.cursor, 'grab'); +}); + +test('the harness reads each part as drawn, an arrow with its line and tip', (t) => { + const { viewer } = gizmoViewer(t, { picked: () => null, ray: null }); + const { input } = fakeInput(viewer); + t.after(() => input.destroy()); + const record = gizmoRecord(); + const gizmo = createCalibrationGizmo({ + viewer, + getActiveRecord: () => record, + applyPatch() {}, + endPatch() {}, + }); + t.after(() => gizmo.destroy()); + assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST'); + gizmo.setEnabled(true); + const parts = gizmo.partsForTest(); + const arrow = parts[`${GIZMO_ID_PREFIX}move-east`]; + assert.equal(arrow.positions.length, 2, 'its line'); + assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip'); + assert.equal(arrow.show, true); + assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true); + assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos); + gizmo.setEnabled(false); + assert.ok( + Object.values(gizmo.partsForTest()).every((part) => part.show === false), + ); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index a7ca3d3b5..bf5a3edf5 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -2,9 +2,11 @@ // near the screen show, a zoomed-out view keeps one camera per world-anchored // cell, and the layer's UI state never rebuilds every camera for a listener // that does not read the list. -import { test } from 'node:test'; +import { afterEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, _setCctvCoverageStateForTest, @@ -15,18 +17,10 @@ import cctvLayer, { const WIDTH = 800; const HEIGHT = 600; -/** - * Records at the given [lon, lat] degrees near the origin, each drawn at the - * screen point `screenAt` gives it (default: the middle of the screen). - */ -function recordsAt( - lonLats, - screenAt = () => ({ x: WIDTH / 2, y: HEIGHT / 2 }), -) { - const screenByPosition = new Map(); +/** Records at the given [lon, lat] degrees near the origin. */ +function recordsAt(lonLats) { const records = lonLats.map(([lon, lat], index) => { const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10); - screenByPosition.set(position, screenAt(index)); return { camera: { id: `cam-${index}`, @@ -40,42 +34,62 @@ function recordsAt( rangeM: 145, mountHeightM: 8, }, - position, + position: { x: position.x, y: position.y, z: position.z }, coverageEntities: [], projection: null, }; }); - return { records, screenByPosition }; + return { records }; } -function viewerAt(heightM, screenByPosition, shiftX = 0) { - return { - isDestroyed: () => false, - camera: { - positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM), - positionCartographic: { latitude: 0, longitude: 0, height: heightM }, - frustum: { fovy: Math.PI / 3 }, +/** + * A viewer looking straight down from `heightM` over `lonDeg` on the + * equator, north up, through a camera port: the view pass projects the + * cameras from its pose. + */ +function viewerAt(heightM, lonDeg = 0) { + const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); + const down = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const north = { x: 0, y: 0, z: 1 }; + const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3()); + const { port } = fakeCameraPort({ + pose: { + lon: lonDeg, + lat: 0, + height: heightM, + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: { x: down.x, y: down.y, z: down.z }, + up: north, + right: { x: right.x, y: right.y, z: right.z }, + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, }, - scene: { + }); + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, - cartesianToCanvasCoordinates: (position) => { - // Match by value: a record's position may be a copy of the fixture's. - const key = [...screenByPosition.keys()].find((candidate) => - Cesium.Cartesian3.equals(candidate, position), - ); - const screen = screenByPosition.get(key); - return screen && { x: screen.x + shiftX, y: screen.y }; - }, - }, - }; + }), + ); + return viewer; } +/** The renderers bound for the running test, let go when it ends. */ +const bindings = []; +afterEach(() => { + for (const unbind of bindings.splice(0)) unbind(); +}); + function shownIds(records) { + const icons = _cctvIconsForTest(); return records - .filter((record) => { - const icons = _cctvIconsForTest(); - return icons.shown(icons.row(record.camera.id)); - }) + .filter((record) => icons.item(record.camera.id)?.show === true) .map((record) => record.camera.id) .sort(); } @@ -89,9 +103,9 @@ const CLUSTER = [ ]; test('zoomed out, cameras sharing a ground cell show one icon', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, }); assert.equal( @@ -106,34 +120,34 @@ test('zoomed out, cameras sharing a ground cell show one icon', () => { }); test('a pan keeps the same winners, and an unchanged view keeps its list', () => { - const { records, screenByPosition } = recordsAt(CLUSTER, (index) => ({ - x: 100 + index * 7, - y: 300, - })); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, }); refreshHorizonCulling(); const before = shownIds(records); const list = _viewRecordIdsForTest(); - for (const shiftX of [3, 11, 20, 37]) { + // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up). + for (const shiftM of [90, 330, 600, 1110]) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition, shiftX), + viewer: viewerAt(20_000, shiftM / 111_320), records, }); refreshHorizonCulling(); - assert.deepEqual(shownIds(records), before, `pan by ${shiftX} px`); + assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`); } + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); }); test('a small zoom within one cell size keeps the same winners', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); const shownAt = (heightM) => { _setCctvCoverageStateForTest({ - viewer: viewerAt(heightM, screenByPosition), + viewer: viewerAt(heightM), records, }); refreshHorizonCulling(); @@ -145,11 +159,11 @@ test('a small zoom within one cell size keeps the same winners', () => { }); test('a healthy camera wins its cell over an unknown one', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); + const { records } = recordsAt(CLUSTER.slice(0, 2)); // Whichever camera the id order would pick, the healthy one must win. for (const id of ['cam-0', 'cam-1']) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, healthById: new Map([[id, { status: 'ok' }]]), }); @@ -159,34 +173,31 @@ test('a healthy camera wins its cell over an unknown one', () => { }); test('the active camera always shows, even in a crowded cell', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3)); + const { records } = recordsAt(CLUSTER.slice(0, 3)); for (const active of records) { _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, activeCameraId: active.camera.id, }); refreshHorizonCulling(); const icons = _cctvIconsForTest(); assert.ok( - icons.shown(icons.row(active.camera.id)), + icons.item(active.camera.id).show, `${active.camera.id} shows while active`, ); } }); test('close up, every camera near the screen shows and far-off ones hide', () => { - const { records, screenByPosition } = recordsAt( - [ - [0, 0], - [0.0001, 0], - [0.0002, 0], - ], - (index) => - index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 }, - ); + // From 300 m up the screen spans some 460 m: the third camera is 1.1 km off. + const { records } = recordsAt([ + [0, 0], + [0.0001, 0], + [0.01, 0], + ]); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, }); refreshHorizonCulling(); @@ -194,9 +205,9 @@ test('close up, every camera near the screen shows and far-off ones hide', () => }); test('a disabled layer skips the view pass', () => { - const { records, screenByPosition } = recordsAt(CLUSTER); + const { records } = recordsAt(CLUSTER); _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000, screenByPosition), + viewer: viewerAt(20_000), records, enabled: false, }); @@ -205,9 +216,9 @@ test('a disabled layer skips the view pass', () => { }); test('UI state builds the full camera list only when it is read', () => { - const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); + const { records } = recordsAt(CLUSTER.slice(0, 2)); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, }); refreshHorizonCulling(); @@ -238,16 +249,13 @@ test('UI state builds the full camera list only when it is read', () => { }); test('the camera picker lists the view, with the active camera first', () => { - const { records, screenByPosition } = recordsAt( - [ - [0, 0], - [0.0001, 0], - [0.0002, 0], - ], - (index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }), - ); + const { records } = recordsAt([ + [0, 0], + [0.01, 0], + [0.0002, 0], + ]); _setCctvCoverageStateForTest({ - viewer: viewerAt(300, screenByPosition), + viewer: viewerAt(300), records, activeCameraId: 'cam-1', }); diff --git a/src/data/focusResumeGate.test.mjs b/src/data/focusResumeGate.test.mjs index eba05fffc..08a9b0aa8 100644 --- a/src/data/focusResumeGate.test.mjs +++ b/src/data/focusResumeGate.test.mjs @@ -4,7 +4,7 @@ import { applyVesselFocusDeemphasis } from './aisLiveVessels.js'; import { applyCctvFocusDeemphasis } from './cctv.js'; import { applySatellitePointFocusDeemphasis } from './satellites.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; -import { createIconSet } from './iconSet.js'; +import { createIconBook } from '../render/motion/iconBook.js'; import { createVesselIconBook } from '../layers/vessels/iconBook.js'; const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 }; @@ -88,10 +88,13 @@ assertResumeGate('vessel', () => { }); assertResumeGate('CCTV', () => { - const icons = createIconSet(); - const row = icons.add('cam-1', { id: 'cam-1' }); - icons.setSize(row, 24, 24); - icons.setShown(row, true); + const icons = createIconBook(); + icons.put({ + id: 'cam-1', + pos: { x: 1, y: 2, z: 3 }, + size: [24, 24], + meta: { id: 'cam-1' }, + }); const record = { camera: { id: 'cam-1' }, position: { x: 1, y: 2, z: 3 } }; return { pass: ({ nowMs, target: focusTarget, previousActiveCount }) => @@ -105,7 +108,7 @@ assertResumeGate('CCTV', () => { cameraDistanceFor: () => 1200, params, }), - readAlpha: () => icons.focus(icons.row('cam-1')), + readAlpha: () => icons.focus('cam-1'), }; }); diff --git a/src/geo/frustum.js b/src/geo/frustum.js index f7fd9a7da..614d2fa50 100644 --- a/src/geo/frustum.js +++ b/src/geo/frustum.js @@ -60,3 +60,42 @@ export function sphereOutside(planes, center, radius) { if (dot(normal, center) + w < -radius) return true; return false; } + +/** + * Canvas coordinates (CSS px, origin top left) of world points on a `width` + * by `height` canvas, as the default renderer projects them from `pose` + * (its frustum's projection matrix times its view matrix, centred, no + * offset): one pose read for many points, rather than a renderer call per + * point. Null behind the eye and before the projection's clip plane at + * `2·far·near / (far + near)` (a little past `near`; `2·near` with no far + * plane), where the renderer's own projection answers nothing. + * @param {{position: object, direction: object, up: object, fovy: number, + * aspectRatio: number, near: number, far: number}} pose + * @param {number} width + * @param {number} height + * @param {{x: number, y: number}} [out] Written and returned by every call. + * @returns {(p: {x: number, y: number, z: number}) => + * ({x: number, y: number}|null)} + */ +export function poseProjector(pose, width, height, out = { x: 0, y: 0 }) { + const { position: e, direction: d, up: u, near, far } = pose; + const r = cross(d, u); + const tanY = Math.tan(0.5 * pose.fovy); + const tanX = pose.aspectRatio * tanY; + // With no far plane the clip plane is at twice `near`, its limit. + const clipDepth = Number.isFinite(far) + ? (2 * far * near) / (far + near) + : 2 * near; + return (p) => { + const vx = p.x - e.x; + const vy = p.y - e.y; + const vz = p.z - e.z; + const depth = vx * d.x + vy * d.y + vz * d.z; + if (!(depth > 0) || depth < clipDepth) return null; + const x = (vx * r.x + vy * r.y + vz * r.z) / (depth * tanX); + const y = (vx * u.x + vy * u.y + vz * u.z) / (depth * tanY); + out.x = (x + 1) * 0.5 * width; + out.y = (1 - y) * 0.5 * height; + return out; + }; +} diff --git a/src/geo/frustum.test.mjs b/src/geo/frustum.test.mjs index fa5269df8..af970932e 100644 --- a/src/geo/frustum.test.mjs +++ b/src/geo/frustum.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import * as Cesium from 'cesium'; -import { frustumPlanes, sphereOutside } from './frustum.js'; +import { frustumPlanes, poseProjector, sphereOutside } from './frustum.js'; /** A camera pose and the Cesium frustum it describes. */ function camera({ position, direction, up, fovy, aspectRatio, near, far }) { @@ -72,3 +72,110 @@ test('the frustum culls spheres as the default renderer does', () => { assert.equal(sphereOutside(planes, behind, 1), true); } }); + +test('points project to the canvas as the default renderer projects them', () => { + const eye = Cesium.Cartesian3.fromDegrees(-0.12, 51.5, 600); + const target = Cesium.Cartesian3.fromDegrees(-0.11, 51.505, 0); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const east = unit(-eye.y, eye.x, 0); + const up = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(east, direction, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + // Landscape and portrait canvases, each at a near and a far `near`. + for (const [width, height, near] of [ + [1280, 720, 0.1], + [1280, 720, 25], + [600, 900, 0.1], + ]) { + const { pose } = camera({ + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: { x: direction.x, y: direction.y, z: direction.z }, + up: { x: up.x, y: up.y, z: up.z }, + fovy: 0.9, + aspectRatio: width / height, + near, + far: 5e8, + }); + // The renderer's view-projection: its frustum's projection matrix times + // the view matrix of the eye's right, up and direction. + const frustum = new Cesium.PerspectiveFrustum({ + // Cesium's `fov` is across the canvas's wider side. + fov: + pose.aspectRatio <= 1 + ? pose.fovy + : 2 * Math.atan(Math.tan(pose.fovy / 2) * pose.aspectRatio), + aspectRatio: pose.aspectRatio, + near, + far: pose.far, + }); + const right = Cesium.Cartesian3.cross( + direction, + up, + new Cesium.Cartesian3(), + ); + const view = Cesium.Matrix4.computeView( + eye, + direction, + up, + right, + new Cesium.Matrix4(), + ); + const m = Cesium.Matrix4.multiply( + frustum.projectionMatrix, + view, + new Cesium.Matrix4(), + ); + const project = poseProjector(pose, width, height); + let shown = 0; + for (let i = 0; i < 400; i++) { + const p = Cesium.Cartesian3.fromDegrees( + -0.12 + ((i % 20) - 10) * 0.002, + 51.5 + (Math.floor(i / 20) - 10) * 0.002, + (i % 9) * 80, + ); + const clip = Cesium.Matrix4.multiplyByVector( + m, + new Cesium.Cartesian4(p.x, p.y, p.z, 1), + new Cesium.Cartesian4(), + ); + const ours = project(p); + if (!(clip.w > 0) || clip.z < 0) { + assert.equal(ours, null, `${i} is not drawn`); + continue; + } + shown += 1; + const x = (clip.x / clip.w + 1) * 0.5 * width; + const y = (1 - clip.y / clip.w) * 0.5 * height; + // Off-screen points land far out: compared to a part in 1e9. + const close = (a, b) => Math.abs(a - b) <= 1e-6 + 1e-9 * Math.abs(b); + assert.ok(close(ours.x, x), `${i} x`); + assert.ok(close(ours.y, y), `${i} y`); + } + assert.ok(shown > 0 && shown < 400, 'some points in front, some not'); + } + // Just before the clip plane past `near`: nothing, as the renderer. + const { pose } = camera({ + position: { x: 0, y: 0, z: 0 }, + direction: { x: 1, y: 0, z: 0 }, + up: { x: 0, y: 0, z: 1 }, + fovy: 1, + aspectRatio: 1, + near: 10, + far: 1000, + }); + const project = poseProjector(pose, 100, 100); + const clipDepth = (2 * 1000 * 10) / 1010; + assert.equal(project({ x: clipDepth - 1e-6, y: 0, z: 0 }), null); + assert.deepEqual(project({ x: clipDepth + 1e-6, y: 0, z: 0 }), { + x: 50, + y: 50, + }); + // An infinite far plane clips at twice `near`, the limit of the finite rule. + const endless = poseProjector({ ...pose, far: Infinity }, 100, 100); + assert.equal(endless({ x: 20 - 1e-6, y: 0, z: 0 }), null); + assert.deepEqual(endless({ x: 20 + 1e-6, y: 0, z: 0 }), { x: 50, y: 50 }); +}); 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 dbcbcc4b2..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); @@ -111,6 +113,7 @@ export function createCctvLayer({ services, source }) { parts.testing._extractPickedCameraIdForTest, _setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest, _cctvIconsForTest: parts.testing._cctvIconsForTest, + _cctvDrawnForTest: parts.testing._cctvDrawnForTest, focusCctvRecord: parts.navigation.focusCctvRecord, maybeAutoHop: parts.navigation.maybeAutoHop, cctvCycleIndex: parts.navigation.cctvCycleIndex, diff --git a/src/layers/cctv/ingestion.js b/src/layers/cctv/ingestion.js index 2613de1e1..2abd06216 100644 --- a/src/layers/cctv/ingestion.js +++ b/src/layers/cctv/ingestion.js @@ -29,8 +29,8 @@ export function createIngestion({ layerState._tilesReadyReenqueued = true; // Per-regime resolution (Task 5): only records unresolved for the // CURRENT surface regime need the completion pass. On globe stacks - // projectionTilesReady() is false while a (hidden) Google tileset - // exists, so this latch effectively fires for the google-3d regime — + // projectionTilesReady() is false (only drawn photoreal tiles can be + // ready), so this latch fires for the google-3d regime alone — // terrain-globe records resolve from the prior in their drain pass. const unresolved = parts.geometryQueue .geometryWorkingSet() diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index e8e0d7ae6..7d17da8db 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -22,7 +22,7 @@ export function createLifecycle({ parts, source, }) { - const { registerSpriteCollection, restoreSpriteOrder } = services.sprites; + const { registerSpriteSet, restoreSpriteOrder } = services.sprites; const { activateCctvCameraFromWorldClick } = services.activation; const { resolvePickId, registerPickOwner, unregisterPickOwner } = services.picking; @@ -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 = []; @@ -173,9 +176,6 @@ export function createLifecycle({ layerState._lastError = null; layerState._lastFocusStyleAt = 0; layerState._activeFocusStyleCount = 0; - // FIX ①/③: the discovered tileset handle is scene-scoped — drop it so a fresh - // init re-discovers against the current scene primitives. - layerState._activeTileset = null; // Task 5: the applied-regime tracker is record-set-scoped — a fresh init // recomputes it against the then-current scene. layerState._lastAppliedRegime = null; @@ -205,10 +205,10 @@ export function createLifecycle({ layerState._lastViewContext = ''; layerState._calibrationById = parts.calibration.loadCalibrationStore(); - registerSpriteCollection( - 'cctv', - parts.rendering.createCameraIcons(layerState._viewer), - ); + // A host without the sprite order still draws the icons, in the + // order they were added. + const iconSetId = parts.rendering.createCameraIcons(layerState._viewer); + registerSpriteSet?.('cctv', iconSetId); const sources = await parts.catalog.loadCameraSources(); const catalogFromSources = parts.catalog.buildCatalogFromSources(sources); @@ -317,7 +317,7 @@ export function createLifecycle({ viewshedColors: viewshedColors( cameraHue(hueIndexById.get(camera.id) ?? 0), ), - viewshedPrimitive: null, + viewshedVolume: null, viewshedActiveTint: false, }; layerState._records.push(record); @@ -396,7 +396,9 @@ export function createLifecycle({ (event) => { if (!layerState._enabled) return; const picked = event.pick; - const cameraId = parts.selection.extractPickedCameraId(picked); + const cameraId = parts.selection.extractPickedCameraId( + event.drawHit ?? null, + ); if (cameraId) { activateCctvCameraFromWorldClick( cameraId, @@ -582,6 +584,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/policy.js b/src/layers/cctv/policy.js index 3b2056480..ee7e1baf4 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -179,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({ heightM: 0, }); -/** Base64-encoded SVG camera icon for the camera icon rows. */ +/** + * Base64-encoded SVG camera icon for the camera icons. Icons rasterise an + * SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a + * 2× display draws it at 60 device px, and it stays sharp there. + */ export const CAMERA_ICON = (() => { - const svg = ` + const svg = ` 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..bb86d7039 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -1,127 +1,96 @@ -import * as Cesium from 'cesium'; import { isHeadingEstimated } from './headingConfidence.js'; import { - ACTIVE_CAMERA_COLOR as ACTIVE_CAMERA_RGBA, + ACTIVE_CAMERA_COLOR, 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, + IDLE_CAMERA_COLOR, + LIVE_CAMERA_COLOR, + 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, } from './policy.js'; -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 { createIconBook } from '../../render/motion/iconBook.js'; import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js'; -import { entityRecord } from '../../data/entityRecords.js'; -import { toColor } from '../../render/cesium/draw.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'; -import '../../render/cesium/globe.js'; +import { + canvasOf, + drawOf, + findCamera, + findGlobe, + findQuery, +} from '../../render/rendererOf.js'; +import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js'; +import { eastNorthUp } from '../../geo/frames.js'; +import { poseProjector } from '../../geo/frustum.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { distance } from '../../geo/vector.js'; -// The policy's renderer colours as the Cesium colours the icons and lines take. -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). */ +/** Icon sets made so far, by every layer: set ids unique to each. */ +let iconSets = 0; + +/** A point's coordinates, as an item keeps them. */ +const copyPoint = (p) => ({ x: p.x, y: p.y, z: p.z }); + +/** Whether two points are the same, coordinate for coordinate. */ +const samePoint = (a, b) => + !!a && !!b && a.x === b.x && a.y === b.y && a.z === b.z; + +/** Degrees to radians. */ +const toRadians = (degrees) => (degrees * Math.PI) / 180; + +/** + * The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25× + * near scale on a 2× display draws it at 60 device px, so it is rasterised + * past the drawn size to stay sharp there. + */ const CAMERA_ICON_PX = 24; -/** - * Its atlas raster: 1.25× near scale on a 2× display draws it at 60 device px, - * so it is rasterised past the drawn size to stay sharp there. - */ -const CAMERA_RASTER_PX = 48; -const CAMERA_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( - 350, - 1.25, - 4_000_000, - 0.42, -); +const CAMERA_SCALE_BY_DISTANCE = Object.freeze({ + near: 350, + nearValue: 1.25, + far: 4_000_000, + farValue: 0.42, +}); /** - * 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. */ @@ -140,70 +109,93 @@ export function createRendering({ parts, source, }) { - /** The scene the icon primitive was added to. */ - let iconScene = null; - /** - * The catalog's icon set and the primitive that draws it. Cameras hold still, - * so each row is a hold segment and the primitive's clock only keeps segment - * times small. Rows draw depth-test-free (field-test fix 2026-07-06: the old + * The catalog's camera icons: an icon draw set, and the book the layer + * reads them back from (`render/motion/iconBook.js`), each item a camera + * by its id. Cameras hold still, so each item's motion is a hold at its + * mount. Items draw depth-test-free (field-test fix 2026-07-06: the old * finite depth-test distance re-engaged at far zoom, where the COARSE * far-LOD Google-3D mesh sits above the true ground and swallowed - * ground-anchored icons); the GPU culls the far side of the globe and + * ground-anchored icons); the set culls the far side of the globe and * refreshHorizonCulling thins the rest. - * @param {Cesium.Viewer} viewer + * @param {object} viewer The layer's viewer. + * @returns {string} The icon set's id, for the sprite order. */ function createCameraIcons(viewer) { // A re-init against a new viewer replaces the icons; the old ones go. destroyCameraIcons(); - const epoch = Cesium.JulianDate.now(); - layerState._icons = createIconSet({ epoch }); - layerState._iconPrimitive = new IconSetPrimitive({ - set: layerState._icons, - renderTime: () => epoch, - requestRender: () => layerState._viewer?.scene?.requestRender?.(), + const set = drawOf(viewer).icons({ + id: `cctv:${++iconSets}:icons`, + horizonCull: true, }); - viewer.scene.primitives.add(layerState._iconPrimitive); - iconScene = viewer.scene; - return layerState._iconPrimitive; + // Columns of no rows put the set's host in the scene now, where the + // sprite order finds it, rather than with its first camera. + set.setColumns?.({ ids: [] }); + layerState._icons = createIconBook(set); + return set.id; } - /** - * Take the icons out of the scene they were added to, whichever viewer the - * caller tears down, and free them: a destroyed primitive left in a live - * scene throws on its next frame. - */ + /** Let the icon draw set go, whichever viewer the caller tears down. */ function destroyCameraIcons() { - const primitive = layerState._iconPrimitive; - if (primitive && iconScene && !iconScene.isDestroyed?.()) - iconScene.primitives.remove(primitive); - if (primitive && !primitive.isDestroyed()) primitive.destroy(); - iconScene = null; - layerState._iconPrimitive = null; + layerState._icons?.dispose(); layerState._icons = null; } - /** Add a camera record's icon row, idle and shown, at its position. */ - function addCameraIcon(record) { - const set = layerState._icons; + /** The icon item a camera record draws, idle and shown, at its position. */ + function cameraIconItem(record) { const id = record.camera.id; - const row = set.add(id, { layer: 'cctv', id }); - const slot = iconAtlas.slot(CAMERA_ICON, CAMERA_RASTER_PX); - set.setImage(row, slot, slot); - set.setSize(row, CAMERA_ICON_PX, CAMERA_ICON_PX); - set.setScaleByDistance(row, CAMERA_SCALE_BY_DISTANCE); - set.setColor(row, cameraColorFor(record)); - set.setShown(row, true); - moveCameraIcon(record); + return { + id, + pos: copyPoint(record.position), + image: CAMERA_ICON, + size: [CAMERA_ICON_PX, CAMERA_ICON_PX], + color: cameraColorFor(record), + scale: 1, + scaleByDistance: CAMERA_SCALE_BY_DISTANCE, + disableDepthTest: Infinity, + motion: { kind: 'hold' }, + meta: { layer: 'cctv', id }, + show: true, + }; } - /** Hold a camera's row at its record's current position. */ + /** + * A camera's icon item with `fields` changed, to write with the pass's + * others in one go (`writeCameraIcons`); null when none of them changes + * or it has no icon, so a large catalog writes only what changed. + */ + function patchedCameraIcon(id, fields) { + const item = layerState._icons?.item(id); + if (!item) return null; + for (const key in fields) + if (item[key] !== fields[key]) return { ...item, ...fields }; + return null; + } + + /** Write a pass's changed icons, in one write to the set. */ + function writeCameraIcons(items) { + if (items.length) layerState._icons?.putMany(items); + } + + /** Add a camera record's icon, idle and shown, once it has a position. */ + function addCameraIcon(record) { + const icons = layerState._icons; + if (!icons || !record.position) return; + icons.put(cameraIconItem(record)); + } + + /** Hold a camera's icon at its record's current position. */ function moveCameraIcon(record) { - const set = layerState._icons; - const row = set?.row(record.camera.id) ?? -1; - if (row < 0 || !record.position) return; - writeHoldSegment(set.segments, row, record.position, 0); - set.segmentWritten(row); + const icons = layerState._icons; + if (!icons || !record.position) return; + const item = icons.item(record.camera.id); + // A camera whose icon waited for a position is drawn now. + if (!item) { + icons.put(cameraIconItem(record)); + return; + } + if (samePoint(item.pos, record.position)) return; + icons.put({ ...item, pos: copyPoint(record.position) }); } /** Icon color: active wins, then live-capable video feeds, then idle stills. */ @@ -240,21 +232,16 @@ export function createRendering({ return; if (nowMs - layerState._lastFocusStyleAt < 80) return; layerState._lastFocusStyleAt = nowMs; - const scene = layerState._viewer.scene; - const camera = layerState._viewer.camera; + const query = findQuery(layerState._viewer); + const eye = findCamera(layerState._viewer)?.pose()?.position; + if (!query || !eye) return; const result = applyCctvFocusDeemphasis({ records: layerState._records, target, previousActiveCount: layerState._activeFocusStyleCount, nowMs, - screenPositionFor: (position) => - Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - layerState._scratchFocusScreen, - ), - cameraDistanceFor: (position) => - Cesium.Cartesian3.distance(camera.positionWC, position), + screenPositionFor: (position) => query.project(position), + cameraDistanceFor: (position) => distance(eye, position), }); layerState._activeFocusStyleCount = result.activeCount; } @@ -263,7 +250,7 @@ export function createRendering({ * Apply the gated CCTV focus pass through the set's focus column (the shader * multiplies it into the base color's alpha). * @param {object} input - * @param {object} [input.icons] The icon set (defaults to the layer's). + * @param {object} [input.icons] The icon book (defaults to the layer's). * @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}} */ @@ -284,28 +271,30 @@ export function createRendering({ let transitioning = false; let activeCount = 0; for (const record of records || []) { - const row = icons?.row(record.camera?.id) ?? -1; - if (row < 0) continue; + const id = record.camera?.id; + const item = icons?.item(id); + if (!item) continue; const position = record.position; + const scale = item.scale ?? 1; // CCTV never publishes a tracked focus target, so every icon is ambient. - const focus = advanceSpriteFocus(icons.metaAt(row), { + const focus = advanceSpriteFocus(item.meta, { // Keep hidden icons in the state/release pass so the active count cannot // drop while a stale dim alpha remains waiting to reappear. screenPosition: - !icons.shown(row) || !position ? null : screenPositionFor(position), + item.show === false || !position ? null : screenPositionFor(position), cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, target, params, - spriteHalfWidthPx: icons.width(row) * icons.scale(row) * 0.5, - spriteHalfHeightPx: icons.height(row) * icons.scale(row) * 0.5, + spriteHalfWidthPx: item.size[0] * scale * 0.5, + spriteHalfHeightPx: item.size[1] * scale * 0.5, }); transitioning ||= focus.transitioning; if (focus.active) activeCount += 1; // Order-independent narrow amendment to always-visible icons: CCTV // contacts retain a non-zero floor while yielding near the tracked target. - if (focusAlphaNeedsWrite(icons.focus(row), focus.factor, params)) { - icons.setFocus(row, focus.factor); + if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) { + icons.setFocus(id, focus.factor); writes += 1; } } @@ -320,7 +309,7 @@ export function createRendering({ */ /** * Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the - * icon shader does on the GPU. With the Cesium globe hidden (Google-3D + * icon shader does on the GPU. With the globe hidden (Google-3D * regime) nothing writes far-side depth and the icons are always-on-top, so * the shown set (cards, geometry, the picker) must not include London's * cluster from a US viewpoint. @@ -342,33 +331,32 @@ export function createRendering({ if ( !layerState._enabled || !layerState._viewer || - layerState._viewer.isDestroyed() || !layerState._records.length ) return false; - const { camera, scene } = layerState._viewer; - const width = scene.canvas.clientWidth || scene.canvas.width || 0; - const height = scene.canvas.clientHeight || scene.canvas.height || 0; + const pose = findCamera(layerState._viewer)?.pose(); + if (!pose?.position) return false; + const canvas = canvasOf(layerState._viewer); + const width = canvas?.clientWidth || canvas?.width || 0; + const height = canvas?.clientHeight || canvas?.height || 0; const minX = -width * VIEW_ICON_MARGIN; const maxX = width * (1 + VIEW_ICON_MARGIN); const minY = -height * VIEW_ICON_MARGIN; const maxY = height * (1 + VIEW_ICON_MARGIN); // Ground metres one pixel covers per metre of distance from the viewer. - const fovy = Number.isFinite(camera.frustum?.fovy) - ? camera.frustum.fovy - : Math.PI / 3; + const fovy = Number.isFinite(pose.fovy) ? pose.fovy : Math.PI / 3; const metresPerPixelPerMetre = (2 * Math.tan(fovy / 2)) / Math.max(1, height); - const viewer = camera.positionWC; - // The horizon test of Cesium's EllipsoidalOccluder, inlined: this loop + const viewer = pose.position; + // The renderer's horizon test (geo/horizon.js), inlined: this loop // visits every camera in the catalog. - const inverseRadii = Cesium.Ellipsoid.WGS84.oneOverRadii; + const inverseRadii = WGS84.oneOverRadii; const cx = viewer.x * inverseRadii.x; const cy = viewer.y * inverseRadii.y; const cz = viewer.z * inverseRadii.z; const limbSquared = cx * cx + cy * cy + cz * cz - 1; const activeId = layerState._activeCameraId; - const project = screenProjector(scene, camera, width, height); + const project = screenProjector(pose, width, height); const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1); const shown = []; const cells = new Map(); @@ -414,11 +402,14 @@ export function createRendering({ record.viewPass = pass; shown.push(record); } - const icons = layerState._icons; + const writes = []; for (const record of layerState._records) { - const row = icons?.row(record.camera.id) ?? -1; - if (row >= 0) icons.setShown(row, record.viewPass === pass); + const item = patchedCameraIcon(record.camera.id, { + show: record.viewPass === pass, + }); + if (item) writes.push(item); } + writeCameraIcons(writes); const previous = layerState._viewRecords; const changed = previous.length !== shown.length || @@ -428,37 +419,21 @@ export function createRendering({ } /** - * Canvas coordinates for world positions. In 3D the pass multiplies by one - * view-projection matrix per call instead of Cesium's per-point - * cartesianToCanvasCoordinates, which dominated the pass on a large - * catalog; other scene modes keep Cesium's projection. - * @returns {(position: Cesium.Cartesian3) => ({x: number, y: number}|null)} + * Canvas coordinates for world positions, from the eye's pose by the + * renderer's perspective projection (geo/frustum.js): one pose read per + * pass rather than a renderer projection per point, which dominated the + * pass on a large catalog. Null behind the eye or before its near plane. + * A pose with no perspective field of view is projected by the renderer, + * point by point. + * @returns {(position: {x: number, y: number, z: number}) => + * ({x: number, y: number}|null)} */ - function screenProjector(scene, camera, width, height) { - const out = layerState._scratchViewScreen; - const projection = camera.frustum?.projectionMatrix; - if ( - scene.mode !== Cesium.SceneMode.SCENE3D || - !projection || - !camera.viewMatrix - ) - return (position) => scene.cartesianToCanvasCoordinates(position, out); - const m = Cesium.Matrix4.multiply( - projection, - camera.viewMatrix, - layerState._scratchViewProjection, - ); - return (p) => { - const w = m[3] * p.x + m[7] * p.y + m[11] * p.z + m[15]; - const z = m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14]; - // Behind the eye or before the near plane: Cesium does not draw it. - if (!(w > 0) || z < 0) return null; - out.x = - ((m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12]) / w + 1) * 0.5 * width; - out.y = - (1 - (m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13]) / w) * 0.5 * height; - return out; - }; + function screenProjector(pose, width, height) { + if (Number.isFinite(pose.fovy) && Number.isFinite(pose.aspectRatio)) { + return poseProjector(pose, width, height, layerState._scratchViewScreen); + } + const query = findQuery(layerState._viewer); + return (position) => query?.project(position) ?? null; } /** @@ -480,7 +455,7 @@ export function createRendering({ return record.viewCellKey; const latStep = 2 ** level / 111_320; const row = Math.floor(lat / latStep); - const rowLat = Cesium.Math.toRadians((row + 0.5) * latStep); + const rowLat = toRadians((row + 0.5) * latStep); const lonStep = latStep / Math.max(0.05, Math.cos(rowLat)); record.viewCellLevel = level; record.viewCellLat = lat; @@ -522,12 +497,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); + } } } @@ -560,16 +541,16 @@ export function createRendering({ coverageVisible, ); } - const icons = layerState._icons; + // Only changed icons are written, in one go after the pass, so across a + // large catalog only the changed rows upload. + const restyled = []; for (const record of layerState._records) { const isActive = record.camera.id === activeId; - const row = icons?.row(record.camera.id) ?? -1; - if (row >= 0) { - // The set skips unchanged writes, so across a large catalog only the - // changed rows upload. - icons.setColor(row, cameraColorFor(record)); - icons.setScale(row, isActive ? 1.25 : 1.0); - } + const icon = patchedCameraIcon(record.camera.id, { + color: cameraColorFor(record), + scale: isActive ? 1.25 : 1.0, + }); + if (icon) restyled.push(icon); if ( layerState._enabled && @@ -594,10 +575,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 +583,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 +631,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); } @@ -671,62 +643,43 @@ export function createRendering({ } } + writeCameraIcons(restyled); if (layerState._icons) layerState._icons.show = !!layerState._enabled; parts.projection.pauseInactiveProjectionFeeds(activeId); } /** - * Reports whether the active Google Photorealistic 3D Tileset (if any) has - * finished loading the tiles in view. Shared mesh-floor sampling is gated on - * this so a one-shot cell never bakes in a miss from still-streaming tiles. - * Discovers + caches the tileset lazily from scene - * primitives (the CCTV module holds only a `_viewer` reference). When no - * tileset is present (OSM fallback) this returns true so ground sampling is - * not permanently blocked. + * Reports whether the photorealistic tiles the scene draws have finished + * loading the tiles in view. Shared mesh-floor sampling is gated on this so + * a one-shot cell never bakes in a miss from still-streaming tiles. * - * Task 5 (review correction, spec §2): a HIDDEN tileset (`show === false`, - * i.e. a globe stack is active) must NOT report ready — Cesium 1.138's - * the shared sampler can only inspect *visible* 3D tilesets, so a sample taken - * against the hidden Google tileset would silently miss. + * Only the photoreal regime (the globe hidden under the tiles) can be + * ready: on a globe stack the tiles are hidden, and the shared sampler can + * only inspect tiles that are drawn, so a sample taken against them would + * silently miss (Task 5, spec §2). The tiles' readiness is the globe + * port's (`isSettled('tiles')`), true as well when no tiles are drawn. * - * @returns {boolean} True when tiles are loaded AND visible (or no tileset - * exists to wait on). + * @returns {boolean} True when the regime is photoreal and its tiles in + * view have loaded. */ function projectionTilesReady() { - if ( - !layerState._activeTileset || - layerState._activeTileset.isDestroyed?.() - ) { - layerState._activeTileset = null; - const primitives = layerState._viewer?.scene?.primitives; - if (primitives && typeof primitives.get === 'function') { - for (let i = 0; i < primitives.length; i++) { - const p = primitives.get(i); - if (p instanceof Cesium.Cesium3DTileset && !p.isDestroyed?.()) { - layerState._activeTileset = p; - break; - } - } - } - } - if (!layerState._activeTileset) return true; - if (layerState._activeTileset.show === false) return false; - return layerState._activeTileset.tilesLoaded === true; + const globe = layerState._viewer ? findGlobe(layerState._viewer) : null; + if (!globe || globe.isGlobeVisible?.() !== false) return false; + return globe.isSettled('tiles') === true; } /** - * 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 +687,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 +696,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,140 +725,129 @@ 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). - * @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. + * 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 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); - } - - /** Whether the scene can pick along a ray (the activation probe needs it). */ - function canPickFromRay() { - return typeof layerState._viewer?.scene?.pickFromRay === 'function'; - } - - /** Removes the layer's coverage entities from the scene. */ - function removeCoverageEntities() { - const viewer = layerState._viewer; - if (!viewer) return; - for (const entity of layerState._coverageEntities) { - viewer.entities.remove(entity); - } + 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, + ]; } /** - * Extracts a camera ID from a scene pick result by checking icon row IDs, - * primitive IDs, and the camera ids the layer keeps for its coverage entities. - * @param {Object|null} picked - Result from scene.pick(). - * @returns {string|null} Camera ID, or null if the pick is not a CCTV entity. + * 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 {Promise<{x: number, y: number, z: number}|null>} Null as well + * when the scene cannot cast rays. */ - function extractPickedCameraId(picked) { - if (!picked) return null; + async function obstructionHit(origin, direction) { + const query = findQuery(layerState._viewer); + if (!query) return null; + return query.rayCast({ origin, direction }, { against: 'surface' }); + } - const entity = cctvPicks.read(picked.id) - ? picked.id - : cctvPicks.read(picked.primitive?.id) - ? picked.primitive.id + /** Whether there is a query port to cast the activation probe through. */ + function canPickFromRay() { + return typeof findQuery(layerState._viewer)?.rayCast === 'function'; + } + + /** Removes the layer's coverage lines from the scene. */ + function removeCoverageEntities() { + parts.drawSets.clearLines(); + } + + /** + * The camera a pick (a draw-port `Hit`: `event.drawHit`, `query.pick`) + * names: an item of the layer's own sets that its record still draws. + * @param {{set: string, id: string, meta?: object}|null} hit + * @returns {string|null} Camera ID, or null if the pick is not a CCTV item. + */ + + function extractPickedCameraId(hit) { + if (!hit || typeof hit.set !== 'string' || typeof hit.id !== 'string') + return null; + + // A camera icon: its item id is the upstream camera id, so a sibling + // may legitimately use the same string. A bare id match is not + // ownership proof: the layer's own icon set must have drawn the pick. + const icons = layerState._icons; + if (icons && hit.set === icons.setId) + return icons.has(hit.id) && layerState._recordById.has(hit.id) + ? hit.id : null; - const value = cctvPicks.read(entity)?.cameraId; - if (value !== undefined) { - 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; - } - // Camera icon row IDs are intentionally the upstream camera ID, so a - // sibling may legitimately use the same string. A bare ID match is not - // ownership proof: require that this layer's icon set drew the pick. - const directId = - typeof picked.id === 'string' - ? picked.id - : typeof picked.primitive?.id === 'string' - ? picked.primitive.id - : null; + // A coverage line or monitor plane: an item of the layer's own sets + // that its record still draws. + const role = parts.drawSets.roleOfSet(hit.set); + if (!role) return null; + const value = hit.meta?.cameraId; const record = - directId === null ? null : layerState._recordById.get(directId); + typeof value === 'string' ? layerState._recordById.get(value) : null; if (!record) return null; - return layerState._icons && picked.iconSet === layerState._icons - ? directId - : 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; } /** * The camera whose icon or coverage is under a screen position (CSS px), - * from one scene pick; null when none is, or the pick throws. + * from one pick; null when none is, or the pick throws. * @param {{x: number, y: number}} position * @returns {string|null} */ function pickCameraIdAt(position) { - let picked = null; + let hit = null; try { - picked = layerState._viewer.scene.pick(position); + hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null; } catch { - picked = null; + hit = null; } - return extractPickedCameraId(picked); + return extractPickedCameraId(hit); } /** @@ -912,17 +855,20 @@ export function createRendering({ * canvas position of a world point on the near side of the horizon (null * behind it or off the projection). * @returns {{width: number, height: number, - * screenOf: (position: object) => ({x: number, y: number}|undefined|null)}} + * screenOf: (position: object) => ({x: number, y: number}|null)}} */ function cardView() { - const { camera, scene } = layerState._viewer; - const occluder = horizonOccluder(camera); + const viewer = layerState._viewer; + const canvas = canvasOf(viewer); + const query = findQuery(viewer); + const eye = findCamera(viewer)?.pose()?.position; + const horizon = eye ? horizonFrom(eye) : null; return { - width: scene.canvas.clientWidth || scene.canvas.width || 0, - height: scene.canvas.clientHeight || scene.canvas.height || 0, + width: canvas?.clientWidth || canvas?.width || 0, + height: canvas?.clientHeight || canvas?.height || 0, screenOf: (position) => - occluder.isPointVisible(position) - ? scene.cartesianToCanvasCoordinates(position) + query && horizon?.isPointVisible(position) + ? query.project(position) : null, }; } @@ -934,10 +880,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 +897,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 +923,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..ef9e633b0 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -2,7 +2,7 @@ // Icon colors under focus de-emphasis (#1200): the focus pass fades each icon // from the same base color the coverage refresh assigns, so a video-feed camera // stays violet while it dims instead of falling back to the idle cyan. -// Teardown takes the icons out of the scene that holds them. +// Teardown lets go of the icon set of the viewer that drew it. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createRendering } from './rendering.js'; @@ -13,85 +13,103 @@ import { } from './policy.js'; import { isVideoFeedType } from '../../sources/cctvTypes.js'; import * as Cesium from 'cesium'; -import { createIconSet } from '../../data/iconSet.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; const FOCUS_FACTOR = 0.5; function assertKeepsColor(icons, id, base, label) { - const row = icons.row(id); - const actual = icons.color(row); - assert.deepEqual( - [actual.red, actual.green, actual.blue, actual.alpha].map( - Cesium.Color.floatToByte, - ), - base.map(Cesium.Color.floatToByte), - `${label}: base color kept`, - ); - assert.equal(icons.focus(row), FOCUS_FACTOR, `${label}: focus`); + assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`); + assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`); } test('focus de-emphasis fades each icon from its own color', () => { const record = (id, feedType) => ({ camera: { id, feedType }, - // No position, so the pass skips screen projection; the focus stub below - // decides the factor on its own. + position: { x: 6378137, y: 0, z: 0 }, }); const idleVideo = record('idle-hls', 'hls'); const idleStill = record('idle-image', 'image'); const activeVideo = record('active-hls', 'hls'); + const viewer = {}; + const camera = fakeCameraPort({ + pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } }, + }); + const projected = []; + const { draw, unbind } = bindFakeDraw(viewer, { + camera: camera.port, + query: { + project: (position) => { + projected.push(position); + return { x: 10, y: 20 }; + }, + }, + }); const state = { _enabled: true, - _viewer: { scene: {}, camera: {} }, + _viewer: viewer, _records: [idleVideo, idleStill, activeVideo], _activeCameraId: activeVideo.camera.id, _activeFocusStyleCount: 0, _lastFocusStyleAt: -Infinity, - _icons: createIconSet(), }; + const distances = []; const focus = { focusNowMs: (nowMs) => nowMs, getFocusTarget: () => ({}), focusPassIsNeeded: () => true, - advanceSpriteFocus: () => ({ - factor: FOCUS_FACTOR, - active: true, - transitioning: false, - }), + advanceSpriteFocus: (meta, input) => { + distances.push(input.cameraDistance); + return { factor: FOCUS_FACTOR, active: true, transitioning: false }; + }, focusAlphaNeedsWrite: () => true, }; - const { addCameraIcon, refreshCctvFocusStyles } = createRendering({ - state, - services: { focus }, - parts: { model: { isVideoFeedType } }, - source: {}, - }); - for (const r of state._records) addCameraIcon(r); + const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } = + createRendering({ + state, + services: { focus }, + parts: { model: { isVideoFeedType } }, + source: {}, + }); + try { + const setId = createCameraIcons(viewer); + for (const r of state._records) addCameraIcon(r); - refreshCctvFocusStyles(1000); + refreshCctvFocusStyles(1000); - const icons = state._icons; - assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video'); - assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still'); - assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video'); - assert.equal(state._activeFocusStyleCount, 3); + const icons = state._icons; + assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video'); + assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still'); + assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video'); + assert.equal(state._activeFocusStyleCount, 3); + assert.equal(projected.length, 3, 'each shown icon is projected'); + assert.deepEqual(distances, [1000, 1000, 1000], 'from the eye'); + // What the set draws: depth-test-free, held at the mount, shrinking + // with distance as before. + const drawn = draw.set(setId).items.get('idle-hls'); + assert.equal(drawn.disableDepthTest, Infinity); + assert.deepEqual(drawn.motion, { kind: 'hold' }); + assert.deepEqual(drawn.pos, idleVideo.position); + assert.deepEqual(drawn.size, [24, 24]); + assert.deepEqual(drawn.scaleByDistance, { + near: 350, + nearValue: 1.25, + far: 4_000_000, + farValue: 0.42, + }); + assert.equal(drawn.focus, FOCUS_FACTOR); + assert.equal(draw.set(setId).spec.horizonCull, true); + } finally { + unbind(); + } }); -test('icons leave the scene they were added to, whichever viewer tears down', () => { - const viewer = () => { - const held = new Set(); - return { - held, - scene: { - requestRender() {}, - primitives: { - add: (p) => held.add(p), - remove: (p) => held.delete(p), - }, - }, - }; - }; - const first = viewer(); - const second = viewer(); +test('the icons go with the viewer that drew them, whichever tears down', () => { + const first = {}; + const second = {}; + const one = bindFakeDraw(first); + const two = bindFakeDraw(second); const state = { _viewer: first }; const { createCameraIcons, destroyCameraIcons } = createRendering({ state, @@ -99,53 +117,62 @@ test('icons leave the scene they were added to, whichever viewer tears down', () parts: {}, source: {}, }); + try { + const old = createCameraIcons(first); + state._viewer = second; + const current = createCameraIcons(second); + assert.notEqual(old, current); + assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go'); + assert.equal(two.draw.sets.get(current).disposed, false); - const old = createCameraIcons(first); - state._viewer = second; - const current = createCameraIcons(second); - assert.equal(first.held.has(old), false, 'a re-init takes out the old icons'); - assert.equal(old.isDestroyed(), true); - - destroyCameraIcons(); - assert.equal(second.held.has(current), false); - assert.equal(current.isDestroyed(), true); - assert.equal(state._icons, null); + destroyCameraIcons(); + assert.equal(two.draw.sets.get(current).disposed, true); + assert.equal(state._icons, null); + } finally { + one.unbind(); + two.unbind(); + } }); -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, ); }); @@ -153,22 +180,188 @@ test('cards go only where the horizon lets the camera see', () => { const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000); const front = Cesium.Cartesian3.fromDegrees(0, 0); const back = Cesium.Cartesian3.fromDegrees(180, 0); - const state = { - _viewer: { - camera: { positionWC: eye }, - scene: { - canvas: { clientWidth: 800, clientHeight: 0, height: 600 }, - cartesianToCanvasCoordinates: () => ({ x: 10, y: 20 }), - }, + const viewer = {}; + const camera = fakeCameraPort({ + pose: { position: { x: eye.x, y: eye.y, z: eye.z } }, + }); + const unbind = bindRenderer(viewer, { + camera: camera.port, + canvas: { clientWidth: 800, clientHeight: 0, height: 600 }, + query: { project: () => ({ x: 10, y: 20 }) }, + }); + try { + const view = createRendering({ + state: { _viewer: viewer }, + services: { focus: {} }, + parts: {}, + }).cardView(); + assert.equal(view.width, 800); + assert.equal(view.height, 600); + assert.deepEqual(view.screenOf(front), { x: 10, y: 20 }); + assert.equal(view.screenOf(back), null); + } finally { + unbind(); + } +}); + +test('the projection tiles are ready only when drawn and settled', () => { + const viewer = {}; + let globeVisible = true; + let settled = true; + const unbind = bindRenderer(viewer, { + globe: { + isGlobeVisible: () => globeVisible, + isSettled: (kind) => kind === 'tiles' && settled, }, - }; - const view = createRendering({ - state, + }); + try { + const { projectionTilesReady } = createRendering({ + state: { _viewer: viewer }, + services: { focus: {} }, + parts: {}, + }); + assert.equal(projectionTilesReady(), false, 'a globe stack hides them'); + globeVisible = false; + assert.equal(projectionTilesReady(), true); + settled = false; + assert.equal(projectionTilesReady(), false, 'still streaming'); + } finally { + unbind(); + } + const bare = createRendering({ + state: { _viewer: {} }, services: { focus: {} }, parts: {}, - }).cardView(); - assert.equal(view.width, 800); - assert.equal(view.height, 600); - assert.deepEqual(view.screenOf(front), { x: 10, y: 20 }); - assert.equal(view.screenOf(back), null); + }); + assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles'); +}); + +test('a view pass writes only the icons it changes, in one write', () => { + const viewer = {}; + const eye = Cesium.Cartesian3.fromDegrees(0, 0, 2000); + const down = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const camera = fakeCameraPort({ + pose: { + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: { x: down.x, y: down.y, z: down.z }, + up: { x: 0, y: 0, z: 1 }, + fovy: Math.PI / 3, + aspectRatio: 4 / 3, + near: 0.1, + far: 5e8, + }, + }); + const { draw, unbind } = bindFakeDraw(viewer, { + camera: camera.port, + canvas: { clientWidth: 800, clientHeight: 600 }, + }); + const record = (id, lon) => { + const p = Cesium.Cartesian3.fromDegrees(lon, 0, 10); + return { + camera: { id, lat: 0, lon }, + position: { x: p.x, y: p.y, z: p.z }, + }; + }; + // One in view, one far off it. + const near = record('near', 0); + const far = record('far', 1); + const state = { + _enabled: true, + _viewer: viewer, + _records: [near, far], + _viewRecords: [], + _healthById: new Map(), + _scratchViewScreen: { x: 0, y: 0 }, + }; + const rendering = createRendering({ + state, + services: { focus: {} }, + parts: { + model: { isVideoFeedType: () => false }, + drawSets: { roleOfSet: () => null }, + }, + source: {}, + }); + try { + const setId = rendering.createCameraIcons(viewer); + for (const r of state._records) rendering.addCameraIcon(r); + const set = draw.set(setId); + const writes = set.writes; + + assert.equal(rendering.refreshHorizonCulling(), true); + assert.equal(set.writes, writes + 1, 'one write for the pass'); + assert.equal(set.items.get('near').show, true); + assert.equal(set.items.get('far').show, false); + + assert.equal(rendering.refreshHorizonCulling(), false); + assert.equal(set.writes, writes + 1, 'an unchanged view writes nothing'); + + // Another layer on the same viewer draws its icons in a set of its own. + const other = createRendering({ + state: { _viewer: viewer }, + services: { focus: {} }, + parts: {}, + source: {}, + }); + const otherId = other.createCameraIcons(viewer); + assert.notEqual(otherId, setId); + assert.equal( + rendering.extractPickedCameraId({ set: otherId, id: 'near' }), + null, + "the other layer's icon is not this layer's camera", + ); + } finally { + unbind(); + } +}); + +test('a pose with no perspective field of view is projected by the renderer', () => { + const viewer = {}; + const camera = fakeCameraPort({ + pose: { position: { x: 7e6, y: 0, z: 0 }, fovy: undefined }, + }); + const asked = []; + const { draw, unbind } = bindFakeDraw(viewer, { + camera: camera.port, + canvas: { clientWidth: 800, clientHeight: 600 }, + query: { + project: (position) => { + asked.push(position.y); + return position.y === 0 ? { x: 400, y: 300 } : null; + }, + }, + }); + // On the ground under the eye, in cells of their own. + const record = (id, y) => ({ + camera: { id, lat: 0, lon: y / 1000 }, + position: { x: 6378137, y, z: 0 }, + }); + const state = { + _enabled: true, + _viewer: viewer, + _records: [record('on', 0), record('off', 1000)], + _viewRecords: [], + _healthById: new Map(), + _scratchViewScreen: { x: 0, y: 0 }, + }; + const rendering = createRendering({ + state, + services: { focus: {} }, + parts: { model: { isVideoFeedType: () => false } }, + source: {}, + }); + try { + const setId = rendering.createCameraIcons(viewer); + for (const r of state._records) rendering.addCameraIcon(r); + rendering.refreshHorizonCulling(); + const set = draw.set(setId); + assert.deepEqual(asked.sort(), [0, 1000]); + assert.equal(set.items.get('on').show, true); + assert.equal(set.items.get('off').show, false); + } finally { + unbind(); + } }); 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/source.test.mjs b/src/layers/cctv/source.test.mjs index a4b276d21..cd5540ccb 100644 --- a/src/layers/cctv/source.test.mjs +++ b/src/layers/cctv/source.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { createCctvSource, createCctvLayer } from './index.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; const camera = { id: 'pack/camera ?x', @@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and setOverlayEntries: noop, setOverlaySourceVisible: noop, }, - sprites: { registerSpriteCollection: noop }, + sprites: { registerSpriteSet: noop }, activation: {}, locations: {}, picking: { unregisterPickOwner: noop }, @@ -134,9 +135,9 @@ test('camera construction is inert and destruction cancels a pending catalog and const a = createCctvLayer({ services, source }); const b = createCctvLayer({ services, source }); assert.equal(listeners.size, 0); - const viewer = { - scene: { primitives: { add: (value) => value, remove: () => true } }, - }; + const viewer = {}; + const { unbind } = bindFakeDraw(viewer); + t.after(unbind); const initializing = a.init(viewer); assert.equal(listeners.size, 1); assert.equal(signal.aborted, false); diff --git a/src/layers/cctv/state.js b/src/layers/cctv/state.js index 3efb82a57..2c542f17a 100644 --- a/src/layers/cctv/state.js +++ b/src/layers/cctv/state.js @@ -13,9 +13,8 @@ export function createState({ services }) { layerState._viewer = null; - /** The catalog's icon set and the primitive that draws it. */ + /** The catalog's camera icons: the icon book over their draw set. */ layerState._icons = null; - layerState._iconPrimitive = null; layerState._records = []; @@ -74,14 +73,9 @@ export function createState({ services }) { layerState._activeFocusStyleCount = 0; - // Screen-point scratches: the projections that fill them write only x and y. - layerState._scratchFocusScreen = { x: 0, y: 0 }; - + // The view pass's screen-point scratch: its projection writes only x and y. layerState._scratchViewScreen = { x: 0, y: 0 }; - /** The view pass's view-projection matrix, column-major. */ - layerState._scratchViewProjection = new Float64Array(16); - // Counts view passes; a record shown by the latest pass carries its number. layerState._viewPassId = 0; @@ -166,13 +160,6 @@ export function createState({ services }) { layerState._lastTransientNotifyAt = 0; - // Cached handle on the active Google Photorealistic 3D Tileset, discovered - // lazily from scene.primitives. Shared mesh-floor sampling is gated on its - // tilesLoaded flag so a coarse-LOD miss is never baked in. Cleared when the - // tileset is destroyed / the layer tears down. - - layerState._activeTileset = null; - // Task 5: last surface regime the record geometry was recomputed for. The // map-stack change listener compares the CURRENT regime (derived live from // whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe' diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index cac86e159..ffd22f96a 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -1,4 +1,13 @@ -import { createIconSet } from '../../data/iconSet.js'; +import { createIconBook } from '../../render/motion/iconBook.js'; + +/** A draw set that draws nothing, for the icon book the tests read. */ +const testIconSet = () => ({ + id: 'cctv:test:icons', + show: true, + upsert() {}, + remove() {}, + dispose() {}, +}); export function createTesting({ state: layerState, services, parts, source }) { /** Test seam: republishes host entries through the real push path, so tests @@ -19,7 +28,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 +48,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, @@ -102,7 +111,6 @@ export function createTesting({ state: layerState, services, parts, source }) { ); layerState._coverageEntities = []; layerState._projectionEntities = []; - layerState._iconPrimitive = null; layerState._activeCameraId = activeCameraId; layerState._autoHopSuspended = false; layerState._enabled = !!enabled; @@ -116,13 +124,39 @@ export function createTesting({ state: layerState, services, parts, source }) { layerState._cameraIndexCache = null; layerState._coverageVisibleIds = new Set(); layerState._neighborCountCache = null; - // A real set (no primitive): every record gets its row as init adds it. - layerState._icons = createIconSet(); + // A real book (over a set that draws nothing): every record gets its + // icon as init adds it. + layerState._icons = createIconBook(testIconSet()); for (const record of layerState._records) if (record?.camera?.id) parts.rendering.addCameraIcon(record); } - /** The layer's icon set, for tests that read what the rows draw. */ + /** + * 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() { + 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 book, for tests that read what the icons draw. */ function _cctvIconsForTest() { return layerState._icons; @@ -135,5 +169,6 @@ export function createTesting({ state: layerState, services, parts, source }) { _extractPickedCameraIdForTest, _setCctvCoverageStateForTest, _cctvIconsForTest, + _cctvDrawnForTest, }; } diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index bc93c9692..ab5573ede 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -37,6 +37,8 @@ import { provideUnboundDraw } from '../rendererOf.js'; import { listenerList, toCartesian, uncaught } from './common.js'; import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js'; import { createModelSets } from './drawModels.js'; +import { createMeshSets } from './drawMeshes.js'; +import { createQuadSets } from './drawQuads.js'; /** The contract's colour as Cesium's. */ export function toColor(color, alpha = 1) { @@ -395,7 +397,9 @@ export function createCesiumDraw({ if ( patchLines(record, list) || patchShapes(record, list) || - (kind === 'models' && modelSets.upsert(record, list)) + (kind === 'models' && modelSets.upsert(record, list)) || + (kind === 'quads' && quadSets.upsert(record, list)) || + (kind === 'meshes' && meshSets.upsert(record, list)) ) { for (const item of list) items.set(item.id, item); if (kind === 'lines') noteFlows(record); @@ -449,7 +453,10 @@ export function createCesiumDraw({ if ( (kind !== 'models' && spec.clampTo !== clampTo) || ((kind === 'points' || kind === 'icons') && spec.blend !== blend) || - ((kind === 'shapes' || kind === 'lines') && + ((kind === 'shapes' || + kind === 'lines' || + kind === 'quads' || + kind === 'meshes') && (spec.pickable !== false) !== pickable) ) rebuild(); @@ -2994,6 +3001,24 @@ export function createCesiumDraw({ requestRender, }); const buildModels = (record) => modelSets.build(record); + const lineWidth = (px) => + typeof scene.clampLineWidth === 'function' + ? scene.clampLineWidth(px) + : Math.min(px, scene.maximumAliasedLineWidth ?? 1); + const quadSets = createQuadSets({ + toColor, + toImage, + pickId, + replaceHost, + lineWidth, + requestRender, + }); + const meshSets = createMeshSets({ + toColor, + pickId, + replaceHost, + requestRender, + }); /** The 3D tilesets in the scene, shown or not. */ function tilesets() { @@ -3032,6 +3057,10 @@ export function createCesiumDraw({ lines: (spec) => makeSet('lines', { ...spec }, buildLines), shapes: (spec) => makeSet('shapes', { ...spec }, buildShapes), models: (spec) => makeSet('models', { ...spec }, buildModels), + quads: (spec) => + makeSet('quads', { ...spec }, (record) => quadSets.build(record)), + meshes: (spec) => + makeSet('meshes', { ...spec }, (record) => meshSets.build(record)), clampState, on(event, cb) { if (event !== 'clampState') return () => {}; @@ -3075,6 +3104,7 @@ export function createCesiumDraw({ cullHorizon(); runFlows(); modelSets.beforeRender(sets.values()); + quadSets.beforeRender(sets.values()); }, /** Each frame, after it drew: clamp state, and ground swaps. */ afterRender() { @@ -3091,9 +3121,11 @@ export function createCesiumDraw({ } // Rows moving on a live clock, and flowing lines, draw on in the // frames that follow. + const playing = quadSets.afterRender(sets.values()); if ( [...sets.values()].some((record) => record.gpu?.animating()) || - flowing() + flowing() || + playing ) requestRender(); }, diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 98870e9c6..f717e05a6 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -5163,3 +5163,268 @@ test('a raised polygon outlines its holes as well as its outer ring', () => } set.dispose(); })); + +test('quads draw a posed plane and its outline, changed in place', () => + withImageClasses(() => { + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const set = part.port.quads({ id: 'monitors' }); + const canvas = { width: 4, height: 4 }; + const other = { width: 4, height: 4 }; + const center = { x: 6378137, y: 10, z: 20 }; + const quad = (extra = {}) => ({ + id: 'q', + center, + orientation: { x: 0, y: 0, z: 0, w: 1 }, + size: [40, 20], + source: { canvas }, + alpha: 0.95, + outline: { color: [0.4, 0.9, 1, 0.55], widthPx: 1 }, + meta: { camera: 'c1' }, + ...extra, + }); + set.set([quad()]); + const host = scene.added[0]; + assert.equal(host.length, 2, 'the plane and its outline'); + const [fill, outline] = [host.get(0), host.get(1)]; + assert.ok(fill.geometryInstances.geometry instanceof Cesium.PlaneGeometry); + assert.ok( + outline.geometryInstances.geometry instanceof Cesium.PlaneOutlineGeometry, + ); + assert.deepEqual(fill.geometryInstances.id, { + set: 'monitors', + id: 'q', + meta: { camera: 'c1' }, + lodGroup: undefined, + }); + // Scaled to its size about its centre, as a plane entity's matrix is. + const scale = Cesium.Matrix4.getScale( + fill.modelMatrix, + new Cesium.Cartesian3(), + ); + assert.deepEqual([scale.x, scale.y, scale.z], [40, 20, 1]); + const at = Cesium.Matrix4.getTranslation( + fill.modelMatrix, + new Cesium.Cartesian3(), + ); + assert.deepEqual({ x: at.x, y: at.y, z: at.z }, center); + const material = fill.appearance.material; + assert.equal(material.type, 'Image'); + assert.equal(material.uniforms.image, canvas); + assert.ok(Math.abs(material.uniforms.color.alpha - 0.95) < 1e-12); + assert.equal(fill.appearance.translucent, true); + + // Moved, resized, faded, hidden and given another canvas: the same plane. + set.upsert([ + quad({ + center: { x: 6378137, y: 30, z: 20 }, + size: [80, 45], + alpha: 0.5, + show: false, + source: { canvas: other }, + meta: { camera: 'c2' }, + }), + ]); + assert.equal(host.get(0), fill, 'changed where it is'); + Cesium.Matrix4.getScale(fill.modelMatrix, scale); + assert.deepEqual([scale.x, scale.y], [80, 45]); + assert.ok( + Cesium.Matrix4.equals(fill.modelMatrix, outline.modelMatrix), + 'the outline follows', + ); + assert.equal(fill.show, false); + assert.equal(outline.show, false); + assert.equal(material.uniforms.image, other, 'the new canvas is read'); + assert.ok(Math.abs(material.uniforms.color.alpha - 0.5) < 1e-12); + assert.deepEqual(fill.geometryInstances.id.meta, { camera: 'c2' }); + + // Unpickable, or without an outline: built anew. + set.upsert([quad({ outline: null, pickable: false })]); + assert.equal(host.length, 1, 'no outline'); + assert.notEqual(host.get(0), fill); + assert.equal(host.get(0).allowPicking, false); + set.remove(['q']); + assert.equal(host.length, 0); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('a video quad keeps frames coming while it plays, read anew at a new size', () => + withImageClasses(() => { + const realVideo = globalThis.HTMLVideoElement; + globalThis.HTMLVideoElement = class extends EventTarget {}; + try { + const scene = fakeScene(); + let renders = 0; + scene.requestRender = () => (renders += 1); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const set = part.port.quads({ id: 'feeds' }); + const video = Object.assign(new globalThis.HTMLVideoElement(), { + readyState: 4, + paused: false, + ended: false, + videoWidth: 640, + videoHeight: 360, + }); + set.set([ + { + id: 'v', + center: { x: 6378137, y: 0, z: 0 }, + orientation: { x: 0, y: 0, z: 0, w: 1 }, + size: [16, 9], + source: { video }, + alpha: 0.95, + }, + ]); + const fill = scene.added[0].get(0); + const first = fill.appearance.material; + assert.equal(first.uniforms.image, video); + part.beforeRender(); + renders = 0; + part.afterRender(); + assert.ok(renders > 0, 'a playing video asks for the next frame'); + // Past the frames a new image needs, a paused video asks for none. + part.afterRender(); + part.afterRender(); + video.paused = true; + renders = 0; + part.afterRender(); + assert.equal(renders, 0, 'a paused video draws no more frames'); + // A new size: a new material reads it, the old one freed once drawn. + video.videoWidth = 1280; + video.videoHeight = 720; + part.beforeRender(); + assert.notEqual(fill.appearance.material, first); + assert.equal(fill.appearance.material.uniforms.image, video); + assert.equal(first.isDestroyed(), false, 'kept until the frame drew'); + part.afterRender(); + assert.equal(first.isDestroyed(), true); + // Paused, it draws again as it plays, with no frame asked for. + renders = 0; + video.dispatchEvent(new Event('playing')); + assert.equal(renders, 1, 'playing again asks for a frame'); + // From the video to a canvas: a material of its own. + const sized = fill.appearance.material; + const canvas = { width: 4, height: 4 }; + const quad = { + id: 'v', + center: { x: 6378137, y: 0, z: 0 }, + orientation: { x: 0, y: 0, z: 0, w: 1 }, + size: [16, 9], + source: { canvas }, + alpha: 0.95, + }; + set.upsert([{ ...quad, show: false }]); + assert.notEqual(fill.appearance.material, sized); + assert.equal(fill.appearance.material.uniforms.image, canvas); + renders = 0; + video.dispatchEvent(new Event('playing')); + assert.equal(renders, 0, 'the video it left is no longer heard'); + // Hidden, the frames its image needs wait until it shows. + part.afterRender(); + part.afterRender(); + part.afterRender(); + set.upsert([quad]); + renders = 0; + part.afterRender(); + assert.ok(renders > 0, 'shown, it asks for the frames its image needs'); + set.dispose(); + } finally { + globalThis.HTMLVideoElement = realVideo; + } + })); + +test('meshes draw their triangles in the frame at their origin', () => + withImageClasses(() => { + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const set = part.port.meshes({ id: 'volumes', pickable: false }); + const positions = new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10]); + const indices = new Uint16Array([0, 1, 2, 0, 1, 3]); + const origin = Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 200); + const mesh = (extra = {}) => ({ + id: 'm', + origin: { x: origin.x, y: origin.y, z: origin.z }, + positions, + indices, + color: [0.2, 0.8, 1, 0.2], + flat: true, + ...extra, + }); + set.set([mesh()]); + const host = scene.added[0]; + assert.equal(host.length, 1); + const primitive = host.get(0); + const geometry = primitive.geometryInstances.geometry; + assert.equal( + geometry.attributes.position.componentDatatype, + Cesium.ComponentDatatype.DOUBLE, + ); + // In the Earth-fixed frame: the east-north-up offsets about the origin. + const frame = Cesium.Transforms.eastNorthUpToFixedFrame(origin); + const values = geometry.attributes.position.values; + for (let i = 0; i < positions.length; i += 3) { + const want = Cesium.Matrix4.multiplyByPoint( + frame, + new Cesium.Cartesian3(positions[i], positions[i + 1], positions[i + 2]), + new Cesium.Cartesian3(), + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + new Cesium.Cartesian3(values[i], values[i + 1], values[i + 2]), + want, + 0, + 1e-6, + ), + `vertex ${i / 3} in place`, + ); + } + assert.equal(geometry.indices, indices); + assert.equal(primitive.allowPicking, false, 'an unpickable set'); + assert.equal(primitive.appearance.flat, true); + assert.equal(primitive.appearance.translucent, true); + assert.equal( + primitive.appearance.renderState.cull.enabled, + false, + 'both faces', + ); + // Hidden: the same primitive. + set.upsert([mesh({ show: false })]); + assert.equal(host.get(0), primitive); + assert.equal(primitive.show, false); + // Moved: built anew where it now is. + const moved = Cesium.Cartesian3.fromDegrees(-97.73, 30.27, 200); + set.upsert([mesh({ origin: { x: moved.x, y: moved.y, z: moved.z } })]); + assert.equal(host.length, 1); + const rebuilt = host.get(0); + assert.notEqual(rebuilt, primitive); + const first = rebuilt.geometryInstances.geometry.attributes.position.values; + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + new Cesium.Cartesian3(first[0], first[1], first[2]), + moved, + 0, + 1e-6, + ), + 'its origin vertex is the new origin', + ); + // A new colour builds it anew. + set.upsert([mesh({ color: '#ff0000' })]); + assert.equal(host.length, 1); + assert.notEqual(host.get(0), rebuilt); + // Lit meshes are closed: their back faces culled. + set.upsert([mesh({ flat: false })]); + assert.equal(host.get(0).appearance.closed, true); + set.clear(); + assert.equal(host.length, 0); + set.dispose(); + })); diff --git a/src/render/cesium/drawMeshes.js b/src/render/cesium/drawMeshes.js new file mode 100644 index 000000000..6119adc78 --- /dev/null +++ b/src/render/cesium/drawMeshes.js @@ -0,0 +1,182 @@ +/** + * @module render/cesium/drawMeshes + * @description The Cesium draw port's `meshes` sets: each item one + * primitive of its triangles, in the east-north-up frame at its `origin`, + * in its colour. `flat` draws it unlit with both faces (a translucent + * volume seen from inside or behind); otherwise it is lit by its own + * normals and its back faces are culled. Its vertices are placed in the + * Earth-fixed frame when it is built (a primitive whose own vertices sit at + * its frame's origin cannot be projected for the 2D views Cesium prepares), + * so any change but `show` builds it anew, at once, and it draws in the + * frame it replaces the old one. `positions` and `indices` are compared by + * identity: give new arrays to change a shape. + */ +import * as Cesium from 'cesium'; + +/** A colour as a key: a CSS string as it is, an RGBA array joined. */ +const colorKey = (color) => + typeof color === 'string' ? color : Array.from(color).join(','); + +/** + * The meshes part of a Cesium draw port. + * @param {{toColor: Function, pickId: Function, replaceHost: Function, + * requestRender: () => void}} options From the draw port. + */ +export function createMeshSets({ + toColor, + pickId, + replaceHost, + requestRender, +}) { + /** The set's host, made once: its meshes are changed where they are. */ + function hostOf(record) { + if (record.host && !record.host.isDestroyed?.()) return record.host; + const host = new Cesium.PrimitiveCollection(); + record.meshes = new Map(); + replaceHost(record, host); + return host; + } + + function notePickIds(record) { + record.pickIds = []; + for (const entry of record.meshes.values()) + record.pickIds.push(entry.pickId); + } + + const pickableOf = (record, item) => + record.spec.pickable !== false && item.pickable !== false; + + const scratchFrame = new Cesium.Matrix4(); + const scratchPoint = new Cesium.Cartesian3(); + + /** The item's east-north-up positions, in the Earth-fixed frame. */ + function fixedPositions(item) { + const { origin, positions } = item; + const frame = Cesium.Transforms.eastNorthUpToFixedFrame( + new Cesium.Cartesian3(origin.x, origin.y, origin.z), + Cesium.Ellipsoid.WGS84, + scratchFrame, + ); + const out = new Float64Array(positions.length); + for (let i = 0; i + 2 < positions.length; i += 3) { + scratchPoint.x = positions[i]; + scratchPoint.y = positions[i + 1]; + scratchPoint.z = positions[i + 2]; + Cesium.Matrix4.multiplyByPoint(frame, scratchPoint, scratchPoint); + out[i] = scratchPoint.x; + out[i + 1] = scratchPoint.y; + out[i + 2] = scratchPoint.z; + } + return out; + } + + /** What an entry's primitive is built from: equal keys need no rebuild. */ + const shapeKey = (record, item) => ({ + origin: `${item.origin.x},${item.origin.y},${item.origin.z}`, + positions: item.positions, + indices: item.indices, + color: colorKey(item.color), + flat: item.flat === true, + pickable: pickableOf(record, item), + }); + + const sameShape = (a, b) => + a.origin === b.origin && + a.positions === b.positions && + a.indices === b.indices && + a.color === b.color && + a.flat === b.flat && + a.pickable === b.pickable; + + function primitiveOf(record, item, entry) { + const values = fixedPositions(item); + const geometry = new Cesium.Geometry({ + attributes: { + position: new Cesium.GeometryAttribute({ + componentDatatype: Cesium.ComponentDatatype.DOUBLE, + componentsPerAttribute: 3, + values, + }), + }, + indices: item.indices, + primitiveType: Cesium.PrimitiveType.TRIANGLES, + boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(values)), + }); + const flat = item.flat === true; + if (!flat) Cesium.GeometryPipeline.computeNormal(geometry); + const color = toColor(item.color); + return new Cesium.Primitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry, + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), + }, + id: entry.pickId, + }), + appearance: new Cesium.PerInstanceColorAppearance({ + flat, + translucent: color.alpha < 1, + // Flat: both faces. Lit: a closed shape, its back faces culled. + closed: !flat, + ...(flat ? { renderState: { cull: { enabled: false } } } : {}), + }), + allowPicking: pickableOf(record, item), + asynchronous: false, + show: item.show !== false, + }); + } + + function put(record, item) { + const host = record.host; + let entry = record.meshes.get(item.id); + if (!entry) { + entry = { + item, + pickId: pickId(record, item), + key: null, + primitive: null, + }; + record.meshes.set(item.id, entry); + } + entry.item = item; + entry.pickId.meta = item.meta; + const key = shapeKey(record, item); + if (entry.primitive && entry.key && sameShape(entry.key, key)) { + entry.primitive.show = item.show !== false; + return; + } + const next = host.add(primitiveOf(record, item, entry)); + if (entry.primitive) host.remove(entry.primitive); + entry.primitive = next; + entry.key = key; + } + + function drop(record, id) { + const entry = record.meshes.get(id); + if (!entry) return; + record.meshes.delete(id); + const host = record.host; + if (entry.primitive && host && !host.isDestroyed()) + host.remove(entry.primitive); + } + + /** Add or change items, by id; true once handled (always, for meshes). */ + function upsert(record, list) { + hostOf(record); + for (const item of list) put(record, item); + notePickIds(record); + requestRender(); + return true; + } + + /** The set's items as they are now: meshes gone dropped, the rest kept. */ + function build(record) { + hostOf(record); + for (const id of [...record.meshes.keys()]) + if (!record.items.has(id)) drop(record, id); + for (const item of record.items.values()) put(record, item); + notePickIds(record); + } + + return { build, upsert }; +} diff --git a/src/render/cesium/drawQuads.js b/src/render/cesium/drawQuads.js new file mode 100644 index 000000000..190f49f20 --- /dev/null +++ b/src/render/cesium/drawQuads.js @@ -0,0 +1,350 @@ +/** + * @module render/cesium/drawQuads + * @description The Cesium draw port's `quads` sets: each item a unit plane + * primitive scaled to its `size`, posed by its `center` and `orientation` + * (the plane lies in the orientation's local x–y plane, width along x, + * height along y, its face toward local +z), textured with its image, + * video or canvas, and its outline beside it, as a Cesium plane entity + * draws them. An update moves, turns, resizes, shows or retextures the + * plane where it is; only a change of pickability or of outline rebuilds + * it. + * + * Choices the contract leaves open, taken conservatively: + * - `orientation` turns the plane in the Earth-fixed frame. + * - A canvas is read when an item first names it, as a Cesium material + * reads one: to show new pixels, name another canvas (two canvases in + * turn, say). The material takes a new image on the frame after it is + * named, so the two drawn frames after a change are asked for (asked + * for again once a hidden quad shows). + * - A video is read every drawn frame, and keeps frames coming while it + * plays and its quad shows (starting again as it plays, seeks or has + * data again); a video whose size changes is read at its new size. A + * change between a video and another source makes a new material, so + * neither reads into the other's texture. + * - Quads are lit by the scene's light and always draw translucent, their + * image's own alpha read, as a plane entity's transparent image material + * does. + */ +import * as Cesium from 'cesium'; +import { toCartesian } from './common.js'; + +const scratchQuaternion = new Cesium.Quaternion(); +const scratchScale = new Cesium.Cartesian3(); + +/** What a quad's material shows: an element, or an image's URL. */ +function sourceOf(source, toImage) { + if (source?.video) return source.video; + if (source?.canvas) return source.canvas; + if (source && 'image' in source) return toImage(source.image); + throw new Error('a quad takes an image, a video or a canvas'); +} + +/** An outline as a key; '' for none. */ +const outlineKey = (outline) => + outline + ? `${typeof outline.color === 'string' ? outline.color : outline.color.join(',')}|${outline.widthPx}` + : ''; + +/** + * The quads part of a Cesium draw port. + * @param {{toColor: Function, toImage: Function, + * pickId: Function, replaceHost: Function, lineWidth: (px: number) => number, + * requestRender: () => void}} options From the draw port. + */ +export function createQuadSets({ + toColor, + toImage, + pickId, + replaceHost, + lineWidth, + requestRender, +}) { + /** Materials replaced this frame, destroyed once it has drawn. */ + let retired = []; + + /** Media events after which a video draws again, with no frame asked. */ + const VIDEO_EVENTS = ['play', 'playing', 'canplay', 'loadeddata', 'seeked']; + + /** Ask for frames on the entry's video's events, while it shows one. */ + function watchVideo(entry) { + unwatchVideo(entry); + const video = entry.source; + if (!isVideo(video)) return; + const wake = () => requestRender(); + for (const name of VIDEO_EVENTS) video.addEventListener?.(name, wake); + entry.unwatch = () => { + for (const name of VIDEO_EVENTS) video.removeEventListener?.(name, wake); + }; + } + + function unwatchVideo(entry) { + entry.unwatch?.(); + entry.unwatch = null; + } + + /** The set's host, made once: its quads are changed where they are. */ + function hostOf(record) { + if (record.host && !record.host.isDestroyed?.()) return record.host; + const host = new Cesium.PrimitiveCollection(); + const quads = new Map(); + // Materials hold their textures, which primitives leave alone: the + // host destroys them as it goes. + const destroyHost = host.destroy.bind(host); + host.destroy = () => { + for (const entry of quads.values()) { + freeMaterial(entry.material); + unwatchVideo(entry); + } + quads.clear(); + return destroyHost(); + }; + record.quads = quads; + replaceHost(record, host); + return host; + } + + function freeMaterial(material) { + if (material && !material.isDestroyed()) material.destroy(); + } + + function imageMaterial(source, alpha) { + return Cesium.Material.fromType('Image', { + image: source, + color: Cesium.Color.WHITE.withAlpha(alpha), + }); + } + + /** Each live entry's pick id, for height queries to see through. */ + function notePickIds(record) { + record.pickIds = []; + for (const entry of record.quads.values()) + record.pickIds.push(entry.pickId); + } + + function matrixOf(item, result) { + const q = item.orientation; + scratchQuaternion.x = q.x; + scratchQuaternion.y = q.y; + scratchQuaternion.z = q.z; + scratchQuaternion.w = q.w; + scratchScale.x = item.size[0]; + scratchScale.y = item.size[1]; + scratchScale.z = 1; + return Cesium.Matrix4.fromTranslationQuaternionRotationScale( + toCartesian(item.center), + scratchQuaternion, + scratchScale, + result, + ); + } + + const pickableOf = (record, item) => + record.spec.pickable !== false && item.pickable !== false; + + /** Build an entry's primitives anew (it is new, or picks or outline changed). */ + function build(record, entry) { + const host = record.host; + const item = entry.item; + const allowPicking = pickableOf(record, item); + const modelMatrix = matrixOf(item, new Cesium.Matrix4()); + entry.source = sourceOf(item.source, toImage); + entry.alpha = item.alpha ?? 1; + entry.material = imageMaterial(entry.source, entry.alpha); + entry.videoSize = null; + entry.fill = host.add( + new Cesium.Primitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry: new Cesium.PlaneGeometry({ + vertexFormat: + Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat, + }), + id: entry.pickId, + }), + appearance: new Cesium.MaterialAppearance({ + material: entry.material, + translucent: true, + closed: false, + }), + modelMatrix, + allowPicking, + asynchronous: false, + show: item.show !== false, + }), + ); + entry.outline = null; + if (item.outline) { + const color = toColor(item.outline.color); + entry.outline = host.add( + new Cesium.Primitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry: new Cesium.PlaneOutlineGeometry(), + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), + }, + id: entry.pickId, + }), + appearance: new Cesium.PerInstanceColorAppearance({ + flat: true, + translucent: color.alpha < 1, + renderState: { lineWidth: lineWidth(item.outline.widthPx ?? 1) }, + }), + modelMatrix: Cesium.Matrix4.clone(modelMatrix), + allowPicking, + asynchronous: false, + show: item.show !== false, + }), + ); + } + entry.pickable = allowPicking; + entry.outlineKey = outlineKey(item.outline); + entry.uploadFrames = 2; + watchVideo(entry); + } + + function drop(record, id) { + const entry = record.quads.get(id); + if (!entry) return; + record.quads.delete(id); + unbuild(record, entry); + } + + function unbuild(record, entry) { + const host = record.host; + for (const primitive of [entry.fill, entry.outline]) + if (primitive && host && !host.isDestroyed()) host.remove(primitive); + freeMaterial(entry.material); + unwatchVideo(entry); + entry.fill = entry.outline = entry.material = null; + } + + /** A new material for an entry, the old one freed once the frame drew. */ + function rebind(entry) { + const old = entry.material; + entry.material = imageMaterial(entry.source, entry.alpha); + entry.fill.appearance.material = entry.material; + entry.videoSize = null; + entry.uploadFrames = 2; + if (old) retired.push(old); + } + + function put(record, item) { + let entry = record.quads.get(item.id); + if (!entry) { + entry = { item, pickId: pickId(record, item) }; + record.quads.set(item.id, entry); + build(record, entry); + return; + } + entry.item = item; + // The pick id is the primitives' own object: changed where it is. + entry.pickId.meta = item.meta; + if ( + entry.pickable !== pickableOf(record, item) || + entry.outlineKey !== outlineKey(item.outline) + ) { + unbuild(record, entry); + build(record, entry); + return; + } + const show = item.show !== false; + matrixOf(item, entry.fill.modelMatrix); + entry.fill.show = show; + if (entry.outline) { + Cesium.Matrix4.clone(entry.fill.modelMatrix, entry.outline.modelMatrix); + entry.outline.show = show; + } + const alpha = item.alpha ?? 1; + if (alpha !== entry.alpha) { + entry.alpha = alpha; + entry.material.uniforms.color = Cesium.Color.WHITE.withAlpha(alpha); + } + const source = sourceOf(item.source, toImage); + if (source !== entry.source) { + const video = isVideo(source) || isVideo(entry.source); + entry.source = source; + if (video) { + // To or from a video: a material of its own, so the video's frames + // are not copied into another source's texture, or the other way. + rebind(entry); + watchVideo(entry); + } else { + // Another canvas or URL: the material reads it anew. + entry.material.uniforms.image = source; + entry.uploadFrames = 2; + } + } + } + + /** Add or change items, by id; true once handled (always, for quads). */ + function upsert(record, list) { + hostOf(record); + for (const item of list) put(record, item); + notePickIds(record); + requestRender(); + return true; + } + + /** The set's items as they are now: quads gone dropped, the rest kept. */ + function rebuild(record) { + hostOf(record); + for (const id of [...record.quads.keys()]) + if (!record.items.has(id)) drop(record, id); + for (const item of record.items.values()) put(record, item); + notePickIds(record); + } + + const isVideo = (source) => + typeof globalThis.HTMLVideoElement === 'function' && + source instanceof globalThis.HTMLVideoElement; + + /** + * Each frame, before it draws: a video whose size changed since its + * texture was made is read at its new size. + */ + function beforeRender(sets) { + for (const record of sets) { + if (record.kind !== 'quads' || !record.quads) continue; + for (const entry of record.quads.values()) { + const video = entry.source; + if (!entry.fill || !isVideo(video) || video.readyState < 2) continue; + const size = `${video.videoWidth}x${video.videoHeight}`; + if (entry.videoSize === null) entry.videoSize = size; + else if (entry.videoSize !== size) rebind(entry); + } + } + } + + /** + * After a frame drew: the materials it replaced go, and a playing video + * on a shown quad, or an image a material is still to take, asks for the + * next frame. True when one did. + */ + function afterRender(sets) { + for (const material of retired) freeMaterial(material); + retired = []; + let playing = false; + for (const record of sets) { + if (record.kind !== 'quads' || !record.quads) continue; + if (record.spec.show === false || record.host?.show === false) continue; + for (const entry of record.quads.values()) { + if (!entry.fill?.show) continue; + // Only a frame that drew the quad counts toward taking its image. + if (entry.uploadFrames > 0) { + entry.uploadFrames -= 1; + playing = true; + } + const video = entry.source; + if ( + isVideo(video) && + !video.paused && + !video.ended && + video.readyState >= 2 + ) + playing = true; + } + } + return playing; + } + + return { build: rebuild, upsert, beforeRender, afterRender }; +} diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index c8b98cec0..273eefc59 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -60,6 +60,8 @@ const GLOBE_CAPABILITIES = [ export function cesiumCapabilities(scene, only) { const all = [ 'models', + 'quads', + 'meshes', 'followFrame', ...GPU_ICON_CAPABILITIES, 'styles', diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 14bd66327..395bcd9aa 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -24,15 +24,16 @@ test('capabilities follow what the scene supports', () => { 'imageHooks', ]; const globe = { show: true }; - assert.deepEqual(cesiumCapabilities({}), ['models', ...effects]); + const draw = ['models', 'quads', 'meshes']; + assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]); // A scene with a globe reads its visibility back. assert.deepEqual(cesiumCapabilities({ globe }), [ - 'models', + ...draw, ...effects, 'globeVisibility', ]); assert.deepEqual(cesiumCapabilities({ pickPositionSupported: true }), [ - 'models', + ...draw, ...effects, 'pickPosition', ]); @@ -43,7 +44,7 @@ test('capabilities follow what the scene supports', () => { sampleHeightSupported: true, }), [ - 'models', + ...draw, ...effects, 'globeVisibility', 'pickPosition', diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 469d285d0..501014a2b 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -7,12 +7,9 @@ "src/cockpitCloudEffects.js", "src/cyberSonarGpu.js", "src/cyberSonarScene.js", - "src/data/cctvGizmo.js", "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", "src/layers/installations/rendering.js", diff --git a/src/render/motion/iconBook.js b/src/render/motion/iconBook.js index 4621564bd..71e01fc08 100644 --- a/src/render/motion/iconBook.js +++ b/src/render/motion/iconBook.js @@ -78,6 +78,15 @@ export function createIconBook(drawSet = null, { capabilities = null } = {}) { else if (expiresAt !== undefined) expiries.set(item.id, expiresAt); drawSet?.upsert([item]); }, + /** + * Draw several items at once, as `put` draws one (a restyle: each keeps + * its motion's expiry), in one write to the set. + */ + putMany(list) { + if (!list.length) return; + for (const item of list) items.set(item.id, item); + drawSet?.upsert(list); + }, remove(id) { expiries.delete(id); if (items.delete(id)) drawSet?.remove([id]); diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index a6829ec8d..510dc35ab 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -86,6 +86,9 @@ const DRAW_FROM_CALLER = new Set([ './layers/street-level/panoramax', './layers/air-quality', './layers/directions', + // Its icons, wireframes, volumes, plane and gizmo draw through `drawOf`; + // it picks, projects and reads the eye and the globe through the ports. + './layers/cctv', // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // throws until then too. './scenes', @@ -116,6 +119,9 @@ const CAMERA_FROM_CALLER = new Set([ './ui/navigation', './voice/commands', './voice/controller', + // It loaded the camera factory only through the CCTV layer it took a + // constant from. + './voice/actions', './voice/realtime-session', ]); 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/services/groundSnap.js b/src/services/groundSnap.js index 012e2ee21..bf9125c4e 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -140,10 +140,11 @@ const SAMPLE_WINDOW_MS = 250; /** * True when the active photoreal tileset has finished streaming the tiles in - * view (cctv.js's projectionTilesReady pattern: first Cesium3DTileset found in - * scene.primitives, duck-typed via its boolean tilesLoaded). Sampling before - * that both blows the frame budget on forced synchronous loads and produces - * misses that would burn retry backoff for nothing. With NO tileset present + * view (the pattern CCTV's projectionTilesReady once used: first + * Cesium3DTileset found in scene.primitives, duck-typed via its boolean + * tilesLoaded). Sampling before that both blows the frame budget on forced + * synchronous loads and produces misses that would burn retry backoff for + * nothing. With NO tileset present * (OSM fallback) this returns true so the sample path is not permanently * blocked — the sample just misses and backs off. * @param {Cesium.Viewer} viewer diff --git a/src/services/meshFloorSampler.js b/src/services/meshFloorSampler.js index 0515c2196..20fca80e8 100644 --- a/src/services/meshFloorSampler.js +++ b/src/services/meshFloorSampler.js @@ -62,7 +62,8 @@ export function createMeshFloorSampler({ /** * True when a VISIBLE 3D tileset in the scene reports its streaming queue - * drained (tilesLoaded) — the mirror of cctv.js's projectionTilesReady. + * drained (tilesLoaded) — as CCTV's projectionTilesReady once did (it now + * asks the globe port whether its drawn photoreal tiles have settled). * Walks top-level primitives only (a handful; once per poll). * @param {Cesium.Scene} scene * @returns {boolean} 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); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 1fd260b45..64f88ece0 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -48,7 +48,7 @@ import { getSelectedEntityContext, isContextRecordActive, } from '../data/contextStore.js'; -import { CCTV_FOCUS_RESULT } from '../layers/cctv/index.js'; +import { CCTV_FOCUS_RESULT } from '../layers/cctv/policy.js'; import { createAnalystEngine, normalizeAnalystSpec,