diff --git a/changelog.d/1702-cctv-nearest-same-camera.md b/changelog.d/1702-cctv-nearest-same-camera.md new file mode 100644 index 0000000000..2ec0298d12 --- /dev/null +++ b/changelog.d/1702-cctv-nearest-same-camera.md @@ -0,0 +1,5 @@ +- Keep the CCTV camera picked with NEAREST, FOCUS or by a scene when it is + the camera CCTV switched to after the view moved. The pick did not stick: + NEAREST's own flight, or the next pan, switched to another camera, so the + panel showed a camera nobody had picked. To keep the camera the list + already shows, press FOCUS (gekh, #1702). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7e86dc45a6..dc586f7ec2 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2061,6 +2061,19 @@ in view finishes loading. The camera picker lists the active camera first, then one camera per visible cell, preferring healthy feeds. It ends with the count of catalog cameras missing from the list. +Turning CCTV on opens on the camera nearest the view. Until someone picks a +camera, each settled move, such as a shared view's flight landing, moves it to +the camera then nearest the view. Automatic selection ends at the first pick: +NEAREST, PREV or NEXT, FOCUS, a camera chosen in the picker, a click on a +camera, a click on empty ground that deselects, an auto-hop step, or a call to +`selectCamera`, `focusNearest`, `focusNearestToPoint` or +`setParams({ selectedCameraId })`, which voice and scenes use. Picking the +camera that is already active counts. The picker shows the automatic camera +as its own option, and a native list sends no change for the option it +already shows, so the list cannot pick that camera: FOCUS does, and so does +NEAREST when that camera is the nearest. Closing the list without a choice +keeps automatic selection. + 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/data/cctvExplicitPickEndsOpening.test.mjs b/src/data/cctvExplicitPickEndsOpening.test.mjs new file mode 100644 index 0000000000..f429ab87f8 --- /dev/null +++ b/src/data/cctvExplicitPickEndsOpening.test.mjs @@ -0,0 +1,138 @@ +// An explicit pick of the camera that a settled move just re-opened must end +// the opening pick. That pick goes through setActiveCamera's UNCHANGED path +// (same camera, already activated); if that path keeps the provisional flag, +// the next settled move (a pan, or the landing of NEAREST's own flight) +// switches the camera away from the one the user chose. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import cctvLayer, { + _setCctvCoverageStateForTest, + _setCctvOverlayHostForTest, + reopenNearestCamera, +} from './cctv.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; + +const BASE = { + headingDeg: 41, + pitchDeg: -5, + fovDeg: 56, + rangeM: 210, + mountHeightM: 100, + groundElevationM: 0, + city: 'London', +}; + +function record(id, lat, lon) { + return { + camera: { ...BASE, id, name: `Camera ${id}`, lat, lon }, + coverageEntities: [], + projection: null, + activationDone: true, + groundResolved: {}, + groundSamples: {}, + groundPrior: 0, + frustumGeometry: null, + frustumPositions: null, + probeClampRangeM: null, + position: Cesium.Cartesian3.fromDegrees(lon, lat, 100), + }; +} + +function viewerAt(lat, lon) { + const viewer = { + isDestroyed: () => false, + eye: { lat, lon, height: 300 }, + scene: { + canvas: { clientWidth: 1200, clientHeight: 800 }, + cartesianToCanvasCoordinates: () => undefined, + primitives: { add: (p) => p, remove: () => true }, + requestRender() {}, + }, + }; + // The layer reads the eye and flies through the renderer's camera port. + viewer.draw = bindFakeDraw(viewer, { + camera: { + pose: () => ({ ...viewer.eye }), + on: () => () => {}, + followed: null, + flyToBounds() {}, + }, + }).draw; + return viewer; +} + +function moveViewer(viewer, lat, lon) { + viewer.eye = { lat, lon, height: 300 }; +} + +function withReopenedLayer(fn) { + _setCctvOverlayHostForTest({ + setEntries() {}, + setVisible() {}, + clearSource() {}, + }); + // Activation builds the projection canvas and frame image. + const originalDocument = globalThis.document; + const originalImage = globalThis.Image; + globalThis.document = { createElement: () => ({ getContext: () => null }) }; + globalThis.Image = class {}; + try { + const trafalgar = record('a-trafalgar', 51.508, -0.128); + const cambridge = record('b-cambridge', 51.513, -0.129); + // enable() assigned the opening camera without activating it. + trafalgar.activationDone = false; + const viewer = viewerAt(51.5081, -0.1281); + _setCctvCoverageStateForTest({ + viewer, + records: [trafalgar, cambridge], + activeCameraId: 'a-trafalgar', + enabled: true, + openingCameraProvisional: true, + }); + // A settled move next to Cambridge Circus re-opens there, still as the + // opening pick. + moveViewer(viewer, 51.5131, -0.1291); + assert.equal(reopenNearestCamera(), true); + assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge'); + fn(viewer); + } finally { + globalThis.document = originalDocument; + globalThis.Image = originalImage; + _setCctvOverlayHostForTest(); + _setCctvCoverageStateForTest({ enabled: false }); + } +} + +for (const [name, pick] of [ + ['NEAREST (focusNearest)', () => cctvLayer.focusNearest({ focus: false })], + ['selectCamera', () => cctvLayer.selectCamera('b-cambridge')], + [ + 'setParams({ selectedCameraId })', + () => cctvLayer.setParams({ selectedCameraId: 'b-cambridge' }), + ], + [ + 'focusNearestToPoint', + () => cctvLayer.focusNearestToPoint(51.513, -0.129, { focus: false }), + ], +]) { + test(`an explicit ${name} pick of the re-opened camera ends the opening pick`, () => { + withReopenedLayer((viewer) => { + pick(); + assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge'); + // A later settled move (a pan, or the landing of the pick's own flight) + // leaves the explicit choice alone. + moveViewer(viewer, 51.5081, -0.1281); + assert.equal(reopenNearestCamera(), false); + assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge'); + }); + }); +} + +test('without a pick, the next settled move still follows the view', () => { + withReopenedLayer((viewer) => { + moveViewer(viewer, 51.5081, -0.1281); + assert.equal(reopenNearestCamera(), true); + assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar'); + }); +}); diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index f6f445b86e..240cf0728e 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -81,9 +81,8 @@ export function createNavigation({ return false; const nearest = nearestCameraIdToViewer(); if (!nearest || nearest === layerState._activeCameraId) return false; - parts.selection.setActiveCamera(nearest); - // setActiveCamera ends the opening pick; this is still that pick. - layerState._openingCameraProvisional = true; + // Still the opening pick: later settled moves may replace it. + parts.selection.setActiveCamera(nearest, { opening: true }); return true; } diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 157d2606bc..0ec62935d2 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -108,10 +108,13 @@ export function createSelection({ * Sets the active camera by ID, initializes its projection runtime, refreshes * its frame, and updates styles. * @param {string} cameraId - ID of the camera to activate. + * @param {Object} [options] + * @param {boolean} [options.opening=false] - The opening camera following + * the view, not someone's pick: settled moves may still replace it. * @returns {'activated'|'unchanged'|'not-found'} Discriminated activation result. */ - function setActiveCamera(cameraId) { + function setActiveCamera(cameraId, { opening = false } = {}) { if (!cameraId || !layerState._recordById.has(cameraId)) return CCTV_ACTIVATION_RESULT.NOT_FOUND; const record = layerState._recordById.get(cameraId); @@ -129,6 +132,9 @@ export function createSelection({ record, ) ) { + // Picking the camera a settled move re-opened is still a pick: later + // settled moves must leave it alone. + if (!opening) layerState._openingCameraProvisional = false; // Browser-only feeds have a separate player; a reselect retries it // without re-running activation or touching the projection geometry. if (parts.model.isBrowserOverlayCamera(record.camera)) { @@ -139,7 +145,7 @@ export function createSelection({ } layerState._activeCameraId = cameraId; layerState._autoHopSuspended = false; - layerState._openingCameraProvisional = false; + layerState._openingCameraProvisional = opening; // A real activation creates projection work — wake the self-stopping loop. parts.projection.startProjectionLoop(); if (previousActiveRecord && previousActiveRecord !== record) { diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index a68755711f..34cd0e854c 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -215,3 +215,16 @@ test('a count click is the card on top for every layer, unless the count yields' picking.unregisterPickOwner('flights'); } }); + +test('same-camera selection ends the opening pick without notifying snapshot feeds', () => { + const fixture = makeSelection('tripcheck-odot'); + fixture.state._openingCameraProvisional = true; + + assert.equal( + fixture.selection.setActiveCamera('same-camera'), + CCTV_ACTIVATION_RESULT.UNCHANGED, + ); + assert.equal(fixture.state._openingCameraProvisional, false); + assert.equal(fixture.state._activeCameraReselection, 0); + assert.equal(fixture.notifications(), 0); +}); diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index f616ab0b19..3136c4eca6 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -108,6 +108,7 @@ export function createTesting({ state: layerState, services, parts, source }) { } = {}) { layerState._viewer = viewer; layerState._records = Array.isArray(records) ? records : []; + layerState._count = layerState._records.length; layerState._recordById = new Map( layerState._records .filter((record) => record?.camera?.id) diff --git a/src/ui/cctvPickerOpening.test.mjs b/src/ui/cctvPickerOpening.test.mjs new file mode 100644 index 0000000000..63fd3bbca4 --- /dev/null +++ b/src/ui/cctvPickerOpening.test.mjs @@ -0,0 +1,197 @@ +// src/ui/cctvPickerOpening.test.mjs — the picker and the opening camera. +// The opening camera follows the view until someone picks one. The picker +// shows it as its own option; a native select fires no change for the +// option it already shows, so FOCUS keeps that camera, and leaving the list +// without a choice lets it follow the view. +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { createPinia } from 'pinia'; +import { createApp, nextTick } from 'vue'; +import cctvLayer, { + _setCctvCoverageStateForTest, + _setCctvOverlayHostForTest, + reopenNearestCamera, +} from '../data/cctv.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { CctvControls } from './cctvControls.js'; +import { useCctvStore } from './stores/cctv.js'; +import CctvPanel from './views/panels/CctvPanel.vue'; + +const TRAFALGAR = [51.508, -0.128]; +const CAMBRIDGE = [51.513, -0.129]; + +function record(id, [lat, lon]) { + return { + camera: { + id, + name: `Camera ${id}`, + city: 'London', + lat, + lon, + headingDeg: 41, + pitchDeg: -5, + fovDeg: 56, + rangeM: 210, + mountHeightM: 100, + groundElevationM: 0, + }, + coverageEntities: [], + projection: null, + activationDone: true, + groundResolved: {}, + groundSamples: {}, + groundPrior: 0, + frustumGeometry: null, + frustumPositions: null, + probeClampRangeM: null, + position: Cesium.Cartesian3.fromDegrees(lon, lat, 100), + }; +} + +function viewerAt([lat, lon]) { + const viewer = { + isDestroyed: () => false, + eye: { lat, lon, height: 300 }, + scene: { + canvas: { clientWidth: 1200, clientHeight: 800 }, + cartesianToCanvasCoordinates: () => undefined, + primitives: { add: (p) => p, remove: () => true }, + requestRender() {}, + }, + }; + // The layer reads the eye and flies through the renderer's camera port. + viewer.draw = bindFakeDraw(viewer, { + camera: { + pose: () => ({ ...viewer.eye }), + on: () => () => {}, + followed: null, + flyToBounds() {}, + }, + }).draw; + return viewer; +} + +/** A settled move: the view is now over `[lat, lon]`. */ +function settleOver(viewer, [lat, lon]) { + viewer.eye = { lat, lon, height: 300 }; + return reopenNearestCamera(); +} + +/** + * CCTV opened at Trafalgar Square, then a settled move re-opened it at + * Cambridge Circus; the panel is connected to the layer. + */ +async function reopenedAtCambridge(t) { + _setCctvOverlayHostForTest({ + setEntries() {}, + setVisible() {}, + clearSource() {}, + }); + // Activation builds the frame image and asks for ground heights; this test + // has no server. happy-dom's request timeout would hold the run open 30 s. + const originalImage = globalThis.Image; + const originalFetch = globalThis.fetch; + const originalTimeout = AbortSignal.timeout; + globalThis.Image = class {}; + globalThis.fetch = async () => { + throw new TypeError('no server in this test'); + }; + AbortSignal.timeout = () => new AbortController().signal; + const trafalgar = record('a-trafalgar', TRAFALGAR); + const cambridge = record('b-cambridge', CAMBRIDGE); + // enable() assigned the opening camera without activating it. + trafalgar.activationDone = false; + const viewer = viewerAt(TRAFALGAR); + _setCctvCoverageStateForTest({ + viewer, + records: [trafalgar, cambridge], + activeCameraId: 'a-trafalgar', + enabled: true, + openingCameraProvisional: true, + }); + + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const pinia = createPinia(); + const app = createApp(CctvPanel).use(pinia); + app.mount(host); + const select = document.getElementById('cctv-camera-select'); + const controls = new CctvControls({ + elements: { + _cctvPanel: document.getElementById('cctv-panel'), + _cctvSelect: select, + _cctvFocusBtn: document.getElementById('cctv-focus-btn'), + }, + cctv: cctvLayer, + actions: { + isEnabled: () => true, + toggleEnabled: async () => true, + runExplicitFocus(select, focus) { + const cameraId = select(); + if (cameraId) focus(cameraId); + }, + setParams: (params) => cctvLayer.setParams(params), + setPanelCollapsed() {}, + syncViewport() {}, + }, + store: useCctvStore(pinia), + }); + controls.connect(); + t.after(() => { + controls.destroy(); + app.unmount(); + globalThis.Image = originalImage; + globalThis.fetch = originalFetch; + AbortSignal.timeout = originalTimeout; + _setCctvOverlayHostForTest(); + _setCctvCoverageStateForTest({ enabled: false }); + }); + + assert.equal(settleOver(viewer, CAMBRIDGE), true); + await nextTick(); + assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge'); + return { viewer, select }; +} + +test('the opening camera shows as its own option', async (t) => { + const { select } = await reopenedAtCambridge(t); + assert.equal(select.value, 'b-cambridge'); + const shown = select.options[select.selectedIndex]; + assert.equal(shown.hidden, false); + assert.equal(shown.disabled, false); + assert.equal( + [...select.options].filter((option) => option.value === 'b-cambridge') + .length, + 1, + 'the list shows the camera once', + ); + assert.ok([...select.options].every((option) => !option.hidden)); +}); + +test('FOCUS on the shown camera keeps it after a pan', async (t) => { + const { viewer, select } = await reopenedAtCambridge(t); + const focus = document.getElementById('cctv-focus-btn'); + assert.equal(focus.disabled, false); + focus.click(); + // The click handler waits for the layer switch before it picks. + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + + assert.equal(settleOver(viewer, TRAFALGAR), false); + assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge'); + assert.equal(select.value, 'b-cambridge'); +}); + +test('leaving the picker without a pick lets the camera follow a pan', async (t) => { + const { viewer, select } = await reopenedAtCambridge(t); + select.focus(); + select.blur(); + await nextTick(); + + assert.equal(settleOver(viewer, TRAFALGAR), true); + await nextTick(); + assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar'); + assert.equal(select.value, 'a-trafalgar'); +});