From 167aa947ce338d90af77eb22af04d08be25eea47 Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 00:11:31 +0100 Subject: [PATCH 01/38] fix(cctv): admit and bound HLS leases by peer --- docs/CURRENT-STATE.md | 7 ++++ scripts/package-boundaries.json | 2 + server/providers/cctv.js | 23 +++++++++-- server/providers/cctv/stream.js | 59 ++++++++++++++++++++++------- src/data/cctvHlsStream.test.mjs | 37 ++++++++++++++++++ src/data/cctvMediaFeedType.test.mjs | 43 +++++++++++++++++++++ 6 files changed, 154 insertions(+), 17 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 55b7a63ab1..9d674d1055 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1,5 +1,12 @@ # God's Eye View Current State +CCTV live-media requests are same-site gated before catalog or media work, including +HLS renewal, segment reads and DELETE cleanup. HLS leases belong to their socket +peer (IPv4-mapped IPv6 is normalized), with eight leases per peer across the two +global sessions. Peers behind the same NAT share that budget; this is resource +admission, not authentication. Native same-origin video and range requests remain +supported. + Shared distance checks use `src/geoDistance.js` with `{ lat, lon }` points and the IUGG mean spherical Earth radius, 6371.0088 km. `greatCircleKm` is canonical; `greatCircleMeters` is its exact metre conversion. Missing, diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ca5dc0c7fa..fc9e4b5e98 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -187,6 +187,8 @@ "exports": ["./server/providers/cctv"], "modules": [ "server/providers/cctv.js", + "server/providers/common/same-site.js", + "src/localRequestGate.mjs", "server/providers/cctv/cap.js", "server/providers/cctv/groundHeights.js", "server/providers/cctv/catalog.js", diff --git a/server/providers/cctv.js b/server/providers/cctv.js index e549753e82..fc8f4f692d 100644 --- a/server/providers/cctv.js +++ b/server/providers/cctv.js @@ -17,6 +17,7 @@ import { CCTV_MAX_SOURCES_CEILING, } from './cctv/constants.js'; import { sanitizeCctvRangeHeader } from './cctv/range.js'; +import { admitSameSite } from './common/same-site.js'; import { createHlsPuller } from './cctv/stream.js'; import { googleServerApiKey } from './places/google-key.js'; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; @@ -135,11 +136,18 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { }); server.middlewares.use('/api/cctv', async (req, res) => { try { + const url = new URL(req.url || '/', 'http://localhost'); + // Refuse before catalog I/O, session creation, renewal or release. + if (url.pathname.startsWith('/media/') && admitSameSite(req, res)) + return; + const clientId = String(req.socket?.remoteAddress || 'unknown').replace( + /^::ffff:/, + '', + ); const sources = await getCctvSources(); const sourceById = new Map( sources.map((source) => [source.id, source]), ); - const url = new URL(req.url || '/', 'http://localhost'); if (url.pathname === '/sources') { const body = { @@ -238,7 +246,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { return; } if (req.method === 'DELETE') { - if (leaseId) puller.release(cameraId, leaseId); + if (leaseId) puller.release(cameraId, leaseId, clientId); res.writeHead(204); res.end(); return; @@ -268,6 +276,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { url.searchParams.get('session'), Number(match[3]), leaseId, + clientId, ); res.writeHead(body ? 200 : 404, { 'Content-Type': 'video/mp2t', @@ -279,10 +288,15 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { const downstream = watchDownstreamClose(res); let entry; const cancelPending = () => { - if (entry) puller.release(cameraId, leaseId); + if (entry) puller.release(cameraId, leaseId, clientId); }; try { - entry = await puller.ensure(cameraId, mediaUrl, leaseId); + entry = await puller.ensure( + cameraId, + mediaUrl, + leaseId, + clientId, + ); if (downstream.closed) { cancelPending(); return; @@ -296,6 +310,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { entry, cameraId, leaseId, + clientId, ); if (downstream.closed) return; if (!playlist) throw new Error('Stream unavailable'); diff --git a/server/providers/cctv/stream.js b/server/providers/cctv/stream.js index 14d1743bb8..46608f294e 100644 --- a/server/providers/cctv/stream.js +++ b/server/providers/cctv/stream.js @@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto'; export const HLS_LIMITS = Object.freeze({ sessions: 2, leasesPerSession: 8, + leasesPerClient: 8, playlistBytes: 256 * 1024, segmentBytes: 4 * 1024 * 1024, sessionBytes: 24 * 1024 * 1024, @@ -138,25 +139,37 @@ export function createHlsPuller({ entry.upstream.clear(); entry.bytes = 0; }; - const release = (cameraId, leaseId) => { + const release = (cameraId, leaseId, clientId = 'legacy') => { const entry = active.get(cameraId); const lease = entry?.leases.get(leaseId); - if (!lease) return; + if (!lease || lease.clientId !== clientId) return; clearTimeout(lease.timer); entry.leases.delete(leaseId); if (!entry.leases.size) stop(cameraId, entry.token); }; - const touch = (entry, leaseId, create = false) => { + const touch = (entry, leaseId, create = false, clientId = 'legacy') => { let lease = entry.leases.get(leaseId); + if (lease && lease.clientId !== clientId) + throw new Error('HLS lease belongs to another client'); if (!lease) { + const clientLeases = [...active.values()].reduce( + (count, session) => + count + + [...session.leases.values()].filter( + (item) => item.clientId === clientId, + ).length, + 0, + ); + if (clientLeases >= limits.leasesPerClient) + throw new Error('HLS client lease capacity reached'); if (!create || entry.leases.size >= limits.leasesPerSession) throw new Error('HLS lease capacity reached'); - lease = {}; + lease = { clientId }; entry.leases.set(leaseId, lease); } clearTimeout(lease.timer); lease.timer = setTimeout( - () => release(entry.cameraId, leaseId), + () => release(entry.cameraId, leaseId, clientId), limits.idleMs, ); lease.timer.unref?.(); @@ -248,7 +261,12 @@ export function createHlsPuller({ } } }; - const ensure = async (cameraId, url, leaseId = 'legacy') => { + const ensure = async ( + cameraId, + url, + leaseId = 'legacy', + clientId = 'legacy', + ) => { if (closed) throw new Error('HLS service closed'); sameOriginHlsUrl(url, url); let entry = active.get(cameraId); @@ -257,7 +275,7 @@ export function createHlsPuller({ entry = null; } if (entry) { - touch(entry, leaseId, true); + touch(entry, leaseId, true, clientId); return entry; } // Reserve synchronously, before any await: concurrent creation is singleflight. @@ -279,8 +297,8 @@ export function createHlsPuller({ pendingDiscontinuity: false, discontinuitiesRemoved: 0, }; + touch(entry, leaseId, true, clientId); active.set(cameraId, entry); - touch(entry, leaseId, true); entry.polling = poll(entry); return entry; }; @@ -292,9 +310,14 @@ export function createHlsPuller({ } return false; }; - const buildPlaylist = async (entry, cameraId, leaseId = 'legacy') => { + const buildPlaylist = async ( + entry, + cameraId, + leaseId = 'legacy', + clientId = 'legacy', + ) => { if (entry.stopping || entry.segments.size < 2) return null; - touch(entry, leaseId); + touch(entry, leaseId, false, clientId); const segments = [...entry.segments.values()].sort((a, b) => a.seq - b.seq); const lines = [ '#EXTM3U', @@ -318,12 +341,22 @@ export function createHlsPuller({ } return lines.join('\n') + '\n'; }; - const getSegment = (cameraId, token, seq, leaseId = 'legacy') => { + const getSegment = ( + cameraId, + token, + seq, + leaseId = 'legacy', + clientId = 'legacy', + ) => { const entry = active.get(cameraId); - if (!entry || entry.token !== token || !entry.leases.has(leaseId)) + if ( + !entry || + entry.token !== token || + entry.leases.get(leaseId)?.clientId !== clientId + ) return null; const body = entry.segments.get(seq)?.body; - if (body) touch(entry, leaseId); + if (body) touch(entry, leaseId, false, clientId); return body || null; }; const shutdown = async () => { diff --git a/src/data/cctvHlsStream.test.mjs b/src/data/cctvHlsStream.test.mjs index a087eebdf8..01f5b15e48 100644 --- a/src/data/cctvHlsStream.test.mjs +++ b/src/data/cctvHlsStream.test.mjs @@ -223,3 +223,40 @@ test('an abandoned consumer expires while a renewed consumer keeps the session', assert.equal(entry.controller.signal.aborted, false); await manager.shutdown(); }); + +test('client lease ownership covers refresh, segments and release, with a bounded client budget', async (t) => { + const manager = createHlsPuller({ + limits: { ...HLS_LIMITS, leasesPerClient: 1, pollMs: 100000 }, + fetchImpl: async (url) => + new Response(url.endsWith('.m3u8') ? playlist : 'abc'), + }); + t.after(() => manager.shutdown()); + const entry = await manager.ensure('a', base, 'lease-a', 'peer-a'); + await manager.waitReady(entry); + await assert.rejects( + manager.ensure('a', base, 'lease-a', 'peer-b'), + /another client/, + ); + assert.equal( + manager.getSegment('a', entry.token, 0, 'lease-a', 'peer-b'), + null, + ); + await assert.rejects( + manager.buildPlaylist(entry, 'a', 'lease-a', 'peer-b'), + /another client/, + ); + manager.release('a', 'lease-a', 'peer-b'); + assert.equal(entry.leases.size, 1); + await assert.rejects( + manager.ensure('b', base, 'lease-b', 'peer-a'), + /client lease capacity/, + ); + assert.equal( + manager.stats().sessions, + 1, + 'failed admission reserves no session', + ); + await manager.ensure('b', base, 'lease-b', 'peer-b'); + manager.release('a', 'lease-a', 'peer-a'); + assert.equal(entry.stopping, true); +}); diff --git a/src/data/cctvMediaFeedType.test.mjs b/src/data/cctvMediaFeedType.test.mjs index 5791e433b1..e6ba9e3eb9 100644 --- a/src/data/cctvMediaFeedType.test.mjs +++ b/src/data/cctvMediaFeedType.test.mjs @@ -268,3 +268,46 @@ test('/frame does not follow a still camera off its origin', async (t) => { [STILL.url], ); }); + +test('cross-site media creation, segment reads and release fail before any catalog or media fetch', async (t) => { + let handler; + const originalFetch = globalThis.fetch; + let calls = 0; + globalThis.fetch = async () => { + calls++; + throw new Error('must not fetch'); + }; + t.after(() => { + globalThis.fetch = originalFetch; + }); + cctvProxy().configureServer({ + middlewares: { + use: (_path, fn) => { + handler = fn; + }, + }, + }); + for (const headers of [ + { origin: 'https://foreign.example' }, + { origin: 'null' }, + { 'sec-fetch-site': 'cross-site' }, + { 'sec-fetch-site': 'same-site' }, + ]) { + for (const [method, url] of [ + ['GET', '/media/camera?lease=test'], + ['DELETE', '/media/camera?lease=test'], + ['GET', '/media/camera/seg_0.ts?lease=test'], + ]) { + const { res } = recordingResponse(); + res.setHeader = (name, value) => { + res.headers[name] = value; + }; + await handler( + { method, url, headers: { host: 'localhost:4173', ...headers } }, + res, + ); + assert.equal(res.statusCode, 403); + } + } + assert.equal(calls, 0); +}); From a7160c62be9794875ecdd757b0f3b8141fd37dd4 Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 00:11:49 +0100 Subject: [PATCH 02/38] docs: record CCTV session admission fix --- changelog.d/1267-cctv-session-admission.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 changelog.d/1267-cctv-session-admission.md diff --git a/changelog.d/1267-cctv-session-admission.md b/changelog.d/1267-cctv-session-admission.md new file mode 100644 index 0000000000..c331e210d5 --- /dev/null +++ b/changelog.d/1267-cctv-session-admission.md @@ -0,0 +1,2 @@ +- Gate CCTV HLS media requests before session work, bind leases to the direct + peer, and bound per-peer leases across shared sessions (asturksever, #1267). From ad003118c5d27a437615e471e98d052150db1116 Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 01:06:53 +0100 Subject: [PATCH 03/38] fix(annotations): cull and budget surface height sampling --- docs/CURRENT-STATE.md | 2 + src/annotations/screenAnnotationRenderer.js | 42 +++++++- .../screenAnnotationRenderer.test.mjs | 102 +++++++++++++++++- 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 55b7a63ab1..12a40da090 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1,5 +1,7 @@ # God's Eye View Current State +Screen annotations reject hidden records and anchors wholly behind the camera or globe horizon before surface sampling. Unresolved visible heights share a 32-sample projection-pass budget, retry at most once per second per anchor on rendered frames, and retain no extra timer or listener. Unsettled points continue retrying as late terrain arrives; behind-camera, horizon and conservative frustum culls run before sampling. Validated heights remain settled in the bounded cache. + Shared distance checks use `src/geoDistance.js` with `{ lat, lon }` points and the IUGG mean spherical Earth radius, 6371.0088 km. `greatCircleKm` is canonical; `greatCircleMeters` is its exact metre conversion. Missing, diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index c6c214fffe..da06b37636 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -83,6 +83,9 @@ export function createScreenAnnotationRenderer( const heightCache = new Map(); const HEIGHT_CACHE_SOFT = 600; // target size; over this we evict keys not used this frame const HEIGHT_CACHE_HARD = 8000; // absolute ceiling (one big ring + others) — never exceeded + let cullingVolume = null; + const heightBounds = new Cesium.BoundingSphere(new Cesium.Cartesian3(), 9500); + let heightBudget = 32; let projGen = 0; // bumped each projection frame; entries used this frame are "hot" function trimHeightCache() { if (heightCache.size <= HEIGHT_CACHE_SOFT) return; @@ -123,6 +126,13 @@ export function createScreenAnnotationRenderer( heightCache.set(key, cached); return cached.h; } + const now = Date.now(); + if (cached && now < cached.nextAttempt) { + cached.gen = projGen; + return cached.h; + } + if (heightBudget <= 0) return cached?.h || 0; + heightBudget--; try { if ( scene.clampToHeightSupported && @@ -144,7 +154,12 @@ export function createScreenAnnotationRenderer( /* tiles not ready */ } const fallback = cached ? cached.h : 0; - heightCache.set(key, { h: fallback, settled: false, gen: projGen }); + heightCache.set(key, { + h: fallback, + settled: false, + gen: projGen, + nextAttempt: now + 1000, + }); trimHeightCache(); return fallback; } @@ -362,6 +377,24 @@ export function createScreenAnnotationRenderer( // Anchor at the real surface height (cached + validated), so marks sit on // the ground/building instead of at sea level. The settle-once cache keeps // it stable (no per-frame jitter that earlier broke nearby projections). + // Cheap conservative endpoint tests precede GPU-backed surface sampling. + // Testing the accepted height range avoids culling an elevated roof solely + // because its sea-level anchor lies just beyond the horizon. + const visibleAt = (height) => { + const point = Cesium.Cartesian3.fromDegrees(lon, lat, height); + Cesium.Cartesian3.subtract(point, scene.camera.positionWC, scratchDir); + return ( + Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) > 0 && + occluder.isPointVisible(point) + ); + }; + Cesium.Cartesian3.fromDegrees(lon, lat, 0, undefined, heightBounds.center); + if ( + cullingVolume?.computeVisibility(heightBounds) === + Cesium.Intersect.OUTSIDE + ) + return null; + if (!visibleAt(0) && !visibleAt(9000)) return null; const world = Cesium.Cartesian3.fromDegrees( lon, lat, @@ -467,6 +500,13 @@ export function createScreenAnnotationRenderer( function projectAll() { if (!records.size) return; + heightBudget = 32; + cullingVolume = + scene.camera.frustum?.computeCullingVolume?.( + scene.camera.positionWC, + scene.camera.directionWC, + scene.camera.upWC, + ) || null; projGen += 1; // new frame: entries touched below are "hot" and survive trimming const trackedRect = trackedEntityRect(); occluder.cameraPosition = scene.camera.positionWC; diff --git a/src/annotations/screenAnnotationRenderer.test.mjs b/src/annotations/screenAnnotationRenderer.test.mjs index ef4509ed0c..94615e831f 100644 --- a/src/annotations/screenAnnotationRenderer.test.mjs +++ b/src/annotations/screenAnnotationRenderer.test.mjs @@ -152,10 +152,17 @@ test('outline upgrade preserves the existing SVG group identity', (t) => { }); const camera = { - positionWC: Cesium.Cartesian3.ZERO, - directionWC: Cesium.Cartesian3.ZERO, + positionWC: Cesium.Cartesian3.fromDegrees(-97.5, 31.2, 1000000), + directionWC: Cesium.Cartesian3.normalize( + Cesium.Cartesian3.negate( + Cesium.Cartesian3.fromDegrees(-97.5, 31.2), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ), positionCartographic: { height: 1000 }, }; + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 100, y: 100 })); const sampledAnchors = []; const scene = { camera, @@ -326,3 +333,94 @@ test('an add that throws after inserting its group unwinds instead of orphaning ); renderer.destroy(); }); + +test('hidden and back-facing annotations do not sample; visible unresolved heights have bounded retries', (t) => { + const previous = globalThis.document; + const previousRaf = globalThis.requestAnimationFrame; + globalThis.document = fakeDocument(); + globalThis.requestAnimationFrame = (fn) => { + fn(); + return 1; + }; + t.after(() => { + globalThis.document = previous; + globalThis.requestAnimationFrame = previousRaf; + }); + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 }); + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ + x: 100, + y: 100, + })); + const camera = { + positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 100000), + directionWC: new Cesium.Cartesian3(-1, 0, 0), + positionCartographic: { height: 100000 }, + moveEnd: new Cesium.Event(), + }; + let samples = 0; + const postRender = new Cesium.Event(); + const scene = { + camera, + canvas: { width: 800, height: 600 }, + postRender, + clampToHeightSupported: true, + clampToHeight() { + samples++; + }, + requestRender() {}, + }; + const renderer = createScreenAnnotationRenderer({ scene, camera }); + const mark = (id, lon) => ({ + id, + type: 'label', + anchor: { lon, lat: 0 }, + label: id, + }); + renderer.add(mark('far-side', 180)); + for (let i = 0; i < 100; i++) postRender.raiseEvent(); + assert.equal(samples, 0); + renderer.add(mark('near-side', 0)); + for (let i = 0; i < 100; i++) postRender.raiseEvent(); + assert.equal(samples, 1); + for (let i = 0; i < 10; i++) { + t.mock.timers.tick(1000); + postRender.raiseEvent(); + } + assert.equal(samples, 11); + camera.moveEnd.raiseEvent(); + postRender.raiseEvent(); + assert.equal(samples, 11, 'camera events cannot bypass the retry interval'); + renderer.update(mark('near-side', 0), { empty: true }); + t.mock.timers.tick(1000); + postRender.raiseEvent(); + assert.equal(samples, 11, 'hidden records do not sample'); + camera.directionWC = new Cesium.Cartesian3(1, 0, 0); + renderer.update(mark('near-side', 0)); + postRender.raiseEvent(); + assert.equal(samples, 11, 'behind-camera anchors do not sample'); + camera.directionWC = new Cesium.Cartesian3(-1, 0, 0); + camera.frustum = { + computeCullingVolume: () => ({ + computeVisibility: () => Cesium.Intersect.OUTSIDE, + }), + }; + postRender.raiseEvent(); + assert.equal(samples, 11, 'outside-frustum anchors do not sample'); + camera.frustum = null; + const before = samples; + renderer.add({ + id: 'large-area', + type: 'area', + label: 'Area', + ring: Array.from({ length: 100 }, (_, i) => [0.001 + i / 10000, 0]), + anchor: { lon: 0, lat: 0 }, + }); + assert.equal( + samples - before, + 32, + 'a projection pass caps synchronous surface work', + ); + renderer.destroy(); + assert.equal(camera.moveEnd.numberOfListeners, 0); + assert.equal(postRender.numberOfListeners, 0); +}); From f2b4162d768adca9d07d310fa923798e6b81b4eb Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 01:07:09 +0100 Subject: [PATCH 04/38] docs: record annotation fix --- changelog.d/1277-annotation-issue-fix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/1277-annotation-issue-fix.md diff --git a/changelog.d/1277-annotation-issue-fix.md b/changelog.d/1277-annotation-issue-fix.md new file mode 100644 index 0000000000..6f17992372 --- /dev/null +++ b/changelog.d/1277-annotation-issue-fix.md @@ -0,0 +1 @@ +- Cull and budget surface height sampling (asturksever, #1277). From 5e9c14db83b26242ce8052f96a5ffeae979349ce Mon Sep 17 00:00:00 2001 From: Said Date: Tue, 20 Oct 2026 14:10:29 +0100 Subject: [PATCH 05/38] test: keep headful CCTV gate rendering when occluded --- changelog.d/1267-cctv-session-admission.md | 1 + scripts/qa-cctv-v2.mjs | 1 + 2 files changed, 2 insertions(+) diff --git a/changelog.d/1267-cctv-session-admission.md b/changelog.d/1267-cctv-session-admission.md index c331e210d5..c331222e70 100644 --- a/changelog.d/1267-cctv-session-admission.md +++ b/changelog.d/1267-cctv-session-admission.md @@ -1,2 +1,3 @@ - Gate CCTV HLS media requests before session work, bind leases to the direct peer, and bound per-peer leases across shared sessions (asturksever, #1267). +- Keep headful CCTV QA rendering active when its window is occluded (asturksever, #1267). diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index 88e0a5a2c4..a6abdffa34 100644 --- a/scripts/qa-cctv-v2.mjs +++ b/scripts/qa-cctv-v2.mjs @@ -454,6 +454,7 @@ async function main() { ...(HEADFUL ? [] : ['--use-gl=angle', '--use-angle=swiftshader']), '--disable-dev-shm-usage', '--disable-web-security', + '--disable-backgrounding-occluded-windows', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--window-size=1280,800', From aa4e0ca936775c2eb7b23e1875c64286dc9ef724 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 23 Oct 2026 12:30:39 +0100 Subject: [PATCH 06/38] Fix annotation height culling review findings (#1277) - Restrict the conservative frustum test to height sampling only: an endpoint outside it still projects at its cached or zero height, so an arrow with one off-frustum endpoint keeps its visible connector and label. - Test a settled height as the actual point; reject an unknown height before sampling only when both ends of the accepted -430..9000 m range fail the same constraint (behind camera, or below horizon), which the convexity of each rejection region makes a proof for the whole range. - Queue keys refused by an exhausted budget and reserve the next pass's budget for the oldest of them, so anchors beyond the first 32 are served under sparse passes while keeping 32 samples per pass and 1 s retries. - Add regressions with a real frustum, a low-angle authored camera, and 33 persistent points under sparse passes; consolidate CURRENT-STATE. Co-Authored-By: Claude Opus 5.5 --- docs/CURRENT-STATE.md | 10 +- src/annotations/screenAnnotationRenderer.js | 130 ++++++++---- .../screenAnnotationRenderer.test.mjs | 186 ++++++++++++++++++ 3 files changed, 291 insertions(+), 35 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f3e6ebd1b4..2adf7da33d 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -9,7 +9,15 @@ broader suffix variants. Follow-ups retain boundary provenance, and cancelled lookups preserve the previous analyst cohort and boundary source. Navigation search keeps a successful geocode, with no search or view-based region recovery. -Screen annotations reject hidden records and anchors wholly behind the camera or globe horizon before surface sampling. Unresolved visible heights share a 32-sample projection-pass budget, retry at most once per second per anchor on rendered frames, and retain no extra timer or listener. Unsettled points continue retrying as late terrain arrives; behind-camera, horizon and conservative frustum culls run before sampling. Validated heights remain settled in the bounded cache. +Screen annotations skip hidden records and, before surface sampling, reject an +unsettled anchor only when its whole accepted height range (-430 to 9000 m) is +behind the camera or below the globe horizon; a settled height is tested as the +actual point. Anchors outside the conservative frustum still project at their +cached or zero height, so a partly visible arrow keeps its connector, but do +not sample. Unresolved visible heights share a 32-sample projection-pass budget, +served oldest-refused first, retry at most once per second per anchor on +rendered frames, and retain no extra timer or listener. Validated heights remain +settled in the bounded cache. Terrain height requests accept at most 64 points, matching the browser service's existing batch size and one bounded upstream chunk. Larger requests return HTTP diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index da06b37636..d7fda32acd 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -83,9 +83,20 @@ export function createScreenAnnotationRenderer( const heightCache = new Map(); const HEIGHT_CACHE_SOFT = 600; // target size; over this we evict keys not used this frame const HEIGHT_CACHE_HARD = 8000; // absolute ceiling (one big ring + others) — never exceeded + // Accepted surface-height range; samples outside it are treated as misses. + const MIN_SURFACE_HEIGHT = -430; + const MAX_SURFACE_HEIGHT = 9000; + const HEIGHT_SAMPLE_BUDGET = 32; // clampToHeight calls per projection pass + const HEIGHT_RETRY_MS = 1000; // minimum interval between misses per anchor let cullingVolume = null; const heightBounds = new Cesium.BoundingSphere(new Cesium.Cartesian3(), 9500); - let heightBudget = 32; + // Fair sampling: keys refused by an exhausted budget queue in arrival order, + // and each pass reserves budget for the oldest queued keys first, so a fixed + // iteration order cannot starve anchors beyond the first budget's worth. + let heightQueue = new Set(); // keys refused in earlier passes, oldest first + let heightReserved = new Set(); // queued keys this pass serves first + let heightRefused = new Set(); // keys refused during this pass + let heightBudget = HEIGHT_SAMPLE_BUDGET; // unreserved slots left this pass let projGen = 0; // bumped each projection frame; entries used this frame are "hot" function trimHeightCache() { if (heightCache.size <= HEIGHT_CACHE_SOFT) return; @@ -113,10 +124,20 @@ export function createScreenAnnotationRenderer( return PALETTE[anno.color] || PALETTE.primary; } + function clearHeights() { + heightCache.clear(); + heightQueue.clear(); + } + + function heightKey(lon, lat) { + return `${lon.toFixed(5)},${lat.toFixed(5)}`; + } + // Best-effort surface height under a coordinate (clamps onto the 3D tiles). // Returns 0 until the tile loads, then caches the validated height. - function groundHeight(lon, lat) { - const key = `${lon.toFixed(5)},${lat.toFixed(5)}`; + // canSample=false returns the cached height (or 0) without surface sampling. + function groundHeight(lon, lat, canSample = true) { + const key = heightKey(lon, lat); const cached = heightCache.get(key); if (cached && cached.settled) { // Mark hot for this frame + bump to most-recently-used so heights for live @@ -127,12 +148,19 @@ export function createScreenAnnotationRenderer( return cached.h; } const now = Date.now(); - if (cached && now < cached.nextAttempt) { + if (cached && (!canSample || now < cached.nextAttempt)) { cached.gen = projGen; return cached.h; } - if (heightBudget <= 0) return cached?.h || 0; - heightBudget--; + if (!canSample) return 0; + if (heightReserved.has(key)) { + heightReserved.delete(key); + } else if (heightBudget > 0) { + heightBudget--; + } else { + heightRefused.add(key); + return cached?.h || 0; + } try { if ( scene.clampToHeightSupported && @@ -143,7 +171,11 @@ export function createScreenAnnotationRenderer( ); if (c) { const h = Cesium.Cartographic.fromCartesian(c).height; - if (Number.isFinite(h) && h > -430 && h < 9000) { + if ( + Number.isFinite(h) && + h > MIN_SURFACE_HEIGHT && + h < MAX_SURFACE_HEIGHT + ) { heightCache.set(key, { h, settled: true, gen: projGen }); trimHeightCache(); return h; @@ -158,7 +190,7 @@ export function createScreenAnnotationRenderer( h: fallback, settled: false, gen: projGen, - nextAttempt: now + 1000, + nextAttempt: now + HEIGHT_RETRY_MS, }); trimHeightCache(); return fallback; @@ -325,7 +357,7 @@ export function createScreenAnnotationRenderer( } catch { /* never inserted */ } - if (records.size === 0) heightCache.clear(); + if (records.size === 0) clearHeights(); throw error; } } @@ -377,29 +409,30 @@ export function createScreenAnnotationRenderer( // Anchor at the real surface height (cached + validated), so marks sit on // the ground/building instead of at sea level. The settle-once cache keeps // it stable (no per-frame jitter that earlier broke nearby projections). - // Cheap conservative endpoint tests precede GPU-backed surface sampling. - // Testing the accepted height range avoids culling an elevated roof solely - // because its sea-level anchor lies just beyond the horizon. - const visibleAt = (height) => { - const point = Cesium.Cartesian3.fromDegrees(lon, lat, height); - Cesium.Cartesian3.subtract(point, scene.camera.positionWC, scratchDir); - return ( - Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) > 0 && - occluder.isPointVisible(point) + // A settled height is tested as the actual point below. An unknown height + // is rejected before GPU-backed surface sampling only when the whole + // accepted height range is proven hidden by one constraint. + let height; + if (heightCache.get(heightKey(lon, lat))?.settled) { + height = groundHeight(lon, lat); + } else { + if (heightRangeHidden(lon, lat)) return null; + // The frustum restricts sampling only; an endpoint outside it still + // projects (at its cached or zero height) so a partly visible arrow, + // route or ring keeps its on-screen connector and label. + Cesium.Cartesian3.fromDegrees( + lon, + lat, + 0, + undefined, + heightBounds.center, ); - }; - Cesium.Cartesian3.fromDegrees(lon, lat, 0, undefined, heightBounds.center); - if ( - cullingVolume?.computeVisibility(heightBounds) === - Cesium.Intersect.OUTSIDE - ) - return null; - if (!visibleAt(0) && !visibleAt(9000)) return null; - const world = Cesium.Cartesian3.fromDegrees( - lon, - lat, - groundHeight(lon, lat), - ); + const inFrustum = + cullingVolume?.computeVisibility(heightBounds) !== + Cesium.Intersect.OUTSIDE; + height = groundHeight(lon, lat, inFrustum); + } + const world = Cesium.Cartesian3.fromDegrees(lon, lat, height); // Reject points behind the camera (they produce wrapped/extreme coords). Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir); if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0) @@ -419,6 +452,21 @@ export function createScreenAnnotationRenderer( return { x: win.x, y: win.y }; } + // Points along one surface normal are linear in height, and each rejection + // region (behind the camera plane; the occluder's cone beyond the horizon + // plane) is convex. So when both height-range endpoints fail the SAME test, + // every intermediate height fails it too. Mixed failures prove nothing. + function heightRangeHidden(lon, lat) { + const low = Cesium.Cartesian3.fromDegrees(lon, lat, MIN_SURFACE_HEIGHT); + const high = Cesium.Cartesian3.fromDegrees(lon, lat, MAX_SURFACE_HEIGHT); + const behind = (point) => { + Cesium.Cartesian3.subtract(point, scene.camera.positionWC, scratchDir); + return Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0; + }; + if (behind(low) && behind(high)) return true; + return !occluder.isPointVisible(low) && !occluder.isPointVisible(high); + } + // Tracked-entity z-order: the tracked aircraft is a Cesium billboard in the // CANVAS, which sits BELOW this SVG overlay (z-90, HTML over canvas). So a screen mark // could hide it. After layout, any mark whose ACTUAL projected bounding box (rings, @@ -500,7 +548,14 @@ export function createScreenAnnotationRenderer( function projectAll() { if (!records.size) return; - heightBudget = 32; + // Serve the oldest refused keys first; the rest of the budget is open. + heightReserved = new Set(); + for (const key of heightQueue) { + if (heightReserved.size >= HEIGHT_SAMPLE_BUDGET) break; + heightReserved.add(key); + } + heightBudget = HEIGHT_SAMPLE_BUDGET - heightReserved.size; + heightRefused = new Set(); cullingVolume = scene.camera.frustum?.computeCullingVolume?.( scene.camera.positionWC, @@ -653,6 +708,13 @@ export function createScreenAnnotationRenderer( } } } + // Still-refused queued keys keep their place; new refusals join the back. + // Keys no longer requesting a sample (settled, culled, removed) drop out. + const nextQueue = new Set(); + for (const key of heightQueue) + if (heightRefused.has(key)) nextQueue.add(key); + for (const key of heightRefused) nextQueue.add(key); + heightQueue = nextQueue; // Keep clustered callouts readable. const placed = []; @@ -733,7 +795,7 @@ export function createScreenAnnotationRenderer( }, 360); records.delete(anno.id); // Board emptied → drop accumulated height samples (natural reset point). - if (records.size === 0) heightCache.clear(); + if (records.size === 0) clearHeights(); } function sync() { @@ -753,7 +815,7 @@ export function createScreenAnnotationRenderer( /* gone */ } records.clear(); - heightCache.clear(); + clearHeights(); } return { add, update, remove, sync, destroy }; diff --git a/src/annotations/screenAnnotationRenderer.test.mjs b/src/annotations/screenAnnotationRenderer.test.mjs index 94615e831f..aba1faec34 100644 --- a/src/annotations/screenAnnotationRenderer.test.mjs +++ b/src/annotations/screenAnnotationRenderer.test.mjs @@ -424,3 +424,189 @@ test('hidden and back-facing annotations do not sample; visible unresolved heigh assert.equal(camera.moveEnd.numberOfListeners, 0); assert.equal(postRender.numberOfListeners, 0); }); + +function sampledLon(world) { + const carto = Cesium.Cartographic.fromCartesian(world); + return Number(Cesium.Math.toDegrees(carto.longitude).toFixed(5)); +} + +function installDom(t) { + const previous = globalThis.document; + const previousRaf = globalThis.requestAnimationFrame; + globalThis.document = fakeDocument(); + globalThis.requestAnimationFrame = (fn) => { + fn(); + return 1; + }; + t.after(() => { + globalThis.document = previous; + globalThis.requestAnimationFrame = previousRaf; + }); +} + +function squareFrustum() { + const frustum = new Cesium.PerspectiveFrustum(); + frustum.fov = Cesium.Math.toRadians(60); + frustum.aspectRatio = 1; + frustum.near = 1; + frustum.far = 1e8; + return frustum; +} + +test('an arrow with one endpoint outside a real frustum keeps its visible connector', (t) => { + installDom(t); + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', (_scene, world) => + sampledLon(world) > 0.1 ? { x: 1100, y: 400 } : { x: 400, y: 400 }, + ); + // 5 km straight down over (0, 0): east is +Y, north is +Z in ECEF here. + const camera = { + positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 5000), + directionWC: new Cesium.Cartesian3(-1, 0, 0), + upWC: new Cesium.Cartesian3(0, 0, 1), + positionCartographic: { height: 5000 }, + frustum: squareFrustum(), + }; + const sampled = []; + const postRender = new Cesium.Event(); + const scene = { + camera, + canvas: { width: 800, height: 800 }, + postRender, + clampToHeightSupported: true, + clampToHeight(world) { + sampled.push(sampledLon(world)); + return world; + }, + }; + // The 0.2-degree endpoint (~22 km east) is well beyond the side plane plus + // the 9.5 km height-bound radius, yet in front of the camera and the horizon. + const far = Cesium.Cartesian3.fromDegrees(0.2, 0, 0); + const volume = camera.frustum.computeCullingVolume( + camera.positionWC, + camera.directionWC, + camera.upWC, + ); + assert.equal( + volume.computeVisibility(new Cesium.BoundingSphere(far, 9500)), + Cesium.Intersect.OUTSIDE, + ); + const renderer = createScreenAnnotationRenderer({ scene, camera }); + renderer.add({ + id: 'partial-arrow', + type: 'arrow', + label: 'Ridge', + anchor: { lon: 0, lat: 0 }, + to: { lon: 0.2, lat: 0 }, + }); + postRender.raiseEvent(); + const { group } = findAnnotationGroup(globalThis.document); + assert.equal(group.style.display, '', 'the arrow stays drawn'); + const path = group.children.find((child) => child.classList.contains('gev-anno-arrow')); + assert.match(path.getAttribute('d'), /^M 400\.0 400\.0 Q .* 1100\.0 400\.0$/); + assert.deepEqual([...new Set(sampled)], [0], 'only the in-frustum endpoint samples'); + renderer.destroy(); +}); + +test('a low-angle cached roof stays visible when range endpoints fail different tests', (t) => { + installDom(t); + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 400, y: 380 })); + // Camera 1 m above the ellipsoid, heading east, pitched 25 degrees down. + const pitch = Cesium.Math.toRadians(25); + const camera = { + positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1), + directionWC: new Cesium.Cartesian3(-Math.sin(pitch), Math.cos(pitch), 0), + upWC: new Cesium.Cartesian3(Math.cos(pitch), Math.sin(pitch), 0), + positionCartographic: { height: 1 }, + frustum: squareFrustum(), + }; + const roofLon = 4000 / 111319.49; + let samples = 0; + const postRender = new Cesium.Event(); + const scene = { + camera, + canvas: { width: 800, height: 800 }, + postRender, + clampToHeightSupported: true, + clampToHeight() { + samples++; + return Cesium.Cartesian3.fromDegrees(roofLon, 0, 20); + }, + }; + // Sanity: height 0 is beyond the horizon and 9000 m is behind the camera, + // while the 20 m roof itself is in front and above the horizon. + const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC); + const ahead = (h) => { + const p = Cesium.Cartesian3.fromDegrees(roofLon, 0, h); + const v = Cesium.Cartesian3.subtract(p, camera.positionWC, new Cesium.Cartesian3()); + return Cesium.Cartesian3.dot(v, camera.directionWC) > 0; + }; + assert.equal(occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(roofLon, 0, 0)), false); + assert.equal(ahead(9000), false); + assert.equal(ahead(20), true); + assert.equal(occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(roofLon, 0, 20)), true); + + const renderer = createScreenAnnotationRenderer({ scene, camera }); + renderer.add({ id: 'roof', type: 'label', label: 'Roof', anchor: { lon: roofLon, lat: 0 } }); + const { group } = findAnnotationGroup(globalThis.document); + assert.equal(samples, 1, 'the unknown height is sampled, not culled'); + assert.equal(group.style.display, ''); + for (let i = 0; i < 5; i++) postRender.raiseEvent(); + assert.equal(samples, 1, 'the settled height is reused'); + assert.equal(group.style.display, '', 'the cached roof point is tested and shown'); + renderer.destroy(); +}); + +test('height retries beyond the first budget are served under sparse passes', (t) => { + installDom(t); + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 }); + t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 100, y: 100 })); + const camera = { + positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 100000), + directionWC: new Cesium.Cartesian3(-1, 0, 0), + positionCartographic: { height: 100000 }, + }; + const lons = Array.from({ length: 33 }, (_, i) => Number(((i + 1) / 1000).toFixed(3))); + const last = lons.at(-1); + let tilesReady = false; + let pass = []; + const postRender = new Cesium.Event(); + const scene = { + camera, + canvas: { width: 800, height: 600 }, + postRender, + clampToHeightSupported: true, + clampToHeight(world) { + const lon = sampledLon(world); + pass.push(lon); + return tilesReady && lon === last ? Cesium.Cartesian3.fromDegrees(lon, 0, 12) : undefined; + }, + }; + const renderer = createScreenAnnotationRenderer({ scene, camera }); + for (const lon of lons) { + renderer.add({ id: `p${lon}`, type: 'label', label: 'P', anchor: { lon, lat: 0 } }); + } + assert.ok(pass.includes(last), 'every point gets its initial miss'); + tilesReady = true; // tiles under the final point arrive after its miss + const lastSamples = []; + for (let i = 0; i < 4; i++) { + t.mock.timers.tick(1000); + pass = []; + postRender.raiseEvent(); + assert.ok(pass.length <= 32, `pass ${i} keeps the 32-sample budget`); + lastSamples.push(pass.filter((lon) => lon === last).length); + } + assert.ok(lastSamples.slice(0, 2).includes(1), 'the 33rd point is served within two passes'); + assert.equal(lastSamples.at(-1), 0, 'and then stays settled'); + // Points refused in one pass are served first in the next: every point is + // retried within any two consecutive sparse passes. + pass = []; + t.mock.timers.tick(1000); + postRender.raiseEvent(); + const firstPass = pass; + pass = []; + t.mock.timers.tick(1000); + postRender.raiseEvent(); + const served = new Set([...firstPass, ...pass]); + for (const lon of lons.slice(0, -1)) assert.ok(served.has(lon), `${lon} retried`); + renderer.destroy(); +}); From 0781b4a8de501095df0107229a99927c01b8b29f Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Tue, 10 Nov 2026 23:54:40 +0000 Subject: [PATCH 07/38] fix(annotations): repair the main merge and port the sampling tests (#1277) The last merge of main kept four tests on a DOM harness that main had removed, so they threw ReferenceError and CI failed. They now run on the store-backed board. The merge had also dropped main's empty-board publish, the leaving/byKey clear in destroy, and three unrelated CURRENT-STATE paragraphs; all are restored. The projection now builds each height-cache key once per point, and the changelog entry says what changed. --- changelog.d/1277-annotation-issue-fix.md | 5 +- docs/CURRENT-STATE.md | 18 ++++++ src/annotations/screenAnnotationRenderer.js | 20 ++++--- .../screenAnnotationRenderer.test.mjs | 58 +++++++++---------- 4 files changed, 64 insertions(+), 37 deletions(-) diff --git a/changelog.d/1277-annotation-issue-fix.md b/changelog.d/1277-annotation-issue-fix.md index 6f17992372..ba5eb97f3b 100644 --- a/changelog.d/1277-annotation-issue-fix.md +++ b/changelog.d/1277-annotation-issue-fix.md @@ -1 +1,4 @@ -- Cull and budget surface height sampling (asturksever, #1277). +- Stop screen annotations sampling surface height for marks that are hidden, + behind the camera or over the horizon. Visible marks still waiting for + terrain share 32 samples per projection pass and retry once a second, so a + large board no longer stalls the frame (asturksever, #1277). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 45562707da..2c919bcbf9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -127,6 +127,24 @@ broader suffix variants. Follow-ups retain boundary provenance, and cancelled lookups preserve the previous analyst cohort and boundary source. Navigation search keeps a successful geocode, with no search or view-based region recovery. +Manager-owned periodic network updates pause while the document is hidden. Returning to a visible tab runs one overdue update per enabled layer without overlapping an active refresh and restarts that layer's polling schedule from the return, so the next poll follows one interval later whether or not the catch-up update succeeds; explicit refresh requests remain available. Transit also defers camera-driven feed admission while hidden and rechecks coverage on return. Visibility listeners are released with their polling intervals. + +Overpass reserves each normalized query before its disk-cache lookup. The +initial disk lookup, upstream quota admission, fetching and memory publication +are coalesced under that reservation. A caller that joined a reservation +rejected by another client's quota retries admission with its own quota. +Stale fallback runs per response after the reservation is released, and disk +writes finish asynchronously. Settled and rejected reservations are removed +only while they still own their map entry. + +External ALPR tags, surveillance-tool fields, voice context text and compact +analyst strings become one line of at most 180 characters (scene labels: 120). +Empty ALPR values stay null, and the cap never splits a surrogate pair. +Canonical analyst identifiers such as `id` and `routeId` stay unchanged, because +voice follow-ups match on them and bikeshare uses the raw station name as its +ID. The text is still untrusted: normalization does not prevent prompt +injection. + Screen annotations skip hidden records and, before surface sampling, reject an unsettled anchor only when its whole accepted height range (-430 to 9000 m) is behind the camera or below the globe horizon; a settled height is tested as the diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index 48e64ddb88..301402f983 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -153,9 +153,8 @@ export function createScreenAnnotationRenderer( // Best-effort surface height under a coordinate (clamps onto the 3D tiles). // Returns 0 until the tile loads, then caches the validated height. // canSample=false returns the cached height (or 0) without surface sampling. - function groundHeight(lon, lat, canSample = true) { - const key = heightKey(lon, lat); - const cached = heightCache.get(key); + // `key` and `cached` are the caller's cache lookup for this coordinate. + function groundHeight(lon, lat, key, cached, canSample = true) { if (cached && cached.settled) { // Mark hot for this frame + bump to most-recently-used so heights for live // marks survive eviction while places we've navigated away from age out. @@ -413,9 +412,11 @@ export function createScreenAnnotationRenderer( // A settled height is tested as the actual point below. An unknown height // is rejected before GPU-backed surface sampling only when the whole // accepted height range is proven hidden by one constraint. + const key = heightKey(lon, lat); + const cached = heightCache.get(key); let height; - if (heightCache.get(heightKey(lon, lat))?.settled) { - height = groundHeight(lon, lat); + if (cached?.settled) { + height = groundHeight(lon, lat, key, cached); } else { if (heightRangeHidden(lon, lat)) return null; // The frustum restricts sampling only; an endpoint outside it still @@ -431,7 +432,7 @@ export function createScreenAnnotationRenderer( const inFrustum = cullingVolume?.computeVisibility(heightBounds) !== Cesium.Intersect.OUTSIDE; - height = groundHeight(lon, lat, inFrustum); + height = groundHeight(lon, lat, key, cached, inFrustum); } const world = Cesium.Cartesian3.fromDegrees(lon, lat, height); // Reject points behind the camera (they produce wrapped/extreme coords). @@ -552,7 +553,10 @@ export function createScreenAnnotationRenderer( } function projectAll() { - if (!records.size) return; + if (!records.size) { + publish(); + return; + } // Serve the oldest refused keys first; the rest of the budget is open. heightReserved = new Set(); for (const key of heightQueue) { @@ -931,6 +935,8 @@ export function createScreenAnnotationRenderer( store.publish(null); } records.clear(); + leaving.clear(); + byKey.clear(); clearHeights(); } diff --git a/src/annotations/screenAnnotationRenderer.test.mjs b/src/annotations/screenAnnotationRenderer.test.mjs index ae7cbcef2c..3dec5314e0 100644 --- a/src/annotations/screenAnnotationRenderer.test.mjs +++ b/src/annotations/screenAnnotationRenderer.test.mjs @@ -584,17 +584,7 @@ test('a mark hidden from Draw is not drawn or placed, and comes back when shown' }); test('hidden and back-facing annotations do not sample; visible unresolved heights have bounded retries', (t) => { - const previous = globalThis.document; - const previousRaf = globalThis.requestAnimationFrame; - globalThis.document = fakeDocument(); - globalThis.requestAnimationFrame = (fn) => { - fn(); - return 1; - }; - t.after(() => { - globalThis.document = previous; - globalThis.requestAnimationFrame = previousRaf; - }); + const store = samplingBoard(t); t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 }); t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 100, @@ -618,7 +608,7 @@ test('hidden and back-facing annotations do not sample; visible unresolved heigh }, requestRender() {}, }; - const renderer = createScreenAnnotationRenderer({ scene, camera }); + const renderer = samplingRenderer(store, scene); const mark = (id, lon) => ({ id, type: 'label', @@ -679,18 +669,29 @@ function sampledLon(world) { return Number(Cesium.Math.toDegrees(carto.longitude).toFixed(5)); } -function installDom(t) { - const previous = globalThis.document; +/** + * A board with no view mounted, for tests that count surface samples: the + * renderer projects on `add` and on each post-render event, and the store + * holds what it would draw. Animation frames run at once. + */ +function samplingBoard(t) { const previousRaf = globalThis.requestAnimationFrame; - globalThis.document = fakeDocument(); globalThis.requestAnimationFrame = (fn) => { fn(); return 1; }; t.after(() => { - globalThis.document = previous; globalThis.requestAnimationFrame = previousRaf; }); + return useScreenAnnotationsStore(createPinia()); +} + +/** The renderer under test, on the given board and scene. */ +function samplingRenderer(store, scene) { + return createScreenAnnotationRenderer( + { scene, camera: scene.camera, trackedEntity: null }, + { store, activeTrackedReadoutId: () => null }, + ); } function squareFrustum() { @@ -703,7 +704,7 @@ function squareFrustum() { } test('an arrow with one endpoint outside a real frustum keeps its visible connector', (t) => { - installDom(t); + const store = samplingBoard(t); t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', (_scene, world) => sampledLon(world) > 0.1 ? { x: 1100, y: 400 } : { x: 400, y: 400 }, ); @@ -739,7 +740,7 @@ test('an arrow with one endpoint outside a real frustum keeps its visible connec volume.computeVisibility(new Cesium.BoundingSphere(far, 9500)), Cesium.Intersect.OUTSIDE, ); - const renderer = createScreenAnnotationRenderer({ scene, camera }); + const renderer = samplingRenderer(store, scene); renderer.add({ id: 'partial-arrow', type: 'arrow', @@ -748,16 +749,16 @@ test('an arrow with one endpoint outside a real frustum keeps its visible connec to: { lon: 0.2, lat: 0 }, }); postRender.raiseEvent(); - const { group } = findAnnotationGroup(globalThis.document); - assert.equal(group.style.display, '', 'the arrow stays drawn'); - const path = group.children.find((child) => child.classList.contains('gev-anno-arrow')); - assert.match(path.getAttribute('d'), /^M 400\.0 400\.0 Q .* 1100\.0 400\.0$/); + const [mark] = store.board.marks; + assert.equal(mark.display, '', 'the arrow stays drawn'); + const path = mark.children.find((child) => child.attrs.class?.includes('gev-anno-arrow')); + assert.match(path.attrs.d, /^M 400\.0 400\.0 Q .* 1100\.0 400\.0$/); assert.deepEqual([...new Set(sampled)], [0], 'only the in-frustum endpoint samples'); renderer.destroy(); }); test('a low-angle cached roof stays visible when range endpoints fail different tests', (t) => { - installDom(t); + const store = samplingBoard(t); t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 400, y: 380 })); // Camera 1 m above the ellipsoid, heading east, pitched 25 degrees down. const pitch = Cesium.Math.toRadians(25); @@ -794,19 +795,18 @@ test('a low-angle cached roof stays visible when range endpoints fail different assert.equal(ahead(20), true); assert.equal(occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(roofLon, 0, 20)), true); - const renderer = createScreenAnnotationRenderer({ scene, camera }); + const renderer = samplingRenderer(store, scene); renderer.add({ id: 'roof', type: 'label', label: 'Roof', anchor: { lon: roofLon, lat: 0 } }); - const { group } = findAnnotationGroup(globalThis.document); assert.equal(samples, 1, 'the unknown height is sampled, not culled'); - assert.equal(group.style.display, ''); + assert.equal(store.board.marks[0].display, ''); for (let i = 0; i < 5; i++) postRender.raiseEvent(); assert.equal(samples, 1, 'the settled height is reused'); - assert.equal(group.style.display, '', 'the cached roof point is tested and shown'); + assert.equal(store.board.marks[0].display, '', 'the cached roof point is tested and shown'); renderer.destroy(); }); test('height retries beyond the first budget are served under sparse passes', (t) => { - installDom(t); + const store = samplingBoard(t); t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 }); t.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 100, y: 100 })); const camera = { @@ -830,7 +830,7 @@ test('height retries beyond the first budget are served under sparse passes', (t return tilesReady && lon === last ? Cesium.Cartesian3.fromDegrees(lon, 0, 12) : undefined; }, }; - const renderer = createScreenAnnotationRenderer({ scene, camera }); + const renderer = samplingRenderer(store, scene); for (const lon of lons) { renderer.add({ id: `p${lon}`, type: 'label', label: 'P', anchor: { lon, lat: 0 } }); } From 3bda877a8a6adf20f43e9e314109875bba2a9f51 Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:34:37 -0600 Subject: [PATCH 08/38] perf(cctv): fetch the active camera's pictures only while they can be seen --- docs/CURRENT-STATE.md | 10 +++ src/layers/cctv/frames.js | 53 +++++++++++ src/layers/cctv/frames.test.mjs | 154 ++++++++++++++++++++++++++++++++ src/ui/cctvPanel.test.mjs | 57 ++++++++++++ src/ui/cctvPresentation.js | 12 ++- 5 files changed, 282 insertions(+), 4 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7292252ac1..3c217960c8 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1976,6 +1976,16 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. +The active camera's pictures follow what can be seen. The monitor plane on the +globe stops fetching its still every 10 s while the sphere around the camera +mount and the plane is outside the view, or all of its points are below the +horizon (a 2D or Columbus scene always counts as visible), and fetches again +on the first refresh tick after it returns; activating or calibrating a camera +always fetches. The panel's still preview is requested only while the tab is +visible and the panel is expanded, and the panel asks for the current picture +when it is shown again. This matches the panel's live video, which already +played only in a visible tab and an expanded panel. + Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. Traffic and bikeshare expose factories through `./layers/traffic` and diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 5049614923..ba0177f225 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -1,3 +1,4 @@ +import * as Cesium from 'cesium'; import { FRAME_SIGNATURE_W, FRAME_SIGNATURE_H, @@ -236,6 +237,53 @@ export function createFrames({ state: layerState, services, parts, source }) { ctx.fillText(status.slice(0, 58), 46, h - 42); } + /** + * Whether a camera's monitor plane can be on screen: the mount, the far cap + * and its corners are bounded by one sphere that is tested against the view + * frustum, and at least one of those points must be above the horizon. + * Anything this cannot judge (no viewer, a 2D or Columbus scene, no geometry + * yet) counts as visible, so a missing input never blocks a picture. + * @param {Object} record - Camera record. + * @returns {boolean} + */ + + function projectionInView(record) { + const viewer = layerState._viewer; + if (!viewer || viewer.isDestroyed?.()) return true; + const { camera, scene } = viewer; + if (!camera || !scene || scene.mode !== Cesium.SceneMode.SCENE3D) + return true; + const placed = record?.frustumPositions; + const points = [ + record?.billboard?.position, + placed?.mount, + placed?.capCenter, + placed?.tl, + placed?.tr, + placed?.br, + placed?.bl, + ].filter(Boolean); + if ( + !points.length || + typeof camera.frustum?.computeCullingVolume !== 'function' + ) + return true; + const occluder = new Cesium.EllipsoidalOccluder( + Cesium.Ellipsoid.WGS84, + camera.positionWC, + ); + if (!points.some((point) => occluder.isPointVisible(point))) return false; + const culling = camera.frustum.computeCullingVolume( + camera.positionWC, + camera.directionWC, + camera.upWC, + ); + return ( + culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)) !== + Cesium.Intersect.OUTSIDE + ); + } + /** * Triggers a new frame fetch for an image-mode projection if the refresh * interval has elapsed. Active cameras refresh more frequently than idle ones. @@ -269,6 +317,10 @@ export function createFrames({ state: layerState, services, parts, source }) { // bypass a provider's explicit minimum between image requests. if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return; if (!force && sinceLastRefresh < refreshMs) return; + // A plane nobody can see (panned away, far side of the globe) needs no new + // picture; the next tick after it comes back fetches one. A forced refresh + // (fresh activation, calibration) still runs. + if (!force && !projectionInView(record)) return; runtime.lastImageRefreshAt = now; const frameUrl = frameUrlFor(record.camera, refreshMs); @@ -402,6 +454,7 @@ export function createFrames({ state: layerState, services, parts, source }) { mediaUrlFor, paintProjectionPlaceholder, refreshProjectionImage, + projectionInView, paintPlaceholderThrottled, drawProjectionFrame, }; diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index 0d03e94576..3253074ba0 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -3,6 +3,7 @@ // 1920x1080 projection canvas, instead of being stretched to fill it. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; import { createFrames, fitToProjection } from './frames.js'; import { FRAME_SIGNATURE_W, @@ -139,3 +140,156 @@ test('same pixels at a new aspect redraw at the new fit', () => { ]); assert.equal(runtime.canvasStamp, 2); }); + +// A camera's monitor plane is fetched only while it can be on screen. The +// viewer is a Cesium camera description over the real WGS84 globe: it hovers +// 30 km above a mount at (0, 0) and looks straight down, so the plane is in +// front of it; turned around, or moved to the far side of the globe, the +// plane is not. +const MOUNT = Cesium.Cartesian3.fromDegrees(0, 0, 20); +const point = (lon, lat, alt = 20) => + Cesium.Cartesian3.fromDegrees(lon, lat, alt); + +function planeRecord() { + const image = {}; + return { + camera: { id: 'plane' }, + billboard: { position: MOUNT }, + frustumPositions: { + mount: MOUNT, + capCenter: point(0.0005, 0, 20), + tl: point(0.0004, 0.0001), + tr: point(0.0006, 0.0001), + br: point(0.0006, -0.0001), + bl: point(0.0004, -0.0001), + }, + projection: { + mode: 'image', + image, + imageLoading: false, + imageReady: false, + lastImageRefreshAt: 0, + }, + }; +} + +function viewerAt(position, direction, up) { + return { + isDestroyed: () => false, + scene: { mode: Cesium.SceneMode.SCENE3D }, + camera: { + positionWC: position, + directionWC: direction, + upWC: up, + frustum: new Cesium.PerspectiveFrustum({ + fov: Cesium.Math.toRadians(60), + aspectRatio: 16 / 9, + near: 1, + far: 5e6, + }), + }, + }; +} + +// Above the mount, looking straight down at the ground. +function lookingDown() { + const position = point(0, 0, 30000); + return viewerAt( + position, + Cesium.Cartesian3.negate(Cesium.Cartesian3.UNIT_X, new Cesium.Cartesian3()), + Cesium.Cartesian3.UNIT_Z, + ); +} + +function framesFor(viewer) { + const state = { + _viewer: viewer, + _healthById: new Map(), + _activeCameraId: 'plane', + }; + return createFrames({ + state, + services: {}, + parts: { + model: { + safeNumber: (value, fallback) => + Number.isFinite(Number(value)) ? Number(value) : fallback, + }, + }, + source: { getFrameUrl: () => '/api/cctv/frame?id=plane' }, + }); +} + +test('a plane in front of the camera fetches its picture', () => { + const frames = framesFor(lookingDown()); + const record = planeRecord(); + assert.equal(frames.projectionInView(record), true); + frames.refreshProjectionImage(record); + assert.match( + record.projection.image.src, + /^\/api\/cctv\/frame\?id=plane&projTs=/, + ); + assert.equal(record.projection.imageLoading, true); +}); + +test('a plane behind the camera is not fetched, but a forced refresh is', () => { + const down = lookingDown(); + const away = viewerAt( + down.camera.positionWC, + Cesium.Cartesian3.UNIT_X, + Cesium.Cartesian3.UNIT_Z, + ); + const frames = framesFor(away); + const record = planeRecord(); + assert.equal(frames.projectionInView(record), false); + frames.refreshProjectionImage(record); + assert.equal(record.projection.image.src, undefined); + assert.equal(record.projection.lastImageRefreshAt, 0); + frames.refreshProjectionImage(record, true); + assert.match(record.projection.image.src, /projTs=/); +}); + +test('a plane below the horizon is not fetched', () => { + const far = point(180, 0, 30000); + const viewer = viewerAt( + far, + Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(MOUNT, far, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ), + Cesium.Cartesian3.UNIT_Z, + ); + const frames = framesFor(viewer); + assert.equal(frames.projectionInView(planeRecord()), false); +}); + +test('a skipped refresh does not use up the interval: the plane fetches once it is back in view', () => { + const record = planeRecord(); + const frames = framesFor(lookingDown()); + const away = viewerAt( + lookingDown().camera.positionWC, + Cesium.Cartesian3.UNIT_X, + Cesium.Cartesian3.UNIT_Z, + ); + const awayFrames = framesFor(away); + awayFrames.refreshProjectionImage(record); + assert.equal(record.projection.image.src, undefined); + frames.refreshProjectionImage(record); + assert.match(record.projection.image.src, /projTs=/); +}); + +test('what cannot be judged counts as visible', () => { + const record = planeRecord(); + assert.equal(framesFor(null).projectionInView(record), true); + assert.equal( + framesFor({ ...lookingDown(), isDestroyed: () => true }).projectionInView( + record, + ), + true, + ); + const flat = lookingDown(); + flat.scene.mode = Cesium.SceneMode.SCENE2D; + assert.equal(framesFor(flat).projectionInView(record), true); + const noGeometry = { camera: { id: 'plane' }, projection: record.projection }; + assert.equal(framesFor(lookingDown()).projectionInView(noGeometry), true); +}); diff --git a/src/ui/cctvPanel.test.mjs b/src/ui/cctvPanel.test.mjs index bc9c83c9be..18d18152c3 100644 --- a/src/ui/cctvPanel.test.mjs +++ b/src/ui/cctvPanel.test.mjs @@ -388,6 +388,8 @@ test('the frame preview renders each step of a camera frame request', async (t) globalThis.Image = prior; }); const { controls, byId } = panel(t); + // The preview loads while the panel is open; the panel starts collapsed. + byId('cctv-panel').classList.remove('collapsed'); const frame = byId('cctv-frame'); const wrap = byId('cctv-frame-wrap'); const badge = byId('cctv-source-badge'); @@ -606,3 +608,58 @@ test('the meta line of a disabled layer does not describe its last camera', () = ); assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /); }); + +test('the still preview is fetched only while the tab and the panel are shown', async (t) => { + const prior = globalThis.Image; + const requests = []; + globalThis.Image = class { + constructor() { + requests.push(this); + } + }; + const hidden = Object.getOwnPropertyDescriptor(document, 'hidden'); + let tabHidden = false; + Object.defineProperty(document, 'hidden', { + configurable: true, + get: () => tabHidden, + }); + t.after(() => { + globalThis.Image = prior; + if (hidden) Object.defineProperty(document, 'hidden', hidden); + else delete document.hidden; + }); + const { controls, byId } = panel(t); + const panelElement = byId('cctv-panel'); + const state = (frameUrl) => ({ + enabled: true, + count: 1, + cameraIndex: [camera], + activeCameraId: 'a', + activeCamera: { ...camera, frameUrl, sourceKind: 'snapshot' }, + }); + + // Collapsed panel: nothing is requested, however often the state arrives. + assert.equal(panelElement.classList.contains('collapsed'), true); + controls._renderCctvState(state('a1.jpg')); + controls._renderCctvState(state('a2.jpg')); + assert.equal(requests.length, 0, 'collapsed panel'); + + // Opening it renders again (the real panel does so from a class observer) + // and asks for the current picture once. + panelElement.classList.remove('collapsed'); + controls._renderCctvState(state('a2.jpg')); + assert.equal(requests.length, 1, 'expanded panel'); + assert.equal(requests[0].src, 'a2.jpg'); + requests[0].onload(); + + // A background tab: refreshed URLs are not requested. + tabHidden = true; + controls._renderCctvState(state('a3.jpg')); + assert.equal(requests.length, 1, 'hidden tab'); + + // Back in the tab: the next render fetches the current URL. + tabHidden = false; + controls._renderCctvState(state('a3.jpg')); + assert.equal(requests.length, 2, 'visible tab'); + assert.equal(requests[1].src, 'a3.jpg'); +}); diff --git a/src/ui/cctvPresentation.js b/src/ui/cctvPresentation.js index 2f4cb8584e..8b2003d0f3 100644 --- a/src/ui/cctvPresentation.js +++ b/src/ui/cctvPresentation.js @@ -274,11 +274,14 @@ export function _renderCctvState(state) { const liveIntent = enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl; this.store.setLive(liveIntent); + // A background tab or a collapsed panel shows nothing, so neither plays the + // video nor fetches the still; the observer and the visibilitychange listener + // render again when the panel is shown. + const panelShown = + !(typeof document !== 'undefined' && document.hidden) && + !this._cctvPanel?.classList?.contains('collapsed'); if (this._cctvVideo) { - const visible = - liveIntent && - !document.hidden && - !this._cctvPanel?.classList.contains('collapsed'); + const visible = liveIntent && panelShown; if (!visible || this._cctvVideoCameraId !== activeId) { this._cctvVideoSurface?.stop(); this._cctvVideoSurface = null; @@ -303,6 +306,7 @@ export function _renderCctvState(state) { // immediate so navigation never waits on the prior camera's request. if ( nextSrc && + panelShown && (cameraChanged || (!frameLoading && this._frame.currentSrc !== nextSrc)) ) { this._queueCctvFrame(nextSrc, nextCameraId, cameraChanged); From 0151c178a4b419545e7bce287b050e8da95f5a05 Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:01:37 -0600 Subject: [PATCH 09/38] docs: changelog fragment for #1543 --- changelog.d/1543-cctv-visible-only-fetch.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1543-cctv-visible-only-fetch.md diff --git a/changelog.d/1543-cctv-visible-only-fetch.md b/changelog.d/1543-cctv-visible-only-fetch.md new file mode 100644 index 0000000000..4db3c8bc7b --- /dev/null +++ b/changelog.d/1543-cctv-visible-only-fetch.md @@ -0,0 +1,4 @@ +- Stop fetching the active CCTV camera's pictures when nobody can see them. The + monitor plane skips its 10 s still while it is off screen or below the + horizon, and the panel's still preview waits for a visible tab and an open + panel (Byrd-IT, #1543). From 9a3fc84935047dc393c1ec0f1e266041f017f40a Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:22:19 -0600 Subject: [PATCH 10/38] fix(cctv): address review of #1543 (horizon test, resume guard, no per-frame allocation, mobile sheet) - frames.test: viewerAt uses Cesium's default far (5e8) so the below-horizon test fails without occluder.isPointVisible - cctvControls: install the resume observer for a still-only panel too - cctvPresentation: panelShown also requires the Cameras sheet on phones; the observer watches body class/data-mobile-sheet - frames.projectionInView: shared horizonOccluder + scratch sphere/array --- changelog.d/1543-cctv-visible-only-fetch.md | 4 +- src/layers/cctv/frames.js | 23 ++++-- src/layers/cctv/frames.test.mjs | 4 +- src/ui/cctvControls.js | 11 ++- src/ui/cctvPanel.test.mjs | 84 ++++++++++++++++++--- src/ui/cctvPresentation.js | 9 ++- 6 files changed, 110 insertions(+), 25 deletions(-) diff --git a/changelog.d/1543-cctv-visible-only-fetch.md b/changelog.d/1543-cctv-visible-only-fetch.md index 4db3c8bc7b..80421a35c2 100644 --- a/changelog.d/1543-cctv-visible-only-fetch.md +++ b/changelog.d/1543-cctv-visible-only-fetch.md @@ -1,4 +1,4 @@ - Stop fetching the active CCTV camera's pictures when nobody can see them. The monitor plane skips its 10 s still while it is off screen or below the - horizon, and the panel's still preview waits for a visible tab and an open - panel (Byrd-IT, #1543). + horizon, and the panel's still preview waits for a visible tab, an open + panel and, on phones, the open Cameras sheet (Byrd-IT, #1543). diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index ba0177f225..8048b0e31a 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -1,4 +1,5 @@ import * as Cesium from 'cesium'; +import { horizonOccluder } from '../../data/iconOrientation.js'; import { FRAME_SIGNATURE_W, FRAME_SIGNATURE_H, @@ -42,6 +43,9 @@ export function fitToProjection(sourceW, sourceH) { }; } +const _scratchPoints = []; +const _scratchSphere = new Cesium.BoundingSphere(); + export function createFrames({ state: layerState, services, parts, source }) { /** * FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw @@ -254,7 +258,10 @@ export function createFrames({ state: layerState, services, parts, source }) { if (!camera || !scene || scene.mode !== Cesium.SceneMode.SCENE3D) return true; const placed = record?.frustumPositions; - const points = [ + // Reused buffers: this runs on every projection tick while out of view. + const points = _scratchPoints; + points.length = 0; + for (const point of [ record?.billboard?.position, placed?.mount, placed?.capCenter, @@ -262,16 +269,15 @@ export function createFrames({ state: layerState, services, parts, source }) { placed?.tr, placed?.br, placed?.bl, - ].filter(Boolean); + ]) { + if (point) points.push(point); + } if ( !points.length || typeof camera.frustum?.computeCullingVolume !== 'function' ) return true; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - camera.positionWC, - ); + const occluder = horizonOccluder(camera); if (!points.some((point) => occluder.isPointVisible(point))) return false; const culling = camera.frustum.computeCullingVolume( camera.positionWC, @@ -279,8 +285,9 @@ export function createFrames({ state: layerState, services, parts, source }) { camera.upWC, ); return ( - culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)) !== - Cesium.Intersect.OUTSIDE + culling.computeVisibility( + Cesium.BoundingSphere.fromPoints(points, _scratchSphere), + ) !== Cesium.Intersect.OUTSIDE ); } diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index 3253074ba0..7beea0c03a 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -185,7 +185,9 @@ function viewerAt(position, direction, up) { fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, - far: 5e6, + // Cesium's default far plane, as the app uses: a smaller one rejects + // the far-side mount before the horizon check is ever reached. + far: 5e8, }), }, }; diff --git a/src/ui/cctvControls.js b/src/ui/cctvControls.js index 1e227c92e2..2d5ad447a6 100644 --- a/src/ui/cctvControls.js +++ b/src/ui/cctvControls.js @@ -73,7 +73,10 @@ export class CctvControls { if (state) this._renderCctvState(state); if (this._cctvChip) this._publishCctvChip({}); }); - if (this._cctvVideo && typeof MutationObserver !== 'undefined') { + if ( + (this._cctvVideo || this._cctvFrame) && + typeof MutationObserver !== 'undefined' + ) { this._videoVisibilityObserver = new MutationObserver(() => this._renderCctvState(this._cctvState), ); @@ -82,6 +85,12 @@ export class CctvControls { attributes: true, attributeFilter: ['class', 'hidden'], }); + // On phones the panel is on screen only while the Cameras sheet is open. + if (typeof document !== 'undefined' && document.body) + this._videoVisibilityObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'data-mobile-sheet'], + }); this.listen(document, 'visibilitychange', () => this._renderCctvState(this._cctvState), ); diff --git a/src/ui/cctvPanel.test.mjs b/src/ui/cctvPanel.test.mjs index 18d18152c3..7612eacc3d 100644 --- a/src/ui/cctvPanel.test.mjs +++ b/src/ui/cctvPanel.test.mjs @@ -609,6 +609,15 @@ test('the meta line of a disabled layer does not describe its last camera', () = assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /); }); +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); +const stillState = (frameUrl) => ({ + enabled: true, + count: 1, + cameraIndex: [camera], + activeCameraId: 'a', + activeCamera: { ...camera, frameUrl, sourceKind: 'snapshot' }, +}); + test('the still preview is fetched only while the tab and the panel are shown', async (t) => { const prior = globalThis.Image; const requests = []; @@ -630,13 +639,7 @@ test('the still preview is fetched only while the tab and the panel are shown', }); const { controls, byId } = panel(t); const panelElement = byId('cctv-panel'); - const state = (frameUrl) => ({ - enabled: true, - count: 1, - cameraIndex: [camera], - activeCameraId: 'a', - activeCamera: { ...camera, frameUrl, sourceKind: 'snapshot' }, - }); + const state = stillState; // Collapsed panel: nothing is requested, however often the state arrives. assert.equal(panelElement.classList.contains('collapsed'), true); @@ -644,22 +647,79 @@ test('the still preview is fetched only while the tab and the panel are shown', controls._renderCctvState(state('a2.jpg')); assert.equal(requests.length, 0, 'collapsed panel'); - // Opening it renders again (the real panel does so from a class observer) - // and asks for the current picture once. + // Opening it resumes through the class observer, with no manual render. panelElement.classList.remove('collapsed'); - controls._renderCctvState(state('a2.jpg')); + await settle(); assert.equal(requests.length, 1, 'expanded panel'); assert.equal(requests[0].src, 'a2.jpg'); requests[0].onload(); // A background tab: refreshed URLs are not requested. tabHidden = true; + document.dispatchEvent(new Event('visibilitychange')); controls._renderCctvState(state('a3.jpg')); assert.equal(requests.length, 1, 'hidden tab'); - // Back in the tab: the next render fetches the current URL. + // Back in the tab: visibilitychange alone fetches the current URL. tabHidden = false; - controls._renderCctvState(state('a3.jpg')); + document.dispatchEvent(new Event('visibilitychange')); assert.equal(requests.length, 2, 'visible tab'); assert.equal(requests[1].src, 'a3.jpg'); }); + +test('the still preview waits for the Cameras sheet on phones', async (t) => { + const prior = globalThis.Image; + const requests = []; + globalThis.Image = class { + constructor() { + requests.push(this); + } + }; + t.after(() => { + globalThis.Image = prior; + document.body.classList.remove('mobile-shell'); + document.body.removeAttribute('data-mobile-sheet'); + }); + const { controls, byId } = panel(t); + byId('cctv-panel').classList.remove('collapsed'); + document.body.classList.add('mobile-shell'); + document.body.setAttribute('data-mobile-sheet', 'layers'); + controls._renderCctvState(stillState('a1.jpg')); + assert.equal(requests.length, 0, 'another sheet is open'); + + document.body.removeAttribute('data-mobile-sheet'); + controls._renderCctvState(stillState('a1.jpg')); + assert.equal(requests.length, 0, 'no sheet is open'); + + document.body.setAttribute('data-mobile-sheet', 'cameras'); + await settle(); + assert.equal(requests.length, 1, 'Cameras sheet opened'); + assert.equal(requests[0].src, 'a1.jpg'); + + // Off a phone the sheet attribute means nothing. + requests[0].onload(); + document.body.classList.remove('mobile-shell'); + document.body.setAttribute('data-mobile-sheet', 'layers'); + controls._renderCctvState(stillState('a2.jpg')); + assert.equal(requests.length, 2, 'desktop ignores the sheet'); +}); + +test('a still-only panel (no video element) resumes from the class change', async (t) => { + const prior = globalThis.Image; + const requests = []; + globalThis.Image = class { + constructor() { + requests.push(this); + } + }; + t.after(() => { + globalThis.Image = prior; + }); + const { controls, byId } = panel(t); + assert.equal(controls._cctvVideo, undefined); + controls._renderCctvState(stillState('a1.jpg')); + assert.equal(requests.length, 0); + byId('cctv-panel').classList.remove('collapsed'); + await settle(); + assert.equal(requests.length, 1); +}); diff --git a/src/ui/cctvPresentation.js b/src/ui/cctvPresentation.js index 8b2003d0f3..7e4b576f62 100644 --- a/src/ui/cctvPresentation.js +++ b/src/ui/cctvPresentation.js @@ -277,9 +277,16 @@ export function _renderCctvState(state) { // A background tab or a collapsed panel shows nothing, so neither plays the // video nor fetches the still; the observer and the visibilitychange listener // render again when the panel is shown. + // On phones the panel also belongs to one sheet: the shell hides it unless + // data-mobile-sheet is 'cameras'. + const body = typeof document !== 'undefined' ? document.body : null; + const sheetClosed = + !!body?.classList?.contains('mobile-shell') && + body.getAttribute('data-mobile-sheet') !== 'cameras'; const panelShown = !(typeof document !== 'undefined' && document.hidden) && - !this._cctvPanel?.classList?.contains('collapsed'); + !this._cctvPanel?.classList?.contains('collapsed') && + !sheetClosed; if (this._cctvVideo) { const visible = liveIntent && panelShown; if (!visible || this._cctvVideoCameraId !== activeId) { From b1b66e9717b4360a092a58e2565ab88ddc16a9d4 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Mon, 9 Nov 2026 06:13:20 -0600 Subject: [PATCH 11/38] fix(cctv): keep below-ellipsoid planes refreshing --- src/layers/cctv/frames.js | 32 ++++++++++++++++++++++++--- src/layers/cctv/frames.test.mjs | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 8048b0e31a..7040d242ed 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -45,6 +45,9 @@ export function fitToProjection(sourceW, sourceH) { const _scratchPoints = []; const _scratchSphere = new Cesium.BoundingSphere(); +const _scratchCartographic = new Cesium.Cartographic(); +// Close to the reference ellipsoid, it is not a reliable terrain horizon. +const LOW_VIEWER_HEIGHT_M = 1000; export function createFrames({ state: layerState, services, parts, source }) { /** @@ -244,7 +247,8 @@ export function createFrames({ state: layerState, services, parts, source }) { /** * Whether a camera's monitor plane can be on screen: the mount, the far cap * and its corners are bounded by one sphere that is tested against the view - * frustum, and at least one of those points must be above the horizon. + * frustum, and at least one of those points must be above the horizon when + * the reference ellipsoid is a reliable occluder for this view. * Anything this cannot judge (no viewer, a 2D or Columbus scene, no geometry * yet) counts as visible, so a missing input never blocks a picture. * @param {Object} record - Camera record. @@ -277,8 +281,30 @@ export function createFrames({ state: layerState, services, parts, source }) { typeof camera.frustum?.computeCullingVolume !== 'function' ) return true; - const occluder = horizonOccluder(camera); - if (!points.some((point) => occluder.isPointVisible(point))) return false; + // The reference ellipsoid can lie above the actual street. Near the + // surface its horizon would incorrectly hide nearby below-ellipsoid planes; + // let the frustum alone decide at low altitude or when height is unknown. + const height = Cesium.Cartographic.fromCartesian( + camera.positionWC, + Cesium.Ellipsoid.WGS84, + _scratchCartographic, + )?.height; + const pointsAboveEllipsoid = points.every((point) => { + const h = Cesium.Cartographic.fromCartesian( + point, + Cesium.Ellipsoid.WGS84, + _scratchCartographic, + )?.height; + return Number.isFinite(h) && h >= 0; + }); + if ( + Number.isFinite(height) && + height >= LOW_VIEWER_HEIGHT_M && + pointsAboveEllipsoid + ) { + const occluder = horizonOccluder(camera); + if (!points.some((point) => occluder.isPointVisible(point))) return false; + } const culling = camera.frustum.computeCullingVolume( camera.positionWC, camera.directionWC, diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index 7beea0c03a..c297311af4 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -251,6 +251,45 @@ test('a plane behind the camera is not fetched, but a forced refresh is', () => assert.match(record.projection.image.src, /projTs=/); }); +test('a nearby plane below the ellipsoid still fetches for a low viewer', () => { + const record = planeRecord(); + const mount = point(0, 0, -18); + const cap = point(0.00054, 0, -18); + const position = point(0.00135, 0, 4); + record.billboard.position = mount; + record.frustumPositions = { mount, capCenter: cap }; + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(cap, position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); + const sphere = Cesium.BoundingSphere.fromPoints([mount, cap]); + const culling = viewer.camera.frustum.computeCullingVolume( + position, + direction, + viewer.camera.upWC, + ); + assert.notEqual(culling.computeVisibility(sphere), Cesium.Intersect.OUTSIDE); + const frames = framesFor(viewer); + assert.equal(frames.projectionInView(record), true); + frames.refreshProjectionImage(record); + assert.match(record.projection.image.src, /projTs=/); + + // An above-threshold viewer still needs a conservative result when the + // entire plane itself is below the reference ellipsoid. + const high = point(0.00135, 0, 1200); + const highDirection = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(cap, high, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + assert.equal( + framesFor( + viewerAt(high, highDirection, Cesium.Cartesian3.UNIT_Z), + ).projectionInView(record), + true, + ); +}); + test('a plane below the horizon is not fetched', () => { const far = point(180, 0, 30000); const viewer = viewerAt( From 564383e4b53f8944b183154b28430bb992ad637d Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Mon, 9 Nov 2026 06:35:22 -0600 Subject: [PATCH 12/38] fix(cctv): retain far-side culling below ellipsoid --- src/layers/cctv/frames.js | 42 +++++++++++---------------------- src/layers/cctv/frames.test.mjs | 38 +++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 28 deletions(-) diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 7040d242ed..95ef0a9794 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -1,5 +1,4 @@ import * as Cesium from 'cesium'; -import { horizonOccluder } from '../../data/iconOrientation.js'; import { FRAME_SIGNATURE_W, FRAME_SIGNATURE_H, @@ -45,9 +44,15 @@ export function fitToProjection(sourceW, sourceH) { const _scratchPoints = []; const _scratchSphere = new Cesium.BoundingSphere(); -const _scratchCartographic = new Cesium.Cartographic(); -// Close to the reference ellipsoid, it is not a reliable terrain horizon. -const LOW_VIEWER_HEIGHT_M = 1000; +// Keep the occluding surface below common negative geoid undulations. +const HORIZON_MARGIN_M = 200; +const _radii = Cesium.Ellipsoid.WGS84.radii; +const _horizonEllipsoid = new Cesium.Ellipsoid( + _radii.x - HORIZON_MARGIN_M, + _radii.y - HORIZON_MARGIN_M, + _radii.z - HORIZON_MARGIN_M, +); +const _horizonOccluder = new Cesium.EllipsoidalOccluder(_horizonEllipsoid); export function createFrames({ state: layerState, services, parts, source }) { /** @@ -281,30 +286,11 @@ export function createFrames({ state: layerState, services, parts, source }) { typeof camera.frustum?.computeCullingVolume !== 'function' ) return true; - // The reference ellipsoid can lie above the actual street. Near the - // surface its horizon would incorrectly hide nearby below-ellipsoid planes; - // let the frustum alone decide at low altitude or when height is unknown. - const height = Cesium.Cartographic.fromCartesian( - camera.positionWC, - Cesium.Ellipsoid.WGS84, - _scratchCartographic, - )?.height; - const pointsAboveEllipsoid = points.every((point) => { - const h = Cesium.Cartographic.fromCartesian( - point, - Cesium.Ellipsoid.WGS84, - _scratchCartographic, - )?.height; - return Number.isFinite(h) && h >= 0; - }); - if ( - Number.isFinite(height) && - height >= LOW_VIEWER_HEIGHT_M && - pointsAboveEllipsoid - ) { - const occluder = horizonOccluder(camera); - if (!points.some((point) => occluder.isPointVisible(point))) return false; - } + // WGS84 can be above the actual street; cull against a surface below it + // instead, while retaining far-side occlusion for low and high viewers. + _horizonOccluder.cameraPosition = camera.positionWC; + if (!points.some((point) => _horizonOccluder.isPointVisible(point))) + return false; const culling = camera.frustum.computeCullingVolume( camera.positionWC, camera.directionWC, diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index c297311af4..d12bd401fb 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -290,6 +290,44 @@ test('a nearby plane below the ellipsoid still fetches for a low viewer', () => ); }); +test('the horizon still rejects a negative-height plane on the far side', () => { + for (const altitude of [4, 30000, 2e7]) { + const record = planeRecord(); + const mount = point(0, 0, -18); + const cap = point(0.00054, 0, -18); + record.billboard.position = mount; + record.frustumPositions = { mount, capCenter: cap }; + const position = point(180, 0, altitude); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); + const sphere = Cesium.BoundingSphere.fromPoints([mount, cap]); + assert.notEqual( + viewer.camera.frustum + .computeCullingVolume(position, direction, viewer.camera.upWC) + .computeVisibility(sphere), + Cesium.Intersect.OUTSIDE, + ); + assert.equal(framesFor(viewer).projectionInView(record), false); + } +}); + +test('a low viewer can see a plane beyond the WGS84 horizon', () => { + const record = planeRecord(); + const mount = point(0, 0, 1); + record.billboard.position = mount; + record.frustumPositions = { mount }; + const position = point(0.2, 0, 4); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); + assert.equal(framesFor(viewer).projectionInView(record), true); +}); + test('a plane below the horizon is not fetched', () => { const far = point(180, 0, 30000); const viewer = viewerAt( From 58872358944341618b048607fae8ea16d02be75a Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Mon, 9 Nov 2026 06:35:39 -0600 Subject: [PATCH 13/38] docs(cctv): describe conservative horizon geometry --- src/layers/cctv/frames.js | 4 ++-- src/layers/cctv/frames.test.mjs | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 95ef0a9794..aab35fcec6 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -252,8 +252,8 @@ export function createFrames({ state: layerState, services, parts, source }) { /** * Whether a camera's monitor plane can be on screen: the mount, the far cap * and its corners are bounded by one sphere that is tested against the view - * frustum, and at least one of those points must be above the horizon when - * the reference ellipsoid is a reliable occluder for this view. + * frustum, and at least one of those points must be above a conservative + * horizon computed from a shrunken reference ellipsoid. * Anything this cannot judge (no viewer, a 2D or Columbus scene, no geometry * yet) counts as visible, so a missing input never blocks a picture. * @param {Object} record - Camera record. diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index d12bd401fb..b21fea1cbc 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -275,8 +275,7 @@ test('a nearby plane below the ellipsoid still fetches for a low viewer', () => frames.refreshProjectionImage(record); assert.match(record.projection.image.src, /projTs=/); - // An above-threshold viewer still needs a conservative result when the - // entire plane itself is below the reference ellipsoid. + // The same below-ellipsoid plane remains visible from a higher viewer. const high = point(0.00135, 0, 1200); const highDirection = Cesium.Cartesian3.normalize( Cesium.Cartesian3.subtract(cap, high, new Cesium.Cartesian3()), From 147d1f5e4ef8b8048b73f73fb67416faa98fcb94 Mon Sep 17 00:00:00 2001 From: Byrd-IT <189950726+Byrd-IT@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:52:15 -0600 Subject: [PATCH 14/38] docs: CURRENT-STATE describes the 200 m horizon margin and the phone Cameras sheet rule (#1543) --- docs/CURRENT-STATE.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 3c217960c8..7cab5e0d5b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1979,12 +1979,13 @@ count of cameras outside the view. The active camera's pictures follow what can be seen. The monitor plane on the globe stops fetching its still every 10 s while the sphere around the camera mount and the plane is outside the view, or all of its points are below the -horizon (a 2D or Columbus scene always counts as visible), and fetches again -on the first refresh tick after it returns; activating or calibrating a camera -always fetches. The panel's still preview is requested only while the tab is -visible and the panel is expanded, and the panel asks for the current picture -when it is shown again. This matches the panel's live video, which already -played only in a visible tab and an expanded panel. +horizon of the WGS84 ellipsoid shrunk by 200 m (a 2D or Columbus scene always +counts as visible), and fetches again on the first refresh tick after it +returns; activating or calibrating a camera always fetches. The panel's still +preview is requested only while the tab is visible and the panel is expanded +(on phones, also while the Cameras sheet is open), and the panel asks for the +current picture when it is shown again. The panel's live video follows the same +rule. Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. From c0752784d239c9fa5294075b14a477cb9b9066b7 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 18 Nov 2026 15:19:38 -0600 Subject: [PATCH 15/38] fix(cctv): cull frames through renderer camera port --- scripts/package-boundaries.json | 1 + src/layers/cctv/frames.js | 76 +++++++++++++------------ src/layers/cctv/frames.test.mjs | 80 ++++++++++++++++++++++++++- src/render/cesium/camera.js | 3 + src/render/cesium/cameraPort.test.mjs | 17 ++++++ src/render/contract/camera.d.ts | 2 + 6 files changed, 143 insertions(+), 36 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a09757f481..269b433f33 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3382,6 +3382,7 @@ "src/layers/cctv/rendering.js", "src/render/motion/iconBook.js", "src/geo/frustum.js", + "src/geo/sphere.js", "src/render/cesium/iconOrientation.js", "src/render/cesium/iconSetPrimitive.js", "src/data/iconSet.js", diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index aab35fcec6..d1b70d5e80 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -1,4 +1,8 @@ -import * as Cesium from 'cesium'; +import { findCamera } from '../../render/rendererOf.js'; +import { offsetEllipsoid } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { frustumPlanes, sphereOutside } from '../../geo/frustum.js'; +import { sphereFromPoints } from '../../geo/sphere.js'; import { FRAME_SIGNATURE_W, FRAME_SIGNATURE_H, @@ -42,17 +46,9 @@ export function fitToProjection(sourceW, sourceH) { }; } -const _scratchPoints = []; -const _scratchSphere = new Cesium.BoundingSphere(); // Keep the occluding surface below common negative geoid undulations. const HORIZON_MARGIN_M = 200; -const _radii = Cesium.Ellipsoid.WGS84.radii; -const _horizonEllipsoid = new Cesium.Ellipsoid( - _radii.x - HORIZON_MARGIN_M, - _radii.y - HORIZON_MARGIN_M, - _radii.z - HORIZON_MARGIN_M, -); -const _horizonOccluder = new Cesium.EllipsoidalOccluder(_horizonEllipsoid); +const _horizonEllipsoid = offsetEllipsoid(-HORIZON_MARGIN_M); export function createFrames({ state: layerState, services, parts, source }) { /** @@ -263,44 +259,54 @@ export function createFrames({ state: layerState, services, parts, source }) { function projectionInView(record) { const viewer = layerState._viewer; if (!viewer || viewer.isDestroyed?.()) return true; - const { camera, scene } = viewer; - if (!camera || !scene || scene.mode !== Cesium.SceneMode.SCENE3D) + const camera = findCamera(viewer); + if (camera?.isWorld3D?.() !== true) return true; + const pose = camera.pose?.(); + const projection = camera.matrices?.()?.projection; + const finiteVector = (v) => v && [v.x, v.y, v.z].every(Number.isFinite); + // A centred perspective is the only shape frustumPlanes can judge exactly. + if ( + !finiteVector(pose?.position) || + !finiteVector(pose.direction) || + !finiteVector(pose.up) || + !(pose.fovy > 0 && pose.fovy < Math.PI) || + !(pose.aspectRatio > 0) || + !(pose.near > 0 && pose.far > pose.near) || + !projection || + projection[8] !== 0 || + projection[9] !== 0 || + projection[15] !== 0 + ) return true; const placed = record?.frustumPositions; - // Reused buffers: this runs on every projection tick while out of view. - const points = _scratchPoints; - points.length = 0; - for (const point of [ - record?.billboard?.position, + const points = [ + record?.position, placed?.mount, placed?.capCenter, placed?.tl, placed?.tr, placed?.br, placed?.bl, - ]) { - if (point) points.push(point); - } + ].filter(Boolean); if ( !points.length || - typeof camera.frustum?.computeCullingVolume !== 'function' + points.some( + (p) => + !Number.isFinite(p.x) || + !Number.isFinite(p.y) || + !Number.isFinite(p.z), + ) ) return true; - // WGS84 can be above the actual street; cull against a surface below it - // instead, while retaining far-side occlusion for low and high viewers. - _horizonOccluder.cameraPosition = camera.positionWC; - if (!points.some((point) => _horizonOccluder.isPointVisible(point))) + const o = _horizonEllipsoid.oneOverRadii; + const eye = pose.position; + // Below the shrunken ellipsoid the occluder can hide nearby visible points. + const outside = Math.hypot(eye.x * o.x, eye.y * o.y, eye.z * o.z) >= 1; + const horizon = outside ? horizonFrom(eye, _horizonEllipsoid) : null; + if (horizon && !points.some((point) => horizon.isPointVisible(point))) return false; - const culling = camera.frustum.computeCullingVolume( - camera.positionWC, - camera.directionWC, - camera.upWC, - ); - return ( - culling.computeVisibility( - Cesium.BoundingSphere.fromPoints(points, _scratchSphere), - ) !== Cesium.Intersect.OUTSIDE - ); + const sphere = sphereFromPoints(points); + return !sphereOutside(frustumPlanes(pose), sphere.center, sphere.radius); } /** diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index b21fea1cbc..dc1958cc20 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -4,6 +4,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindRenderer } from '../../render/rendererOf.js'; import { createFrames, fitToProjection } from './frames.js'; import { FRAME_SIGNATURE_W, @@ -174,7 +175,7 @@ function planeRecord() { } function viewerAt(position, direction, up) { - return { + const viewer = { isDestroyed: () => false, scene: { mode: Cesium.SceneMode.SCENE3D }, camera: { @@ -191,6 +192,22 @@ function viewerAt(position, direction, up) { }), }, }; + bindRenderer(viewer, { + camera: { + isWorld3D: () => viewer.scene.mode === Cesium.SceneMode.SCENE3D, + pose: () => ({ + position: viewer.camera.positionWC, + direction: viewer.camera.directionWC, + up: viewer.camera.upWC, + fovy: viewer.camera.frustum.fovy, + aspectRatio: viewer.camera.frustum.aspectRatio, + near: viewer.camera.frustum.near, + far: viewer.camera.frustum.far, + }), + matrices: () => ({ projection: viewer.camera.frustum.projectionMatrix }), + }, + }); + return viewer; } // Above the mount, looking straight down at the ground. @@ -356,6 +373,67 @@ test('a skipped refresh does not use up the interval: the plane fetches once it assert.match(record.projection.image.src, /projTs=/); }); +test('the renderer scene host culls the far side without raw viewer access', () => { + const native = lookingDown(); + const viewer = { isDestroyed: () => false }; + const camera = native.camera; + const unbind = bindRenderer(viewer, { + camera: { + isWorld3D: () => true, + matrices: () => ({ projection: camera.frustum.projectionMatrix }), + pose: () => ({ + position: camera.positionWC, + direction: Cesium.Cartesian3.UNIT_X, + up: camera.upWC, + fovy: camera.frustum.fovy, + aspectRatio: camera.frustum.aspectRatio, + near: camera.frustum.near, + far: camera.frustum.far, + }), + }, + }); + try { + assert.equal(framesFor(viewer).projectionInView(planeRecord()), false); + } finally { + unbind(); + } +}); + +test('deep viewers do not lose nearby planes to the horizon test', () => { + const mount = point(0, 0, -350); + const position = point(0.00135, 0, -300); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const record = planeRecord(); + record.frustumPositions = { mount }; + record.position = mount; + assert.equal( + framesFor( + viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z), + ).projectionInView(record), + true, + ); +}); + +test('flat, unknown, and off-centre projections fail open', () => { + const native = lookingDown(); + native.camera.directionWC = Cesium.Cartesian3.UNIT_X; + native.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; + assert.equal(framesFor(native).projectionInView(planeRecord()), true); + native.scene.mode = Cesium.SceneMode.SCENE3D; + native.camera.frustum.xOffset = 0.1; + assert.equal(framesFor(native).projectionInView(planeRecord()), true); + const host = {}; + const unbind = bindRenderer(host, { camera: { pose: () => ({}) } }); + try { + assert.equal(framesFor(host).projectionInView(planeRecord()), true); + } finally { + unbind(); + } +}); + test('what cannot be judged counts as visible', () => { const record = planeRecord(); assert.equal(framesFor(null).projectionInView(record), true); diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 34fab328e3..46257ff344 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -350,6 +350,9 @@ export function createCesiumCamera({ } const cameraPort = { + // The ECEF camera pose describes the globe only in 3D. Consumers that + // cannot prove this must avoid globe-only visibility culling. + isWorld3D: () => scene.mode === Cesium.SceneMode.SCENE3D, on: (event, cb, options) => cameraEvents.on(event, cb, options), onCommand: (cb) => commandHooks.on(cb), setView(spec) { diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs index 967ff1f761..92922b71ec 100644 --- a/src/render/cesium/cameraPort.test.mjs +++ b/src/render/cesium/cameraPort.test.mjs @@ -337,6 +337,23 @@ test('the camera port gives the clock its own tick back as it goes', () => { } }); +test('camera reports globe mode and fails closed for other modes', () => { + const { scene, camera } = headlessCamera(); + scene.postUpdate = new Cesium.Event(); + scene.requestRender = () => {}; + const { port } = createCesiumCamera({ scene, camera, report: () => {} }); + for (const [mode, expected] of [ + [Cesium.SceneMode.SCENE3D, true], + [Cesium.SceneMode.SCENE2D, false], + [Cesium.SceneMode.COLUMBUS_VIEW, false], + [Cesium.SceneMode.MORPHING, false], + [undefined, false], + ]) { + scene.mode = mode; + assert.equal(port.isWorld3D(), expected); + } +}); + test('setFov holds the vertical angle across resizes, and waits for a first one', () => { const { scene, camera } = headlessCamera(); scene.postUpdate = new Cesium.Event(); diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index a9b1f7d5ae..82023db6ff 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -234,6 +234,8 @@ export type CameraEvent = 'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd'; export interface CameraPort { + /** True only when its pose is an ECEF view of the 3D globe. Missing means unknown. */ + isWorld3D?(): boolean; pose(): CameraPose; /** * Place the eye. A position with a `{direction, up}` orientation is placed From b98b9d390f88d8831390f2211b5279b88cf08ccb Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 18 Nov 2026 15:31:59 -0600 Subject: [PATCH 16/38] fix(cctv): reuse renderer visibility scratch state --- scripts/package-boundaries.json | 1 - src/layers/cctv/frames.js | 66 ++++---------------- src/layers/cctv/frames.test.mjs | 54 +++++++++-------- src/render/cesium/camera.js | 87 ++++++++++++++++++++++++++- src/render/cesium/cameraPort.test.mjs | 18 +++--- src/render/contract/camera.d.ts | 4 +- 6 files changed, 137 insertions(+), 93 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 269b433f33..a09757f481 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3382,7 +3382,6 @@ "src/layers/cctv/rendering.js", "src/render/motion/iconBook.js", "src/geo/frustum.js", - "src/geo/sphere.js", "src/render/cesium/iconOrientation.js", "src/render/cesium/iconSetPrimitive.js", "src/data/iconSet.js", diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index d1b70d5e80..d92afd79ec 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -1,8 +1,4 @@ import { findCamera } from '../../render/rendererOf.js'; -import { offsetEllipsoid } from '../../geo/ellipsoid.js'; -import { horizonFrom } from '../../geo/horizon.js'; -import { frustumPlanes, sphereOutside } from '../../geo/frustum.js'; -import { sphereFromPoints } from '../../geo/sphere.js'; import { FRAME_SIGNATURE_W, FRAME_SIGNATURE_H, @@ -46,9 +42,7 @@ export function fitToProjection(sourceW, sourceH) { }; } -// Keep the occluding surface below common negative geoid undulations. -const HORIZON_MARGIN_M = 200; -const _horizonEllipsoid = offsetEllipsoid(-HORIZON_MARGIN_M); +const _scratchPoints = []; export function createFrames({ state: layerState, services, parts, source }) { /** @@ -260,53 +254,19 @@ export function createFrames({ state: layerState, services, parts, source }) { const viewer = layerState._viewer; if (!viewer || viewer.isDestroyed?.()) return true; const camera = findCamera(viewer); - if (camera?.isWorld3D?.() !== true) return true; - const pose = camera.pose?.(); - const projection = camera.matrices?.()?.projection; - const finiteVector = (v) => v && [v.x, v.y, v.z].every(Number.isFinite); - // A centred perspective is the only shape frustumPlanes can judge exactly. - if ( - !finiteVector(pose?.position) || - !finiteVector(pose.direction) || - !finiteVector(pose.up) || - !(pose.fovy > 0 && pose.fovy < Math.PI) || - !(pose.aspectRatio > 0) || - !(pose.near > 0 && pose.far > pose.near) || - !projection || - projection[8] !== 0 || - projection[9] !== 0 || - projection[15] !== 0 - ) - return true; + if (typeof camera?.visiblePoints !== 'function') return true; const placed = record?.frustumPositions; - const points = [ - record?.position, - placed?.mount, - placed?.capCenter, - placed?.tl, - placed?.tr, - placed?.br, - placed?.bl, - ].filter(Boolean); - if ( - !points.length || - points.some( - (p) => - !Number.isFinite(p.x) || - !Number.isFinite(p.y) || - !Number.isFinite(p.z), - ) - ) - return true; - const o = _horizonEllipsoid.oneOverRadii; - const eye = pose.position; - // Below the shrunken ellipsoid the occluder can hide nearby visible points. - const outside = Math.hypot(eye.x * o.x, eye.y * o.y, eye.z * o.z) >= 1; - const horizon = outside ? horizonFrom(eye, _horizonEllipsoid) : null; - if (horizon && !points.some((point) => horizon.isPointVisible(point))) - return false; - const sphere = sphereFromPoints(points); - return !sphereOutside(frustumPlanes(pose), sphere.center, sphere.radius); + const points = _scratchPoints; + points.length = 0; + if (record?.position) points.push(record.position); + if (placed?.mount) points.push(placed.mount); + if (placed?.capCenter) points.push(placed.capCenter); + if (placed?.tl) points.push(placed.tl); + if (placed?.tr) points.push(placed.tr); + if (placed?.br) points.push(placed.br); + if (placed?.bl) points.push(placed.bl); + // Unknown modes or unsupported cameras must not suppress pictures. + return camera.visiblePoints(points, 200) !== false; } /** diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index dc1958cc20..2aca236a5e 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -5,6 +5,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { bindRenderer } from '../../render/rendererOf.js'; +import { createPointsVisibility } from '../../render/cesium/camera.js'; import { createFrames, fitToProjection } from './frames.js'; import { FRAME_SIGNATURE_W, @@ -194,17 +195,7 @@ function viewerAt(position, direction, up) { }; bindRenderer(viewer, { camera: { - isWorld3D: () => viewer.scene.mode === Cesium.SceneMode.SCENE3D, - pose: () => ({ - position: viewer.camera.positionWC, - direction: viewer.camera.directionWC, - up: viewer.camera.upWC, - fovy: viewer.camera.frustum.fovy, - aspectRatio: viewer.camera.frustum.aspectRatio, - near: viewer.camera.frustum.near, - far: viewer.camera.frustum.far, - }), - matrices: () => ({ projection: viewer.camera.frustum.projectionMatrix }), + visiblePoints: createPointsVisibility(viewer.scene, viewer.camera), }, }); return viewer; @@ -377,20 +368,9 @@ test('the renderer scene host culls the far side without raw viewer access', () const native = lookingDown(); const viewer = { isDestroyed: () => false }; const camera = native.camera; + camera.directionWC = Cesium.Cartesian3.UNIT_X; const unbind = bindRenderer(viewer, { - camera: { - isWorld3D: () => true, - matrices: () => ({ projection: camera.frustum.projectionMatrix }), - pose: () => ({ - position: camera.positionWC, - direction: Cesium.Cartesian3.UNIT_X, - up: camera.upWC, - fovy: camera.frustum.fovy, - aspectRatio: camera.frustum.aspectRatio, - near: camera.frustum.near, - far: camera.frustum.far, - }), - }, + camera: { visiblePoints: createPointsVisibility(native.scene, camera) }, }); try { assert.equal(framesFor(viewer).projectionInView(planeRecord()), false); @@ -399,6 +379,28 @@ test('the renderer scene host culls the far side without raw viewer access', () } }); +test('visibility checks reuse the points array across ticks', () => { + const seen = []; + const host = {}; + const unbind = bindRenderer(host, { + camera: { + visiblePoints: (points) => { + seen.push(points); + return true; + }, + }, + }); + try { + const frames = framesFor(host); + frames.projectionInView(planeRecord()); + frames.projectionInView(planeRecord()); + assert.equal(seen.length, 2); + assert.strictEqual(seen[0], seen[1]); + } finally { + unbind(); + } +}); + test('deep viewers do not lose nearby planes to the horizon test', () => { const mount = point(0, 0, -350); const position = point(0.00135, 0, -300); @@ -417,13 +419,13 @@ test('deep viewers do not lose nearby planes to the horizon test', () => { ); }); -test('flat, unknown, and off-centre projections fail open', () => { +test('flat and unknown projections fail open', () => { const native = lookingDown(); native.camera.directionWC = Cesium.Cartesian3.UNIT_X; native.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; assert.equal(framesFor(native).projectionInView(planeRecord()), true); native.scene.mode = Cesium.SceneMode.SCENE3D; - native.camera.frustum.xOffset = 0.1; + native.camera.directionWC = undefined; assert.equal(framesFor(native).projectionInView(planeRecord()), true); const host = {}; const unbind = bindRenderer(host, { camera: { pose: () => ({}) } }); diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 46257ff344..e589de38d6 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -86,6 +86,89 @@ function sameMatrix(array, matrix) { return true; } +/** Conservative globe/frustum visibility; null means unknown. */ +export function createPointsVisibility(scene, camera) { + const visibilitySphere = new Cesium.BoundingSphere(); + let visibilityMargin = null; + let visibilityEllipsoid = null; + let visibilityOccluder = null; + return function visiblePoints(points, marginM) { + if ( + scene.mode !== Cesium.SceneMode.SCENE3D || + !points?.length || + !Number.isFinite(marginM) || + marginM < 0 || + typeof camera.frustum?.computeCullingVolume !== 'function' + ) + return null; + const radii = Cesium.Ellipsoid.WGS84.radii; + if (marginM >= Math.min(radii.x, radii.y, radii.z)) return null; + const eye = camera.positionWC; + if ( + !eye || + !Number.isFinite(eye.x) || + !Number.isFinite(eye.y) || + !Number.isFinite(eye.z) + ) + return null; + const direction = camera.directionWC; + const up = camera.upWC; + if ( + !direction || + !up || + !Number.isFinite(direction.x) || + !Number.isFinite(direction.y) || + !Number.isFinite(direction.z) || + !Number.isFinite(up.x) || + !Number.isFinite(up.y) || + !Number.isFinite(up.z) + ) + return null; + for (const p of points) { + if ( + !p || + !Number.isFinite(p.x) || + !Number.isFinite(p.y) || + !Number.isFinite(p.z) + ) + return null; + } + if (visibilityMargin !== marginM) { + visibilityMargin = marginM; + visibilityEllipsoid = new Cesium.Ellipsoid( + radii.x - marginM, + radii.y - marginM, + radii.z - marginM, + ); + visibilityOccluder = new Cesium.EllipsoidalOccluder(visibilityEllipsoid); + } + const inverse = visibilityEllipsoid.oneOverRadii; + const outside = + Math.hypot(eye.x * inverse.x, eye.y * inverse.y, eye.z * inverse.z) >= 1; + if (outside) { + visibilityOccluder.cameraPosition = eye; + let visible = false; + for (const p of points) { + if (visibilityOccluder.isPointVisible(p)) { + visible = true; + break; + } + } + if (!visible) return false; + } + const culling = camera.frustum.computeCullingVolume( + eye, + camera.directionWC, + camera.upWC, + ); + return ( + culling.computeVisibility( + Cesium.BoundingSphere.fromPoints(points, visibilitySphere), + ) !== Cesium.Intersect.OUTSIDE + ); + }; +} + /** * @param {{scene: object, camera: object, report: (error: unknown) => void, * widget?: object, capabilities?: ReadonlySet, @@ -350,9 +433,7 @@ export function createCesiumCamera({ } const cameraPort = { - // The ECEF camera pose describes the globe only in 3D. Consumers that - // cannot prove this must avoid globe-only visibility culling. - isWorld3D: () => scene.mode === Cesium.SceneMode.SCENE3D, + visiblePoints: createPointsVisibility(scene, camera), on: (event, cb, options) => cameraEvents.on(event, cb, options), onCommand: (cb) => commandHooks.on(cb), setView(spec) { diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs index 92922b71ec..5328fca3f0 100644 --- a/src/render/cesium/cameraPort.test.mjs +++ b/src/render/cesium/cameraPort.test.mjs @@ -337,21 +337,23 @@ test('the camera port gives the clock its own tick back as it goes', () => { } }); -test('camera reports globe mode and fails closed for other modes', () => { +test('camera visibility is unknown outside 3D and resolves on the globe', () => { const { scene, camera } = headlessCamera(); scene.postUpdate = new Cesium.Event(); scene.requestRender = () => {}; const { port } = createCesiumCamera({ scene, camera, report: () => {} }); - for (const [mode, expected] of [ - [Cesium.SceneMode.SCENE3D, true], - [Cesium.SceneMode.SCENE2D, false], - [Cesium.SceneMode.COLUMBUS_VIEW, false], - [Cesium.SceneMode.MORPHING, false], - [undefined, false], + const points = [Cesium.Cartesian3.fromDegrees(0, 0, 10)]; + for (const mode of [ + Cesium.SceneMode.SCENE2D, + Cesium.SceneMode.COLUMBUS_VIEW, + Cesium.SceneMode.MORPHING, + undefined, ]) { scene.mode = mode; - assert.equal(port.isWorld3D(), expected); + assert.equal(port.visiblePoints(points, 200), null); } + scene.mode = Cesium.SceneMode.SCENE3D; + assert.equal(typeof port.visiblePoints(points, 200), 'boolean'); }); test('setFov holds the vertical angle across resizes, and waits for a first one', () => { diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index 82023db6ff..8bf2705242 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -234,8 +234,8 @@ export type CameraEvent = 'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd'; export interface CameraPort { - /** True only when its pose is an ECEF view of the 3D globe. Missing means unknown. */ - isWorld3D?(): boolean; + /** Conservative visibility of an ECEF point set, with a horizon margin in metres; null means unknown. */ + visiblePoints?(points: Ecef[], horizonMarginM: number): boolean | null; pose(): CameraPose; /** * Place the eye. A position with a `{direction, up}` orientation is placed From 02c60c0a208328d7fe7da692c9bd5e3d1a966fc7 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 18 Nov 2026 15:42:17 -0600 Subject: [PATCH 17/38] fix(cctv): fail open before projection geometry exists --- src/layers/cctv/frames.js | 1 + src/layers/cctv/frames.test.mjs | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index d92afd79ec..41c59f0e24 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -256,6 +256,7 @@ export function createFrames({ state: layerState, services, parts, source }) { const camera = findCamera(viewer); if (typeof camera?.visiblePoints !== 'function') return true; const placed = record?.frustumPositions; + if (!placed) return true; const points = _scratchPoints; points.length = 0; if (record?.position) points.push(record.position); diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index 2aca236a5e..d2c6b1a6d7 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -448,6 +448,10 @@ test('what cannot be judged counts as visible', () => { const flat = lookingDown(); flat.scene.mode = Cesium.SceneMode.SCENE2D; assert.equal(framesFor(flat).projectionInView(record), true); - const noGeometry = { camera: { id: 'plane' }, projection: record.projection }; + const noGeometry = { + camera: { id: 'plane' }, + projection: record.projection, + position: point(180, 0, 20), + }; assert.equal(framesFor(lookingDown()).projectionInView(noGeometry), true); }); From 28007e20efbbb05f0b2079013d9cca90c1c534c5 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 18 Nov 2026 16:17:57 -0600 Subject: [PATCH 18/38] fix(cctv): register camera point visibility capability --- src/layers/cctv/frames.js | 3 ++- src/render/cesium/camera.js | 3 ++- src/render/cesium/controlledCamera.test.mjs | 2 ++ src/render/cesium/ports.js | 5 ++++- src/render/cesium/ports.test.mjs | 1 + src/render/contract/common.d.ts | 2 ++ src/render/contract/index.js | 2 ++ src/render/stub/index.js | 2 ++ src/render/stub/stub.test.mjs | 9 +++++++++ 9 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index 41c59f0e24..c0a820dd3d 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -43,6 +43,7 @@ export function fitToProjection(sourceW, sourceH) { } const _scratchPoints = []; +const HORIZON_MARGIN_M = 200; export function createFrames({ state: layerState, services, parts, source }) { /** @@ -267,7 +268,7 @@ export function createFrames({ state: layerState, services, parts, source }) { if (placed?.br) points.push(placed.br); if (placed?.bl) points.push(placed.bl); // Unknown modes or unsupported cameras must not suppress pictures. - return camera.visiblePoints(points, 200) !== false; + return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false; } /** diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index e589de38d6..bcf251224f 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -433,7 +433,6 @@ export function createCesiumCamera({ } const cameraPort = { - visiblePoints: createPointsVisibility(scene, camera), on: (event, cb, options) => cameraEvents.on(event, cb, options), onCommand: (cb) => commandHooks.on(cb), setView(spec) { @@ -753,6 +752,8 @@ export function createCesiumCamera({ }); // Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a // `lookAt` target's, or the identity. + if (!capabilities || capabilities.has('pointVisibility')) + cameraPort.visiblePoints = createPointsVisibility(scene, camera); if (!capabilities || capabilities.has('followFrame')) cameraPort.followFrame = () => { if (!lastFollowFrame || !sameMatrix(lastFollowFrame, camera.transform)) diff --git a/src/render/cesium/controlledCamera.test.mjs b/src/render/cesium/controlledCamera.test.mjs index 54945e31a3..e92f74c8da 100644 --- a/src/render/cesium/controlledCamera.test.mjs +++ b/src/render/cesium/controlledCamera.test.mjs @@ -321,6 +321,8 @@ test('the application’s Cesium renderer runs the controller around its preUpda const renderer = await plugin.create({ container: {} }); assert.equal(scene.screenSpaceCameraController.enableInputs, false); assert.equal(typeof renderer.camera.native.setPose, 'function'); + assert.equal(renderer.capabilities.has('pointVisibility'), true); + assert.equal(renderer.camera.visiblePoints([], 200), null); renderer.frame.on('preUpdate', () => order.push('preUpdate')); scene.preUpdate.raise(scene, Cesium.JulianDate.fromDate(new Date(5000))); assert.deepEqual(order, [['before', 5000], 'preUpdate', 'after']); diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 5f73daa482..ba69cb1991 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -13,7 +13,7 @@ * absent, never stubbed. */ import * as Cesium from 'cesium'; -import { createCesiumCamera } from './camera.js'; +import { createCesiumCamera, createPointsVisibility } from './camera.js'; import { createControlledCamera } from './controlledCamera.js'; import { listenerList, toCartesian, uncaught } from './common.js'; import { createCesiumCredits } from './credits.js'; @@ -80,6 +80,7 @@ export function cesiumCapabilities(scene, only) { // Raster shells; other field kinds are refused. 'fields', 'followFrame', + 'pointVisibility', // Cesium's AUTODETECT tracking frame (`follow.js`). 'followAutodetect', 'cameraChangeThreshold', @@ -484,6 +485,8 @@ export function createCesiumPorts( : {}), }); const cameraPort = cameraPart.port; + if (controlled && capabilities.has('pointVisibility')) + cameraPort.visiblePoints = createPointsVisibility(scene, camera); measureCameraChanged = cameraPart.measureChanged ?? null; const effectsPart = createCesiumEffects(scene, { capabilities, diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index fc0e40bff2..e7cb9582a2 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -12,6 +12,7 @@ import { createNativeClick } from './nativeClick.js'; test('capabilities follow what the scene supports', () => { const effects = [ 'followFrame', + 'pointVisibility', 'followAutodetect', 'cameraChangeThreshold', 'columns', diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts index df585c2484..09b15c4acd 100644 --- a/src/render/contract/common.d.ts +++ b/src/render/contract/common.d.ts @@ -179,6 +179,8 @@ export type Capability = | 'pickPosition' /** Points tested against the frame's depth (`query.occlusionTest`). */ | 'occlusionTest' + /** Conservative camera visibility of a point set (`camera.visiblePoints`). */ + | 'pointVisibility' /** Outward user zooms that keep the Earth framed (`controls.keepEarthFramed`). */ | 'keepEarthFramed' /** Height sampling against tiles and terrain. */ diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 2198b6226c..c18e0e5cb2 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -48,6 +48,7 @@ export const CAPABILITIES = Object.freeze([ 'followFrame', 'cameraChangeThreshold', 'occlusionTest', + 'pointVisibility', 'keepEarthFramed', ]); @@ -207,6 +208,7 @@ export const PORTS = deepFreeze({ 'matrices', ), ['followFrame', 'followFrame'], + ['visiblePoints', 'pointVisibility'], ['controls.keepEarthFramed', 'keepEarthFramed'], ]), query: Object.fromEntries([ diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 9eb21cfc58..85451d63c3 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -261,6 +261,8 @@ export function createStubRenderer(options = {}) { camera.setViewRectangle(viewRectangle); if (capabilities.has('followFrame')) camera.port.followFrame = camera.eyeFrame; + if (capabilities.has('pointVisibility')) + camera.port.visiblePoints = () => null; camera.port.setView({ destination: { lon: -97.7431, lat: 30.2672, height: 15000000 }, }); diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index d2da3f359d..04517dd6fe 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -40,6 +40,15 @@ test('the stub passes the conformance suite', async () => { ]); }); +test('point visibility capability is optional and the stub reports unknown', () => { + const without = createStubRenderer({ capabilities: [] }); + const withVisibility = createStubRenderer({ + capabilities: ['pointVisibility'], + }); + assert.equal(without.camera.visiblePoints, undefined); + assert.equal(withVisibility.camera.visiblePoints([], 200), null); +}); + test('a frame runs the contract’s steps in order', () => { const r = createStubRenderer(); r.frame.requestRender('test'); From b020a1cd91a0a265e736586eb9911a02303253c0 Mon Sep 17 00:00:00 2001 From: brandonabyrd Date: Wed, 18 Nov 2026 16:25:19 -0600 Subject: [PATCH 19/38] docs: describe camera point visibility capability --- docs/RENDERER-CONTRACT.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 76d547cb09..26a5b789ef 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -81,6 +81,9 @@ optional: target's east-north-up frame, or the identity. `setView` keeps that frame while it places a world pose. A share link's follow offset is re-expressed in it, satellites included. +- `camera.visiblePoints(points, horizonMarginM)` (capability `pointVisibility`) + conservatively reports whether a point set may be visible; `null` means the + renderer cannot determine visibility and callers should fail open. - `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that changes whenever what surface heights answer against changes (base, terrain or photoreal route swapped, the globe shown or hidden) and never From 99a70a0e0c13716283355529e1d78f09f8105eea Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:28:51 +0400 Subject: [PATCH 20/38] fix(cctv): keep the Context camera card's still and tidy the visibility port The still preview gate looked only at the CCTV panel, so the Context camera card, which reads the same frame, stopped updating while the panel was collapsed or another phone sheet was open. A mounted card now counts itself in the CCTV store, and the still is requested while the panel or a card is shown; live video still follows the panel only. Review follow-ups in the same area: - visiblePoints is registered once, in createCesiumPorts, and drops checks for input that cannot happen; the contract documents horizonMarginM and when it answers false or null. - The layer passes the mount and the four corners once each and asks findCamera for the port. - Phone sheet names come from a shared module instead of literals. - Layer tests cover the fetch gate; the geometry cases moved to the camera port tests. Comments and CURRENT-STATE match the code. --- changelog.d/1543-cctv-visible-only-fetch.md | 4 +- docs/CURRENT-STATE.md | 18 +- docs/RENDERER-CONTRACT.md | 8 +- scripts/package-boundaries.json | 3 + src/layers/cctv/frames.js | 30 +- src/layers/cctv/frames.test.mjs | 296 +++----------------- src/render/cesium/camera.js | 53 +--- src/render/cesium/cameraPort.test.mjs | 136 ++++++++- src/render/cesium/ports.js | 2 +- src/render/contract/camera.d.ts | 9 +- src/ui/cctvControls.js | 16 +- src/ui/cctvPanel.test.mjs | 112 +++++--- src/ui/cctvPresentation.js | 37 ++- src/ui/contextCardFrame.test.mjs | 167 +++++++++++ src/ui/mobileSheets.js | 25 ++ src/ui/mobileShell.js | 39 +-- src/ui/stores/cctv.js | 9 + src/ui/views/panels/CctvPreview.vue | 11 +- 18 files changed, 545 insertions(+), 430 deletions(-) create mode 100644 src/ui/contextCardFrame.test.mjs create mode 100644 src/ui/mobileSheets.js diff --git a/changelog.d/1543-cctv-visible-only-fetch.md b/changelog.d/1543-cctv-visible-only-fetch.md index 80421a35c2..f12c20dbf3 100644 --- a/changelog.d/1543-cctv-visible-only-fetch.md +++ b/changelog.d/1543-cctv-visible-only-fetch.md @@ -1,4 +1,4 @@ - Stop fetching the active CCTV camera's pictures when nobody can see them. The monitor plane skips its 10 s still while it is off screen or below the - horizon, and the panel's still preview waits for a visible tab, an open - panel and, on phones, the open Cameras sheet (Byrd-IT, #1543). + horizon, and the still preview waits for a visible tab and an open panel or + Context camera card (on phones, the open Cameras or Context sheet) (Byrd-IT, #1543). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7cab5e0d5b..9d6038a653 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1976,16 +1976,14 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. -The active camera's pictures follow what can be seen. The monitor plane on the -globe stops fetching its still every 10 s while the sphere around the camera -mount and the plane is outside the view, or all of its points are below the -horizon of the WGS84 ellipsoid shrunk by 200 m (a 2D or Columbus scene always -counts as visible), and fetches again on the first refresh tick after it -returns; activating or calibrating a camera always fetches. The panel's still -preview is requested only while the tab is visible and the panel is expanded -(on phones, also while the Cameras sheet is open), and the panel asks for the -current picture when it is shown again. The panel's live video follows the same -rule. +The active camera's pictures follow what can be seen. The monitor plane skips +its 10 s still while the renderer reports it off screen or below the horizon, +and fetches on the first refresh tick after it is back. Activating or +calibrating a camera bypasses visibility and the usual refresh interval, but +still waits for an in-flight request and the provider's minimum interval. +The panel's still and live video run only while the tab is visible and the +panel is open (on phones, the Cameras sheet). The still also loads while +Context shows the camera's card (on phones, the Context sheet). Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 26a5b789ef..9134799705 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -82,8 +82,12 @@ optional: while it places a world pose. A share link's follow offset is re-expressed in it, satellites included. - `camera.visiblePoints(points, horizonMarginM)` (capability `pointVisibility`) - conservatively reports whether a point set may be visible; `null` means the - renderer cannot determine visibility and callers should fail open. + is whether any of the points may be on screen: `false` only when their + bounding sphere is outside the view or all of them are below the horizon + of the WGS84 ellipsoid shrunk by `horizonMarginM` metres; `null` when it + cannot tell (not a 3D scene, an empty point set, or a non-finite point or + camera vector), and callers count that as visible. Supply a finite, + nonnegative margin smaller than the shortest WGS84 radius. - `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that changes whenever what surface heights answer against changes (base, terrain or photoreal route swapped, the globe shown or hidden) and never diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a09757f481..3d6c2d9652 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1067,6 +1067,7 @@ "src/ui/cctv.js", "src/ui/cctvBindings.js", "src/ui/cctvCalibration.js", + "src/ui/mobileSheets.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", "src/ui/cctvVideo.js", @@ -1301,6 +1302,7 @@ "src/data/distanceFormat.js", "src/i18n/marker.js", "src/ui/mobileShell.js", + "src/ui/mobileSheets.js", "src/exclusiveSurfaces.js", "src/ui/placeNames.js", "src/hudLayouts.js", @@ -4708,6 +4710,7 @@ "src/ui/applicationShell.js", "src/ui/railEdgeScroll.js", "src/ui/mobileShell.js", + "src/ui/mobileSheets.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", "src/ui/locationNavigation.js", diff --git a/src/layers/cctv/frames.js b/src/layers/cctv/frames.js index c0a820dd3d..7ca4d4b6fc 100644 --- a/src/layers/cctv/frames.js +++ b/src/layers/cctv/frames.js @@ -42,7 +42,9 @@ export function fitToProjection(sourceW, sourceH) { }; } +const PLANE_POINTS = ['mount', 'tl', 'tr', 'br', 'bl']; const _scratchPoints = []; +// Keep the occluding surface below common negative geoid undulations. const HORIZON_MARGIN_M = 200; export function createFrames({ state: layerState, services, parts, source }) { @@ -241,33 +243,18 @@ export function createFrames({ state: layerState, services, parts, source }) { } /** - * Whether a camera's monitor plane can be on screen: the mount, the far cap - * and its corners are bounded by one sphere that is tested against the view - * frustum, and at least one of those points must be above a conservative - * horizon computed from a shrunken reference ellipsoid. - * Anything this cannot judge (no viewer, a 2D or Columbus scene, no geometry - * yet) counts as visible, so a missing input never blocks a picture. + * Whether a camera's monitor plane may be on screen; what cannot be judged counts as visible. * @param {Object} record - Camera record. * @returns {boolean} */ - function projectionInView(record) { - const viewer = layerState._viewer; - if (!viewer || viewer.isDestroyed?.()) return true; - const camera = findCamera(viewer); + const camera = findCamera(layerState._viewer); if (typeof camera?.visiblePoints !== 'function') return true; - const placed = record?.frustumPositions; + const placed = record.frustumPositions; if (!placed) return true; const points = _scratchPoints; points.length = 0; - if (record?.position) points.push(record.position); - if (placed?.mount) points.push(placed.mount); - if (placed?.capCenter) points.push(placed.capCenter); - if (placed?.tl) points.push(placed.tl); - if (placed?.tr) points.push(placed.tr); - if (placed?.br) points.push(placed.br); - if (placed?.bl) points.push(placed.bl); - // Unknown modes or unsupported cameras must not suppress pictures. + for (const key of PLANE_POINTS) points.push(placed[key]); return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false; } @@ -304,9 +291,7 @@ export function createFrames({ state: layerState, services, parts, source }) { // bypass a provider's explicit minimum between image requests. if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return; if (!force && sinceLastRefresh < refreshMs) return; - // A plane nobody can see (panned away, far side of the globe) needs no new - // picture; the next tick after it comes back fetches one. A forced refresh - // (fresh activation, calibration) still runs. + // Skip before stamping lastImageRefreshAt, so the first tick back in view fetches. if (!force && !projectionInView(record)) return; runtime.lastImageRefreshAt = now; @@ -441,7 +426,6 @@ export function createFrames({ state: layerState, services, parts, source }) { mediaUrlFor, paintProjectionPlaceholder, refreshProjectionImage, - projectionInView, paintPlaceholderThrottled, drawProjectionFrame, }; diff --git a/src/layers/cctv/frames.test.mjs b/src/layers/cctv/frames.test.mjs index d2c6b1a6d7..0170797e09 100644 --- a/src/layers/cctv/frames.test.mjs +++ b/src/layers/cctv/frames.test.mjs @@ -3,9 +3,7 @@ // 1920x1080 projection canvas, instead of being stretched to fill it. import { test } from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import { bindRenderer } from '../../render/rendererOf.js'; -import { createPointsVisibility } from '../../render/cesium/camera.js'; import { createFrames, fitToProjection } from './frames.js'; import { FRAME_SIGNATURE_W, @@ -143,31 +141,23 @@ test('same pixels at a new aspect redraw at the new fit', () => { assert.equal(runtime.canvasStamp, 2); }); -// A camera's monitor plane is fetched only while it can be on screen. The -// viewer is a Cesium camera description over the real WGS84 globe: it hovers -// 30 km above a mount at (0, 0) and looks straight down, so the plane is in -// front of it; turned around, or moved to the far side of the globe, the -// plane is not. -const MOUNT = Cesium.Cartesian3.fromDegrees(0, 0, 20); -const point = (lon, lat, alt = 20) => - Cesium.Cartesian3.fromDegrees(lon, lat, alt); +const MOUNT = { x: 0, y: 0, z: 0 }; function planeRecord() { - const image = {}; return { camera: { id: 'plane' }, - billboard: { position: MOUNT }, + position: MOUNT, frustumPositions: { mount: MOUNT, - capCenter: point(0.0005, 0, 20), - tl: point(0.0004, 0.0001), - tr: point(0.0006, 0.0001), - br: point(0.0006, -0.0001), - bl: point(0.0004, -0.0001), + capCenter: { x: 1, y: 0, z: 0 }, + tl: { x: 1, y: -1, z: 1 }, + tr: { x: 1, y: 1, z: 1 }, + br: { x: 1, y: 1, z: -1 }, + bl: { x: 1, y: -1, z: -1 }, }, projection: { mode: 'image', - image, + image: {}, imageLoading: false, imageReady: false, lastImageRefreshAt: 0, @@ -175,42 +165,6 @@ function planeRecord() { }; } -function viewerAt(position, direction, up) { - const viewer = { - isDestroyed: () => false, - scene: { mode: Cesium.SceneMode.SCENE3D }, - camera: { - positionWC: position, - directionWC: direction, - upWC: up, - frustum: new Cesium.PerspectiveFrustum({ - fov: Cesium.Math.toRadians(60), - aspectRatio: 16 / 9, - near: 1, - // Cesium's default far plane, as the app uses: a smaller one rejects - // the far-side mount before the horizon check is ever reached. - far: 5e8, - }), - }, - }; - bindRenderer(viewer, { - camera: { - visiblePoints: createPointsVisibility(viewer.scene, viewer.camera), - }, - }); - return viewer; -} - -// Above the mount, looking straight down at the ground. -function lookingDown() { - const position = point(0, 0, 30000); - return viewerAt( - position, - Cesium.Cartesian3.negate(Cesium.Cartesian3.UNIT_X, new Cesium.Cartesian3()), - Cesium.Cartesian3.UNIT_Z, - ); -} - function framesFor(viewer) { const state = { _viewer: viewer, @@ -230,28 +184,33 @@ function framesFor(viewer) { }); } -test('a plane in front of the camera fetches its picture', () => { - const frames = framesFor(lookingDown()); +function framesWithCamera(t, camera) { + const host = {}; + t.after(bindRenderer(host, { camera })); + return framesFor(host); +} + +test('a plane the renderer may show fetches its picture', (t) => { + const visiblePoints = t.mock.fn(() => true); + const frames = framesWithCamera(t, { visiblePoints }); const record = planeRecord(); - assert.equal(frames.projectionInView(record), true); frames.refreshProjectionImage(record); assert.match( record.projection.image.src, /^\/api\/cctv\/frame\?id=plane&projTs=/, ); assert.equal(record.projection.imageLoading, true); + assert.equal(visiblePoints.mock.callCount(), 1); + const [points, margin] = visiblePoints.mock.calls[0].arguments; + const { mount, tl, tr, br, bl } = record.frustumPositions; + assert.deepEqual(points, [mount, tl, tr, br, bl]); + assert.equal(points[0], mount); + assert.equal(margin, 200); }); -test('a plane behind the camera is not fetched, but a forced refresh is', () => { - const down = lookingDown(); - const away = viewerAt( - down.camera.positionWC, - Cesium.Cartesian3.UNIT_X, - Cesium.Cartesian3.UNIT_Z, - ); - const frames = framesFor(away); +test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => { + const frames = framesWithCamera(t, { visiblePoints: () => false }); const record = planeRecord(); - assert.equal(frames.projectionInView(record), false); frames.refreshProjectionImage(record); assert.equal(record.projection.image.src, undefined); assert.equal(record.projection.lastImageRefreshAt, 0); @@ -259,199 +218,32 @@ test('a plane behind the camera is not fetched, but a forced refresh is', () => assert.match(record.projection.image.src, /projTs=/); }); -test('a nearby plane below the ellipsoid still fetches for a low viewer', () => { +test('a skipped refresh does not use up the interval', (t) => { + let visible = false; + const frames = framesWithCamera(t, { visiblePoints: () => visible }); const record = planeRecord(); - const mount = point(0, 0, -18); - const cap = point(0.00054, 0, -18); - const position = point(0.00135, 0, 4); - record.billboard.position = mount; - record.frustumPositions = { mount, capCenter: cap }; - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(cap, position, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ); - const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); - const sphere = Cesium.BoundingSphere.fromPoints([mount, cap]); - const culling = viewer.camera.frustum.computeCullingVolume( - position, - direction, - viewer.camera.upWC, - ); - assert.notEqual(culling.computeVisibility(sphere), Cesium.Intersect.OUTSIDE); - const frames = framesFor(viewer); - assert.equal(frames.projectionInView(record), true); frames.refreshProjectionImage(record); - assert.match(record.projection.image.src, /projTs=/); - - // The same below-ellipsoid plane remains visible from a higher viewer. - const high = point(0.00135, 0, 1200); - const highDirection = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(cap, high, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ); - assert.equal( - framesFor( - viewerAt(high, highDirection, Cesium.Cartesian3.UNIT_Z), - ).projectionInView(record), - true, - ); -}); - -test('the horizon still rejects a negative-height plane on the far side', () => { - for (const altitude of [4, 30000, 2e7]) { - const record = planeRecord(); - const mount = point(0, 0, -18); - const cap = point(0.00054, 0, -18); - record.billboard.position = mount; - record.frustumPositions = { mount, capCenter: cap }; - const position = point(180, 0, altitude); - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ); - const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); - const sphere = Cesium.BoundingSphere.fromPoints([mount, cap]); - assert.notEqual( - viewer.camera.frustum - .computeCullingVolume(position, direction, viewer.camera.upWC) - .computeVisibility(sphere), - Cesium.Intersect.OUTSIDE, - ); - assert.equal(framesFor(viewer).projectionInView(record), false); - } -}); - -test('a low viewer can see a plane beyond the WGS84 horizon', () => { - const record = planeRecord(); - const mount = point(0, 0, 1); - record.billboard.position = mount; - record.frustumPositions = { mount }; - const position = point(0.2, 0, 4); - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ); - const viewer = viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z); - assert.equal(framesFor(viewer).projectionInView(record), true); -}); - -test('a plane below the horizon is not fetched', () => { - const far = point(180, 0, 30000); - const viewer = viewerAt( - far, - Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(MOUNT, far, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ), - Cesium.Cartesian3.UNIT_Z, - ); - const frames = framesFor(viewer); - assert.equal(frames.projectionInView(planeRecord()), false); -}); - -test('a skipped refresh does not use up the interval: the plane fetches once it is back in view', () => { - const record = planeRecord(); - const frames = framesFor(lookingDown()); - const away = viewerAt( - lookingDown().camera.positionWC, - Cesium.Cartesian3.UNIT_X, - Cesium.Cartesian3.UNIT_Z, - ); - const awayFrames = framesFor(away); - awayFrames.refreshProjectionImage(record); assert.equal(record.projection.image.src, undefined); + visible = true; frames.refreshProjectionImage(record); assert.match(record.projection.image.src, /projTs=/); }); -test('the renderer scene host culls the far side without raw viewer access', () => { - const native = lookingDown(); - const viewer = { isDestroyed: () => false }; - const camera = native.camera; - camera.directionWC = Cesium.Cartesian3.UNIT_X; - const unbind = bindRenderer(viewer, { - camera: { visiblePoints: createPointsVisibility(native.scene, camera) }, - }); - try { - assert.equal(framesFor(viewer).projectionInView(planeRecord()), false); - } finally { - unbind(); +test('what cannot be judged counts as visible', (t) => { + for (const frames of [ + framesWithCamera(t, { visiblePoints: () => null }), + framesWithCamera(t, { pose: () => ({}) }), + framesFor(null), + ]) { + const record = planeRecord(); + frames.refreshProjectionImage(record); + assert.match(record.projection.image.src, /projTs=/); } -}); -test('visibility checks reuse the points array across ticks', () => { - const seen = []; - const host = {}; - const unbind = bindRenderer(host, { - camera: { - visiblePoints: (points) => { - seen.push(points); - return true; - }, - }, - }); - try { - const frames = framesFor(host); - frames.projectionInView(planeRecord()); - frames.projectionInView(planeRecord()); - assert.equal(seen.length, 2); - assert.strictEqual(seen[0], seen[1]); - } finally { - unbind(); - } -}); - -test('deep viewers do not lose nearby planes to the horizon test', () => { - const mount = point(0, 0, -350); - const position = point(0.00135, 0, -300); - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.subtract(mount, position, new Cesium.Cartesian3()), - new Cesium.Cartesian3(), - ); - const record = planeRecord(); - record.frustumPositions = { mount }; - record.position = mount; - assert.equal( - framesFor( - viewerAt(position, direction, Cesium.Cartesian3.UNIT_Z), - ).projectionInView(record), - true, - ); -}); - -test('flat and unknown projections fail open', () => { - const native = lookingDown(); - native.camera.directionWC = Cesium.Cartesian3.UNIT_X; - native.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; - assert.equal(framesFor(native).projectionInView(planeRecord()), true); - native.scene.mode = Cesium.SceneMode.SCENE3D; - native.camera.directionWC = undefined; - assert.equal(framesFor(native).projectionInView(planeRecord()), true); - const host = {}; - const unbind = bindRenderer(host, { camera: { pose: () => ({}) } }); - try { - assert.equal(framesFor(host).projectionInView(planeRecord()), true); - } finally { - unbind(); - } -}); - -test('what cannot be judged counts as visible', () => { - const record = planeRecord(); - assert.equal(framesFor(null).projectionInView(record), true); - assert.equal( - framesFor({ ...lookingDown(), isDestroyed: () => true }).projectionInView( - record, - ), - true, - ); - const flat = lookingDown(); - flat.scene.mode = Cesium.SceneMode.SCENE2D; - assert.equal(framesFor(flat).projectionInView(record), true); - const noGeometry = { - camera: { id: 'plane' }, - projection: record.projection, - position: point(180, 0, 20), - }; - assert.equal(framesFor(lookingDown()).projectionInView(noGeometry), true); + const noGeometry = planeRecord(); + delete noGeometry.frustumPositions; + const visiblePoints = t.mock.fn(() => false); + framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry); + assert.equal(visiblePoints.mock.callCount(), 0); + assert.match(noGeometry.projection.image.src, /projTs=/); }); diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index bcf251224f..9c31d34c8d 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -86,6 +86,9 @@ function sameMatrix(array, matrix) { return true; } +const finiteVector = (v) => + !!v && Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z); + /** Conservative globe/frustum visibility; null means unknown. */ export function createPointsVisibility(scene, camera) { const visibilitySphere = new Cesium.BoundingSphere(); @@ -93,47 +96,20 @@ export function createPointsVisibility(scene, camera) { let visibilityEllipsoid = null; let visibilityOccluder = null; return function visiblePoints(points, marginM) { - if ( - scene.mode !== Cesium.SceneMode.SCENE3D || - !points?.length || - !Number.isFinite(marginM) || - marginM < 0 || - typeof camera.frustum?.computeCullingVolume !== 'function' - ) - return null; - const radii = Cesium.Ellipsoid.WGS84.radii; - if (marginM >= Math.min(radii.x, radii.y, radii.z)) return null; const eye = camera.positionWC; - if ( - !eye || - !Number.isFinite(eye.x) || - !Number.isFinite(eye.y) || - !Number.isFinite(eye.z) - ) - return null; const direction = camera.directionWC; const up = camera.upWC; if ( - !direction || - !up || - !Number.isFinite(direction.x) || - !Number.isFinite(direction.y) || - !Number.isFinite(direction.z) || - !Number.isFinite(up.x) || - !Number.isFinite(up.y) || - !Number.isFinite(up.z) + scene.mode !== Cesium.SceneMode.SCENE3D || + !points?.length || + !finiteVector(eye) || + !finiteVector(direction) || + !finiteVector(up) || + !points.every(finiteVector) ) return null; - for (const p of points) { - if ( - !p || - !Number.isFinite(p.x) || - !Number.isFinite(p.y) || - !Number.isFinite(p.z) - ) - return null; - } if (visibilityMargin !== marginM) { + const radii = Cesium.Ellipsoid.WGS84.radii; visibilityMargin = marginM; visibilityEllipsoid = new Cesium.Ellipsoid( radii.x - marginM, @@ -143,6 +119,7 @@ export function createPointsVisibility(scene, camera) { visibilityOccluder = new Cesium.EllipsoidalOccluder(visibilityEllipsoid); } const inverse = visibilityEllipsoid.oneOverRadii; + // Inside the ellipsoid Cesium's occluder hides nearby points; judge by the frustum alone. const outside = Math.hypot(eye.x * inverse.x, eye.y * inverse.y, eye.z * inverse.z) >= 1; if (outside) { @@ -156,11 +133,7 @@ export function createPointsVisibility(scene, camera) { } if (!visible) return false; } - const culling = camera.frustum.computeCullingVolume( - eye, - camera.directionWC, - camera.upWC, - ); + const culling = camera.frustum.computeCullingVolume(eye, direction, up); return ( culling.computeVisibility( Cesium.BoundingSphere.fromPoints(points, visibilitySphere), @@ -752,8 +725,6 @@ export function createCesiumCamera({ }); // Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a // `lookAt` target's, or the identity. - if (!capabilities || capabilities.has('pointVisibility')) - cameraPort.visiblePoints = createPointsVisibility(scene, camera); if (!capabilities || capabilities.has('followFrame')) cameraPort.followFrame = () => { if (!lastFollowFrame || !sameMatrix(lastFollowFrame, camera.transform)) diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs index 5328fca3f0..36d841efed 100644 --- a/src/render/cesium/cameraPort.test.mjs +++ b/src/render/cesium/cameraPort.test.mjs @@ -19,7 +19,7 @@ import { headlessCamera, withVirtualClock, } from './cameraGoldens.js'; -import { createCesiumCamera } from './camera.js'; +import { createCesiumCamera, createPointsVisibility } from './camera.js'; import { createCesiumPorts } from './ports.js'; import { bindRenderer, cameraOf } from '../rendererOf.js'; @@ -337,11 +337,20 @@ test('the camera port gives the clock its own tick back as it goes', () => { } }); -test('camera visibility is unknown outside 3D and resolves on the globe', () => { - const { scene, camera } = headlessCamera(); - scene.postUpdate = new Cesium.Event(); +test('visiblePoints is there only with its capability, and unknown outside 3D', (t) => { + const { scene } = headlessCamera(); + for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender']) + scene[name] = new Cesium.Event(); + scene.primitives = { add() {}, remove() {} }; scene.requestRender = () => {}; - const { port } = createCesiumCamera({ scene, camera, report: () => {} }); + const viewer = { scene, clock: { currentTime: Cesium.JulianDate.now() } }; + const without = createCesiumPorts(viewer, { capabilities: new Set() }); + assert.equal(without.camera.visiblePoints, undefined); + without.dispose(); + const ports = createCesiumPorts(viewer, { + capabilities: new Set(['pointVisibility']), + }); + t.after(() => ports.dispose()); const points = [Cesium.Cartesian3.fromDegrees(0, 0, 10)]; for (const mode of [ Cesium.SceneMode.SCENE2D, @@ -350,10 +359,123 @@ test('camera visibility is unknown outside 3D and resolves on the globe', () => undefined, ]) { scene.mode = mode; - assert.equal(port.visiblePoints(points, 200), null); + assert.equal(ports.camera.visiblePoints(points, 200), null); } scene.mode = Cesium.SceneMode.SCENE3D; - assert.equal(typeof port.visiblePoints(points, 200), 'boolean'); + assert.equal(typeof ports.camera.visiblePoints(points, 200), 'boolean'); +}); + +const point = (lon, lat, altitude = 20) => + Cesium.Cartesian3.fromDegrees(lon, lat, altitude); +const down = Cesium.Cartesian3.negate( + Cesium.Cartesian3.UNIT_X, + new Cesium.Cartesian3(), +); +const up = Cesium.Cartesian3.UNIT_Z; +const frustum = new Cesium.PerspectiveFrustum({ + fov: Cesium.Math.toRadians(60), + aspectRatio: 16 / 9, + near: 1, + // Cesium's default far plane, as the app uses. + far: 5e8, +}); + +function visibility(position, direction, up) { + const visiblePoints = createPointsVisibility( + { mode: Cesium.SceneMode.SCENE3D }, + { positionWC: position, directionWC: direction, upWC: up, frustum }, + ); + return (points) => visiblePoints(points, 200); +} + +function directionTo(position, target) { + return Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); +} + +function assertInFrustum(points, position, direction) { + const culling = frustum.computeCullingVolume(position, direction, up); + assert.notEqual( + culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)), + Cesium.Intersect.OUTSIDE, + ); +} + +test('a plane in front of the camera is visible', () => { + assert.equal(visibility(point(0, 0, 30000), down, up)([point(0, 0)]), true); +}); + +test('a plane behind the camera is outside the frustum', () => { + assert.equal( + visibility(point(0, 0, 30000), Cesium.Cartesian3.UNIT_X, up)([point(0, 0)]), + false, + ); +}); + +test('a corner can be in view when the mount and centre are outside', () => { + const visible = visibility(point(0, 0, 30000), down, up); + const mount = point(0.3, 0); + const points = [ + mount, + point(0.1, 0.0001), + point(0.3, 0.0001), + point(0.3, -0.0001), + point(0.1, -0.0001), + ]; + assert.equal(visible(points), true); + assert.equal(visible([mount]), false); + assert.equal(visible([point(0.2, 0)]), false); +}); + +test('a nearby plane below the ellipsoid is visible to low and high viewers', () => { + const cap = point(0.00054, 0, -18); + const points = [point(0, 0, -18), cap]; + for (const altitude of [4, 1200]) { + const position = point(0.00135, 0, altitude); + const direction = directionTo(position, cap); + assertInFrustum(points, position, direction); + assert.equal(visibility(position, direction, up)(points), true); + } +}); + +test('the horizon rejects a negative-height plane on the far side', () => { + const mount = point(0, 0, -18); + const points = [mount, point(0.00054, 0, -18)]; + for (const altitude of [4, 30000, 2e7]) { + const position = point(180, 0, altitude); + const direction = directionTo(position, mount); + assertInFrustum(points, position, direction); + assert.equal(visibility(position, direction, up)(points), false); + } +}); + +test('a low viewer can see a plane beyond the WGS84 horizon', () => { + const mount = point(0, 0, 1); + const position = point(0.2, 0, 4); + assert.equal( + visibility(position, directionTo(position, mount), up)([mount]), + true, + ); +}); + +test('deep viewers do not lose nearby planes to the horizon test', () => { + const mount = point(0, 0, -350); + const position = point(0.00135, 0, -300); + assert.equal( + visibility(position, directionTo(position, mount), up)([mount]), + true, + ); +}); + +test('a non-finite camera direction leaves visibility unknown', () => { + const visible = visibility( + point(0, 0, 30000), + new Cesium.Cartesian3(NaN, 0, 0), + up, + ); + assert.equal(visible([point(0, 0)]), null); }); test('setFov holds the vertical angle across resizes, and waits for a first one', () => { diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index ba69cb1991..6a9329ab90 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -485,7 +485,7 @@ export function createCesiumPorts( : {}), }); const cameraPort = cameraPart.port; - if (controlled && capabilities.has('pointVisibility')) + if (capabilities.has('pointVisibility')) cameraPort.visiblePoints = createPointsVisibility(scene, camera); measureCameraChanged = cameraPart.measureChanged ?? null; const effectsPart = createCesiumEffects(scene, { diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index 8bf2705242..d1f12fd156 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -234,7 +234,14 @@ export type CameraEvent = 'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd'; export interface CameraPort { - /** Conservative visibility of an ECEF point set, with a horizon margin in metres; null means unknown. */ + /** + * Whether any of the ECEF points may be on screen: false only when their + * bounding sphere is outside the view or all of them are below the horizon + * of WGS84 shrunk by `horizonMarginM` metres; null when it cannot tell + * (not a 3D scene, an empty point set, or a non-finite point or camera + * vector), which callers treat as visible. Supply a finite, nonnegative + * margin smaller than the shortest WGS84 radius. + */ visiblePoints?(points: Ecef[], horizonMarginM: number): boolean | null; pose(): CameraPose; /** diff --git a/src/ui/cctvControls.js b/src/ui/cctvControls.js index 2d5ad447a6..11440f3a95 100644 --- a/src/ui/cctvControls.js +++ b/src/ui/cctvControls.js @@ -1,3 +1,5 @@ +import { watch } from 'vue'; +import { MOBILE_SHEET_ATTR } from './mobileSheets.js'; import { EMPTY_CCTV_FRAME, _clearCctvFrame, @@ -86,11 +88,14 @@ export class CctvControls { attributeFilter: ['class', 'hidden'], }); // On phones the panel is on screen only while the Cameras sheet is open. - if (typeof document !== 'undefined' && document.body) - this._videoVisibilityObserver.observe(document.body, { - attributes: true, - attributeFilter: ['class', 'data-mobile-sheet'], - }); + this._videoVisibilityObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', MOBILE_SHEET_ATTR], + }); + this._offPreviewCards = watch( + () => this.store.previewCards, + () => this._renderCctvState(this._cctvState), + ); this.listen(document, 'visibilitychange', () => this._renderCctvState(this._cctvState), ); @@ -163,6 +168,7 @@ export class CctvControls { this._quebecCctvOverlay?.dispose(); this._cctvVideoSurface?.stop(); this._videoVisibilityObserver?.disconnect(); + this._offPreviewCards?.(); this._actionGeneration++; this.listeners.abort(); this._cctvUnsubscribe?.(); diff --git a/src/ui/cctvPanel.test.mjs b/src/ui/cctvPanel.test.mjs index 7612eacc3d..dc082cb652 100644 --- a/src/ui/cctvPanel.test.mjs +++ b/src/ui/cctvPanel.test.mjs @@ -20,7 +20,7 @@ const BUTTONS = { _cctvProjectionBtn: 'cctv-projection-btn', }; -function panel(t) { +function panel(t, { video = false } = {}) { document.body.replaceChildren(); const host = document.body.appendChild(document.createElement('div')); const pinia = createPinia(); @@ -32,6 +32,7 @@ function panel(t) { document.getElementById(id), ]), ); + if (video) elements._cctvVideo = document.getElementById('cctv-video'); const controls = new CctvControls({ elements: { ...elements, @@ -377,16 +378,7 @@ test('a second edit of the same chip gets a fresh input', async (t) => { }); test('the frame preview renders each step of a camera frame request', async (t) => { - const prior = globalThis.Image; - const requests = []; - globalThis.Image = class { - constructor() { - requests.push(this); - } - }; - t.after(() => { - globalThis.Image = prior; - }); + const requests = mockImages(t); const { controls, byId } = panel(t); // The preview loads while the panel is open; the panel starts collapsed. byId('cctv-panel').classList.remove('collapsed'); @@ -610,15 +602,7 @@ test('the meta line of a disabled layer does not describe its last camera', () = }); const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); -const stillState = (frameUrl) => ({ - enabled: true, - count: 1, - cameraIndex: [camera], - activeCameraId: 'a', - activeCamera: { ...camera, frameUrl, sourceKind: 'snapshot' }, -}); - -test('the still preview is fetched only while the tab and the panel are shown', async (t) => { +function mockImages(t) { const prior = globalThis.Image; const requests = []; globalThis.Image = class { @@ -626,6 +610,22 @@ test('the still preview is fetched only while the tab and the panel are shown', requests.push(this); } }; + t.after(() => { + globalThis.Image = prior; + }); + return requests; +} + +const stillState = (frameUrl, id = 'a') => ({ + enabled: true, + count: 2, + cameraIndex: [camera, { ...camera, id: 'b' }], + activeCameraId: id, + activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' }, +}); + +test('the still preview is fetched only while the tab and the panel are shown', async (t) => { + const requests = mockImages(t); const hidden = Object.getOwnPropertyDescriptor(document, 'hidden'); let tabHidden = false; Object.defineProperty(document, 'hidden', { @@ -633,11 +633,11 @@ test('the still preview is fetched only while the tab and the panel are shown', get: () => tabHidden, }); t.after(() => { - globalThis.Image = prior; if (hidden) Object.defineProperty(document, 'hidden', hidden); else delete document.hidden; }); const { controls, byId } = panel(t); + assert.equal(controls._cctvVideo, undefined); const panelElement = byId('cctv-panel'); const state = stillState; @@ -668,15 +668,8 @@ test('the still preview is fetched only while the tab and the panel are shown', }); test('the still preview waits for the Cameras sheet on phones', async (t) => { - const prior = globalThis.Image; - const requests = []; - globalThis.Image = class { - constructor() { - requests.push(this); - } - }; + const requests = mockImages(t); t.after(() => { - globalThis.Image = prior; document.body.classList.remove('mobile-shell'); document.body.removeAttribute('data-mobile-sheet'); }); @@ -704,22 +697,53 @@ test('the still preview waits for the Cameras sheet on phones', async (t) => { assert.equal(requests.length, 2, 'desktop ignores the sheet'); }); -test('a still-only panel (no video element) resumes from the class change', async (t) => { - const prior = globalThis.Image; - const requests = []; - globalThis.Image = class { - constructor() { - requests.push(this); - } - }; - t.after(() => { - globalThis.Image = prior; - }); +test('a camera picked while the panel is collapsed shows its own still on expanding', async (t) => { + const requests = mockImages(t); const { controls, byId } = panel(t); - assert.equal(controls._cctvVideo, undefined); + const panelElement = byId('cctv-panel'); + panelElement.classList.remove('collapsed'); controls._renderCctvState(stillState('a1.jpg')); - assert.equal(requests.length, 0); - byId('cctv-panel').classList.remove('collapsed'); - await settle(); assert.equal(requests.length, 1); + assert.equal(requests[0].src, 'a1.jpg'); + panelElement.classList.add('collapsed'); + await settle(); + controls._renderCctvState(stillState('b1.jpg', 'b')); + assert.equal(requests.length, 1); + requests[0].onload(); + panelElement.classList.remove('collapsed'); + await settle(); + await nextTick(); + assert.equal(requests.length, 2); + assert.equal(requests[1].src, 'b1.jpg'); + assert.equal(byId('cctv-frame').dataset.cameraId, 'b'); + assert.notEqual(byId('cctv-frame').getAttribute('src'), 'a1.jpg'); +}); + +test('leaving the Cameras sheet stops the live video and coming back starts it again', async (t) => { + const { controls, byId } = panel(t, { video: true }); + byId('cctv-panel').classList.remove('collapsed'); + document.body.classList.add('mobile-shell'); + document.body.setAttribute('data-mobile-sheet', 'cameras'); + t.after(() => { + document.body.classList.remove('mobile-shell'); + document.body.removeAttribute('data-mobile-sheet'); + }); + controls._renderCctvState({ + enabled: true, + count: 1, + cameraIndex: [camera], + activeCameraId: 'a', + activeCamera: { ...camera, isVideo: true }, + }); + const first = controls._cctvVideoSurface; + assert.ok(first); + const stop = t.mock.method(first, 'stop'); + document.body.setAttribute('data-mobile-sheet', 'layers'); + await settle(); + assert.equal(stop.mock.callCount(), 1); + assert.equal(controls._cctvVideoSurface, null); + document.body.setAttribute('data-mobile-sheet', 'cameras'); + await settle(); + assert.ok(controls._cctvVideoSurface); + assert.notEqual(controls._cctvVideoSurface, first); }); diff --git a/src/ui/cctvPresentation.js b/src/ui/cctvPresentation.js index 7e4b576f62..2c637465e3 100644 --- a/src/ui/cctvPresentation.js +++ b/src/ui/cctvPresentation.js @@ -4,6 +4,15 @@ import { cctvSourceLabelText, cctvSourceMessageText } from './cctvFrames.js'; import { createCctvVideoSurface } from './cctvVideo.js'; import { presentCctvCalibration } from './cctvCalibration.js'; import { roundHeadingDegrees } from '../data/headingDegrees.js'; +import { + MOBILE_SHELL_CLASS, + MOBILE_SHEET_ATTR, + sheetForPanelId, +} from './mobileSheets.js'; + +const CAMERAS_SHEET = sheetForPanelId('cctv-panel'); +const CONTEXT_SHEET = sheetForPanelId('global-context-panel'); + export function _calBadgeLabel(badge) { switch (badge) { case 'calibrated': @@ -274,19 +283,21 @@ export function _renderCctvState(state) { const liveIntent = enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl; this.store.setLive(liveIntent); - // A background tab or a collapsed panel shows nothing, so neither plays the - // video nor fetches the still; the observer and the visibilitychange listener - // render again when the panel is shown. - // On phones the panel also belongs to one sheet: the shell hides it unless - // data-mobile-sheet is 'cameras'. - const body = typeof document !== 'undefined' ? document.body : null; - const sheetClosed = - !!body?.classList?.contains('mobile-shell') && - body.getAttribute('data-mobile-sheet') !== 'cameras'; + // A background tab, a collapsed panel or a closed phone sheet shows no + // picture; the observers and visibilitychange render again on showing. + const body = globalThis.document?.body; + const phone = body?.classList.contains(MOBILE_SHELL_CLASS); + const sheet = body?.getAttribute(MOBILE_SHEET_ATTR); + const tabShown = !!body && !document.hidden; const panelShown = - !(typeof document !== 'undefined' && document.hidden) && - !this._cctvPanel?.classList?.contains('collapsed') && - !sheetClosed; + tabShown && + !this._cctvPanel?.classList.contains('collapsed') && + (!phone || sheet === CAMERAS_SHEET); + // Context's camera card shows the same still. + const cardShown = + tabShown && + this.store.previewCards > 0 && + (!phone || sheet === CONTEXT_SHEET); if (this._cctvVideo) { const visible = liveIntent && panelShown; if (!visible || this._cctvVideoCameraId !== activeId) { @@ -313,7 +324,7 @@ export function _renderCctvState(state) { // immediate so navigation never waits on the prior camera's request. if ( nextSrc && - panelShown && + (panelShown || cardShown) && (cameraChanged || (!frameLoading && this._frame.currentSrc !== nextSrc)) ) { this._queueCctvFrame(nextSrc, nextCameraId, cameraChanged); diff --git a/src/ui/contextCardFrame.test.mjs b/src/ui/contextCardFrame.test.mjs new file mode 100644 index 0000000000..475f65f53a --- /dev/null +++ b/src/ui/contextCardFrame.test.mjs @@ -0,0 +1,167 @@ +import '../testSupport/registerDom.mjs'; +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPinia } from 'pinia'; +import { createApp, nextTick } from 'vue'; +import { CctvControls } from './cctvControls.js'; +import { useCctvStore } from './stores/cctv.js'; +import CctvPanel from './views/panels/CctvPanel.vue'; +import CctvPreview from './views/panels/CctvPreview.vue'; + +const settle = () => new Promise((r) => setTimeout(r, 0)); +const camera = { + id: 'a', + city: 'Austin', + name: 'Congress Ave', + headingDeg: 91.6, + fovDeg: 60, + rangeM: 120.4, + sourceLabel: 'Configured Source', + calBadge: 'curated', +}; +const stillState = (frameUrl, id = 'a') => ({ + enabled: true, + count: 2, + cameraIndex: [camera, { ...camera, id: 'b' }], + activeCameraId: id, + activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' }, +}); + +function fixture(t, { card = true } = {}) { + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const cardHost = document.body.appendChild(document.createElement('div')); + const pinia = createPinia(); + const app = createApp(CctvPanel).use(pinia); + app.mount(host); + let preview; + function mountCard() { + preview = createApp(CctvPreview, { cameraId: 'a' }).use(pinia); + preview.mount(cardHost); + } + if (card) mountCard(); + const controls = new CctvControls({ + elements: { + _cctvPanel: document.getElementById('cctv-panel'), + _cctvFrame: document.getElementById('cctv-frame'), + _cctvFrameWrap: document.getElementById('cctv-frame-wrap'), + }, + cctv: {}, + actions: { + isEnabled: () => true, + setPanelCollapsed() {}, + syncViewport() {}, + }, + store: useCctvStore(pinia), + }); + t.after(() => { + controls.destroy(); + app.unmount(); + preview?.unmount(); + }); + return { + controls, + cardHost, + mountCard, + panelEl: document.getElementById('cctv-panel'), + }; +} + +function mockImages(t) { + const prior = globalThis.Image; + const requests = []; + globalThis.Image = class { + constructor() { + requests.push(this); + } + }; + t.after(() => { + globalThis.Image = prior; + }); + return requests; +} + +test('desktop: the Context card keeps refreshing while the accordion folds CCTV', async (t) => { + const requests = mockImages(t); + const { controls, cardHost, panelEl } = fixture(t); + panelEl.classList.remove('collapsed'); + controls._renderCctvState(stillState('a1.jpg')); + assert.equal(requests.length, 1); + requests[0].onload(); + await settle(); + await nextTick(); + assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a1.jpg'); + // Context opens: the desktop accordion folds CCTV (class collapsed). + panelEl.classList.add('collapsed'); + await settle(); + controls._renderCctvState(stillState('a2.jpg')); + assert.equal(requests.length, 2); + assert.equal(requests[1].src, 'a2.jpg'); + requests[1].onload(); + controls._renderCctvState(stillState('a3.jpg')); + assert.equal(requests.length, 3); + assert.equal(requests[2].src, 'a3.jpg'); + requests[2].onload(); + await settle(); + await nextTick(); + assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a3.jpg'); +}); + +test('phone: a camera picked with the Context sheet open gets its still', async (t) => { + const requests = mockImages(t); + t.after(() => { + document.body.classList.remove('mobile-shell'); + document.body.removeAttribute('data-mobile-sheet'); + }); + const { controls, cardHost, panelEl } = fixture(t); + document.body.classList.add('mobile-shell'); + document.body.setAttribute('data-mobile-sheet', 'context'); + panelEl.classList.remove('collapsed'); + controls._renderCctvState(stillState('a1.jpg')); + controls._renderCctvState(stillState('a2.jpg')); + await settle(); + await nextTick(); + assert.ok( + requests.length >= 1, + 'the Context card on the Context sheet requests the still', + ); + requests.at(-1).onload(); + await settle(); + await nextTick(); + assert.ok( + cardHost.querySelector('.cctv-preview__expand'), + 'the card shows a frame, not Acquiring frame…', + ); +}); + +test('phone: the card on a closed Context sheet waits', async (t) => { + const requests = mockImages(t); + const { controls, panelEl } = fixture(t); + panelEl.classList.add('collapsed'); + document.body.classList.add('mobile-shell'); + document.body.setAttribute('data-mobile-sheet', 'layers'); + t.after(() => { + document.body.classList.remove('mobile-shell'); + document.body.removeAttribute('data-mobile-sheet'); + }); + controls._renderCctvState(stillState('a1.jpg')); + assert.equal(requests.length, 0); + document.body.setAttribute('data-mobile-sheet', 'context'); + await settle(); + assert.equal(requests.length, 1); + assert.equal(requests[0].src, 'a1.jpg'); +}); + +test('desktop: a card that mounts asks for the still', async (t) => { + const requests = mockImages(t); + const { controls, panelEl, mountCard } = fixture(t, { card: false }); + panelEl.classList.add('collapsed'); + controls._renderCctvState(stillState('a1.jpg')); + await settle(); + assert.equal(requests.length, 0); + mountCard(); + await settle(); + await nextTick(); + assert.equal(requests.length, 1); + assert.equal(requests[0].src, 'a1.jpg'); +}); diff --git a/src/ui/mobileSheets.js b/src/ui/mobileSheets.js new file mode 100644 index 0000000000..3187d15cc1 --- /dev/null +++ b/src/ui/mobileSheets.js @@ -0,0 +1,25 @@ +export const MOBILE_SHELL_CLASS = 'mobile-shell'; +export const MOBILE_SHEET_ATTR = 'data-mobile-sheet'; + +/** + * Panels each sheet expands. A sheet also shows its rail's other panels + * collapsed (Scenes under Layers), per styles/mobile-shell.css. + */ +export const MOBILE_SHEET_PANELS = Object.freeze({ + layers: Object.freeze(['data-panel']), + cameras: Object.freeze(['cctv-panel', 'street-level-panel']), + context: Object.freeze(['global-context-panel']), + search: Object.freeze(['location-bar']), + more: Object.freeze(['control-panel', 'pp-toggles']), +}); + +/** + * @param {string} panelId + * @returns {string|null} The sheet that presents `panelId`. + */ +export function sheetForPanelId(panelId) { + for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) { + if (ids.includes(panelId)) return sheet; + } + return null; +} diff --git a/src/ui/mobileShell.js b/src/ui/mobileShell.js index 7570e2d170..861add6ba2 100644 --- a/src/ui/mobileShell.js +++ b/src/ui/mobileShell.js @@ -18,22 +18,20 @@ import { readPanelState, } from './rail/panelState.js'; +import { + MOBILE_SHELL_CLASS, + MOBILE_SHEET_ATTR, + MOBILE_SHEET_PANELS, +} from './mobileSheets.js'; + +export { + MOBILE_SHELL_CLASS, + MOBILE_SHEET_ATTR, + MOBILE_SHEET_PANELS, + sheetForPanelId, +} from './mobileSheets.js'; + export const MOBILE_SHELL_MEDIA_QUERY = '(max-width: 720px)'; -export const MOBILE_SHELL_CLASS = 'mobile-shell'; -export const MOBILE_SHEET_ATTR = 'data-mobile-sheet'; - -/** - * Panels each sheet expands. A sheet also shows its rail's other panels - * collapsed (Scenes under Layers), per styles/mobile-shell.css. - */ -export const MOBILE_SHEET_PANELS = Object.freeze({ - layers: Object.freeze(['data-panel']), - cameras: Object.freeze(['cctv-panel', 'street-level-panel']), - context: Object.freeze(['global-context-panel']), - search: Object.freeze(['location-bar']), - more: Object.freeze(['control-panel', 'pp-toggles']), -}); - export const MOBILE_TABS = Object.freeze([ Object.freeze({ sheet: 'layers', label: msg('Layers'), icon: 'layers' }), Object.freeze({ sheet: 'cameras', label: msg('Cameras'), icon: 'videocam' }), @@ -58,17 +56,6 @@ const BORROWED_PANELS = Object.freeze([ const BORROW_OPTIONS = Object.freeze({ persist: false, syncShare: false }); -/** - * @param {string} panelId - * @returns {string|null} The sheet that presents `panelId`. - */ -export function sheetForPanelId(panelId) { - for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) { - if (ids.includes(panelId)) return sheet; - } - return null; -} - /** * The sheet after a tab press: the same tab closes its sheet, another opens. * @param {string|null} current diff --git a/src/ui/stores/cctv.js b/src/ui/stores/cctv.js index eaea1d6780..b0a6cfdb59 100644 --- a/src/ui/stores/cctv.js +++ b/src/ui/stores/cctv.js @@ -20,6 +20,8 @@ export const useCctvStore = defineStore('gev-cctv', () => { /** The preview: requested and shown frame, loading and error state. */ const frame = shallowRef(null); + /** Number of camera cards outside the panel showing its preview, including Context's card. */ + const previewCards = shallowRef(0); /** Whether the live video surface replaces the still frame. */ const live = shallowRef(false); /** `{label, state}` for the source badge; null until first synced. */ @@ -49,6 +51,11 @@ export const useCctvStore = defineStore('gev-cctv', () => { frame.value = markRaw(next); } + /** @param {boolean} shown */ + function showPreviewCard(shown) { + previewCards.value = Math.max(0, previewCards.value + (shown ? 1 : -1)); + } + /** @param {boolean} on */ function setLive(on) { live.value = Boolean(on); @@ -73,6 +80,7 @@ export const useCctvStore = defineStore('gev-cctv', () => { view, calEdit, frame, + previewCards, live, sourceBadge, summary, @@ -80,6 +88,7 @@ export const useCctvStore = defineStore('gev-cctv', () => { publish, setCalEdit, setFrame, + showPreviewCard, setLive, setSourceBadge, setSummary, diff --git a/src/ui/views/panels/CctvPreview.vue b/src/ui/views/panels/CctvPreview.vue index f5aae41cf2..15a4fa5f7d 100644 --- a/src/ui/views/panels/CctvPreview.vue +++ b/src/ui/views/panels/CctvPreview.vue @@ -1,5 +1,5 @@