From 607796737cc377f315fb4fe939fcf60d17466ced Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 14:26:37 +0400 Subject: [PATCH 1/9] feat(cctv): show how many cameras a thinned marker stands for Zoomed out, the layer keeps one camera per ground cell and drew it as an ordinary icon, so nothing showed that dozens or hundreds of other cameras sat behind it. A cell with two or more cameras is now one round marker with the count inside, at the centre of its cameras. Single cameras and the active camera keep their icons. The count covers the whole cell, so it does not change while the cell crosses the screen edge. Markers that would overlap on screen merge into one carrying their sum. Counts above 999 use the compact form of the UI language and widen the marker into a pill. Clicking a marker zooms to its group and does not choose a camera. Ambient cards and coverage attach only to cameras drawn as icons; the camera picker keeps one representative per visible cell as before. --- docs/CURRENT-STATE.md | 20 +- scripts/format-scope.json | 2 + scripts/package-boundaries.json | 6 + src/data/cctvCellCounts.js | 161 ++++++++ src/data/cctvCellCounts.test.mjs | 49 +++ src/data/cctvViewThinning.test.mjs | 418 ++++++++++++++++++-- src/layers/cctv/cards.js | 2 +- src/layers/cctv/countMarkers.js | 120 ++++++ src/layers/cctv/lifecycle.js | 4 + src/layers/cctv/navigation.js | 27 +- src/layers/cctv/policy.js | 9 + src/layers/cctv/presentation.js | 2 +- src/layers/cctv/rendering.js | 130 ++++-- src/layers/cctv/rendering.test.mjs | 6 + src/layers/cctv/selection.js | 8 +- src/layers/cctv/selection.test.mjs | 43 ++ src/layers/cctv/state.js | 4 + src/layers/cctv/testing.js | 8 + src/render/cesium/screenModulation.js | 7 + src/render/cesium/screenModulation.test.mjs | 16 + 20 files changed, 965 insertions(+), 77 deletions(-) create mode 100644 src/data/cctvCellCounts.js create mode 100644 src/data/cctvCellCounts.test.mjs create mode 100644 src/layers/cctv/countMarkers.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5a2114a0b8..5d3441608c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1952,14 +1952,18 @@ directory. Every `/api/cctv` route refuses cross-site browser requests but accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. -The CCTV layer draws only the cameras on or near the screen. Zoomed out, it -keeps one camera per ground cell sized to the view, preferring a healthy feed, -and the cells are anchored to the ground so a pan keeps the same cameras. The -active camera always shows. Ground placement and coverage geometry load only -for the cameras in view, with at most two attempts per camera and view regime. -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 CCTV layer draws only the cameras on or near the screen. Zoomed out, a +ground cell containing multiple cameras shows a cyan count at their centre. +The count includes cameras beyond the screen edge and excludes cameras beyond +the horizon. Counts that would overlap on screen merge into one that carries +their sum. Clicking a count zooms to its group. Single cameras keep their icons, +and the active camera has its own icon and is excluded from the count. Close +up, even co-located cameras show individually. Ambient cards and coverage +attach to individual cameras. Ground placement has at most two attempts per +camera and view regime. The view pass reruns while the camera moves, paced by +its own cost. The camera picker lists the active camera first, keeps one +representative per visible cell, preferring healthy feeds, and closes with +the count of cameras outside the view. 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/scripts/format-scope.json b/scripts/format-scope.json index 76d86f698d..429862c7c7 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -625,6 +625,8 @@ "src/layers/cctv/health.js", "src/data/cctv.js", "src/data/cctvCatalogCap.test.mjs", + "src/data/cctvCellCounts.test.mjs", + "src/data/cctvViewThinning.test.mjs", "src/data/cctvDisplayCode.test.mjs", "src/data/cctvFootprint.js", "src/data/cctvGroundHeights.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a5a719033b..93ccb828cb 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3282,6 +3282,8 @@ "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/iconOrientation.js", "src/data/screenRotation.js", @@ -4233,6 +4235,8 @@ "src/data/cctvFootprint.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/cockpitAirLod.js", "src/data/cockpitContactDot.js", @@ -5559,6 +5563,8 @@ "src/data/cctvFootprint.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/cockpitAirLod.js", "src/data/cockpitContactDot.js", diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js new file mode 100644 index 0000000000..8c4c7a226b --- /dev/null +++ b/src/data/cctvCellCounts.js @@ -0,0 +1,161 @@ +import { formatNumber } from '../i18n/index.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; + +/** Exact small counts and compact thousands in the current UI locale. */ +export function formatCameraCount(count) { + return formatNumber( + count, + count < 1000 ? undefined : { notation: 'compact' }, + ); +} + +/** An empty cell and its on-screen picker candidate. */ +export function createCameraCell(key) { + return { + key, + count: 0, + latSum: 0, + lonSum: 0, + heightSum: 0, + south: Infinity, + north: -Infinity, + west: Infinity, + east: -Infinity, + low: Infinity, + high: -Infinity, + winner: null, + rank: Infinity, + }; +} + +/** Accumulate one horizon-visible mount in its ground cell. */ +export function addCellCamera(cell, camera) { + const { lat, lon, absoluteHeightM: height = 0 } = camera; + cell.count++; + // Integer sums make the mean independent of catalog order, to about a centimetre. + cell.latSum += Math.round(lat * 1e7); + cell.lonSum += Math.round(lon * 1e7); + cell.heightSum += Math.round(height * 100); + cell.south = Math.min(cell.south, lat); + cell.north = Math.max(cell.north, lat); + cell.west = Math.min(cell.west, lon); + cell.east = Math.max(cell.east, lon); + cell.low = Math.min(cell.low, height); + cell.high = Math.max(cell.high, height); +} + +/** Geographic mean on the globe surface at the mean mount height. */ +export function cellCenter(cell) { + return fromDegrees( + cell.lonSum / (1e7 * cell.count), + cell.latSum / (1e7 * cell.count), + cell.heightSum / (100 * cell.count), + ); +} + +/** A padded sphere around the group's geographic rectangle and mount heights. */ +export function cellBounds(cell) { + const lat = (cell.north + cell.south) / 2; + const lon = (cell.east + cell.west) / 2; + const height = (cell.high + cell.low) / 2; + // The parallel nearest the equator bounds the width of every row. + const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180; + // Half the diagonal plus 20% padding on every side. + const radius = + 0.6 * + Math.hypot( + (cell.east - cell.west) * 111_320 * Math.cos(parallel), + (cell.north - cell.south) * 111_320, + cell.high - cell.low, + ); + return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) }; +} + +/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */ +function addCell(target, cell) { + target.count += cell.count; + target.latSum += cell.latSum; + target.lonSum += cell.lonSum; + target.heightSum += cell.heightSum; + target.south = Math.min(target.south, cell.south); + target.north = Math.max(target.north, cell.north); + target.west = Math.min(target.west, cell.west); + target.east = Math.max(target.east, cell.east); + target.low = Math.min(target.low, cell.low); + target.high = Math.max(target.high, cell.high); +} + +/** Claim the touching pills in this marker's bucket and its eight neighbors. */ +function collectNeighbors(marker, grid, members, height, mergeDistance) { + for (let col = -1; col <= 1; col++) { + for (let row = -1; row <= 1; row++) { + const bucket = grid.get(`${marker.col + col},${marker.row + row}`); + if (!bucket) continue; + for (const other of bucket) { + // Distance between the horizontal centre segments of the two pills. + const extra = (marker.width + other.width) / 2 - height; + const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); + const dy = marker.y - other.y; + if (dx * dx + dy * dy >= mergeDistance * mergeDistance) continue; + bucket.delete(other); + members.push(other); + } + } + } +} + +/** + * Merge connected groups of overlapping horizontal pills. Each marker occupies + * one grid bucket. Even the widest pill can only touch its eight neighbors. + * Ground cells stay intact for the camera picker and individual-icon pass. + */ +export function mergeCountCells( + cells, + project, + widthFor, + height, + mergeDistance, +) { + const gap = mergeDistance - height; + let columnWidth = mergeDistance; + const markers = cells.map((cell) => { + const screen = project(cellCenter(cell)); + const width = widthFor(cell.count); + columnWidth = Math.max(columnWidth, width + gap); + // The view projector reuses its result object. + return { cell, x: screen?.x, y: screen?.y, width }; + }); + const grid = new Map(); + for (const marker of markers) { + if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue; + marker.col = Math.floor(marker.x / columnWidth); + marker.row = Math.floor(marker.y / mergeDistance); + const key = `${marker.col},${marker.row}`; + if (!grid.has(key)) grid.set(key, new Set()); + marker.bucket = grid.get(key); + marker.bucket.add(marker); + } + + const groups = []; + const members = []; + for (const seed of markers) { + if (!seed.bucket) { + groups.push(seed.cell); + continue; + } + if (!seed.bucket.delete(seed)) continue; + members.length = 0; + members.push(seed); + for (let i = 0; i < members.length; i++) + collectNeighbors(members[i], grid, members, height, mergeDistance); + + if (members.length === 1) { + groups.push(seed.cell); + } else { + const group = createCameraCell(seed.cell.key); + for (const member of members) addCell(group, member.cell); + groups.push(group); + } + } + return groups; +} diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs new file mode 100644 index 0000000000..bfa421bd91 --- /dev/null +++ b/src/data/cctvCellCounts.test.mjs @@ -0,0 +1,49 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { distance } from '../geo/vector.js'; +import { getLocale, setLocale } from '../i18n/index.js'; +import { + createCameraCell, + addCellCamera, + cellCenter, + cellBounds, + formatCameraCount, +} from './cctvCellCounts.js'; + +test('camera counts are exact through 999 and compact in the active locale', () => { + const previous = getLocale(); + try { + for (const locale of ['en', 'fr', 'ja']) { + setLocale(locale); + for (const n of [2, 999, 1000, 12345]) { + const format = new Intl.NumberFormat( + locale, + n < 1000 ? {} : { notation: 'compact' }, + ); + assert.equal(formatCameraCount(n), format.format(n)); + } + } + } finally { + setLocale(previous); + } +}); + +test('the marker mean weights every mount and the flight bounds cover the outlier', () => { + const cameras = [ + { lon: 12, lat: 52, absoluteHeightM: 30 }, + { lon: 12, lat: 52, absoluteHeightM: 40 }, + { lon: 12.003, lat: 52.006, absoluteHeightM: 50 }, + ]; + const cell = createCameraCell(); + for (const camera of cameras) addCellCamera(cell, camera); + const expected = fromDegrees(12.001, 52.002, 40); + assert.ok(distance(cellCenter(cell), expected) < 0.001); + const bounds = cellBounds(cell); + for (const { lon, lat, absoluteHeightM } of cameras) { + assert.ok( + distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) < + bounds.radius, + ); + } +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index bf5a3edf5b..1820ee8050 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -1,16 +1,22 @@ // src/data/cctvViewThinning.test.mjs — the CCTV view pass: only cameras on or -// near the screen show, a zoomed-out view keeps one camera per world-anchored -// cell, and the layer's UI state never rebuilds every camera for a listener +// near the screen show, a zoomed-out view groups neighboring cameras, and the layer's UI state never rebuilds every camera for a listener // that does not read the list. -import { afterEach, test } from 'node:test'; +import { afterEach, beforeEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { getLocale, setLocale } from '../i18n/index.js'; import { bindRenderer } from '../render/rendererOf.js'; +import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, + _extractPickedCameraIdForTest, + bindCctvWorldClickGesture, + applyCctvFocusDeemphasis, + reopenNearestCamera, _setCctvCoverageStateForTest, _viewRecordIdsForTest, + refreshCoverageStyles, refreshHorizonCulling, } from './cctv.js'; @@ -33,6 +39,7 @@ function recordsAt(lonLats) { fovDeg: 44, rangeM: 145, mountHeightM: 8, + absoluteHeightM: 10, }, position: { x: position.x, y: position.y, z: position.z }, coverageEntities: [], @@ -47,7 +54,7 @@ function recordsAt(lonLats) { * equator, north up, through a camera port: the view pass projects the * cameras from its pose. */ -function viewerAt(heightM, lonDeg = 0) { +function viewerAt(heightM, lonDeg = 0, flights = []) { const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); const down = Cesium.Cartesian3.normalize( Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), @@ -70,6 +77,7 @@ function viewerAt(heightM, lonDeg = 0) { far: 5e8, }, }); + port.flyToBounds = (bounds, options) => flights.push({ bounds, options }); const viewer = {}; bindings.push( bindRenderer(viewer, { @@ -82,7 +90,28 @@ function viewerAt(heightM, lonDeg = 0) { /** The renderers bound for the running test, let go when it ends. */ const bindings = []; +const paintedLabels = new Map(); +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + beginPath() {}, + arc() {}, + roundRect() {}, + measureText: (text) => ({ width: text.length * 15 }), + fill() {}, + stroke() {}, + fillText(text, x, y, maxWidth) { + paintedLabels.set(text, maxWidth ?? Infinity); + }, + }), + }), + }; +}); + afterEach(() => { + paintedLabels.clear(); + delete globalThis.document; for (const unbind of bindings.splice(0)) unbind(); }); @@ -102,21 +131,42 @@ const CLUSTER = [ [0.2, 0], ]; -test('zoomed out, cameras sharing a ground cell show one icon', () => { - const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ - viewer: viewerAt(20_000), - records, +/** Count billboards the layer currently shows. */ +function markers() { + const book = cctvLayer._cctvDrawnForTest().counts; + return book.show + ? book + .ids() + .map(book.item) + .filter((item) => item.show) + : []; +} + +/** Send a clean count-marker click through the layer's world click handler. */ +function clickMarker(marker) { + const set = cctvLayer._cctvDrawnForTest().counts.setId; + const hit = { set, id: marker.id, meta: marker.meta }; + assert.equal(_extractPickedCameraIdForTest(hit), null); + const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, () => { + assert.fail('a count click reached activation or empty-click deselection'); }); - assert.equal( - refreshHorizonCulling(), - true, - 'the first pass changes the view', + click({ drawHit: hit, gesture: { travelPx: 0, durationMs: 20 } }); +} + +test('a crowded cell shows its count and a singleton keeps its icon', () => { + const { records } = recordsAt(CLUSTER); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + assert.equal(refreshHorizonCulling(), true); + assert.deepEqual(shownIds(records), ['cam-3']); + assert.deepEqual(_viewRecordIdsForTest(), ['cam-3']); + assert.deepEqual( + markers().map((item) => item.meta.count), + [3], + ); + assert.deepEqual( + cctvLayer.getDetectableObjects().map((o) => o.sourceId), + ['cam-3'], ); - const shown = shownIds(records); - assert.equal(shown.length, 2, 'one for the cluster, one for the far camera'); - assert.ok(shown.includes('cam-3'), 'a camera alone in its cell shows'); - assert.deepEqual(_viewRecordIdsForTest().sort(), shown); }); test('a pan keeps the same winners, and an unchanged view keeps its list', () => { @@ -126,7 +176,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => records, }); refreshHorizonCulling(); - const before = shownIds(records); + const before = cctvLayer.getUIState().cameraIndex; const list = _viewRecordIdsForTest(); // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up). for (const shiftM of [90, 330, 600, 1110]) { @@ -135,7 +185,11 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => records, }); refreshHorizonCulling(); - assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`); + assert.deepEqual( + cctvLayer.getUIState().cameraIndex, + before, + `pan by ${shiftM} m`, + ); } _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); @@ -151,16 +205,17 @@ test('a small zoom within one cell size keeps the same winners', () => { records, }); refreshHorizonCulling(); - return shownIds(records); + return cctvLayer.getUIState().cameraIndex; }; // Cells come in power-of-two metre steps: about 1.5 km and 1.6 km cells at // these heights fall in the same step, so the same cameras win. assert.deepEqual(shownAt(20_500), shownAt(20_000)); }); -test('a healthy camera wins its cell over an unknown one', () => { +test('the picker prefers the healthy camera and the marker stays at the mean', () => { const { records } = recordsAt(CLUSTER.slice(0, 2)); // Whichever camera the id order would pick, the healthy one must win. + let first; for (const id of ['cam-0', 'cam-1']) { _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), @@ -168,7 +223,16 @@ test('a healthy camera wins its cell over an unknown one', () => { healthById: new Map([[id, { status: 'ok' }]]), }); refreshHorizonCulling(); - assert.deepEqual(shownIds(records), [id]); + assert.deepEqual( + cctvLayer.getUIState().cameraIndex.map((c) => c.id), + [id], + ); + const { pos } = markers()[0]; + const center = Cesium.Cartesian3.fromDegrees(0.0005, 0, 10); + assert.ok(Cesium.Cartesian3.distance(pos, center) < 0.02); + if (first) assert.deepEqual(pos, first); + first = pos; + records.reverse(); } }); @@ -181,6 +245,10 @@ test('the active camera always shows, even in a crowded cell', () => { activeCameraId: active.camera.id, }); refreshHorizonCulling(); + assert.deepEqual( + markers().map((item) => item.meta.count), + [2], + ); const icons = _cctvIconsForTest(); assert.ok( icons.item(active.camera.id).show, @@ -268,3 +336,309 @@ test('the camera picker lists the view, with the active camera first', () => { ); assert.equal(state.cameras.length, 3, 'the full list is still every camera'); }); + +test('panning a cell across the padded screen edge keeps its full count', () => { + const { records } = recordsAt([ + [0.277, 0], + [0.28, 0], + [0.29, 0], + ]); + for (const lon of [0.015, 0]) { + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000, lon), records }); + refreshHorizonCulling(); + assert.deepEqual( + markers().map((item) => item.meta.count), + [3], + ); + if (lon === 0) + assert.equal(cctvLayer.getUIState().cameraIndex[0].id, 'cam-0'); + } +}); + +test('only members on the near side of the horizon count', () => { + // At 20 km the limb crosses this cell between 4.55 and 4.69 degrees. + // All three mounts project inside the screen in the query-port fixture. + const { records } = recordsAt([ + [4.5, 0], + [4.55, 0], + [4.69, 0], + ]); + const viewer = {}; + const { port } = fakeCameraPort({ + pose: { + position: Cesium.Cartesian3.fromDegrees(0, 0, 20_000), + fovy: undefined, + }, + }); + bindings.push( + bindRenderer(viewer, { + camera: port, + canvas: { width: WIDTH, height: HEIGHT }, + query: { project: () => ({ x: 400, y: 300 }) }, + }), + ); + _setCctvCoverageStateForTest({ viewer, records }); + refreshHorizonCulling(); + assert.deepEqual( + markers().map((item) => item.meta.count), + [2], + ); +}); + +test('co-located cameras separate below the minimum cell size', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + ]); + _setCctvCoverageStateForTest({ viewer: viewerAt(300), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']); + assert.deepEqual(markers(), []); +}); + +test('a count click frames its members and preserves an explicit camera choice', () => { + for (const spread of [0, 0.01]) { + const flights = []; + const { records } = recordsAt([ + [0, 0], + [spread, 0], + [0.2, 0], + ]); + _setCctvCoverageStateForTest({ + viewer: viewerAt(20_000, 0, flights), + records, + activeCameraId: 'cam-2', + openingCameraProvisional: false, + }); + refreshHorizonCulling(); + const marker = markers()[0]; + clickMarker(marker); + assert.equal(flights.length, 1); + const { bounds, options } = flights[0]; + for (const record of records.slice(0, 2)) + assert.ok( + bounds.radius > + Cesium.Cartesian3.distance(bounds.center, record.position), + ); + const range = options.offset.range; + assert.ok(range > 0 && range < 10_000); + // Run the same view pass at the requested destination. + const center = Cesium.Cartographic.fromCartesian(bounds.center); + const destination = viewerAt( + center.height + range, + Cesium.Math.toDegrees(center.longitude), + ); + assert.equal(reopenNearestCamera(), false); + assert.equal(cctvLayer.getUIState().activeCameraId, 'cam-2'); + _setCctvCoverageStateForTest({ + viewer: destination, + records, + activeCameraId: 'cam-2', + }); + refreshHorizonCulling(); + assert.deepEqual(markers(), []); + assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']); + } +}); + +test('disabling the layer hides its counts', () => { + const { records } = recordsAt(CLUSTER); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.equal(markers().length, 1); + cctvLayer.disable(); + assert.deepEqual(markers(), []); +}); + +test('coverage leaves grouped neighbors and returns when their icons separate', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + [0, 0], + ]); + // Lines already materialised at close zoom. + for (const record of records) record.coverageEntities = [{ show: true }]; + const viewer = viewerAt(20_000); + _setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0' }); + refreshCoverageStyles(); + refreshHorizonCulling(); + assert.deepEqual( + records.map((r) => r.coverageEntities[0].show), + [true, false, false], + ); + records[1].camera.lon = 0.05; + records[1].position = Cesium.Cartesian3.fromDegrees(0.05, 0, 10); + refreshHorizonCulling(); + assert.deepEqual( + records.map((r) => r.coverageEntities[0].show), + [true, true, true], + ); + assert.deepEqual(markers(), []); +}); + +test('count markers share the camera focus fade and recover on release', () => { + const { records } = recordsAt(CLUSTER); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const target = { + screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, + cameraDistance: 1000, + }; + const params = DEFAULT_FOCUS_DEEMPHASIS_PARAMS; + let previousActiveCount = 0; + const tick = (nowMs, target) => { + previousActiveCount = applyCctvFocusDeemphasis({ + records, + nowMs, + target, + params, + previousActiveCount, + screenPositionFor: () => ({ x: 50, y: 50 }), + cameraDistanceFor: () => 1200, + }).activeCount; + }; + tick(0, target); + tick(params.attackMs + 1, target); + assert.equal(markers()[0].focus, params.dimFloor); + tick(params.attackMs + 2, null); + tick(params.attackMs + params.releaseMs + 3, null); + assert.equal(markers()[0].focus, 1); +}); + +test('overlapping cells merge at their weighted centre and keep every camera in the flight bounds', () => { + // The meridian separates the two near cells at every grid level. + const { records } = recordsAt([ + [-0.001, 0], + [-0.001, 0], + [0.002, 0], + [0.002, 0], + [0.002, 0], + [0.05, 0], + [0.05, 0], + [0, 0.001], + [0, -0.001], + ]); + const flights = []; + let previous; + for (const [pan, order] of [ + [0, records], + [0.003, [...records].reverse()], + ]) { + _setCctvCoverageStateForTest({ + viewer: viewerAt(20_000, pan, flights), + records: order, + activeCameraId: 'cam-7', + healthById: new Map([[order[0].camera.id, { status: 'ok' }]]), + }); + refreshHorizonCulling(); + const shown = markers(); + assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']); + assert.equal( + shown.reduce((sum, m) => sum + m.meta.count, 0), + 7, + ); + assert.deepEqual( + shown.map((m) => m.meta.count).sort((a, b) => a - b), + [2, 5], + ); + const merged = shown.find((m) => m.meta.count === 5); + assert.ok( + Cesium.Cartesian3.distance( + merged.pos, + Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), + ) < 0.01, + ); + const positions = shown.map((m) => [m.id, m.pos]); + if (previous) assert.deepEqual(positions, previous); + previous = positions; + clickMarker(merged); + const { bounds } = flights.at(-1); + assert.ok( + records + .slice(0, 5) + .every( + (r) => + Cesium.Cartesian3.distance(r.position, bounds.center) < + bounds.radius, + ), + ); + assert.ok( + bounds.radius < 300, + 'the separate cell stays outside the flight bounds', + ); + } +}); + +test('long localized labels use their measured width on the canvas and billboard', () => { + const locale = getLocale(); + try { + setLocale('ru'); + const { records } = recordsAt([ + ...Array(1300).fill([-0.008, 0]), + [0.06, 0], + [0.06, 0], + ]); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const short = markers().find((m) => m.meta.count === 2); + const long = markers().find((m) => m.meta.count === 1300); + assert.equal(short.image.canvas.width, short.image.canvas.height); + assert.ok(long.image.canvas.width > long.image.canvas.height); + assert.equal(long.size[1], short.size[1]); + assert.equal( + long.size[0] / long.size[1], + long.image.canvas.width / long.image.canvas.height, + ); + const text = new Intl.NumberFormat('ru', { notation: 'compact' }).format( + 1300, + ); + assert.ok(paintedLabels.get(text) >= text.length * 15); + assert.ok( + long.image.canvas.width > text.length * 15, + 'the digits have padding', + ); + } finally { + setLocale(locale); + } +}); + +test('a wider localized pill merges a horizontal neighbor beyond the circle diameter', () => { + const locale = getLocale(); + try { + setLocale('ru'); + // The centers are 46 CSS pixels apart. Only the pill reaches its neighbor. + const at = (count) => { + const { records } = recordsAt([ + ...Array(count).fill([-0.008, 0]), + [0.008, 0], + [0.008, 0], + ]); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + return markers().map((m) => m.meta.count); + }; + assert.deepEqual(at(2), [2, 2]); + assert.deepEqual(at(1300), [1302]); + } finally { + setLocale(locale); + } +}); + +test('a merged centre can pick up a third count marker', () => { + // The two northern centres are 35 px apart. Each is 40 px from the + // southern one, but their combined centre is only 36 px away. + const { records } = recordsAt([ + [-0.006, 0], + [-0.006, 0], + [0.006, 0], + [0.006, 0], + [0, -0.0126], + [0, -0.0126], + ]); + _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.deepEqual( + markers().map((m) => m.meta.count), + [6], + ); +}); diff --git a/src/layers/cctv/cards.js b/src/layers/cctv/cards.js index 203d64e400..ad95d085a5 100644 --- a/src/layers/cctv/cards.js +++ b/src/layers/cctv/cards.js @@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) { let rank = 0; const push = (id, { pinned = false, active = false } = {}) => { const record = layerState._recordById.get(id); - if (!record?.position) return; + if (!record?.position || (!active && record.viewGrouped)) return; entries.push( createCctvThumbnailOverlayEntry({ id, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js new file mode 100644 index 0000000000..8ebdba5142 --- /dev/null +++ b/src/layers/cctv/countMarkers.js @@ -0,0 +1,120 @@ +import { createIconBook } from '../../render/motion/iconBook.js'; +import { + cellCenter, + formatCameraCount, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { getLocale } from '../../i18n/index.js'; +import { + COUNT_MARKER_PX, + COUNT_MERGE_DISTANCE_PX, + COUNT_MERGE_PASSES, +} from './policy.js'; + +/** A pool of static count billboards sharing one canvas for each label. */ +export function createCountMarkers(set) { + const book = createIconBook(set); + const images = new Map(); + const groups = []; + let locale; + + /** Rasterise at twice the CSS size to keep small digits sharp. */ + function imageFor(text) { + if (images.has(text)) return images.get(text); + const canvas = document.createElement('canvas'); + const size = COUNT_MARKER_PX * 2; + const ctx = canvas.getContext('2d'); + const font = 'bold 26px sans-serif'; + ctx.font = font; + canvas.width = Math.max(size, Math.ceil(ctx.measureText(text).width) + 24); + canvas.height = size; + ctx.beginPath(); + ctx.roundRect(2, 2, canvas.width - 4, size - 4, size / 2 - 2); + ctx.fillStyle = '#0e1720'; + ctx.fill(); + ctx.lineWidth = 3; + ctx.strokeStyle = '#75e7ff'; + ctx.stroke(); + ctx.fillStyle = ctx.strokeStyle; + ctx.font = font; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(text, canvas.width / 2, size / 2); + const image = { canvas, key: `cctv-count:${text}` }; + images.set(text, image); + return image; + } + + /** Reuse the first slots for visible cells and hide the unused tail. */ + function update(cells, project) { + const writes = []; + const nextLocale = getLocale(); + let slot = 0; + // Ground-key order keeps the pooled slots stable across pans and health changes. + let visible = cells + .filter((cell) => cell.count > 1) + .sort((a, b) => a.key.localeCompare(b.key)); + const widthFor = (count) => + imageFor(formatCameraCount(count)).canvas.width / 2; + for ( + let pass = 0; + pass < COUNT_MERGE_PASSES && visible.length > 1; + pass++ + ) { + const merged = mergeCountCells( + visible, + project, + widthFor, + COUNT_MARKER_PX, + COUNT_MERGE_DISTANCE_PX, + ); + if (merged.length === visible.length) break; + visible = merged; + } + for (const cell of visible) { + const index = slot++; + const last = groups[index]; + groups[index] = cell; + // Bounds are live for picking even when the drawn label and mean stay put. + if ( + nextLocale === locale && + last?.count === cell.count && + last.lonSum === cell.lonSum && + last.latSum === cell.latSum && + last.heightSum === cell.heightSum + ) + continue; + const id = `cctv-count:${index}`; + const previous = book.item(id); + const pos = cellCenter(cell); + const image = imageFor(formatCameraCount(cell.count)); + const meta = previous?.meta ?? { aggregate: true, slot: index }; + meta.count = cell.count; + writes.push({ + id, + pos, + image, + meta, + size: [image.canvas.width / 2, COUNT_MARKER_PX], + disableDepthTest: Infinity, + show: true, + focus: previous?.focus, + }); + } + locale = nextLocale; + groups.length = slot; + for (let i = slot; i < book.size; i++) { + const item = book.item(`cctv-count:${i}`); + if (item.show) writes.push({ ...item, show: false }); + } + book.putMany(writes); + if (!book.show) book.show = true; + } + /** Resolve only a visible pooled billboard belonging to this layer. */ + function pickedCell(hit) { + if (!book.show || !hit || hit.set !== book.setId) return null; + const item = book.item(hit.id); + return item?.show ? groups[item.meta.slot] : null; + } + return { book, update, pickedCell }; +} diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 233a2b38e7..b20592d396 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -163,9 +163,11 @@ export function createLifecycle({ layerState._records = []; layerState._recordById = new Map(); layerState._viewRecords = []; + layerState._pickerRecords = []; layerState._cameraIndexCache = null; layerState._coverageVisibleIds = new Set(); layerState._neighborCountCache = null; + layerState._coverageCohort = null; layerState._viewUnpublished = false; layerState._viewPose = null; layerState._viewMotionPass = null; @@ -386,6 +388,7 @@ export function createLifecycle({ parts.rendering.refreshHorizonCulling(); const input = inputFor(layerState._viewer); + layerState._clickSubscription?.(); const unsubscribeClick = parts.selection.bindCctvWorldClickGesture( input, (event) => { @@ -536,6 +539,7 @@ export function createLifecycle({ parts.rendering.hideCctvVisuals(); // Nothing is in view while the layer is off. layerState._viewRecords = []; + layerState._pickerRecords = []; layerState._cameraIndexCache = null; parts.presentation.notifyListeners(); }, diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index eaa9a888fc..8e69d9e5e8 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,6 +1,7 @@ import { isFollowing } from '../../data/followed.js'; -import { CCTV_FOCUS_RESULT } from './policy.js'; -import { cameraOf } from '../../render/rendererOf.js'; +import { cellBounds } from '../../data/cctvCellCounts.js'; +import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js'; +import { cameraOf, canvasOf } from '../../render/rendererOf.js'; export function createNavigation({ state: layerState, @@ -104,6 +105,27 @@ export function createNavigation({ return CCTV_FOCUS_RESULT.FOCUSED; } + /** Frame a group's padded bounds from above, including coincident mounts. */ + function zoomToCell(cell) { + const viewer = layerState._viewer; + const camera = cameraOf(viewer); + const pose = camera.pose(); + const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2); + const canvas = canvasOf(viewer); + const height = canvas?.clientHeight || canvas?.height || 1; + const halfFov = Math.atan(tanHalfY * Math.min(1, pose.aspectRatio || 1)); + const bounds = cellBounds(cell); + // A tight group lands comfortably inside the individual-icon level. + const closeRange = + (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); + const range = Math.max(closeRange, bounds.radius / Math.sin(halfFov)); + camera.flyToBounds(bounds, { + offset: { heading: 0, pitch: -Math.PI / 2, range }, + durationS: 1.2, + easing: 'cubicInOut', + }); + } + function focusCamera(cameraId, duration = 2.2) { return focusCctvRecord( layerState._viewer, @@ -179,6 +201,7 @@ export function createNavigation({ openingCameraId, reopenNearestCamera, focusCctvRecord, + zoomToCell, focusCamera, maybeAutoHop, cctvCycleIndex, diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index ee7e1baf44..e728d5707d 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -71,6 +71,15 @@ export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; +// Diameter of a grouped camera marker in CSS pixels. +export const COUNT_MARKER_PX = 34; + +// Separation of two circular counts, including a four-pixel gap between rings. +export const COUNT_MERGE_DISTANCE_PX = COUNT_MARKER_PX + 4; + +// Recheck moved centres and wider labels while bounding work on motion ticks. +export const COUNT_MERGE_PASSES = 3; + // Icons this far past the screen edge (fraction of its size) still show, so // a pan does not reveal empty ground before the next view pass. diff --git a/src/layers/cctv/presentation.js b/src/layers/cctv/presentation.js index f23c007334..ed8a715ebd 100644 --- a/src/layers/cctv/presentation.js +++ b/src/layers/cctv/presentation.js @@ -319,7 +319,7 @@ export function createPresentation({ */ function cameraIndex() { - const view = layerState._viewRecords; + const view = layerState._pickerRecords; const active = parts.selection.getActiveRecord(); const cached = layerState._cameraIndexCache; if (cached?.view === view && cached.active === active) return cached.list; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index b0e964c1be..7dc1c2f956 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -1,3 +1,5 @@ +import { createCountMarkers } from './countMarkers.js'; +import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js'; import { isHeadingEstimated } from './headingConfidence.js'; import { ACTIVE_CAMERA_COLOR, @@ -139,6 +141,14 @@ export function createRendering({ // with its first camera. set.setColumns?.({ ids: [] }); layerState._icons = createIconBook(set); + layerState._counts = createCountMarkers( + drawOf(viewer).icons({ + id: `cctv:${iconSets}:counts`, + horizonCull: true, + show: false, + drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0, + }), + ); return set.id; } @@ -146,6 +156,8 @@ export function createRendering({ function destroyCameraIcons() { layerState._icons?.dispose(); layerState._icons = null; + layerState._counts?.book.dispose(); + layerState._counts = null; } /** The icon item a camera record draws, idle and shown, at its position. */ @@ -223,7 +235,7 @@ export function createRendering({ /** * Focus modulation rides the layer's existing animation loop; no additional - * scene listener is installed. Only camera-icon alpha changes here — coverage + * scene listener is installed. Camera and count icons share the fade. Coverage * geometry and monitor-plane styling retain their established cadence. */ @@ -276,11 +288,10 @@ export function createRendering({ let writes = 0; let transitioning = false; let activeCount = 0; - for (const record of records || []) { - const id = record.camera?.id; - const item = icons?.item(id); - if (!item) continue; - const position = record.position; + /** Advance one icon or count billboard on the shared focus clock. */ + function apply(book, id, position) { + const item = book?.item(id); + if (!item) return; const scale = item.scale ?? 1; // CCTV never publishes a tracked focus target, so every icon is ambient. const focus = advanceSpriteFocus(item.meta, { @@ -299,34 +310,23 @@ export function createRendering({ if (focus.active) activeCount += 1; // Order-independent narrow amendment to always-visible icons: CCTV // contacts retain a non-zero floor while yielding near the tracked target. - if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) { - icons.setFocus(id, focus.factor); + if (focusAlphaNeedsWrite(book.focus(id), focus.factor, params)) { + book.setFocus(id, focus.factor); writes += 1; } } + for (const record of records || []) + apply(icons, record.camera?.id, record.position); + const counts = layerState._counts?.book; + for (const id of counts?.ids() ?? []) + apply(counts, id, counts.item(id).pos); return { writes, transitioning, activeCount, ran: true }; } /** - * Updates visual styles (colors, widths, visibility) for all camera icons, - * coverage polylines, viewshed volumes, and projection entities based on which - * camera is active, whether the layer is enabled, and the current - * coverage-mode/projection toggle states. - */ - /** - * Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the - * icon shader does on the GPU. With the globe hidden (Google-3D - * regime) nothing writes far-side depth and the icons are always-on-top, so - * the shown set (cards, geometry, the picker) must not include London's - * cluster from a US viewpoint. - * - * The same pass thins the view so a large catalog stays readable and cheap: - * icons well off screen hide, and each camera competes for a world-anchored - * cell sized to VIEW_CELL_PX at its distance (healthiest first, then a stable - * id order). The active camera shows whenever it is above the horizon - * and near the screen, even in a crowded cell. The shown records become - * `_viewRecords`, the working set for geometry, cards and the camera picker; - * the array keeps its identity while the shown set is unchanged. + * Group horizon-visible mounts by ground cell. Every cell with a member + * near the screen contributes a representative to the picker. Singletons + * and the active camera also enter the icon, geometry and card working set. * * Runs on camera settle, throttled during motion, on resize, enable and * activation changes — never per frame. @@ -365,7 +365,9 @@ export function createRendering({ const project = screenProjector(pose, width, height); const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1); const shown = []; + const picker = []; const cells = new Map(); + const visibleCells = []; for (const record of layerState._records) { const position = record.position; if (!position) continue; @@ -381,12 +383,12 @@ export function createRendering({ ) continue; const screen = project(position); - if ( - !screen || - !(screen.x >= minX && screen.x <= maxX) || - !(screen.y >= minY && screen.y <= maxY) - ) - continue; + const nearScreen = + screen && + screen.x >= minX && + screen.x <= maxX && + screen.y >= minY && + screen.y <= maxY; const dx = position.x - viewer.x; const dy = position.y - viewer.y; const dz = position.z - viewer.z; @@ -395,21 +397,53 @@ export function createRendering({ metresPerPixelPerMetre * Math.sqrt(dx * dx + dy * dy + dz * dz); if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) { - record.viewPass = pass; + if (!nearScreen) continue; + record.viewPass = record.pickerPass = pass; shown.push(record); + picker.push(record); continue; } const key = worldCellKey(record, cellM); + let cell = cells.get(key); + if (!cell) { + cell = createCameraCell(key); + cells.set(key, cell); + } + addCellCamera(cell, record.camera); + record.viewCell = cell; + if (!nearScreen) continue; + // The picker ranks only candidates that were in its padded viewport. + if (!cell.winner) visibleCells.push(cell); const rank = viewRank(record); - const holder = cells.get(key); - if (!holder || rank < holder.rank) cells.set(key, { record, rank }); + if (rank < cell.rank) { + cell.winner = record; + cell.rank = rank; + } } - for (const { record } of cells.values()) { - record.viewPass = pass; - shown.push(record); + for (const cell of visibleCells) { + const record = cell.winner; + picker.push(record); + record.pickerPass = pass; + if (cell.count === 1) { + record.viewPass = pass; + shown.push(record); + } } + layerState._counts?.update(visibleCells, project); const writes = []; + let coverageChanged = false; + let cardsChanged = false; for (const record of layerState._records) { + const cell = record.viewCell; + record.viewCell = null; + const grouped = Boolean(cell?.winner && cell.count > 1); + if (grouped !== !!record.viewGrouped) { + const id = record.camera.id; + coverageChanged ||= layerState._coverageCohort?.has(id); + cardsChanged ||= + layerState._cardIds?.has(id) || layerState._hoverCardId === id; + } + record.viewGrouped = grouped; const item = patchedCameraIcon(record.camera.id, { show: record.viewPass === pass, }); @@ -421,7 +455,14 @@ export function createRendering({ previous.length !== shown.length || previous.some((record) => record.viewPass !== pass); if (changed) layerState._viewRecords = shown; - return changed; + const oldPicker = layerState._pickerRecords ?? []; + const pickerChanged = + picker.length !== oldPicker.length || + oldPicker.some((record) => record.pickerPass !== pass); + if (pickerChanged) layerState._pickerRecords = picker; + if (coverageChanged) refreshCoverageStyles(); + if (cardsChanged) parts.cards.pushAmbientCardEntries(); + return changed || pickerChanged; } /** @@ -526,6 +567,7 @@ export function createRendering({ ); parts.projection.clearProjectionOverlay(); if (layerState._icons) layerState._icons.show = false; + if (layerState._counts) layerState._counts.book.show = false; parts.projection.pauseInactiveProjectionFeeds(null); } @@ -535,8 +577,12 @@ export function createRendering({ const activeRecord = parts.selection.getActiveRecord(); parts.geometry.ensureActiveCoverageEntities(activeRecord); const activeId = activeRecord?.camera.id || null; - const coverageVisible = - parts.geometry.buildCoverageVisibleSet(activeRecord); + const cohort = parts.geometry.buildCoverageVisibleSet(activeRecord); + layerState._coverageCohort = cohort; + const coverageVisible = new Set(); + for (const id of cohort) { + if (!layerState._recordById.get(id)?.viewGrouped) coverageVisible.add(id); + } // Drawn coverage needs geometry too (geometryQueue's working set). layerState._coverageVisibleIds = coverageVisible; const coverageOn = layerState._coverageMode !== 'off'; diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 00bdb33397..8092ec0557 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -128,15 +128,21 @@ test('the icons go with the viewer that drew them, whichever tears down', () => }); try { const old = createCameraIcons(first); + const oldCounts = state._counts.book.setId; state._viewer = second; const current = createCameraIcons(second); assert.notEqual(old, current); assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go'); assert.equal(two.draw.sets.get(current).disposed, false); + assert.equal(one.draw.sets.get(oldCounts).disposed, true); + const counts = two.draw.set(state._counts.book.setId); + assert.equal(counts.spec.horizonCull, true); destroyCameraIcons(); assert.equal(two.draw.sets.get(current).disposed, true); assert.equal(state._icons, null); + assert.equal(counts.disposed, true); + assert.equal(state._counts, null); } finally { one.unbind(); two.unbind(); diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 5676c045bc..a1f9683847 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -41,6 +41,12 @@ export function createSelection({ function bindCctvWorldClickGesture(input, onClick) { return input.onClick((event) => { if (!isTrackingClickGesture(event.gesture)) return; + const cell = + layerState._enabled && layerState._counts?.pickedCell(event.drawHit); + if (cell) { + parts.navigation.zoomToCell(cell); + return; + } onClick(event); }); } @@ -139,11 +145,11 @@ export function createSelection({ // is looking at ever asks. void parts.ground.resolveFootprintGround(record); record.activationDone = true; - parts.rendering.refreshCoverageStyles(); // The active camera's icon always shows; the previously active one // competes for its cell again. Its coverage neighbours join the working // set and are queued for grounding. parts.rendering.refreshHorizonCulling(); + parts.rendering.refreshCoverageStyles(); parts.geometryQueue.enqueueViewGeometry(); // The newly active camera leaves the ambient ring (its monitor plane takes // over); the freed slot re-fills on this same pass. diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 92ee536706..34d18271da 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -1,6 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { createNavigation } from './navigation.js'; import { createSelection } from './selection.js'; function makeSelection(sourceKind) { @@ -52,3 +54,44 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry assert.equal(fixture.state._activeCameraReselection, 1); assert.equal(fixture.notifications(), 1); }); + +test('a count click preserves the provisional opening pick until the view settles', () => { + const viewer = {}; + const flights = []; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy: Math.PI / 3, aspectRatio: 1 }), + flyToBounds: (bounds) => flights.push(bounds), + }, + canvas: { height: 600 }, + }); + try { + const cell = { west: 1, east: 2, south: 0, north: 0, low: 0, high: 0 }; + const state = { + _enabled: true, + _viewer: viewer, + _openingCameraProvisional: true, + _activeCameraId: 'opening', + _counts: { pickedCell: () => cell }, + }; + const parts = {}; + parts.navigation = createNavigation({ state, parts }); + const selection = createSelection({ + state, + parts, + services: { activation: {}, picking: {} }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => { + assert.fail('a count click reached activation or deselection'); + }, + ); + click({ drawHit: {}, gesture: { travelPx: 0, durationMs: 20 } }); + assert.equal(flights.length, 1); + assert.equal(state._activeCameraId, 'opening'); + assert.equal(state._openingCameraProvisional, true); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/state.js b/src/layers/cctv/state.js index d33453873c..a6778de8f3 100644 --- a/src/layers/cctv/state.js +++ b/src/layers/cctv/state.js @@ -15,6 +15,7 @@ export function createState({ services }) { /** The catalog's camera icons: the icon book over their draw set. */ layerState._icons = null; + layerState._counts = null; layerState._records = []; @@ -95,10 +96,13 @@ export function createState({ services }) { // work over these, not the whole catalog. layerState._viewRecords = []; + // Includes a health-ranked representative for each visible group. + layerState._pickerRecords = []; // Coverage ids refreshCoverageStyles last drew: part of the geometry // working set even when their icons are thinned out. + layerState._coverageCohort = null; layerState._coverageVisibleIds = new Set(); // View pass triggers besides camera settle: an interval while the camera diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index 3a024f7767..65afc5cb61 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -1,3 +1,4 @@ +import { createCountMarkers } from './countMarkers.js'; import { createIconBook } from '../../render/motion/iconBook.js'; /** A draw set that draws nothing, for the icon book the tests read. */ @@ -123,12 +124,18 @@ export function createTesting({ state: layerState, services, parts, source }) { layerState._showProjection = !!showProjection; layerState._healthById = healthById; layerState._viewRecords = []; + layerState._pickerRecords = []; layerState._cameraIndexCache = null; layerState._coverageVisibleIds = new Set(); layerState._neighborCountCache = null; + layerState._coverageCohort = null; // A real book (over a set that draws nothing): every record gets its // icon as init adds it. layerState._icons = createIconBook(testIconSet()); + layerState._counts = createCountMarkers({ + ...testIconSet(), + id: 'cctv:test:counts', + }); for (const record of layerState._records) if (record?.camera?.id) parts.rendering.addCameraIcon(record); } @@ -148,6 +155,7 @@ export function createTesting({ state: layerState, services, parts, source }) { for (const runtime of layerState._projectionEntities) if (runtime?.plane) planes[runtime.plane.id] = runtime.plane; return { + counts: layerState._counts?.book, gizmo: layerState._gizmo?.partsForTest() ?? {}, coverage, planes, diff --git a/src/render/cesium/screenModulation.js b/src/render/cesium/screenModulation.js index 45c2c4bffa..53fee1bca5 100644 --- a/src/render/cesium/screenModulation.js +++ b/src/render/cesium/screenModulation.js @@ -485,6 +485,13 @@ export function createCesiumScreenModulation(scene, { frame, onChange }) { ? 'icon' : null; if (!kind || !native.shaderProgram || !native.uniformMap) continue; + // Aggregate billboards occupy their own collection and represent groups. + if ( + kind === 'billboard' && + native.owner.length && + native.owner.get(0).id?.meta?.aggregate === true + ) + continue; const source = native.shaderProgram; // Label backgrounds are non-SDF billboard batches. The version-tested // engine pick association distinguishes them without enumerating diff --git a/src/render/cesium/screenModulation.test.mjs b/src/render/cesium/screenModulation.test.mjs index 62927bbe2d..c88c74b3e2 100644 --- a/src/render/cesium/screenModulation.test.mjs +++ b/src/render/cesium/screenModulation.test.mjs @@ -606,3 +606,19 @@ test('disposal does not overwrite a successor update owner', () => { assert.equal(f.primitives.update, successor); f.primitives.destroy(); }); + +test('aggregate markers keep their native billboard command during a contact sweep', () => { + const owner = new Cesium.BillboardCollection(); + owner.add({ id: { meta: { aggregate: true } } }); + const command = { owner, uniformMap: {}, shaderProgram: {} }; + const f = fixture({ commands: [command] }); + try { + f.part.set(sweep()); + assert.equal(f.draw()[0], command); + assert.equal(f.part.stats.supported, true); + } finally { + f.part.dispose(); + owner.destroy(); + f.primitives.destroy(); + } +}); From 87bff9957b8d05442a24af034e8bff5bd5b3bd50 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:02:07 +0400 Subject: [PATCH 2/9] fix(cctv): draw the count marker's ring cleanly The ring was three texture pixels wide and touched the sprite edge, so at screen size it came out one jagged pixel wide with a clipped top and bottom, and the sharpen pass pushed it towards white with an orange fringe over bright ground. Draw it two screen pixels wide, inset from the sprite edge so its outer edge antialiases, with a dark rim outside it. Labels of up to three digits always stay in a circle; longer ones get a pill with room for its rounded ends. --- src/layers/cctv/countMarkers.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 8ebdba5142..6577c2904a 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -24,15 +24,34 @@ export function createCountMarkers(set) { const canvas = document.createElement('canvas'); const size = COUNT_MARKER_PX * 2; const ctx = canvas.getContext('2d'); - const font = 'bold 26px sans-serif'; + const font = 'bold 24px sans-serif'; ctx.font = font; - canvas.width = Math.max(size, Math.ceil(ctx.measureText(text).width) + 24); + // A two-pixel ring survives the halving to screen size, and the clear + // margin leaves its outer edge room to antialias inside the sprite. + const ring = 4; + const margin = 4; + const inset = margin + ring / 2; + // Up to three digits sit inside the circle; a longer label gets a pill + // with room for its rounded ends. + const textWidth = Math.ceil(ctx.measureText(text).width); + const fitsCircle = textWidth <= size - 2 * (margin + ring) - 4; + canvas.width = fitsCircle ? size : textWidth + 2 * (margin + ring + 12); canvas.height = size; ctx.beginPath(); - ctx.roundRect(2, 2, canvas.width - 4, size - 4, size / 2 - 2); + ctx.roundRect( + inset, + inset, + canvas.width - 2 * inset, + size - 2 * inset, + size / 2 - inset, + ); + // A dark rim outside the ring keeps it off bright ground. + ctx.lineWidth = ring + 4; + ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; + ctx.stroke(); ctx.fillStyle = '#0e1720'; ctx.fill(); - ctx.lineWidth = 3; + ctx.lineWidth = ring; ctx.strokeStyle = '#75e7ff'; ctx.stroke(); ctx.fillStyle = ctx.strokeStyle; From aabfa5e08494a78742e73f281d9dd77e687aec54 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:31:20 +0400 Subject: [PATCH 3/9] fix(cctv): paint count markers on the world overlay canvas The scene renders at CSS resolution and is stretched on a high-density display, so a count marker drawn as a scene sprite looked coarse next to the camera callouts, which the world overlay paints at device density. Paint the markers through the overlay's custom paint lane instead, in the callouts' typeface. Each paint reprojects the group centres; a click is resolved against the rectangles painted in the last frame and still zooms to the group without choosing a camera. A marker that would cover HUD chrome is skipped, as overlay entries are. With no aggregate sprites left, the contact sweep no longer needs to skip them, so that exclusion is removed. --- docs/CURRENT-STATE.md | 3 +- src/data/cctvViewThinning.test.mjs | 341 +++++++++++++++----- src/layers/cctv/countMarkers.js | 287 ++++++++++------ src/layers/cctv/rendering.js | 79 +++-- src/layers/cctv/rendering.test.mjs | 62 +++- src/layers/cctv/selection.js | 3 +- src/layers/cctv/selection.test.mjs | 12 +- src/layers/cctv/testing.js | 14 +- src/overlays/worldOverlay.js | 3 + src/overlays/worldOverlay.test.mjs | 5 + src/render/cesium/screenModulation.js | 7 - src/render/cesium/screenModulation.test.mjs | 16 - 12 files changed, 583 insertions(+), 249 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5d3441608c..f79aa705fd 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,7 +1953,8 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows a cyan count at their centre. +ground cell containing multiple cameras shows a cyan count at their centre, +drawn on the world overlay at the same resolution as camera callouts. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 1820ee8050..ac134670e8 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -10,7 +10,6 @@ import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, - _extractPickedCameraIdForTest, bindCctvWorldClickGesture, applyCctvFocusDeemphasis, reopenNearestCamera, @@ -90,27 +89,113 @@ function viewerAt(heightM, lonDeg = 0, flights = []) { /** The renderers bound for the running test, let go when it ends. */ const bindings = []; -const paintedLabels = new Map(); +let painter; +let paintRequests; +let measured; +let glyphWidth; +let ctx; +const fonts = new EventTarget(); + +function seedCoverage(options) { + _setCctvCoverageStateForTest({ + ...options, + registerPaintLane(_lane, paint) { + painter = paint; + return { + requestPaint() { + paintRequests++; + }, + setActive() {}, + unregister() {}, + }; + }, + }); +} + beforeEach(() => { + paintRequests = 0; + measured = 0; + glyphWidth = 8; globalThis.document = { + fonts, createElement: () => ({ getContext: () => ({ - beginPath() {}, - arc() {}, - roundRect() {}, - measureText: (text) => ({ width: text.length * 15 }), - fill() {}, - stroke() {}, - fillText(text, x, y, maxWidth) { - paintedLabels.set(text, maxWidth ?? Infinity); + measureText(text) { + measured++; + return { width: text.length * glyphWidth }; }, }), }), }; + let savedState; + ctx = { + font: 'initial', + globalAlpha: 1, + fillStyle: 'initial', + strokeStyle: 'initial', + textAlign: 'start', + textBaseline: 'top', + lineWidth: 1, + labels: [], + shapes: [], + save() { + savedState = { ...this }; + }, + restore() { + Object.assign(this, savedState); + }, + beginPath() {}, + fill() {}, + stroke() {}, + roundRect(...args) { + this.shapes.push(args); + }, + fillText(text, x, y) { + this.labels.push({ + text, + x, + y, + alpha: this.globalAlpha, + font: this.font, + }); + }, + }; }); +/** Reproject on each paint in CSS pixels, as the host does. */ +function paint(overrides = {}) { + ctx.labels.length = ctx.shapes.length = 0; + painter({ + ctx, + width: WIDTH, + height: HEIGHT, + dpr: 2, + viewProjectionMatrix: new Float64Array([ + 0, + 0, + 0, + 0, + 2 / (30 * WIDTH), + 0, + 0, + 0, + 0, + 2 / (30 * HEIGHT), + 0, + 0, + 0, + 0, + 0, + 1, + ]), + occluder: { isPointVisible: () => true }, + overlapsHardUi: () => false, + ...overrides, + }); + return ctx.labels; +} + afterEach(() => { - paintedLabels.clear(); delete globalThis.document; for (const unbind of bindings.splice(0)) unbind(); }); @@ -131,36 +216,38 @@ const CLUSTER = [ [0.2, 0], ]; -/** Count billboards the layer currently shows. */ +/** Groups from the latest view pass. */ function markers() { - const book = cctvLayer._cctvDrawnForTest().counts; - return book.show - ? book - .ids() - .map(book.item) - .filter((item) => item.show) - : []; + return cctvLayer._cctvDrawnForTest().counts.markers; } -/** Send a clean count-marker click through the layer's world click handler. */ +/** Click the CSS position of the painted count with a camera underneath it. */ function clickMarker(marker) { - const set = cctvLayer._cctvDrawnForTest().counts.setId; - const hit = { set, id: marker.id, meta: marker.meta }; - assert.equal(_extractPickedCameraIdForTest(hit), null); - const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, () => { - assert.fail('a count click reached activation or empty-click deselection'); + const { x, y } = paint().find((label) => label.text === marker.text); + const hit = { set: _cctvIconsForTest().setId, id: 'cam-0' }; + let fallback; + const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, (event) => { + fallback = event.drawHit; }); - click({ drawHit: hit, gesture: { travelPx: 0, durationMs: 20 } }); + const gesture = { travelPx: 0, durationMs: 20 }; + click({ drawHit: hit, screenPosition: { x, y }, gesture }); + assert.equal(fallback, undefined); + click({ + drawHit: hit, + screenPosition: { x: x + marker.width / 2 + 1, y }, + gesture, + }); + assert.equal(fallback, hit); } test('a crowded cell shows its count and a singleton keeps its icon', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); assert.equal(refreshHorizonCulling(), true); assert.deepEqual(shownIds(records), ['cam-3']); assert.deepEqual(_viewRecordIdsForTest(), ['cam-3']); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [3], ); assert.deepEqual( @@ -171,7 +258,7 @@ test('a crowded cell shows its count and a singleton keeps its icon', () => { test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, }); @@ -180,7 +267,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => const list = _viewRecordIdsForTest(); // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up). for (const shiftM of [90, 330, 600, 1110]) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, shiftM / 111_320), records, }); @@ -191,7 +278,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => `pan by ${shiftM} m`, ); } - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); @@ -200,7 +287,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => test('a small zoom within one cell size keeps the same winners', () => { const { records } = recordsAt(CLUSTER); const shownAt = (heightM) => { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(heightM), records, }); @@ -217,7 +304,7 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( // Whichever camera the id order would pick, the healthy one must win. let first; for (const id of ['cam-0', 'cam-1']) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, healthById: new Map([[id, { status: 'ok' }]]), @@ -239,14 +326,14 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( test('the active camera always shows, even in a crowded cell', () => { const { records } = recordsAt(CLUSTER.slice(0, 3)); for (const active of records) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, activeCameraId: active.camera.id, }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [2], ); const icons = _cctvIconsForTest(); @@ -264,7 +351,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () => [0.0001, 0], [0.01, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, }); @@ -274,7 +361,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () => test('a disabled layer skips the view pass', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, enabled: false, @@ -285,7 +372,7 @@ test('a disabled layer skips the view pass', () => { test('UI state builds the full camera list only when it is read', () => { const { records } = recordsAt(CLUSTER.slice(0, 2)); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, }); @@ -322,7 +409,7 @@ test('the camera picker lists the view, with the active camera first', () => { [0.01, 0], [0.0002, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, activeCameraId: 'cam-1', @@ -344,10 +431,10 @@ test('panning a cell across the padded screen edge keeps its full count', () => [0.29, 0], ]); for (const lon of [0.015, 0]) { - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000, lon), records }); + seedCoverage({ viewer: viewerAt(20_000, lon), records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [3], ); if (lon === 0) @@ -377,10 +464,10 @@ test('only members on the near side of the horizon count', () => { query: { project: () => ({ x: 400, y: 300 }) }, }), ); - _setCctvCoverageStateForTest({ viewer, records }); + seedCoverage({ viewer, records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [2], ); }); @@ -390,7 +477,7 @@ test('co-located cameras separate below the minimum cell size', () => { [0, 0], [0, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(300), records }); + seedCoverage({ viewer: viewerAt(300), records }); refreshHorizonCulling(); assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']); assert.deepEqual(markers(), []); @@ -404,7 +491,7 @@ test('a count click frames its members and preserves an explicit camera choice', [spread, 0], [0.2, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, 0, flights), records, activeCameraId: 'cam-2', @@ -430,7 +517,7 @@ test('a count click frames its members and preserves an explicit camera choice', ); assert.equal(reopenNearestCamera(), false); assert.equal(cctvLayer.getUIState().activeCameraId, 'cam-2'); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: destination, records, activeCameraId: 'cam-2', @@ -443,11 +530,13 @@ test('a count click frames its members and preserves an explicit camera choice', test('disabling the layer hides its counts', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.equal(markers().length, 1); + const [label] = paint(); cctvLayer.disable(); - assert.deepEqual(markers(), []); + assert.deepEqual(paint(), []); + assert.equal(cctvLayer._cctvDrawnForTest().counts.pickedCell(label), null); }); test('coverage leaves grouped neighbors and returns when their icons separate', () => { @@ -459,7 +548,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', // Lines already materialised at close zoom. for (const record of records) record.coverageEntities = [{ show: true }]; const viewer = viewerAt(20_000); - _setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0' }); + seedCoverage({ viewer, records, activeCameraId: 'cam-0' }); refreshCoverageStyles(); refreshHorizonCulling(); assert.deepEqual( @@ -478,7 +567,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', test('count markers share the camera focus fade and recover on release', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, @@ -499,10 +588,10 @@ test('count markers share the camera focus fade and recover on release', () => { }; tick(0, target); tick(params.attackMs + 1, target); - assert.equal(markers()[0].focus, params.dimFloor); + assert.equal(paint()[0].alpha, params.dimFloor); tick(params.attackMs + 2, null); tick(params.attackMs + params.releaseMs + 3, null); - assert.equal(markers()[0].focus, 1); + assert.equal(paint()[0].alpha, 1); }); test('overlapping cells merge at their weighted centre and keep every camera in the flight bounds', () => { @@ -524,7 +613,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in [0, records], [0.003, [...records].reverse()], ]) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, pan, flights), records: order, activeCameraId: 'cam-7', @@ -534,21 +623,21 @@ test('overlapping cells merge at their weighted centre and keep every camera in const shown = markers(); assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']); assert.equal( - shown.reduce((sum, m) => sum + m.meta.count, 0), + shown.reduce((sum, m) => sum + m.cell.count, 0), 7, ); assert.deepEqual( - shown.map((m) => m.meta.count).sort((a, b) => a - b), + shown.map((m) => m.cell.count).sort((a, b) => a - b), [2, 5], ); - const merged = shown.find((m) => m.meta.count === 5); + const merged = shown.find((m) => m.cell.count === 5); assert.ok( Cesium.Cartesian3.distance( merged.pos, Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), ) < 0.01, ); - const positions = shown.map((m) => [m.id, m.pos]); + const positions = shown.map((m) => [m.cell.key, m.pos]); if (previous) assert.deepEqual(positions, previous); previous = positions; clickMarker(merged); @@ -569,7 +658,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in } }); -test('long localized labels use their measured width on the canvas and billboard', () => { +test('the overlay paints short counts as circles and long localized labels as pills', () => { const locale = getLocale(); try { setLocale('ru'); @@ -578,25 +667,38 @@ test('long localized labels use their measured width on the canvas and billboard [0.06, 0], [0.06, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - const short = markers().find((m) => m.meta.count === 2); - const long = markers().find((m) => m.meta.count === 1300); - assert.equal(short.image.canvas.width, short.image.canvas.height); - assert.ok(long.image.canvas.width > long.image.canvas.height); - assert.equal(long.size[1], short.size[1]); - assert.equal( - long.size[0] / long.size[1], - long.image.canvas.width / long.image.canvas.height, - ); + const short = markers().find((m) => m.cell.count === 2); + const long = markers().find((m) => m.cell.count === 1300); + const measurements = measured; + assert.equal(measurements, 1); + const labels = paint(); + refreshHorizonCulling(); + assert.equal(measured, measurements); const text = new Intl.NumberFormat('ru', { notation: 'compact' }).format( 1300, ); - assert.ok(paintedLabels.get(text) >= text.length * 15); - assert.ok( - long.image.canvas.width > text.length * 15, - 'the digits have padding', - ); + assert.equal(labels.length, 2); + assert.equal(ctx.shapes.length, labels.length); + const [sx, sy, sw, sh] = + ctx.shapes[labels.findIndex((l) => l.text === '2')]; + const [lx, ly, lw, lh] = + ctx.shapes[labels.findIndex((l) => l.text === text)]; + assert.equal(sw, sh); + assert.ok(lw > text.length * glyphWidth); + assert.equal(lh, sh); + // The four-pixel outer stroke extends two pixels on each side of the path. + assert.equal(sw + 4, short.width); + assert.equal(lw + 4, long.width); + assert.equal(sy + sh / 2, HEIGHT / 2); + assert.equal(ly + lh / 2, HEIGHT / 2); + assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); + assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); + assert.match(labels[0].font, /JetBrains Mono/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); + assert.equal(ctx.lineWidth, 1); } finally { setLocale(locale); } @@ -613,9 +715,9 @@ test('a wider localized pill merges a horizontal neighbor beyond the circle diam [0.008, 0], [0.008, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - return markers().map((m) => m.meta.count); + return markers().map((m) => m.cell.count); }; assert.deepEqual(at(2), [2, 2]); assert.deepEqual(at(1300), [1302]); @@ -635,10 +737,95 @@ test('a merged centre can pick up a third count marker', () => { [0, -0.0126], [0, -0.0126], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((m) => m.meta.count), + markers().map((m) => m.cell.count), [6], ); }); + +test('each paint follows the overlay projection, horizon and hard HUD exclusions', () => { + const { records } = recordsAt([ + [-0.001, 0], + [-0.001, 0], + [0.001, 0], + [0.001, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const counts = cctvLayer._cctvDrawnForTest().counts; + assert.ok(paintRequests > 0); + const requests = paintRequests; + const widths = measured; + assert.deepEqual( + paint().map(({ text, x, y }) => [text, x, y]), + [['4', 400, 300]], + ); + const first = { x: 400, y: 300 }; + assert.equal(counts.pickedCell(first).count, 4); + const at = (x) => { + const matrix = new Float64Array(16); + matrix[12] = (2 * x) / WIDTH - 1; + matrix[15] = 1; + return { viewProjectionMatrix: matrix }; + }; + assert.equal(paint(at(100))[0].x, 100); + assert.equal(counts.pickedCell(first), null); + assert.deepEqual(paint(at(-100)), []); + assert.deepEqual(paint({ occluder: { isPointVisible: () => false } }), []); + assert.deepEqual(paint({ overlapsHardUi: () => true }), []); + assert.equal(counts.pickedCell(first), null); + refreshHorizonCulling(); + assert.equal(measured, widths); + assert.equal(paintRequests, requests); +}); + +test('loaded font metrics remerge visible cells without waiting for a move', () => { + const locale = getLocale(); + try { + setLocale('ru'); + glyphWidth = 3; + const { records } = recordsAt([ + ...Array(1300).fill([-0.009, 0]), + [0.009, 0], + [0.009, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.equal(markers().length, 2); + glyphWidth = 12; + fonts.dispatchEvent(new Event('loadingdone')); + assert.deepEqual( + markers().map((m) => m.cell.count), + [1302], + ); + assert.equal(paint().length, 1); + } finally { + setLocale(locale); + } +}); + +test('hits follow paint order and keep the last painted group until the overlay clears', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + [0.05, 0], + [0.05, 0], + [0.05, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const point = { x: WIDTH / 2, y: HEIGHT / 2 }; + const matrix = new Float64Array(16); + matrix[15] = 1; + const labels = paint({ viewProjectionMatrix: matrix }); + const counts = cctvLayer._cctvDrawnForTest().counts; + assert.equal(labels.length, 2); + const top = counts.pickedCell(point); + assert.equal(String(top.count), labels.at(-1).text); + counts.update([], () => null); + assert.equal(counts.pickedCell(point), top); + assert.deepEqual(paint(), []); + assert.equal(counts.pickedCell(point), null); +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 6577c2904a..740519b132 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -1,80 +1,62 @@ -import { createIconBook } from '../../render/motion/iconBook.js'; import { cellCenter, formatCameraCount, mergeCountCells, } from '../../data/cctvCellCounts.js'; -import { getLocale } from '../../i18n/index.js'; +import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { COUNT_MARKER_PX, COUNT_MERGE_DISTANCE_PX, COUNT_MERGE_PASSES, } from './policy.js'; -/** A pool of static count billboards sharing one canvas for each label. */ -export function createCountMarkers(set) { - const book = createIconBook(set); - const images = new Map(); - const groups = []; - let locale; +const FONT = WORLD_OVERLAY_STYLE.fontTitle; +const RING = '#75e7ff'; - /** Rasterise at twice the CSS size to keep small digits sharp. */ - function imageFor(text) { - if (images.has(text)) return images.get(text); - const canvas = document.createElement('canvas'); - const size = COUNT_MARKER_PX * 2; - const ctx = canvas.getContext('2d'); - const font = 'bold 24px sans-serif'; - ctx.font = font; - // A two-pixel ring survives the halving to screen size, and the clear - // margin leaves its outer edge room to antialias inside the sprite. - const ring = 4; - const margin = 4; - const inset = margin + ring / 2; - // Up to three digits sit inside the circle; a longer label gets a pill - // with room for its rounded ends. - const textWidth = Math.ceil(ctx.measureText(text).width); - const fitsCircle = textWidth <= size - 2 * (margin + ring) - 4; - canvas.width = fitsCircle ? size : textWidth + 2 * (margin + ring + 12); - canvas.height = size; - ctx.beginPath(); - ctx.roundRect( - inset, - inset, - canvas.width - 2 * inset, - size - 2 * inset, - size / 2 - inset, - ); - // A dark rim outside the ring keeps it off bright ground. - ctx.lineWidth = ring + 4; - ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; - ctx.stroke(); - ctx.fillStyle = '#0e1720'; - ctx.fill(); - ctx.lineWidth = ring; - ctx.strokeStyle = '#75e7ff'; - ctx.stroke(); - ctx.fillStyle = ctx.strokeStyle; - ctx.font = font; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - ctx.fillText(text, canvas.width / 2, size / 2); - const image = { canvas, key: `cctv-count:${text}` }; - images.set(text, image); - return image; +/** Merged camera groups and their last painted hit rectangles in CSS pixels. */ +export function createCountMarkers(registerPaintLane, id, refreshView) { + const markers = []; + const hits = []; + const widths = new Map(); + const fonts = globalThis.document?.fonts; + let measureCtx; + let hitCount = 0; + const lane = registerPaintLane?.('ambient-label', paint, { + id, + active: false, + target: 'shared', + }); + fonts?.addEventListener?.('loadingdone', fontsLoaded); + + /** Font changes can widen a pill enough to merge it with its neighbor. */ + function fontsLoaded() { + widths.clear(); + if (!markers.length) return; + refreshView(); + lane?.requestPaint(); } - /** Reuse the first slots for visible cells and hide the unused tail. */ + /** Short labels fit the circle. A longer label leaves room for rounded ends. */ + function widthForText(text) { + if (text.length <= 3) return COUNT_MARKER_PX; + let width = widths.get(text); + if (width === undefined) { + measureCtx ??= document.createElement('canvas').getContext('2d'); + measureCtx.font = FONT; + width = Math.max( + COUNT_MARKER_PX + 1, + Math.ceil(measureCtx.measureText(text).width) + 20, + ); + widths.set(text, width); + } + return width; + } + + /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ function update(cells, project) { - const writes = []; - const nextLocale = getLocale(); - let slot = 0; - // Ground-key order keeps the pooled slots stable across pans and health changes. let visible = cells .filter((cell) => cell.count > 1) .sort((a, b) => a.key.localeCompare(b.key)); - const widthFor = (count) => - imageFor(formatCameraCount(count)).canvas.width / 2; for ( let pass = 0; pass < COUNT_MERGE_PASSES && visible.length > 1; @@ -83,57 +65,160 @@ export function createCountMarkers(set) { const merged = mergeCountCells( visible, project, - widthFor, + (count) => widthForText(formatCameraCount(count)), COUNT_MARKER_PX, COUNT_MERGE_DISTANCE_PX, ); if (merged.length === visible.length) break; visible = merged; } - for (const cell of visible) { - const index = slot++; - const last = groups[index]; - groups[index] = cell; - // Bounds are live for picking even when the drawn label and mean stay put. + let changed = visible.length !== markers.length; + for (let i = 0; i < visible.length; i++) { + const cell = visible[i]; + const marker = markers[i] ?? (markers[i] = { focus: 1 }); + const last = marker.cell; + const text = formatCameraCount(cell.count); + const width = widthForText(text); if ( - nextLocale === locale && - last?.count === cell.count && - last.lonSum === cell.lonSum && - last.latSum === cell.latSum && - last.heightSum === cell.heightSum + !last || + last.count !== cell.count || + last.latSum !== cell.latSum || + last.lonSum !== cell.lonSum || + last.heightSum !== cell.heightSum + ) { + marker.pos = cellCenter(cell); + changed = true; + } else if ( + last.west !== cell.west || + last.east !== cell.east || + last.south !== cell.south || + last.north !== cell.north || + last.low !== cell.low || + last.high !== cell.high + ) { + changed = true; + } + changed ||= text !== marker.text || width !== marker.width; + marker.cell = cell; + marker.text = text; + marker.width = width; + // Paint never grows the hit buffer, even when a pan reveals every group. + hits[i] ??= {}; + } + markers.length = visible.length; + // Keep the last frame pickable until the host clears its pixels. + lane?.setActive(markers.length > 0 || hitCount > 0); + if (changed) lane?.requestPaint(); + } + + /** Draw at device density using the host's CSS-pixel transform and projection. */ + function paint(frame) { + if (!markers.length) { + // Deactivating invalidates the host, so finish the shared frame first. + if (hitCount) queueMicrotask(deactivateIfEmpty); + hitCount = 0; + return; + } + hitCount = 0; + const { ctx, occluder, viewProjectionMatrix: m } = frame; + const height = COUNT_MARKER_PX; + ctx.save(); + try { + ctx.font = FONT; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + for (let i = 0; i < markers.length; i++) { + const marker = markers[i]; + const { x: px, y: py, z: pz } = marker.pos; + const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; + if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) + continue; + const x = + (0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) * + frame.width; + const y = + (0.5 - (0.5 * (m[1] * px + m[5] * py + m[9] * pz + m[13])) / w) * + frame.height; + const rect = hits[hitCount]; + rect.x = x - marker.width / 2; + rect.y = y - height / 2; + rect.w = marker.width; + rect.h = height; + if ( + rect.x >= frame.width || + rect.y >= frame.height || + rect.x + rect.w <= 0 || + rect.y + rect.h <= 0 || + frame.overlapsHardUi(rect) + ) + continue; + ctx.globalAlpha = marker.focus; + ctx.beginPath(); + ctx.roundRect( + rect.x + 2, + rect.y + 2, + rect.w - 4, + height - 4, + height / 2 - 2, + ); + ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; + ctx.lineWidth = 4; + ctx.stroke(); + ctx.fillStyle = '#0e1720'; + ctx.fill(); + ctx.strokeStyle = RING; + ctx.lineWidth = 2; + ctx.stroke(); + ctx.fillStyle = RING; + ctx.fillText(marker.text, x, y); + rect.cell = marker.cell; + hitCount++; + } + } finally { + ctx.restore(); + } + } + + /** Resolve the topmost group actually painted at this screen position. */ + function pickedCell(point) { + if (!point) return null; + for (let i = hitCount - 1; i >= 0; i--) { + const rect = hits[i]; + if ( + point.x >= rect.x && + point.x <= rect.x + rect.w && + point.y >= rect.y && + point.y <= rect.y + rect.h ) - continue; - const id = `cctv-count:${index}`; - const previous = book.item(id); - const pos = cellCenter(cell); - const image = imageFor(formatCameraCount(cell.count)); - const meta = previous?.meta ?? { aggregate: true, slot: index }; - meta.count = cell.count; - writes.push({ - id, - pos, - image, - meta, - size: [image.canvas.width / 2, COUNT_MARKER_PX], - disableDepthTest: Infinity, - show: true, - focus: previous?.focus, - }); + return rect.cell; } - locale = nextLocale; - groups.length = slot; - for (let i = slot; i < book.size; i++) { - const item = book.item(`cctv-count:${i}`); - if (item.show) writes.push({ ...item, show: false }); - } - book.putMany(writes); - if (!book.show) book.show = true; + return null; } - /** Resolve only a visible pooled billboard belonging to this layer. */ - function pickedCell(hit) { - if (!book.show || !hit || hit.set !== book.setId) return null; - const item = book.item(hit.id); - return item?.show ? groups[item.meta.slot] : null; + + /** A new group may already have arrived since the empty frame. */ + function deactivateIfEmpty() { + if (!markers.length) lane?.setActive(false); } - return { book, update, pickedCell }; + + /** Release the visible groups and clear their hit targets immediately. */ + function hide() { + markers.length = hits.length = hitCount = 0; + lane?.setActive(false); + } + + /** Unhook this viewer's painter and its font listener. */ + function dispose() { + markers.length = hits.length = hitCount = 0; + fonts?.removeEventListener?.('loadingdone', fontsLoaded); + lane?.unregister(); + } + + return { + markers, + update, + pickedCell, + hide, + dispose, + requestPaint: () => lane?.requestPaint(), + }; } diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 7dc1c2f956..d041a1c681 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -13,6 +13,7 @@ import { IDLE_COVERAGE_EDGE_MUTED, ACTIVE_COVERAGE_EDGE_DEPTHFAIL, IDLE_COVERAGE_COLOR, + COUNT_MARKER_PX, VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, @@ -142,12 +143,9 @@ export function createRendering({ set.setColumns?.({ ids: [] }); layerState._icons = createIconBook(set); layerState._counts = createCountMarkers( - drawOf(viewer).icons({ - id: `cctv:${iconSets}:counts`, - horizonCull: true, - show: false, - drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0, - }), + services.overlays?.registerWorldOverlayPaintLane, + `cctv:${iconSets}:counts`, + refreshHorizonCulling, ); return set.id; } @@ -156,7 +154,7 @@ export function createRendering({ function destroyCameraIcons() { layerState._icons?.dispose(); layerState._icons = null; - layerState._counts?.book.dispose(); + layerState._counts?.dispose(); layerState._counts = null; } @@ -288,38 +286,52 @@ export function createRendering({ let writes = 0; let transitioning = false; let activeCount = 0; - /** Advance one icon or count billboard on the shared focus clock. */ - function apply(book, id, position) { - const item = book?.item(id); - if (!item) return; - const scale = item.scale ?? 1; - // CCTV never publishes a tracked focus target, so every icon is ambient. - const focus = advanceSpriteFocus(item.meta, { - // Keep hidden icons in the state/release pass so the active count cannot - // drop while a stale dim alpha remains waiting to reappear. - screenPosition: - item.show === false || !position ? null : screenPositionFor(position), + /** A changed focus factor for a camera icon or a painted count. */ + function changedFocus(owner, position, shown, width, height, current) { + const focus = advanceSpriteFocus(owner, { + screenPosition: shown && position ? screenPositionFor(position) : null, cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, target, params, - spriteHalfWidthPx: item.size[0] * scale * 0.5, - spriteHalfHeightPx: item.size[1] * scale * 0.5, + spriteHalfWidthPx: width / 2, + spriteHalfHeightPx: height / 2, }); transitioning ||= focus.transitioning; - if (focus.active) activeCount += 1; - // Order-independent narrow amendment to always-visible icons: CCTV - // contacts retain a non-zero floor while yielding near the tracked target. - if (focusAlphaNeedsWrite(book.focus(id), focus.factor, params)) { - book.setFocus(id, focus.factor); - writes += 1; - } + if (focus.active) activeCount++; + if (!focusAlphaNeedsWrite(current, focus.factor, params)) return null; + writes++; + return focus.factor; } - for (const record of records || []) - apply(icons, record.camera?.id, record.position); - const counts = layerState._counts?.book; - for (const id of counts?.ids() ?? []) - apply(counts, id, counts.item(id).pos); + for (const record of records || []) { + const id = record.camera?.id; + const item = icons?.item(id); + if (!item) continue; + const scale = item.scale ?? 1; + const factor = changedFocus( + item.meta, + record.position, + item.show !== false, + item.size[0] * scale, + item.size[1] * scale, + icons.focus(id), + ); + if (factor !== null) icons.setFocus(id, factor); + } + const counts = layerState._counts; + const iconWrites = writes; + for (const marker of counts?.markers ?? []) { + const factor = changedFocus( + marker, + marker.pos, + true, + marker.width, + COUNT_MARKER_PX, + marker.focus, + ); + if (factor !== null) marker.focus = factor; + } + if (writes > iconWrites) counts.requestPaint(); return { writes, transitioning, activeCount, ran: true }; } @@ -567,7 +579,7 @@ export function createRendering({ ); parts.projection.clearProjectionOverlay(); if (layerState._icons) layerState._icons.show = false; - if (layerState._counts) layerState._counts.book.show = false; + layerState._counts?.hide(); parts.projection.pauseInactiveProjectionFeeds(null); } @@ -911,6 +923,7 @@ export function createRendering({ * @returns {string|null} */ function pickCameraIdAt(position) { + if (layerState._counts?.pickedCell(position)) return null; let hit = null; try { hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null; diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 8092ec0557..aa53c5ab0c 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -120,28 +120,46 @@ test('the icons go with the viewer that drew them, whichever tears down', () => const one = bindFakeDraw(first); const two = bindFakeDraw(second); const state = { _viewer: first }; + const lanes = []; + const overlays = { + registerWorldOverlayPaintLane(name, paint, options) { + const lane = { + name, + paint, + options, + unregister() { + this.disposed = true; + }, + }; + lanes.push(lane); + return lane; + }, + }; const { createCameraIcons, destroyCameraIcons } = createRendering({ state, - services: { focus: {} }, + services: { focus: {}, overlays }, parts: {}, source: {}, }); try { const old = createCameraIcons(first); - const oldCounts = state._counts.book.setId; + assert.equal(one.draw.sets.size, 1); + assert.equal(lanes[0].name, 'ambient-label'); + assert.equal(lanes[0].options.target, 'shared'); + assert.equal(lanes[0].options.active, false); state._viewer = second; const current = createCameraIcons(second); assert.notEqual(old, current); assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go'); assert.equal(two.draw.sets.get(current).disposed, false); - assert.equal(one.draw.sets.get(oldCounts).disposed, true); - const counts = two.draw.set(state._counts.book.setId); - assert.equal(counts.spec.horizonCull, true); + assert.equal(lanes[0].disposed, true); + lanes[0].paint({}); destroyCameraIcons(); assert.equal(two.draw.sets.get(current).disposed, true); assert.equal(state._icons, null); - assert.equal(counts.disposed, true); + assert.equal(lanes[1].disposed, true); + lanes[1].paint({}); assert.equal(state._counts, null); } finally { one.unbind(); @@ -382,3 +400,35 @@ test('a pose with no perspective field of view is projected by the renderer', () unbind(); } }); + +test('hover picks the underlying camera only outside a painted count', () => { + const viewer = {}; + const icon = { set: 'icons', id: 'camera' }; + let picks = 0; + const unbind = bindRenderer(viewer, { + query: { + pick() { + picks++; + return icon; + }, + }, + }); + try { + const state = { + _viewer: viewer, + _counts: { pickedCell: ({ x }) => (x <= 17 ? {} : null) }, + _icons: { setId: icon.set, has: () => true }, + _recordById: new Map([[icon.id, {}]]), + }; + const rendering = createRendering({ + state, + services: { focus: {} }, + parts: {}, + }); + assert.equal(rendering.pickCameraIdAt({ x: 17, y: 0 }), null); + assert.equal(picks, 0); + assert.equal(rendering.pickCameraIdAt({ x: 18, y: 0 }), icon.id); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index a1f9683847..6948b2a8a2 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -42,7 +42,8 @@ export function createSelection({ return input.onClick((event) => { if (!isTrackingClickGesture(event.gesture)) return; const cell = - layerState._enabled && layerState._counts?.pickedCell(event.drawHit); + layerState._enabled && + layerState._counts?.pickedCell(event.screenPosition); if (cell) { parts.navigation.zoomToCell(cell); return; diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 34d18271da..f03ded5ceb 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -72,7 +72,9 @@ test('a count click preserves the provisional opening pick until the view settle _viewer: viewer, _openingCameraProvisional: true, _activeCameraId: 'opening', - _counts: { pickedCell: () => cell }, + _counts: { + pickedCell: (point) => (point?.x === 14 && point.y === 26 ? cell : null), + }, }; const parts = {}; parts.navigation = createNavigation({ state, parts }); @@ -87,7 +89,13 @@ test('a count click preserves the provisional opening pick until the view settle assert.fail('a count click reached activation or deselection'); }, ); - click({ drawHit: {}, gesture: { travelPx: 0, durationMs: 20 } }); + click({ + screenPosition: { x: 14, y: 26 }, + get drawHit() { + assert.fail('the camera underneath was picked'); + }, + gesture: { travelPx: 0, durationMs: 20 }, + }); assert.equal(flights.length, 1); assert.equal(state._activeCameraId, 'opening'); assert.equal(state._openingCameraProvisional, true); diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index 65afc5cb61..f616ab0b19 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -91,6 +91,7 @@ export function createTesting({ state: layerState, services, parts, source }) { * @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode. * @param {boolean} [options.showProjection=false] Projection visibility. * @param {Map} [options.healthById] Health rows by camera id. + * @param {Function} [options.registerPaintLane] Receives the count painter. * @returns {void} */ @@ -103,6 +104,7 @@ export function createTesting({ state: layerState, services, parts, source }) { showProjection = false, healthById = new Map(), openingCameraProvisional = false, + registerPaintLane, } = {}) { layerState._viewer = viewer; layerState._records = Array.isArray(records) ? records : []; @@ -132,10 +134,12 @@ export function createTesting({ state: layerState, services, parts, source }) { // A real book (over a set that draws nothing): every record gets its // icon as init adds it. layerState._icons = createIconBook(testIconSet()); - layerState._counts = createCountMarkers({ - ...testIconSet(), - id: 'cctv:test:counts', - }); + layerState._counts?.dispose(); + layerState._counts = createCountMarkers( + registerPaintLane, + 'cctv:test:counts', + parts.rendering.refreshHorizonCulling, + ); for (const record of layerState._records) if (record?.camera?.id) parts.rendering.addCameraIcon(record); } @@ -155,7 +159,7 @@ export function createTesting({ state: layerState, services, parts, source }) { for (const runtime of layerState._projectionEntities) if (runtime?.plane) planes[runtime.plane.id] = runtime.plane; return { - counts: layerState._counts?.book, + counts: layerState._counts, gizmo: layerState._gizmo?.partsForTest() ?? {}, coverage, planes, diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 39a3f626cc..451e04812b 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -243,6 +243,9 @@ const _customPaintFrame = { cameraHeight: Number.NaN, occluder: null, keyhole: null, + // Anchored custom glyphs yield to the same below-host chrome as entries. + overlapsHardUi: (rect) => + overlayRectIntersectsAnyHard(rect, _uiOcclusionRects), uiRects: _uiOcclusionRects, uiRectCount: 0, layoutRevision: 0, diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index 4b27e73aeb..ac04274210 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -1514,9 +1514,14 @@ test('a placement is only ever kept under chrome that composites ABOVE the host' const paintedUnder = (occluders) => { const env = installMockEnvironment({ width: 400, height: 300, dpr: 1, occluders }); initWorldOverlay(env.viewer); + let hardUi; + registerWorldOverlayPaintLane('ambient-label', (frame) => { + hardUi = frame.overlapsHardUi({ x: 180, y: 130, w: 40, h: 40 }); + }, { id: 'anchored-label', active: true }); setOverlayEntries('ambient', [selectedEntry('CONTACT')]); env.postRender.raise(); const { paintedCount } = getWorldOverlayDiagnostics(); + assert.equal(hardUi, paintedCount === 0); env.cleanup(); return paintedCount; }; diff --git a/src/render/cesium/screenModulation.js b/src/render/cesium/screenModulation.js index 53fee1bca5..45c2c4bffa 100644 --- a/src/render/cesium/screenModulation.js +++ b/src/render/cesium/screenModulation.js @@ -485,13 +485,6 @@ export function createCesiumScreenModulation(scene, { frame, onChange }) { ? 'icon' : null; if (!kind || !native.shaderProgram || !native.uniformMap) continue; - // Aggregate billboards occupy their own collection and represent groups. - if ( - kind === 'billboard' && - native.owner.length && - native.owner.get(0).id?.meta?.aggregate === true - ) - continue; const source = native.shaderProgram; // Label backgrounds are non-SDF billboard batches. The version-tested // engine pick association distinguishes them without enumerating diff --git a/src/render/cesium/screenModulation.test.mjs b/src/render/cesium/screenModulation.test.mjs index c88c74b3e2..62927bbe2d 100644 --- a/src/render/cesium/screenModulation.test.mjs +++ b/src/render/cesium/screenModulation.test.mjs @@ -606,19 +606,3 @@ test('disposal does not overwrite a successor update owner', () => { assert.equal(f.primitives.update, successor); f.primitives.destroy(); }); - -test('aggregate markers keep their native billboard command during a contact sweep', () => { - const owner = new Cesium.BillboardCollection(); - owner.add({ id: { meta: { aggregate: true } } }); - const command = { owner, uniformMap: {}, shaderProgram: {} }; - const f = fixture({ commands: [command] }); - try { - f.part.set(sweep()); - assert.equal(f.draw()[0], command); - assert.equal(f.part.stats.supported, true); - } finally { - f.part.dispose(); - owner.destroy(); - f.primitives.destroy(); - } -}); From c536d22ff09ac8cd08799d64a3a0e815f7d1dad0 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 20:48:33 +0400 Subject: [PATCH 4/9] feat(cctv): green count markers that grow with the count and carry a camera icon A count marker now says what it counts and how much: - Its height grows with the count, from 40 px for two cameras to 58 px for several thousand, with clear fill around the digits. - A small single-camera map icon sits under the top of the ring and the number just below the centre, so the two never touch. The icon is built from the same sprite as a single camera on the map. - Thousands print as 1.7K or 12K in every UI language. - The camera layer is green: count markers and idle single cameras share the colour, the active camera stays gold and live-video cameras violet. --- changelog.d/1808-cctv-camera-counts.md | 7 + docs/CURRENT-STATE.md | 8 +- src/data/cctv.test.mjs | 16 +- src/data/cctvCellCounts.js | 45 +-- src/data/cctvCellCounts.test.mjs | 65 +++- src/data/cctvViewThinning.test.mjs | 518 +++++++++++++++++++------ src/layers/cctv/countMarkers.js | 246 ++++++++++-- src/layers/cctv/policy.js | 65 +++- src/layers/cctv/rendering.js | 23 +- src/layers/cctv/rendering.test.mjs | 28 +- 10 files changed, 806 insertions(+), 215 deletions(-) create mode 100644 changelog.d/1808-cctv-camera-counts.md diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md new file mode 100644 index 0000000000..7ffb4bd262 --- /dev/null +++ b/changelog.d/1808-cctv-camera-counts.md @@ -0,0 +1,7 @@ +- Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a + ground cell with two or more cameras is one round marker with a small camera + icon and the count (`999`, `1.7K`, `12K` in every language); it grows with + the count, merges with a neighbour it would overlap, and a click zooms in + until the group splits. The camera layer's colour is now green: count + markers and idle single cameras share it, the active camera stays gold and + live-video cameras stay violet (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f79aa705fd..4c1669a931 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,8 +1953,10 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows a cyan count at their centre, -drawn on the world overlay at the same resolution as camera callouts. +ground cell containing multiple cameras shows, at their centre, a marker with +a small green camera pictogram under its top edge and the count just below its +middle. The marker grows with the count and is drawn on the world overlay at +the same resolution as camera callouts. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, @@ -7339,7 +7341,7 @@ silently demoting every later lookup for the session. ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a - periodic white flash). Camera icons are cyan for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` + periodic white flash). Camera icons are green for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` default 36 → 250, hard bound 300), filtered to `camera_status === TURNED_ON` (~815 live of 1,003 rows). City packs (2026-07-04): Caltrans (districts 4/7/11/3 — SF, LA, San Diego, Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index 35a634c6cf..fa9ee0eea1 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -85,6 +85,7 @@ import { } from '../cctvFocusRequest.js'; import { ACTIVE_CAMERA_COLOR, + CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; @@ -353,7 +354,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu } }); -test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { +test('camera icons are violet for video feeds, green for stills, amber when active', () => { const record = (id, feedType) => ({ camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, // Every catalog record is placed as it is made, and drawn there. @@ -385,6 +386,19 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR); assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); assert.equal(icons.item(idleVideo.camera.id).scale, 1); + const image = (record) => icons.item(record.camera.id).image; + assert.deepEqual(IDLE_CAMERA_COLOR, [93 / 255, 1, 143 / 255, 1]); + const idleImage = image(idleStill); + assert.match(atob(idleImage.split(',')[1]), /stroke="#fff"/); + assert.equal(image(activeVideo), CAMERA_ICON); + assert.equal(image(idleVideo), CAMERA_ICON); + idleStill.camera.feedType = 'hls'; + refreshCoverageStyles(); + assert.equal(image(idleStill), CAMERA_ICON); + idleStill.camera.feedType = 'image'; + refreshCoverageStyles(); + assert.equal(image(idleStill), idleImage); + } finally { _setCctvCoverageStateForTest({ enabled: false }); unbind(); diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 8c4c7a226b..0543925ed2 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -1,12 +1,11 @@ -import { formatNumber } from '../i18n/index.js'; import { fromDegrees } from '../geo/ellipsoid.js'; -/** Exact small counts and compact thousands in the current UI locale. */ +/** Exact camera counts below a thousand, then rounded thousands with a K suffix. */ export function formatCameraCount(count) { - return formatNumber( - count, - count < 1000 ? undefined : { notation: 'compact' }, - ); + if (count < 1000) return String(count); + const thousands = + count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000); + return `${thousands}K`; } /** An empty cell and its on-screen picker candidate. */ @@ -86,17 +85,18 @@ function addCell(target, cell) { } /** Claim the touching pills in this marker's bucket and its eight neighbors. */ -function collectNeighbors(marker, grid, members, height, mergeDistance) { +function collectNeighbors(marker, grid, members, gap) { for (let col = -1; col <= 1; col++) { for (let row = -1; row <= 1; row++) { const bucket = grid.get(`${marker.col + col},${marker.row + row}`); if (!bucket) continue; for (const other of bucket) { // Distance between the horizontal centre segments of the two pills. - const extra = (marker.width + other.width) / 2 - height; + const extra = marker.halfSegment + other.halfSegment; const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); const dy = marker.y - other.y; - if (dx * dx + dy * dy >= mergeDistance * mergeDistance) continue; + const reach = marker.radius + other.radius + gap; + if (dx * dx + dy * dy >= reach * reach) continue; bucket.delete(other); members.push(other); } @@ -109,27 +109,28 @@ function collectNeighbors(marker, grid, members, height, mergeDistance) { * one grid bucket. Even the widest pill can only touch its eight neighbors. * Ground cells stay intact for the camera picker and individual-icon pass. */ -export function mergeCountCells( - cells, - project, - widthFor, - height, - mergeDistance, -) { - const gap = mergeDistance - height; - let columnWidth = mergeDistance; +export function mergeCountCells(cells, project, sizeFor, gap) { + let columnWidth = 0; + let rowHeight = 0; const markers = cells.map((cell) => { const screen = project(cellCenter(cell)); - const width = widthFor(cell.count); + const { width, height } = sizeFor(cell.count); columnWidth = Math.max(columnWidth, width + gap); + rowHeight = Math.max(rowHeight, height + gap); // The view projector reuses its result object. - return { cell, x: screen?.x, y: screen?.y, width }; + return { + cell, + x: screen?.x, + y: screen?.y, + halfSegment: (width - height) / 2, + radius: height / 2, + }; }); const grid = new Map(); for (const marker of markers) { if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue; marker.col = Math.floor(marker.x / columnWidth); - marker.row = Math.floor(marker.y / mergeDistance); + marker.row = Math.floor(marker.y / rowHeight); const key = `${marker.col},${marker.row}`; if (!grid.has(key)) grid.set(key, new Set()); marker.bucket = grid.get(key); @@ -147,7 +148,7 @@ export function mergeCountCells( members.length = 0; members.push(seed); for (let i = 0; i < members.length; i++) - collectNeighbors(members[i], grid, members, height, mergeDistance); + collectNeighbors(members[i], grid, members, gap); if (members.length === 1) { groups.push(seed.cell); diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index bfa421bd91..49eb59faaf 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -9,20 +9,28 @@ import { cellCenter, cellBounds, formatCameraCount, + mergeCountCells, } from './cctvCellCounts.js'; -test('camera counts are exact through 999 and compact in the active locale', () => { +test('camera counts use the same Latin digits and K notation in every UI language', () => { const previous = getLocale(); + const examples = [ + [2, '2'], + [999, '999'], + [1000, '1K'], + [1150, '1.2K'], + [1687, '1.7K'], + [9960, '10K'], + [10000, '10K'], + [12345, '12K'], + [12500, '13K'], + [1000000, '1000K'], + ]; try { - for (const locale of ['en', 'fr', 'ja']) { + for (const locale of ['en', 'ru', 'ja', 'ar']) { setLocale(locale); - for (const n of [2, 999, 1000, 12345]) { - const format = new Intl.NumberFormat( - locale, - n < 1000 ? {} : { notation: 'compact' }, - ); - assert.equal(formatCameraCount(n), format.format(n)); - } + for (const [count, label] of examples) + assert.equal(formatCameraCount(count), label, `${locale}: ${count}`); } } finally { setLocale(previous); @@ -47,3 +55,42 @@ test('the marker mean weights every mount and the flight bounds cover the outlie ); } }); + +test('stadiums merge by their own radii and segment lengths across grid boundaries', () => { + const sizes = { + 2: { width: 28, height: 28 }, + 7350: { width: 80, height: 48 }, + }; + const gap = 4; + const check = (counts, positions, expected) => { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + gap, + ); + assert.deepEqual( + groups.map((cell) => cell.count), + expected, + ); + assert.equal( + groups.reduce((sum, cell) => sum + cell.count, 0), + counts[0] + counts[1], + ); + }; + const origin = { x: 35, y: 37 }; + // Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear. + check([2, 7350], [origin, { x: 35, y: 78 }], [7352]); + check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]); + // The large pill's centre segment extends 16 pixels towards the circle. + check([7350, 2], [origin, { x: 92, y: 37 }], [7352]); + check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]); + check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]); + // Large pills can reach across a row boundary at their full diameter. + check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index ac134670e8..e78810b87a 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -4,7 +4,9 @@ import { afterEach, beforeEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { getLocale, setLocale } from '../i18n/index.js'; +import { CAMERA_GREEN } from '../layers/cctv/policy.js'; +import { createCameraGlyphCache } from '../layers/cctv/countMarkers.js'; +import { createCameraCell } from './cctvCellCounts.js'; import { bindRenderer } from '../render/rendererOf.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; @@ -93,8 +95,59 @@ let painter; let paintRequests; let measured; let glyphWidth; +let inkHalfHeight; let ctx; const fonts = new EventTarget(); +let rasters; +let spriteImages; + +/** Model the sprite’s neutral highlights, dark fills and translucent edges. */ +function markerCanvas() { + const canvas = {}; + const context = { + measureText(text) { + measured++; + return { + width: text.length * glyphWidth, + actualBoundingBoxAscent: inkHalfHeight, + actualBoundingBoxDescent: inkHalfHeight, + }; + }, + drawImage(image, x, y, width, height) { + assert.equal(image.loaded, true); + assert.deepEqual( + [x, y, width, height], + [0, 0, canvas.width, canvas.height], + ); + canvas.source = image.src; + const h = Math.floor(height / 2); + canvas.ink = [2, 3, Math.floor(h * 1.5), h]; + rasters.push(canvas); + }, + getImageData() { + const data = new Uint8ClampedArray(canvas.width * canvas.height * 4); + const [left, top, width, height] = canvas.ink; + for (let y = top; y < top + height; y++) { + for (let x = left; x < left + width; x++) { + const shade = x === left ? 255 : 64; + data.set( + [shade, shade, shade, y === top ? 1 : 255], + (y * canvas.width + x) * 4, + ); + } + } + return { data }; + }, + putImageData({ data }) { + const [left, top] = canvas.ink; + const start = (top * canvas.width + left) * 4; + canvas.stroke = [...data.slice(start, start + 4)]; + canvas.fill = [...data.slice(start + 4, start + 8)]; + }, + }; + canvas.getContext = () => context; + return canvas; +} function seedCoverage(options) { _setCctvCoverageStateForTest({ @@ -113,21 +166,23 @@ function seedCoverage(options) { } beforeEach(() => { + spriteImages = []; + globalThis.Image = class { + constructor() { + spriteImages.push(this); + } + finish() { + this.loaded = true; + this.onload(); + } + }; paintRequests = 0; measured = 0; glyphWidth = 8; - globalThis.document = { - fonts, - createElement: () => ({ - getContext: () => ({ - measureText(text) { - measured++; - return { width: text.length * glyphWidth }; - }, - }), - }), - }; - let savedState; + inkHalfHeight = 4; + rasters = []; + globalThis.document = { fonts, createElement: markerCanvas }; + const stack = []; ctx = { font: 'initial', globalAlpha: 1, @@ -136,17 +191,32 @@ beforeEach(() => { textAlign: 'start', textBaseline: 'top', lineWidth: 1, + glyphs: [], + rings: [], labels: [], shapes: [], save() { - savedState = { ...this }; + stack.push({ ...this }); }, restore() { - Object.assign(this, savedState); + Object.assign(this, stack.pop()); }, beginPath() {}, fill() {}, - stroke() {}, + drawImage(image, left, top, sw, sh, x, y, width, height) { + assert.deepEqual([left, top, sw, sh], image.ink); + assert.ok(Math.abs(width / height - sw / sh) < 1e-9); + this.glyphs.push({ + image, + x: x + width / 2, + y: y + height / 2, + width, + height, + }); + }, + stroke() { + this.rings.push(this.strokeStyle); + }, roundRect(...args) { this.shapes.push(args); }, @@ -155,6 +225,7 @@ beforeEach(() => { text, x, y, + color: this.fillStyle, alpha: this.globalAlpha, font: this.font, }); @@ -164,12 +235,16 @@ beforeEach(() => { /** Reproject on each paint in CSS pixels, as the host does. */ function paint(overrides = {}) { - ctx.labels.length = ctx.shapes.length = 0; + ctx.glyphs.length = + ctx.rings.length = + ctx.labels.length = + ctx.shapes.length = + 0; painter({ ctx, width: WIDTH, height: HEIGHT, - dpr: 2, + dpr: 1, viewProjectionMatrix: new Float64Array([ 0, 0, @@ -196,6 +271,7 @@ function paint(overrides = {}) { } afterEach(() => { + delete globalThis.Image; delete globalThis.document; for (const unbind of bindings.splice(0)) unbind(); }); @@ -314,7 +390,8 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( cctvLayer.getUIState().cameraIndex.map((c) => c.id), [id], ); - const { pos } = markers()[0]; + const { pos, height } = markers()[0]; + assert.equal(height, 40); const center = Cesium.Cartesian3.fromDegrees(0.0005, 0, 10); assert.ok(Cesium.Cartesian3.distance(pos, center) < 0.02); if (first) assert.deepEqual(pos, first); @@ -637,7 +714,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), ) < 0.01, ); - const positions = shown.map((m) => [m.cell.key, m.pos]); + const positions = shown.map((m) => [m.cell.key, m.pos, m.height, m.width]); if (previous) assert.deepEqual(positions, previous); previous = positions; clickMarker(merged); @@ -658,84 +735,137 @@ test('overlapping cells merge at their weighted centre and keep every camera in } }); -test('the overlay paints short counts as circles and long localized labels as pills', () => { - const locale = getLocale(); - try { - setLocale('ru'); +test('the overlay paints narrow count labels as circles and wide labels as pills', () => { + glyphWidth = 10; + const { records } = recordsAt([ + ...Array(1300).fill([-0.008, 0]), + ...Array(99).fill([0.06, 0]), + [0.1, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const short = markers().find((m) => m.cell.count === 99); + const long = markers().find((m) => m.cell.count === 1300); + const measurements = measured; + assert.equal(measurements, 2); + const pending = paint().map(({ text, x, y }) => [text, x, y]); + const pendingShapes = [...ctx.shapes]; + const requests = paintRequests; + assert.equal(ctx.glyphs.length, 0); + assert.equal(spriteImages.length, 1); + spriteImages[0].finish(); + assert.equal(paintRequests, requests + 1); + const labels = paint(); + assert.deepEqual( + labels.map(({ text, x, y }) => [text, x, y]), + pending, + ); + assert.deepEqual(ctx.shapes, pendingShapes); + refreshHorizonCulling(); + assert.equal(measured, measurements); + const text = '1.3K'; + assert.equal(labels.length, 2); + assert.equal(ctx.shapes.length, labels.length); + const [sx, sy, sw, sh] = ctx.shapes[labels.findIndex((l) => l.text === '99')]; + const [lx, ly, lw, lh] = ctx.shapes[labels.findIndex((l) => l.text === text)]; + assert.equal(sw, sh); + assert.ok(lw > lh); + assert.ok(lw > text.length * glyphWidth); + assert.equal(sh + 4, 48); + assert.equal(lh + 4, 54); + // The four-pixel outer stroke extends two pixels on each side of the path. + assert.equal(sw + 4, short.width); + assert.equal(lw + 4, long.width); + assert.equal(sy + sh / 2, HEIGHT / 2); + assert.equal(ly + lh / 2, HEIGHT / 2); + assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); + assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); + assert.equal(ctx.glyphs.length, labels.length); + assert.equal(CAMERA_GREEN, '#5dff8f'); + assert.deepEqual( + ctx.rings.filter((_, i) => i % 2 === 1), + labels.map(() => CAMERA_GREEN), + ); + for (const [i, label] of labels.entries()) { + const glyph = ctx.glyphs[i]; + const [left, top, w, h] = ctx.shapes[i]; + const cx = left + w / 2, + cy = top + h / 2; + assert.equal(glyph.x, cx); + assert.equal(label.x, cx); + assert.deepEqual(glyph.image.stroke, [93, 255, 143, 1]); + assert.deepEqual(glyph.image.fill, [23, 64, 36, 1]); + assert.equal(label.color, CAMERA_GREEN); + const radius = h / 2 - 1; + // 48 and 54 px markers: the glyph and its top gap grow with the marker. + const grown = (h + 4 - 40) / 18; + assert.ok(Math.abs(glyph.height - (7.5 + 2.5 * grown)) < 1e-9); + assert.ok( + Math.abs(glyph.y - glyph.height / 2 - (cy - radius + 3 + grown)) < 1e-9, + ); + // The middle of the digits sits a fifth of the inner radius below centre. + assert.ok(Math.abs(label.y - (cy + 0.2 * radius)) < 1e-9); + assert.ok(label.y - inkHalfHeight - (glyph.y + glyph.height / 2) >= 5); + for (const [width, edgeY, padding] of [ + [glyph.width, glyph.y - glyph.height / 2, 2], + [label.text.length * glyphWidth, label.y + inkHalfHeight, 6], + ]) { + const chord = 2 * Math.sqrt(radius ** 2 - (edgeY - cy) ** 2); + assert.ok((w - h + chord - width) / 2 >= padding - 1e-9); + } + } + const builds = rasters.length; + const images = ctx.glyphs.map((glyph) => glyph.image); + assert.notEqual(images[0], images[1]); + const idleCamera = _cctvIconsForTest().item(records.at(-1).camera.id); + assert.equal(idleCamera.show, true); + for (const image of images) assert.equal(image.source, idleCamera.image); + paint(); + assert.deepEqual( + ctx.glyphs.map((glyph) => glyph.image), + images, + ); + assert.equal(rasters.length, builds); + assert.equal(paintRequests, requests + 1); + assert.match(labels[0].font, /JetBrains Mono/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); + assert.equal(ctx.lineWidth, 1); + ctx.drawImage = () => { + throw new Error('glyph paint failed'); + }; + assert.throws(() => paint(), /glyph paint failed/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); +}); + +test('a wide count label merges a horizontal neighbor beyond the circle diameter', () => { + glyphWidth = 12; + // The centers are 56 CSS pixels apart. Only the pill reaches its neighbor. + const at = (count) => { const { records } = recordsAt([ - ...Array(1300).fill([-0.008, 0]), - [0.06, 0], - [0.06, 0], + ...Array(count).fill([-0.0097, 0]), + [0.0097, 0], + [0.0097, 0], ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - const short = markers().find((m) => m.cell.count === 2); - const long = markers().find((m) => m.cell.count === 1300); - const measurements = measured; - assert.equal(measurements, 1); - const labels = paint(); - refreshHorizonCulling(); - assert.equal(measured, measurements); - const text = new Intl.NumberFormat('ru', { notation: 'compact' }).format( - 1300, - ); - assert.equal(labels.length, 2); - assert.equal(ctx.shapes.length, labels.length); - const [sx, sy, sw, sh] = - ctx.shapes[labels.findIndex((l) => l.text === '2')]; - const [lx, ly, lw, lh] = - ctx.shapes[labels.findIndex((l) => l.text === text)]; - assert.equal(sw, sh); - assert.ok(lw > text.length * glyphWidth); - assert.equal(lh, sh); - // The four-pixel outer stroke extends two pixels on each side of the path. - assert.equal(sw + 4, short.width); - assert.equal(lw + 4, long.width); - assert.equal(sy + sh / 2, HEIGHT / 2); - assert.equal(ly + lh / 2, HEIGHT / 2); - assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); - assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); - assert.match(labels[0].font, /JetBrains Mono/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); - assert.equal(ctx.lineWidth, 1); - } finally { - setLocale(locale); - } -}); - -test('a wider localized pill merges a horizontal neighbor beyond the circle diameter', () => { - const locale = getLocale(); - try { - setLocale('ru'); - // The centers are 46 CSS pixels apart. Only the pill reaches its neighbor. - const at = (count) => { - const { records } = recordsAt([ - ...Array(count).fill([-0.008, 0]), - [0.008, 0], - [0.008, 0], - ]); - seedCoverage({ viewer: viewerAt(20_000), records }); - refreshHorizonCulling(); - return markers().map((m) => m.cell.count); - }; - assert.deepEqual(at(2), [2, 2]); - assert.deepEqual(at(1300), [1302]); - } finally { - setLocale(locale); - } + return markers().map((m) => m.cell.count); + }; + assert.deepEqual(at(2), [2, 2]); + assert.deepEqual(at(1300), [1302]); }); test('a merged centre can pick up a third count marker', () => { - // The two northern centres are 35 px apart. Each is 40 px from the - // southern one, but their combined centre is only 36 px away. + // The northern pair is 42 px apart. Its centre is 44.5 px from the + // southern group, within reach only after the count grows from two to four. const { records } = recordsAt([ - [-0.006, 0], - [-0.006, 0], - [0.006, 0], - [0.006, 0], - [0, -0.0126], - [0, -0.0126], + [-0.0073, 0], + [-0.0073, 0], + [0.0073, 0], + [0.0073, 0], + [0, -0.0154], + [0, -0.0154], ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); @@ -758,10 +888,10 @@ test('each paint follows the overlay projection, horizon and hard HUD exclusions assert.ok(paintRequests > 0); const requests = paintRequests; const widths = measured; - assert.deepEqual( - paint().map(({ text, x, y }) => [text, x, y]), - [['4', 400, 300]], - ); + const [label] = paint(); + assert.equal(label.text, '4'); + assert.equal(label.x, 400); + assert.ok(label.y > 300); const first = { x: 400, y: 300 }; assert.equal(counts.pickedCell(first).count, 4); const at = (x) => { @@ -782,28 +912,22 @@ test('each paint follows the overlay projection, horizon and hard HUD exclusions }); test('loaded font metrics remerge visible cells without waiting for a move', () => { - const locale = getLocale(); - try { - setLocale('ru'); - glyphWidth = 3; - const { records } = recordsAt([ - ...Array(1300).fill([-0.009, 0]), - [0.009, 0], - [0.009, 0], - ]); - seedCoverage({ viewer: viewerAt(20_000), records }); - refreshHorizonCulling(); - assert.equal(markers().length, 2); - glyphWidth = 12; - fonts.dispatchEvent(new Event('loadingdone')); - assert.deepEqual( - markers().map((m) => m.cell.count), - [1302], - ); - assert.equal(paint().length, 1); - } finally { - setLocale(locale); - } + glyphWidth = 3; + const { records } = recordsAt([ + ...Array(1300).fill([-0.0097, 0]), + [0.0097, 0], + [0.0097, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.equal(markers().length, 2); + glyphWidth = 14; + fonts.dispatchEvent(new Event('loadingdone')); + assert.deepEqual( + markers().map((m) => m.cell.count), + [1302], + ); + assert.equal(paint().length, 1); }); test('hits follow paint order and keep the last painted group until the overlay clears', () => { @@ -829,3 +953,165 @@ test('hits follow paint order and keep the last painted group until the overlay assert.deepEqual(paint(), []); assert.equal(counts.pickedCell(point), null); }); + +test('paint, HUD exclusions and hit rectangles use the count-scaled height', () => { + seedCoverage({ viewer: viewerAt(20_000) }); + const counts = cctvLayer._cctvDrawnForTest().counts; + for (const [count, height] of [ + [2, 40], + [10, 44], + [100, 48], + [1000, 54], + [3162, 56], + [3163, 56], + [7350, 58], + [1e8, 58], + ]) { + const cell = { ...createCameraCell('cell'), count }; + for (const lon of [0, 0.025]) { + counts.update( + [{ ...cell, lonSum: Math.round(lon * 1e7) * count }], + () => null, + ); + if (!spriteImages[0]?.loaded) spriteImages[0].finish(); + let rect; + const [label] = paint({ + overlapsHardUi(value) { + rect = { ...value }; + return false; + }, + }); + if (height === 40 || height === 58) + assert.equal(ctx.glyphs[0].height, height === 40 ? 7.5 : 10); + const marker = markers()[0]; + assert.equal(marker.height, height); + assert.equal(rect.h, height); + assert.equal(rect.w, marker.width); + const [x, y, w, h] = ctx.shapes[0]; + assert.deepEqual( + [x - 2, y - 2, w + 4, h + 4], + [rect.x, rect.y, rect.w, rect.h], + ); + for (const sign of [-1, 1]) { + const edgeY = rect.y + height / 2 + (sign * height) / 2; + assert.equal(counts.pickedCell({ x: label.x, y: edgeY }).count, count); + assert.equal( + counts.pickedCell({ x: label.x, y: edgeY + sign * 0.1 }), + null, + ); + } + } + // Centred 23 px above the canvas: the taller badges still cross the edge. + const matrix = new Float64Array(16); + matrix[13] = 1 + 46 / HEIGHT; + matrix[15] = 1; + assert.equal( + paint({ viewProjectionMatrix: matrix }).length, + height > 46 ? 1 : 0, + ); + } +}); + +test('measured ink width selects the circle or pill and clears the curved ring', () => { + const { records } = recordsAt(Array(99).fill([0, 0])); + seedCoverage({ viewer: viewerAt(20_000), records }); + for (const [width, extent, circle] of [ + [7, 4, true], + [25, 4, false], + // Width-only metrics reserve the full type height below the baseline. + [6, undefined, true], + ]) { + glyphWidth = width; + inkHalfHeight = extent; + fonts.dispatchEvent(new Event('loadingdone')); + refreshHorizonCulling(); + const [label] = paint(); + const [, top, pathWidth, pathHeight] = ctx.shapes[0]; + assert.equal(pathHeight + 4, 48); + assert.equal(pathWidth === pathHeight, circle); + // At the top of the ink, the circle ends narrow the usable inner width. + const innerRadius = pathHeight / 2 - 1; + const edge = label.y + (extent ?? 6) - (top + pathHeight / 2); + const clearWidth = + pathWidth - pathHeight + 2 * Math.sqrt(innerRadius ** 2 - edge ** 2); + assert.ok((clearWidth - label.text.length * width) / 2 >= 6); + } +}); + +test('equal-size camera groups share a camera sprite and follow overlay pixel density', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + [0.05, 0], + [0.05, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + spriteImages[0].finish(); + paint({ dpr: 1 }); + const low = ctx.glyphs[0].image; + assert.equal(ctx.glyphs[1].image, low); + const builds = rasters.length; + paint({ dpr: 2 }); + const high = ctx.glyphs[0].image; + assert.equal(ctx.glyphs[1].image, high); + assert.notEqual(high, low); + // The raster follows the device density; the painted size does not. + assert.deepEqual([low.width, high.width], [16, 30]); + assert.equal(ctx.glyphs[0].height, 7.5); + paint({ dpr: 2 }); + assert.equal(rasters.length, builds + 1); + paint({ dpr: 1 }); + assert.equal(ctx.glyphs[0].image, low); + assert.equal(rasters.length, builds + 1); +}); + +test('the glyph cache draws its supplied map sprite and multiplies its colours', () => { + const source = + 'data:image/svg+xml,' + + encodeURIComponent( + '', + ); + const glyphFor = createCameraGlyphCache(markerCanvas, source); + assert.equal(glyphFor(12, 2, CAMERA_GREEN), null); + assert.equal(spriteImages[0].src, source); + spriteImages[0].finish(); + const green = glyphFor(12, 2, CAMERA_GREEN); + assert.equal(glyphFor(12, 2, CAMERA_GREEN), green); + const white = glyphFor(12, 2, '#ffffff'); + assert.notEqual(white, green); + assert.deepEqual( + rasters.map(({ source: drawn }) => drawn), + [source, source], + ); + assert.deepEqual(white.canvas.stroke, [255, 255, 255, 1]); + assert.deepEqual(white.canvas.fill, [64, 64, 64, 1]); +}); + +test('a sprite that loads after disposal does not request a paint', () => { + const { records } = recordsAt(CLUSTER); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + cctvLayer._cctvDrawnForTest().counts.dispose(); + const requests = paintRequests; + spriteImages[0].finish(); + assert.equal(rasters.length, 0); + assert.equal(paintRequests, requests); +}); + +test('counts still paint when an offscreen 2D context is unavailable', () => { + document.createElement = () => ({ getContext: () => null }); + const { records } = recordsAt([ + [0, 0], + [0, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + spriteImages[0].finish(); + assert.deepEqual( + paint().map((label) => label.text), + ['2'], + ); + assert.equal(ctx.glyphs.length, 0); + assert.equal(ctx.shapes.length, 1); +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 740519b132..b6f38e7fe7 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -5,19 +5,112 @@ import { } from '../../data/cctvCellCounts.js'; import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { - COUNT_MARKER_PX, - COUNT_MERGE_DISTANCE_PX, + CAMERA_GREEN, + IDLE_CAMERA_ICON, + COUNT_BASE_PX, + COUNT_PX_PER_DECADE, + COUNT_MIN_HEIGHT_PX, + COUNT_MAX_HEIGHT_PX, + COUNT_TEXT_PADDING_PX, + COUNT_GLYPH_MIN_PX, + COUNT_GLYPH_MAX_PX, + COUNT_GLYPH_TOP_MIN_PX, + COUNT_GLYPH_TOP_MAX_PX, + COUNT_GLYPH_PADDING_PX, + COUNT_LABEL_DROP, + COUNT_MERGE_GAP_PX, COUNT_MERGE_PASSES, } from './policy.js'; const FONT = WORLD_OVERLAY_STYLE.fontTitle; -const RING = '#75e7ff'; +// Reserve the camera's landscape slot even while the map sprite is loading. +const GLYPH_ASPECT = 1.5; +const RING_PX = 2; +const RIM_PX = 1; +const STROKE_INSET = RIM_PX + RING_PX / 2; + +/** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ +function rasterizeGlyph(canvas, image, size, dpr, color) { + if (!canvas) return null; + // The artwork occupies just over half the height of the square SVG viewport. + const side = 2 * Math.ceil(size * dpr); + canvas.width = canvas.height = side; + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + ctx.drawImage(image, 0, 0, side, side); + const pixels = ctx.getImageData(0, 0, side, side); + const { data } = pixels; + const rgb = Number.parseInt(color.slice(1), 16); + const red = (rgb >> 16) / 255; + const green = ((rgb >> 8) & 255) / 255; + const blue = (rgb & 255) / 255; + let left = side, + top = side, + right = -1, + bottom = -1; + for (let y = 0; y < side; y++) { + for (let x = 0; x < side; x++) { + const i = (y * side + x) * 4; + if (!data[i + 3]) continue; + data[i] *= red; + data[i + 1] *= green; + data[i + 2] *= blue; + left = Math.min(left, x); + right = Math.max(right, x); + top = Math.min(top, y); + bottom = y; + } + } + if (right < 0) return null; + ctx.putImageData(pixels, 0, 0); + const width = right - left + 1; + const height = bottom - top + 1; + const scale = Math.min(size / height, (size * GLYPH_ASPECT) / width); + return { + canvas, + left, + top, + width, + height, + drawWidth: width * scale, + drawHeight: height * scale, + }; +} + +/** Load the map artwork once, then share each tinted device-density raster. */ +export function createCameraGlyphCache(createCanvas, source, onLoad) { + const glyphs = new Map(); + let image; + let ready = false; + return (size, dpr, color) => { + if (!image && typeof Image !== 'undefined') { + image = new Image(); + image.onload = () => { + ready = true; + onLoad?.(); + }; + image.src = source; + } + if (!ready) return null; + const key = `${size}:${dpr}:${color}`; + if (!glyphs.has(key)) { + glyphs.set(key, rasterizeGlyph(createCanvas(), image, size, dpr, color)); + } + return glyphs.get(key); + }; +} /** Merged camera groups and their last painted hit rectangles in CSS pixels. */ -export function createCountMarkers(registerPaintLane, id, refreshView) { +export function createCountMarkers( + registerPaintLane, + id, + refreshView, + createCanvas = () => globalThis.document?.createElement('canvas'), +) { + let dpr = Math.max(1, Number(globalThis.window?.devicePixelRatio) || 1); const markers = []; const hits = []; - const widths = new Map(); + const textMetrics = new Map(); const fonts = globalThis.document?.fonts; let measureCtx; let hitCount = 0; @@ -26,30 +119,81 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { active: false, target: 'shared', }); + const glyphFor = createCameraGlyphCache( + createCanvas, + IDLE_CAMERA_ICON, + () => { + if (!markers.length) return; + refreshGlyphs(); + lane?.requestPaint(); + }, + ); fonts?.addEventListener?.('loadingdone', fontsLoaded); /** Font changes can widen a pill enough to merge it with its neighbor. */ function fontsLoaded() { - widths.clear(); + textMetrics.clear(); if (!markers.length) return; refreshView(); lane?.requestPaint(); } - /** Short labels fit the circle. A longer label leaves room for rounded ends. */ - function widthForText(text) { - if (text.length <= 3) return COUNT_MARKER_PX; - let width = widths.get(text); - if (width === undefined) { - measureCtx ??= document.createElement('canvas').getContext('2d'); - measureCtx.font = FONT; - width = Math.max( - COUNT_MARKER_PX + 1, - Math.ceil(measureCtx.measureText(text).width) + 20, - ); - widths.set(text, width); + /** Seat the glyph under the top of the ring and the count just below centre. */ + function sizeFor(count) { + const text = formatCameraCount(count); + let metrics = textMetrics.get(text); + if (!metrics) { + measureCtx ??= createCanvas()?.getContext('2d'); + if (measureCtx) { + measureCtx.font = FONT; + measureCtx.textBaseline = 'middle'; + metrics = measureCtx.measureText(text); + } else { + metrics = { width: text.length * 8 }; + } + textMetrics.set(text, metrics); } - return width; + const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count); + const clamped = Math.max( + COUNT_MIN_HEIGHT_PX, + Math.min(COUNT_MAX_HEIGHT_PX, diameter), + ); + const height = 2 * Math.round(clamped / 2); + const grown = + (height - COUNT_MIN_HEIGHT_PX) / + (COUNT_MAX_HEIGHT_PX - COUNT_MIN_HEIGHT_PX); + const glyphHeight = + COUNT_GLYPH_MIN_PX + (COUNT_GLYPH_MAX_PX - COUNT_GLYPH_MIN_PX) * grown; + const radius = height / 2 - RIM_PX - RING_PX; + const glyphTop = + COUNT_GLYPH_TOP_MIN_PX + + (COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown - + radius; + // Width-only metrics use half the 12 px type size on each side of the baseline. + const ascent = metrics.actualBoundingBoxAscent ?? 6; + const descent = metrics.actualBoundingBoxDescent ?? 6; + const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2; + // Each row must clear the ring at the edge where the circle is narrowest. + const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2)); + const extra = Math.max( + 0, + Math.ceil( + Math.max( + metrics.width + 2 * COUNT_TEXT_PADDING_PX - chordAt(labelY + descent), + glyphHeight * GLYPH_ASPECT + + 2 * COUNT_GLYPH_PADDING_PX - + chordAt(glyphTop), + ), + ), + ); + return { + text, + width: height + extra, + height, + glyphHeight, + glyphBottom: glyphTop + glyphHeight, + labelY, + }; } /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ @@ -65,9 +209,8 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { const merged = mergeCountCells( visible, project, - (count) => widthForText(formatCameraCount(count)), - COUNT_MARKER_PX, - COUNT_MERGE_DISTANCE_PX, + sizeFor, + COUNT_MERGE_GAP_PX, ); if (merged.length === visible.length) break; visible = merged; @@ -77,8 +220,7 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { const cell = visible[i]; const marker = markers[i] ?? (markers[i] = { focus: 1 }); const last = marker.cell; - const text = formatCameraCount(cell.count); - const width = widthForText(text); + const size = sizeFor(cell.count); if ( !last || last.count !== cell.count || @@ -98,10 +240,14 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ) { changed = true; } - changed ||= text !== marker.text || width !== marker.width; + changed ||= + size.text !== marker.text || + size.width !== marker.width || + size.glyphBottom !== marker.glyphBottom || + size.labelY !== marker.labelY; marker.cell = cell; - marker.text = text; - marker.width = width; + Object.assign(marker, size); + marker.glyph = glyphFor(size.glyphHeight, dpr, CAMERA_GREEN); // Paint never grows the hit buffer, even when a pan reveals every group. hits[i] ??= {}; } @@ -111,6 +257,12 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { if (changed) lane?.requestPaint(); } + /** Attach the raster for the current overlay density to each visible group. */ + function refreshGlyphs() { + for (const marker of markers) + marker.glyph = glyphFor(marker.glyphHeight, dpr, CAMERA_GREEN); + } + /** Draw at device density using the host's CSS-pixel transform and projection. */ function paint(frame) { if (!markers.length) { @@ -121,7 +273,10 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { } hitCount = 0; const { ctx, occluder, viewProjectionMatrix: m } = frame; - const height = COUNT_MARKER_PX; + if (dpr !== frame.dpr) { + dpr = frame.dpr; + refreshGlyphs(); + } ctx.save(); try { ctx.font = FONT; @@ -129,6 +284,7 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ctx.textBaseline = 'middle'; for (let i = 0; i < markers.length; i++) { const marker = markers[i]; + const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) @@ -155,22 +311,36 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ctx.globalAlpha = marker.focus; ctx.beginPath(); ctx.roundRect( - rect.x + 2, - rect.y + 2, - rect.w - 4, - height - 4, - height / 2 - 2, + rect.x + STROKE_INSET, + rect.y + STROKE_INSET, + rect.w - 2 * STROKE_INSET, + height - 2 * STROKE_INSET, + height / 2 - STROKE_INSET, ); ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; - ctx.lineWidth = 4; + ctx.lineWidth = RING_PX + 2 * RIM_PX; ctx.stroke(); ctx.fillStyle = '#0e1720'; ctx.fill(); - ctx.strokeStyle = RING; - ctx.lineWidth = 2; + ctx.strokeStyle = CAMERA_GREEN; + ctx.lineWidth = RING_PX; ctx.stroke(); - ctx.fillStyle = RING; - ctx.fillText(marker.text, x, y); + ctx.fillStyle = CAMERA_GREEN; + const glyph = marker.glyph; + if (glyph) { + ctx.drawImage( + glyph.canvas, + glyph.left, + glyph.top, + glyph.width, + glyph.height, + x - glyph.drawWidth / 2, + y + marker.glyphBottom - glyph.drawHeight, + glyph.drawWidth, + glyph.drawHeight, + ); + } + ctx.fillText(marker.text, x, y + marker.labelY); rect.cell = marker.cell; hitCount++; } diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index e728d5707d..17ed1ae561 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -71,11 +71,38 @@ export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; -// Diameter of a grouped camera marker in CSS pixels. -export const COUNT_MARKER_PX = 34; +// Diameter at one camera before applying the size limits, in CSS pixels. +export const COUNT_BASE_PX = 38; -// Separation of two circular counts, including a four-pixel gap between rings. -export const COUNT_MERGE_DISTANCE_PX = COUNT_MARKER_PX + 4; +// Extra diameter for each tenfold increase in camera count. +export const COUNT_PX_PER_DECADE = 5; + +// Minimum height of a count marker in CSS pixels. +export const COUNT_MIN_HEIGHT_PX = 40; + +// Maximum height of a count marker in CSS pixels. +export const COUNT_MAX_HEIGHT_PX = 58; + +// Clear fill between the count and the inside of the ring, in CSS pixels. +export const COUNT_TEXT_PADDING_PX = 6; + +// Height of the camera glyph in the smallest and the largest marker. +export const COUNT_GLYPH_MIN_PX = 7.5; +export const COUNT_GLYPH_MAX_PX = 10; + +// Clear fill above the glyph in the smallest and the largest marker. +export const COUNT_GLYPH_TOP_MIN_PX = 3; +export const COUNT_GLYPH_TOP_MAX_PX = 4; + +// Clear fill between the glyph's top corners and the inside of the ring. +export const COUNT_GLYPH_PADDING_PX = 2; + +// The middle of the digits sits this share of the inner radius below the +// marker's centre, which leaves the glyph clear of the count. +export const COUNT_LABEL_DROP = 0.2; + +// Minimum gap between the outer rims of two separate markers. +export const COUNT_MERGE_GAP_PX = 4; // Recheck moved centres and wider labels while bounding work on motion ticks. export const COUNT_MERGE_PASSES = 3; @@ -194,25 +221,30 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({ * 2× display draws it at 60 device px, and it stays sharp there. */ -export const CAMERA_ICON = (() => { +function cameraIcon(neutral) { + const tone = (original, gray) => (neutral ? gray : original); + const stroke = tone('#75e7ff', '#fff'); const svg = ` - - - + + + - - - - - + + + + + `; return 'data:image/svg+xml;base64,' + btoa(svg); -})(); +} + +export const CAMERA_ICON = cameraIcon(false); +export const IDLE_CAMERA_ICON = cameraIcon(true); /** * Seed camera definitions used when no live sources are available. @@ -450,7 +482,10 @@ export const CAMERA_SEEDS = [ // Visual style constants: renderer colours, [r, g, b, a] in 0..1 // --------------------------------------------------------------------------- -export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88); +/** Shared accent for idle still cameras and grouped cameras. */ +export const CAMERA_GREEN = '#5dff8f'; + +export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN); export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95); diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index d041a1c681..c794519295 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -4,6 +4,7 @@ import { isHeadingEstimated } from './headingConfidence.js'; import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, + IDLE_CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, ACTIVE_COVERAGE_CENTER, @@ -13,7 +14,6 @@ import { IDLE_COVERAGE_EDGE_MUTED, ACTIVE_COVERAGE_EDGE_DEPTHFAIL, IDLE_COVERAGE_COLOR, - COUNT_MARKER_PX, VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, @@ -33,6 +33,10 @@ import { poseProjector } from '../../geo/frustum.js'; import { horizonFrom } from '../../geo/horizon.js'; import { distance } from '../../geo/vector.js'; +const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR }; +const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR }; +const LIVE_ICON_STYLE = { image: CAMERA_ICON, color: LIVE_CAMERA_COLOR }; + /** An RGBA colour with another alpha. */ const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha]; @@ -164,9 +168,8 @@ export function createRendering({ return { id, pos: copyPoint(record.position), - image: CAMERA_ICON, + ...cameraIconStyleFor(record), size: [CAMERA_ICON_PX, CAMERA_ICON_PX], - color: cameraColorFor(record), scale: 1, scaleByDistance: CAMERA_SCALE_BY_DISTANCE, disableDepthTest: Infinity, @@ -215,12 +218,12 @@ export function createRendering({ icons.put({ ...item, pos: copyPoint(record.position) }); } - /** Icon color: active wins, then live-capable video feeds, then idle stills. */ - function cameraColorFor(record) { + /** Select the sprite and tint together when a camera changes state. */ + function cameraIconStyleFor(record) { if (record.camera.id === layerState._activeCameraId) - return ACTIVE_CAMERA_COLOR; - if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR; - return IDLE_CAMERA_COLOR; + return ACTIVE_ICON_STYLE; + if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_ICON_STYLE; + return IDLE_ICON_STYLE; } const { @@ -326,7 +329,7 @@ export function createRendering({ marker.pos, true, marker.width, - COUNT_MARKER_PX, + marker.height, marker.focus, ); if (factor !== null) marker.focus = factor; @@ -611,7 +614,7 @@ export function createRendering({ for (const record of layerState._records) { const isActive = record.camera.id === activeId; const icon = patchedCameraIcon(record.camera.id, { - color: cameraColorFor(record), + ...cameraIconStyleFor(record), scale: isActive ? 1.25 : 1.0, }); if (icon) restyled.push(icon); diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index aa53c5ab0c..6d4600ec3b 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -1,7 +1,7 @@ // src/layers/cctv/rendering.test.mjs // Icon colors under focus de-emphasis (#1200): the focus pass fades each icon // from the same base color the coverage refresh assigns, so a video-feed camera -// stays violet while it dims instead of falling back to the idle cyan. +// stays violet while it dims instead of falling back to the idle green. // Teardown lets go of the icon set of the viewer that drew it. import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -114,6 +114,32 @@ test('focus de-emphasis fades each icon from its own color', () => { } }); +test('focus uses the painted half-width and half-height of each count', () => { + const markers = [ + { width: 40, height: 40 }, + { width: 72, height: 58 }, + ]; + const sizes = []; + const rendering = createRendering({ + state: { _counts: { markers } }, + services: { + focus: { + focusPassIsNeeded: () => true, + advanceSpriteFocus(_owner, { spriteHalfWidthPx, spriteHalfHeightPx }) { + sizes.push([spriteHalfWidthPx, spriteHalfHeightPx]); + return { factor: 1 }; + }, + focusAlphaNeedsWrite: () => false, + }, + }, + }); + rendering.applyCctvFocusDeemphasis({}); + assert.deepEqual(sizes, [ + [20, 20], + [36, 29], + ]); +}); + test('the icons go with the viewer that drew them, whichever tears down', () => { const first = {}; const second = {}; From 65942008bf1b23b1ff2a88046bee9d9934f87141 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 21:23:41 +0400 Subject: [PATCH 5/9] fix(cctv): count a lone camera in the marker it sits against A ground cell with one camera always drew its icon, so at some zooms a camera poked out from under a count marker with its own callout. An icon closer than the merge gap to a count marker now joins that marker: the count grows by one and the icon, its callout and its card are not drawn. Two lone cameras with no count beside them stay two icons, and the active camera always keeps its own icon. --- changelog.d/1808-cctv-camera-counts.md | 9 ++-- docs/CURRENT-STATE.md | 4 +- src/data/cctvCellCounts.js | 4 ++ src/data/cctvCellCounts.test.mjs | 41 ++++++++++++++++++ src/data/cctvViewThinning.test.mjs | 60 ++++++++++++++++++++------ src/layers/cctv/countMarkers.js | 18 ++++++-- src/layers/cctv/policy.js | 4 ++ src/layers/cctv/rendering.js | 9 ++-- 8 files changed, 125 insertions(+), 24 deletions(-) diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 7ffb4bd262..8de3034801 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -1,7 +1,8 @@ - Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a ground cell with two or more cameras is one round marker with a small camera icon and the count (`999`, `1.7K`, `12K` in every language); it grows with - the count, merges with a neighbour it would overlap, and a click zooms in - until the group splits. The camera layer's colour is now green: count - markers and idle single cameras share it, the active camera stays gold and - live-video cameras stay violet (gekh, #1808). + the count, merges with a neighbour it would overlap, takes in a lone camera + whose icon would sit against it, and a click zooms in until the group + splits. The camera layer's colour is now green: count markers and idle + single cameras share it, the active camera stays gold and live-video cameras + stay violet (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4c1669a931..a6069e262b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1956,7 +1956,9 @@ The CCTV layer draws only the cameras on or near the screen. Zoomed out, a ground cell containing multiple cameras shows, at their centre, a marker with a small green camera pictogram under its top edge and the count just below its middle. The marker grows with the count and is drawn on the world overlay at -the same resolution as camera callouts. +the same resolution as camera callouts. A lone camera whose icon would sit +within 4 px of a marker is counted in that marker instead of being drawn; the +active camera always keeps its own icon. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 0543925ed2..bf746f6e1a 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -91,6 +91,8 @@ function collectNeighbors(marker, grid, members, gap) { const bucket = grid.get(`${marker.col + col},${marker.row + row}`); if (!bucket) continue; for (const other of bucket) { + // Lone cameras join a count beside them, never each other. + if (marker.cell.count === 1 && other.cell.count === 1) continue; // Distance between the horizontal centre segments of the two pills. const extra = marker.halfSegment + other.halfSegment; const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); @@ -107,6 +109,8 @@ function collectNeighbors(marker, grid, members, gap) { /** * Merge connected groups of overlapping horizontal pills. Each marker occupies * one grid bucket. Even the widest pill can only touch its eight neighbors. + * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and + * joins a count it touches; two such cells alone stay apart. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index 49eb59faaf..66d9702c36 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -94,3 +94,44 @@ test('stadiums merge by their own radii and segment lengths across grid boundari // Large pills can reach across a row boundary at their full diameter. check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]); }); + +test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => { + const sizes = { + 1: { width: 24, height: 24 }, + 9: { width: 40, height: 40 }, + }; + const gap = 4; + const check = (counts, positions, expected) => { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + gap, + ); + assert.deepEqual( + groups.map((cell) => cell.count), + expected, + ); + // A lone camera that stays apart is still its own cell object. + assert.deepEqual( + groups.filter((cell) => cell.count === 1), + cells.filter((cell) => groups.includes(cell) && cell.count === 1), + ); + }; + const at = (x, y = 100) => ({ x, y }); + // Radii 20 and 12: the four-pixel gap is clear at 36 pixels. + check([9, 1], [at(100), at(135)], [10]); + check([9, 1], [at(100), at(136)], [9, 1]); + check([1, 9], [at(135), at(100)], [10]); + // Overlapping icons with no count beside them stay two icons. + check([1, 1], [at(100), at(110)], [1, 1]); + // A count takes every lone camera it touches, on either side. + check([1, 9, 1], [at(70), at(100), at(130)], [11]); + // A lone camera that only touches another lone camera is left alone. + check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index e78810b87a..0b0be24703 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -332,6 +332,43 @@ test('a crowded cell shows its count and a singleton keeps its icon', () => { ); }); +test('a lone camera beside a count joins it, unless it is the active camera', () => { + // Three cameras north of a cell boundary, one 111 m away south of it. + const { records } = recordsAt([ + [0.0005, 0.0005], + [0.0006, 0.0005], + [0.0007, 0.0005], + [0.0006, -0.0005], + [0.2, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-4']); + assert.deepEqual(_viewRecordIdsForTest(), ['cam-4']); + assert.deepEqual( + markers().map((item) => item.cell.count), + [4], + ); + assert.deepEqual( + cctvLayer.getDetectableObjects().map((o) => o.sourceId), + ['cam-4'], + ); + // The picker still offers one camera from each ground cell. + assert.equal(cctvLayer.getUIState().cameraIndex.length, 3); + + seedCoverage({ + viewer: viewerAt(20_000), + records, + activeCameraId: 'cam-3', + }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-3', 'cam-4']); + assert.deepEqual( + markers().map((item) => item.cell.count), + [3], + ); +}); + test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ @@ -698,20 +735,22 @@ test('overlapping cells merge at their weighted centre and keep every camera in }); refreshHorizonCulling(); const shown = markers(); - assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']); + // The lone camera 111 m south sits under the merged marker and joins it; + // the active one beside it keeps its own icon. + assert.deepEqual(shownIds(records), ['cam-7']); assert.equal( shown.reduce((sum, m) => sum + m.cell.count, 0), - 7, + 8, ); assert.deepEqual( shown.map((m) => m.cell.count).sort((a, b) => a - b), - [2, 5], + [2, 6], ); - const merged = shown.find((m) => m.cell.count === 5); + const merged = shown.find((m) => m.cell.count === 6); assert.ok( Cesium.Cartesian3.distance( merged.pos, - Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), + Cesium.Cartesian3.fromDegrees(0.004 / 6, -0.001 / 6, 10), ) < 0.01, ); const positions = shown.map((m) => [m.cell.key, m.pos, m.height, m.width]); @@ -720,13 +759,10 @@ test('overlapping cells merge at their weighted centre and keep every camera in clickMarker(merged); const { bounds } = flights.at(-1); assert.ok( - records - .slice(0, 5) - .every( - (r) => - Cesium.Cartesian3.distance(r.position, bounds.center) < - bounds.radius, - ), + [...records.slice(0, 5), records[8]].every( + (r) => + Cesium.Cartesian3.distance(r.position, bounds.center) < bounds.radius, + ), ); assert.ok( bounds.radius < 300, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index b6f38e7fe7..84831c12d4 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -19,6 +19,7 @@ import { COUNT_GLYPH_PADDING_PX, COUNT_LABEL_DROP, COUNT_MERGE_GAP_PX, + COUNT_SINGLE_ICON_PX, COUNT_MERGE_PASSES, } from './policy.js'; @@ -28,6 +29,10 @@ const GLYPH_ASPECT = 1.5; const RING_PX = 2; const RIM_PX = 1; const STROKE_INSET = RIM_PX + RING_PX / 2; +const SINGLE_ICON = Object.freeze({ + width: COUNT_SINGLE_ICON_PX, + height: COUNT_SINGLE_ICON_PX, +}); /** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ function rasterizeGlyph(canvas, image, size, dpr, color) { @@ -198,9 +203,9 @@ export function createCountMarkers( /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ function update(cells, project) { - let visible = cells - .filter((cell) => cell.count > 1) - .sort((a, b) => a.key.localeCompare(b.key)); + // Lone cameras take part so that one beside a count joins it. + let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); + const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); for ( let pass = 0; pass < COUNT_MERGE_PASSES && visible.length > 1; @@ -209,12 +214,17 @@ export function createCountMarkers( const merged = mergeCountCells( visible, project, - sizeFor, + footprint, COUNT_MERGE_GAP_PX, ); if (merged.length === visible.length) break; visible = merged; } + // A lone camera that is no longer its own entry now counts in a marker. + const apart = new Set(visible); + for (const cell of cells) + if (cell.count === 1) cell.absorbed = !apart.has(cell); + visible = visible.filter((cell) => cell.count > 1); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 17ed1ae561..06fc5788fd 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -104,6 +104,10 @@ export const COUNT_LABEL_DROP = 0.2; // Minimum gap between the outer rims of two separate markers. export const COUNT_MERGE_GAP_PX = 4; +// On-screen size of a lone camera's icon when testing it against a count +// marker: an icon closer than the merge gap joins that count. +export const COUNT_SINGLE_ICON_PX = 24; + // Recheck moved centres and wider labels while bounding work on motion ticks. export const COUNT_MERGE_PASSES = 3; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index c794519295..2d50592ac3 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -435,23 +435,26 @@ export function createRendering({ cell.rank = rank; } } + // Marks each lone camera that a count marker beside it has taken in. + layerState._counts?.update(visibleCells, project); for (const cell of visibleCells) { const record = cell.winner; picker.push(record); record.pickerPass = pass; - if (cell.count === 1) { + if (cell.count === 1 && !cell.absorbed) { record.viewPass = pass; shown.push(record); } } - layerState._counts?.update(visibleCells, project); const writes = []; let coverageChanged = false; let cardsChanged = false; for (const record of layerState._records) { const cell = record.viewCell; record.viewCell = null; - const grouped = Boolean(cell?.winner && cell.count > 1); + const grouped = Boolean( + cell?.winner && (cell.count > 1 || cell.absorbed), + ); if (grouped !== !!record.viewGrouped) { const id = record.camera.id; coverageChanged ||= layerState._coverageCohort?.has(id); From 2e18673df89e52644da634967239f11b018b5ae8 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 00:03:34 +0400 Subject: [PATCH 6/9] fix(cctv): stand cameras and count markers on the drawn terrain When the terrain height batch loses a chunk to the rate limit, the cameras in it keep a sea-level fallback height. In the mountains that put them far under the surface, so the view pass judged them by a point that was not where they are drawn: a tilted view dropped the count marker, a click on the marker framed empty ground, and icons drifted on tilt and pan. - A camera with no real ground height takes the height of the terrain the globe draws once it is near the screen (up to 300 reads a pass, through the height service), and a later answer from the batch replaces it. - A count marker is anchored to the drawn terrain under its centre, and a click frames that ground. - Cameras on one mount draw side by side, 30 px apart, each with its own callout, instead of as one icon with several callouts. The photoreal map stack is not covered: terrain is not the surface there. --- changelog.d/1808-cctv-camera-counts.md | 5 +- docs/CURRENT-STATE.md | 12 +- src/data/cctvCellCounts.js | 28 +++- src/data/cctvViewThinning.test.mjs | 187 ++++++++++++++++++++++++- src/layers/cctv/controls.js | 3 +- src/layers/cctv/countMarkers.js | 25 +++- src/layers/cctv/ground.js | 115 +++++++++------ src/layers/cctv/policy.js | 8 ++ src/layers/cctv/rendering.js | 139 ++++++++++++++++-- 9 files changed, 453 insertions(+), 69 deletions(-) diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 8de3034801..6b565362f9 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -5,4 +5,7 @@ whose icon would sit against it, and a click zooms in until the group splits. The camera layer's colour is now green: count markers and idle single cameras share it, the active camera stays gold and live-video cameras - stay violet (gekh, #1808). + stay violet. Cameras that share one mount draw side by side instead of as + one icon with several callouts, and a camera the terrain height service + never answered for stands on the drawn terrain instead of drifting under + it (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index a6069e262b..585f3e1138 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1958,7 +1958,17 @@ a small green camera pictogram under its top edge and the count just below its middle. The marker grows with the count and is drawn on the world overlay at the same resolution as camera callouts. A lone camera whose icon would sit within 4 px of a marker is counted in that marker instead of being drawn; the -active camera always keeps its own icon. +active camera always keeps its own icon. On a globe map a marker stands on +the drawn terrain under its cameras' mean position, and a click frames that +ground. A camera the terrain height batch never answered for (no prior, or +the geoid fallback a failed or rate-limited chunk leaves) takes the terrain +the globe draws under it as its ground once it is near the screen, up to 300 +cameras a view pass, and reads it again from less than half as far; a batch +answer that arrives later replaces it. Without this such a camera sits near +sea level, drifts across mountain terrain as the view tilts or pans, and +never leaves its count. Cameras on one mount (the same point to about a +metre) draw side by side, 30 px apart, once they show as icons; their records +keep the mount's position. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index bf746f6e1a..bbafd051ad 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -43,12 +43,28 @@ export function addCellCamera(cell, camera) { cell.high = Math.max(cell.high, height); } -/** Geographic mean on the globe surface at the mean mount height. */ +/** Mean longitude and latitude of a cell's mounts, in degrees. */ +export function cellLonLat(cell) { + return { + lon: cell.lonSum / (1e7 * cell.count), + lat: cell.latSum / (1e7 * cell.count), + }; +} + +/** + * Geographic mean of the mounts. Its height is the drawn ground under it + * when the cell carries one (`groundM`), since a camera nobody has looked at + * yet may still hold a catalog height far from the terrain; otherwise the + * mean mount height. + */ export function cellCenter(cell) { + const { lon, lat } = cellLonLat(cell); return fromDegrees( - cell.lonSum / (1e7 * cell.count), - cell.latSum / (1e7 * cell.count), - cell.heightSum / (100 * cell.count), + lon, + lat, + Number.isFinite(cell.groundM) + ? cell.groundM + : cell.heightSum / (100 * cell.count), ); } @@ -56,7 +72,9 @@ export function cellCenter(cell) { export function cellBounds(cell) { const lat = (cell.north + cell.south) / 2; const lon = (cell.east + cell.west) / 2; - const height = (cell.high + cell.low) / 2; + const height = Number.isFinite(cell.groundM) + ? cell.groundM + : (cell.high + cell.low) / 2; // The parallel nearest the equator bounds the width of every row. const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180; // Half the diagonal plus 20% padding on every side. diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 0b0be24703..7293e1aac8 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -55,7 +55,7 @@ function recordsAt(lonLats) { * equator, north up, through a camera port: the view pass projects the * cameras from its pose. */ -function viewerAt(heightM, lonDeg = 0, flights = []) { +function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); const down = Cesium.Cartesian3.normalize( Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), @@ -84,6 +84,7 @@ function viewerAt(heightM, lonDeg = 0, flights = []) { bindRenderer(viewer, { camera: port, canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + ...ports, }), ); return viewer; @@ -369,6 +370,190 @@ test('a lone camera beside a count joins it, unless it is the active camera', () ); }); +test('cameras the height batch never answered for take the drawn terrain', () => { + // Two mounts on one pole in the mountains and a lone camera. The batch + // answered for none of them, so they hold the catalog height (10 m), far + // under the terrain; a fourth camera has its answer and keeps it. + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.2, 0], + [0.3, 0], + ]); + // A failed chunk leaves the geoid fallback; a real answer is 'reearth'. + records[2].groundPrior = { ellipsoid: -20, source: 'geoid-fallback' }; + records[3].groundPrior = { ellipsoid: 2, source: 'reearth' }; + const flights = []; + const samples = []; + let terrain = 1872.4; + let globeShown = true; + const ports = { + globe: { isGlobeVisible: () => globeShown }, + query: { + sampleHeightNow(point, options) { + samples.push([point, options]); + return terrain; + }, + }, + }; + const heightOf = (position) => + Cesium.Cartographic.fromCartesian(position).height; + const icon = (i) => _cctvIconsForTest().item(records[i].camera.id); + seedCoverage({ viewer: viewerAt(20_000, 0, flights, ports), records }); + + // The photoreal stack hides the globe: terrain is not the surface there. + globeShown = false; + refreshHorizonCulling(); + assert.equal(samples.length, 0); + assert.ok(Math.abs(heightOf(records[0].position) - 10) < 0.01); + + // Terrain that has not loaded leaves a camera where it is, to be read again. + globeShown = true; + terrain = null; + refreshHorizonCulling(); + assert.ok(samples.length >= 3); + assert.ok(samples.every(([, options]) => options.against === 'terrain')); + assert.equal(records[0].groundPrior, undefined); + assert.ok(Math.abs(heightOf(markers()[0].pos) - 10) < 0.01); + + terrain = 1872.4; + refreshHorizonCulling(); + // Each unanswered camera stands its mount height above the drawn terrain. + for (const i of [0, 1, 2]) { + assert.equal(records[i].groundPrior.source, 'drawn-terrain'); + assert.ok(Math.abs(records[i].camera.absoluteHeightM - 1880.4) < 1e-9); + assert.ok(Math.abs(heightOf(records[i].position) - 1880.4) < 0.01); + assert.ok(Math.abs(heightOf(icon(i).pos) - 1880.4) < 0.01); + } + // The answered one is left alone. + assert.equal(records[3].groundPrior.source, 'reearth'); + assert.ok(Math.abs(heightOf(records[3].position) - 10) < 0.01); + // The count stands on the terrain and its click frames the ground there. + const [marker] = markers(); + assert.equal(marker.cell.count, 2); + assert.ok(Math.abs(heightOf(marker.pos) - 1872) < 0.01); + clickMarker(marker); + assert.ok(Math.abs(heightOf(flights.at(-1).bounds.center) - 1872) < 0.01); + + // Read once: the same view does not read a camera's terrain again. + samples.length = 0; + refreshHorizonCulling(); + assert.ok(samples.every(([point]) => Math.abs(point.lat - 0.0005) < 1e-9)); + + // From less than half as far the finer terrain is read and replaces it. + terrain = 1890; + seedCoverage({ viewer: viewerAt(9_000, 0, flights, ports), records }); + refreshHorizonCulling(); + assert.ok(Math.abs(records[0].camera.absoluteHeightM - 1898) < 1e-9); + assert.equal(records[3].groundPrior.source, 'reearth'); +}); + +test('a tilted view keeps the count of cameras that stood under the terrain', () => { + // The same pole seen from 200 m above the terrain and 1 km away, a view + // 11 degrees below the horizontal. Projected from its catalog height the + // pole falls below the padded screen and its count vanishes; on the + // terrain it is in the middle of the view. + const { records } = recordsAt([ + [0, 0], + [0, 0], + ]); + const ground = 1872; + const eye = Cesium.Cartesian3.fromDegrees(0, -0.009, ground + 200); + const target = Cesium.Cartesian3.fromDegrees(0, 0, ground); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + const plain = ({ x, y, z }) => ({ x, y, z }); + const { port } = fakeCameraPort({ + pose: { + lon: 0, + lat: -0.009, + height: ground + 200, + position: plain(eye), + direction: plain(direction), + up: plain(up), + right: plain(right), + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, + }, + }); + let terrain = null; + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, + canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + globe: { isGlobeVisible: () => true }, + query: { sampleHeightNow: () => terrain }, + }), + ); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal(markers().length, 0, 'under the terrain it is off the screen'); + terrain = ground; + refreshHorizonCulling(); + assert.deepEqual( + markers().map((item) => item.cell.count), + [2], + ); +}); + +test('cameras on one mount draw side by side once they show as icons', () => { + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + // Close enough that every camera shows: about 0.87 m a pixel. + seedCoverage({ viewer: viewerAt(460), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-0', 'cam-1', 'cam-2']); + const icons = _cctvIconsForTest(); + const [a, b, c] = records.map((record) => icons.item(record.camera.id).pos); + // 30 px apart along the screen's horizontal, centred on the shared mount. + const metres = Cesium.Cartesian3.distance(a, b); + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; + assert.ok(Math.abs(metres / metresPerPixel - 30) < 0.5); + const middle = Cesium.Cartesian3.midpoint(a, b, new Cesium.Cartesian3()); + assert.ok(Cesium.Cartesian3.distance(middle, records[0].position) < 1e-6); + // The third camera, 11 m away, has a mount of its own. + assert.ok(Cesium.Cartesian3.distance(c, records[2].position) < 1e-6); + // The records keep the mount; callouts follow the drawn icons. + assert.ok( + Cesium.Cartesian3.distance(records[0].position, records[1].position) < 1e-9, + ); + const callouts = cctvLayer.getDetectableObjects(); + for (const [i, pos] of [a, b].entries()) { + const callout = callouts.find((o) => o.sourceId === `cam-${i}`); + assert.ok(Cesium.Cartesian3.distance(callout.position, pos) < 1e-9); + } + // An unchanged view writes nothing more. + const before = [a, b]; + refreshHorizonCulling(); + assert.equal(icons.item('cam-0').pos, before[0]); + assert.equal(icons.item('cam-1').pos, before[1]); + + // Grouped again, both icons are back on the mount for their next showing. + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), []); + for (const i of [0, 1]) + assert.ok( + Cesium.Cartesian3.distance( + _cctvIconsForTest().item(`cam-${i}`).pos, + records[i].position, + ) < 1e-6, + ); +}); + test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ diff --git a/src/layers/cctv/controls.js b/src/layers/cctv/controls.js index 1f83b7468a..09ba71f72b 100644 --- a/src/layers/cctv/controls.js +++ b/src/layers/cctv/controls.js @@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) { for (let i = start; i < records.length; i += stride) { const camera = records[i].camera; objects.push({ - position: records[i].position, + // A camera sharing its mount is drawn beside its mates. + position: records[i].spreadPosition ?? records[i].position, sourceId: camera.id, // Short semantic code where the id is opaque (see cameraDisplayCode). id: `CAM-${camera.code || camera.id}`, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 84831c12d4..89fa278bb5 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -1,5 +1,6 @@ import { cellCenter, + cellLonLat, formatCameraCount, mergeCountCells, } from '../../data/cctvCellCounts.js'; @@ -201,16 +202,32 @@ export function createCountMarkers( }; } - /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ - function update(cells, project) { + /** + * Reuse marker slots in ground-key order, and invalidate only changed frames. + * `groundHeight(lon, lat)` answers the drawn terrain height in metres, or + * null where it is not loaded; with it a count stands on the ground it + * marks whatever heights its cameras hold. + */ + function update(cells, project, groundHeight = null) { // Lone cameras take part so that one beside a count joins it. let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); + /** A lone camera keeps its icon's own position; a count goes to ground. */ + const ground = (list) => { + if (!groundHeight) return; + for (const cell of list) { + if (cell.count === 1 || cell.groundM !== undefined) continue; + const { lon, lat } = cellLonLat(cell); + const height = groundHeight(lon, lat); + cell.groundM = Number.isFinite(height) ? Math.round(height) : null; + } + }; for ( let pass = 0; pass < COUNT_MERGE_PASSES && visible.length > 1; pass++ ) { + ground(visible); const merged = mergeCountCells( visible, project, @@ -225,6 +242,7 @@ export function createCountMarkers( for (const cell of cells) if (cell.count === 1) cell.absorbed = !apart.has(cell); visible = visible.filter((cell) => cell.count > 1); + ground(visible); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; @@ -236,7 +254,8 @@ export function createCountMarkers( last.count !== cell.count || last.latSum !== cell.latSum || last.lonSum !== cell.lonSum || - last.heightSum !== cell.heightSum + last.heightSum !== cell.heightSum || + last.groundM !== cell.groundM ) { marker.pos = cellCenter(cell); changed = true; diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 0b57cba135..84db00b13e 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -214,56 +214,82 @@ export function createGround({ state: layerState, services, parts, source }) { let applied = 0; let moved = 0; for (let i = 0; i < records.length && i < priors.length; i++) { - const record = records[i]; - const prior = priors[i]; - if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue; - // Stale-record guard: init() may have re-run (destroy/init cycle) while - // the batch was in flight — only touch records still live in the map. - if (layerState._recordById.get(record.camera.id) !== record) continue; - record.groundPrior = prior; - // Keep the cheap pre-enable altitude consistent for records whose - // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). - if (!record.frustumPositions) { - record.camera.absoluteHeightM = - prior.ellipsoid + record.camera.mountHeightM; - } - // Cameras without geometry only move their icon onto the prior, so the - // view pass projects the right point; their frustums are built when - // they enter the view, as recomputing the whole catalog here would - // stall a large one. - if (!record.frustumGeometry) { - if (record.position) { - // In place: the record keeps its position object. - const { x, y, z } = fromDegrees( - record.camera.lon, - record.camera.lat, - record.camera.absoluteHeightM, - ); - record.position.x = x; - record.position.y = y; - record.position.z = z; - parts.rendering.moveCameraIcon(record); - moved += 1; - } - continue; - } - const regime = currentSurfaceRegime(); - if (regime === 'terrain-globe') { - // Prior IS the resolution — re-latch onto the fresh value. - parts.geometry.updateRecordGeometry(record, { sampleGround: false }); - applied += 1; - } else if (!Number.isFinite(record.groundSamples['google-3d'])) { - // Still awaiting the shared floor: snap interim geometry onto the exact - // prior (pure recompute; the shared cell may refine later). - parts.geometry.applyFrustumGeometry(record, prior.ellipsoid); - applied += 1; - } + const outcome = applyGroundPrior(records[i], priors[i]); + if (outcome === 'moved') moved += 1; + else if (outcome === 'applied') applied += 1; } if (moved && parts.rendering.refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); if (applied || moved) parts.presentation.notifyListeners(); } + /** + * Gives one live record a ground prior: `'moved'` when only its icon went + * onto the prior in place, `'applied'` when its geometry was recomputed, + * null when nothing changed. Pure recomputes, no scene queries. + */ + function applyGroundPrior(record, prior) { + if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null; + // Stale-record guard: init() may have re-run (destroy/init cycle) while + // the batch was in flight — only touch records still live in the map. + if (layerState._recordById.get(record.camera.id) !== record) return null; + record.groundPrior = prior; + // Keep the cheap pre-enable altitude consistent for records whose + // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). + if (!record.frustumPositions) { + record.camera.absoluteHeightM = + prior.ellipsoid + record.camera.mountHeightM; + } + // Cameras without geometry only move their icon onto the prior, so the + // view pass projects the right point; their frustums are built when + // they enter the view, as recomputing the whole catalog here would + // stall a large one. + if (!record.frustumGeometry) { + if (!record.position) return null; + // In place: the record keeps its position object. + const { x, y, z } = fromDegrees( + record.camera.lon, + record.camera.lat, + record.camera.absoluteHeightM, + ); + record.position.x = x; + record.position.y = y; + record.position.z = z; + parts.rendering.moveCameraIcon(record); + return 'moved'; + } + const regime = currentSurfaceRegime(); + if (regime === 'terrain-globe') { + // Prior IS the resolution — re-latch onto the fresh value. + parts.geometry.updateRecordGeometry(record, { sampleGround: false }); + return 'applied'; + } + if (!Number.isFinite(record.groundSamples['google-3d'])) { + // Still awaiting the shared floor: snap interim geometry onto the exact + // prior (pure recompute; the shared cell may refine later). + parts.geometry.applyFrustumGeometry(record, prior.ellipsoid); + return 'applied'; + } + return null; + } + + /** + * A camera the height batch never answered for (a failed or rate-limited + * chunk leaves it on the catalog's fabricated ground) takes the terrain + * the globe draws under it as its prior, so that it stands on the surface + * the user sees. `rangeM` is how far the eye was when the terrain was + * read: a closer look reads finer terrain and replaces it, and so does a + * batch answer that arrives later. + * @returns {'moved'|'applied'|null} As `applyGroundPrior`. + */ + function adoptDrawnGround(record, heightM, rangeM) { + return applyGroundPrior(record, { + ellipsoid: heightM, + source: 'drawn-terrain', + rangeM, + }); + } + /** * Task 5: surface-regime change handler ('gev:map-stack-changed' * CustomEvent, dispatched by main.js from MapStackController.onChange). The @@ -399,6 +425,7 @@ export function createGround({ state: layerState, services, parts, source }) { resolveCommittedGroundAnchor, resolveGroundPriors, applyLateGroundPriors, + adoptDrawnGround, handleMapStackChanged, }; } diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 06fc5788fd..87fdaf4c32 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -71,6 +71,14 @@ export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; +// Cameras on one mount (the same point to about a metre) draw side by side, +// this many pixels apart, once they show as icons. +export const VIEW_SITE_SPREAD_PX = 30; + +// Cameras without a ground height that one view pass may read from the drawn +// terrain. The rest wait for the next pass. +export const VIEW_GROUND_READS = 300; + // Diameter at one camera before applying the size limits, in CSS pixels. export const COUNT_BASE_PX = 38; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 2d50592ac3..a2d5a7663c 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -17,6 +17,8 @@ import { VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, + VIEW_SITE_SPREAD_PX, + VIEW_GROUND_READS, } from './policy.js'; import { createIconBook } from '../../render/motion/iconBook.js'; import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js'; @@ -27,6 +29,7 @@ import { findGlobe, findQuery, } from '../../render/rendererOf.js'; +import { heightsOf } from '../../queries/heights.js'; import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js'; import { eastNorthUp } from '../../geo/frames.js'; import { poseProjector } from '../../geo/frustum.js'; @@ -383,6 +386,16 @@ export function createRendering({ const picker = []; const cells = new Map(); const visibleCells = []; + // The terrain the globe draws, where it is the surface (not on the + // photoreal stack) and loaded: null elsewhere. + const heights = heightsOf(layerState._viewer); + const groundHeight = + findQuery(layerState._viewer) && + findGlobe(layerState._viewer)?.isGlobeVisible?.() === true + ? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' }) + : null; + let groundReads = groundHeight ? VIEW_GROUND_READS : 0; + const regrounded = []; for (const record of layerState._records) { const position = record.position; if (!position) continue; @@ -397,20 +410,49 @@ export function createRendering({ (vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared ) continue; - const screen = project(position); + let screen = project(position); + let range = distance(position, viewer); + // A camera the height batch never answered for (no prior, or the + // geoid fallback a failed chunk leaves) sits near sea level, which can + // be kilometres under the terrain: it would project to the wrong + // place, drift as the view moves and measure too far for its cell. + // Anywhere near the screen, it takes the drawn terrain. + const prior = record.groundPrior; + const drawn = prior?.source === 'drawn-terrain'; + if ( + groundReads > 0 && + (!prior || + prior.source === 'geoid-fallback' || + (drawn && prior.rangeM > 2 * range)) && + screen && + screen.x >= -width && + screen.x <= 2 * width && + screen.y >= -height && + screen.y <= 2 * height + ) { + groundReads--; + const ground = groundHeight(record.camera.lon, record.camera.lat); + if (Number.isFinite(ground)) { + if (drawn && Math.abs(ground - prior.ellipsoid) < 1) { + prior.rangeM = range; + } else if (record.frustumGeometry) { + // Recomputing geometry writes draw sets: after this pass. + regrounded.push([record, ground, range]); + } else if ( + parts.ground.adoptDrawnGround(record, ground, range) === 'moved' + ) { + screen = project(position); + range = distance(position, viewer); + } + } + } const nearScreen = screen && screen.x >= minX && screen.x <= maxX && screen.y >= minY && screen.y <= maxY; - const dx = position.x - viewer.x; - const dy = position.y - viewer.y; - const dz = position.z - viewer.z; - const cellM = - VIEW_CELL_PX * - metresPerPixelPerMetre * - Math.sqrt(dx * dx + dy * dy + dz * dz); + const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range; if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) { if (!nearScreen) continue; record.viewPass = record.pickerPass = pass; @@ -435,8 +477,10 @@ export function createRendering({ cell.rank = rank; } } - // Marks each lone camera that a count marker beside it has taken in. - layerState._counts?.update(visibleCells, project); + // A count stands on the drawn terrain too: its cell may be too far for + // its cameras to have been read. Marks each lone camera that a count + // marker beside it has taken in. + layerState._counts?.update(visibleCells, project, groundHeight); for (const cell of visibleCells) { const record = cell.winner; picker.push(record); @@ -446,6 +490,7 @@ export function createRendering({ shown.push(record); } } + spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; let cardsChanged = false; @@ -462,12 +507,21 @@ export function createRendering({ layerState._cardIds?.has(id) || layerState._hoverCardId === id; } record.viewGrouped = grouped; - const item = patchedCameraIcon(record.camera.id, { - show: record.viewPass === pass, - }); + const fields = { show: record.viewPass === pass }; + if (record.spreadPass === pass) { + const drawn = layerState._icons?.item(record.camera.id)?.pos; + if (!drawn || !samePoint(drawn, record.spreadPosition)) + fields.pos = copyPoint(record.spreadPosition); + } else if (record.spreadPosition) { + // No longer beside a mount mate: back onto its own position. + record.spreadPosition = null; + fields.pos = copyPoint(record.position); + } + const item = patchedCameraIcon(record.camera.id, fields); if (item) writes.push(item); } writeCameraIcons(writes); + if (regrounded.length) queueMicrotask(() => reground(regrounded)); const previous = layerState._viewRecords; const changed = previous.length !== shown.length || @@ -483,6 +537,65 @@ export function createRendering({ return changed || pickerChanged; } + /** + * Cameras that have geometry take the drawn terrain after the pass that + * read it, then the view is passed again from their new positions. + */ + function reground(entries) { + let changed = false; + for (const [record, ground, range] of entries) + changed = + parts.ground.adoptDrawnGround(record, ground, range) !== null || + changed; + if (!changed) return; + if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); + parts.presentation.notifyListeners(); + } + + /** + * Cameras on one mount would draw as one icon with several callouts. Among + * the cameras shown, those that share a point to about a metre get draw + * positions side by side along the screen's horizontal, in id order, + * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The + * record's own position is untouched: geometry and cards keep the mount. + */ + function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { + const { right, direction, position: eye } = pose; + if (!right || !direction || shown.length < 2) return; + const mounts = new Map(); + for (const record of shown) { + const { lat, lon } = record.camera; + const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`; + const mates = mounts.get(key); + if (mates) mates.push(record); + else mounts.set(key, [record]); + } + for (const mates of mounts.values()) { + if (mates.length < 2) continue; + mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id)); + for (let i = 0; i < mates.length; i++) { + const record = mates[i]; + const p = record.position; + // A pixel's width on the ground grows with depth along the view. + const depth = + (p.x - eye.x) * direction.x + + (p.y - eye.y) * direction.y + + (p.z - eye.z) * direction.z; + const metres = + (i - (mates.length - 1) / 2) * + VIEW_SITE_SPREAD_PX * + metresPerPixelPerMetre * + depth; + record.spreadPosition = { + x: p.x + right.x * metres, + y: p.y + right.y * metres, + z: p.z + right.z * metres, + }; + record.spreadPass = pass; + } + } + } + /** * Canvas coordinates for world positions, from the eye's pose by the * renderer's perspective projection (geo/frustum.js): one pose read per From 81fe7f88cc7bb0b3b39b6c9463fafabef4ecd63c Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 03:07:04 +0400 Subject: [PATCH 7/9] fix(cctv): settle the review of the count markers Bugs: - Cameras on one mount stay side by side after their geometry is built, so a click or a settled view no longer folds them back into one icon. - A count click yields to a card drawn over the marker and to another layer's object under it, waits while the cockpit or tracking holds the view, and flies at most halfway, so a long chain of cameras still splits. - The active camera's icon is never covered by a count, transparent corners of the marker no longer catch clicks, and a count hidden under the HUD keeps its lone cameras. - A lone camera joins only its nearest count and never bridges two; cameras close enough to draw as icons take part too, at their drawn icon size. - Groups across the antimeridian keep their longitude; the flight frames the highest mount; markers on ground below the ellipsoid stay visible; counts fade outside the Scope circle. - Mounts less than a metre apart count as one mount. - A drawn-terrain height survives a late fallback answer, is read for an unresolved camera and for one projected off the window, is re-read when the terrain under it finishes loading or the terrain source changes, and the read budget no longer goes to the same misses each pass. Cleanup: the glyph draws from one green SVG sprite instead of recolouring pixels, marker-only constants move next to their use, layout tests check behaviour rather than formulas, and docs and comments match the code. docs/I18N.md names the one fixed notation of count badges as an exception. --- changelog.d/1808-cctv-camera-counts.md | 19 +- docs/CURRENT-STATE.md | 47 +- docs/I18N.md | 1 + scripts/format-scope.json | 3 + scripts/package-boundaries.json | 1 + src/app/layers/cctv.js | 3 +- src/data/cameraFraming.js | 2 +- src/data/cctv.test.mjs | 4 +- src/data/cctvCellCounts.js | 114 +++-- src/data/cctvCellCounts.test.mjs | 139 ++++-- src/data/cctvViewPass.test.mjs | 254 +++++++++++ src/data/cctvViewThinning.test.mjs | 572 ++++++++++++++++--------- src/layers/cctv/countMarkers.js | 284 ++++++------ src/layers/cctv/countMarkers.test.mjs | 136 ++++++ src/layers/cctv/ground.js | 28 +- src/layers/cctv/ground.test.mjs | 64 +++ src/layers/cctv/lifecycle.js | 34 +- src/layers/cctv/lifecycle.test.mjs | 34 ++ src/layers/cctv/navigation.js | 33 +- src/layers/cctv/policy.js | 106 +++-- src/layers/cctv/presentation.js | 19 +- src/layers/cctv/rendering.js | 261 ++++++++--- src/layers/cctv/rendering.test.mjs | 1 + src/layers/cctv/selection.js | 28 +- src/layers/cctv/selection.test.mjs | 47 ++ src/layers/cctv/state.js | 12 +- 26 files changed, 1608 insertions(+), 638 deletions(-) create mode 100644 src/data/cctvViewPass.test.mjs create mode 100644 src/layers/cctv/countMarkers.test.mjs create mode 100644 src/layers/cctv/ground.test.mjs diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 6b565362f9..7c87538cd1 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -1,11 +1,8 @@ -- Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a - ground cell with two or more cameras is one round marker with a small camera - icon and the count (`999`, `1.7K`, `12K` in every language); it grows with - the count, merges with a neighbour it would overlap, takes in a lone camera - whose icon would sit against it, and a click zooms in until the group - splits. The camera layer's colour is now green: count markers and idle - single cameras share it, the active camera stays gold and live-video cameras - stay violet. Cameras that share one mount draw side by side instead of as - one icon with several callouts, and a camera the terrain height service - never answered for stands on the drawn terrain instead of drifting under - it (gekh, #1808). +- Zoomed out, a CCTV ground cell with two or more cameras is now one round + marker with a camera icon and the count (`999`, `1.7K`, `12K` in every + language). It grows with the count, merges with markers it would overlap, + takes in a lone camera right beside it, and zooms in on click until the + group splits. Idle cameras and markers are green. The active camera stays + amber and video cameras violet. Cameras on one mount draw side by side, and + a camera the terrain height service never answered for stands on the drawn + terrain (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 585f3e1138..cef2a2699d 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,32 +1953,27 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows, at their centre, a marker with -a small green camera pictogram under its top edge and the count just below its -middle. The marker grows with the count and is drawn on the world overlay at -the same resolution as camera callouts. A lone camera whose icon would sit -within 4 px of a marker is counted in that marker instead of being drawn; the -active camera always keeps its own icon. On a globe map a marker stands on -the drawn terrain under its cameras' mean position, and a click frames that -ground. A camera the terrain height batch never answered for (no prior, or -the geoid fallback a failed or rate-limited chunk leaves) takes the terrain -the globe draws under it as its ground once it is near the screen, up to 300 -cameras a view pass, and reads it again from less than half as far; a batch -answer that arrives later replaces it. Without this such a camera sits near -sea level, drifts across mountain terrain as the view tilts or pans, and -never leaves its count. Cameras on one mount (the same point to about a -metre) draw side by side, 30 px apart, once they show as icons; their records -keep the mount's position. -The count includes cameras beyond the screen edge and excludes cameras beyond -the horizon. Counts that would overlap on screen merge into one that carries -their sum. Clicking a count zooms to its group. Single cameras keep their icons, -and the active camera has its own icon and is excluded from the count. Close -up, even co-located cameras show individually. Ambient cards and coverage -attach to individual cameras. Ground placement has at most two attempts per -camera and view regime. The view pass reruns while the camera moves, paced by -its own cost. The camera picker lists the active camera first, keeps one -representative per visible cell, preferring healthy feeds, and closes with -the count of cameras outside the view. +ground cell with two or more cameras shows one marker at their mean position. A +green camera pictogram sits under its top edge and the count just below its +middle. The marker grows with the count and paints on the world overlay at +callout resolution. The count covers the whole cell up to the horizon, including +its off-screen cameras. Overlapping markers merge and add their counts. A lone +camera whose icon would touch a marker joins the nearest one, unless the HUD +hides that marker. The active camera keeps its own icon beside any marker that +would cover it and stays out of the count. A click on a marker zooms in on its +group, at least halving the distance each time. The view stays put while the +cockpit or a tracked object holds it. Ambient cards and coverage attach only to +cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A +camera the height batch never answered for takes the drawn terrain as its ground +once it is near the screen. It reads that height again from much closer, once +the terrain in view has loaded, or when the terrain source changes. A later +Re:Earth answer replaces it. A fallback preserves it. Close up every camera +shows. Cameras on one mount draw side by side and their records keep the mount. +Ground placement has at most two attempts per camera and view regime. The view +pass reruns while the camera moves, paced by its own cost, and when the terrain +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. 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/I18N.md b/docs/I18N.md index 4799cded25..efad640373 100644 --- a/docs/I18N.md +++ b/docs/I18N.md @@ -107,6 +107,7 @@ Call it before views render. `onLocaleChange` listeners word their text again at - **Translate the label, not the value.** Layer ids, enums, share-link parameters, API fields, voice tool schemas and feed data (callsigns, vessel and place names) stay as they are; translate only the text shown for them. - **No `t()` at module top level.** Keep the English in `msg()` and call `t()` when rendering. - **Numbers and dates** go through `formatNumber`, `formatDate`, `formatRelativeTime` and `formatUtcDayMonth` from `src/i18n/index.js`, which follow the active language. + Compact CCTV count badges painted on the map use Latin digits, a decimal point and a `K` suffix for thousands (`999`, `1.7K`, `12K`). Each badge keeps its width and reads the same across locales. Format these badges only with `formatCameraCount` in `src/data/cctvCellCounts.js`. - **Identical English means identical translation,** unless you give it a context: `t('CLEAR', { context: 'action' })` (a button) is its own catalog entry, `action|CLEAR`, while `t('CLEAR')` (the sky) stays separate. English output is the same. - **Text that should stay English** (a brand, a code, a unit symbol) is simply not wrapped. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 429862c7c7..ca63034fd1 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -626,6 +626,7 @@ "src/data/cctv.js", "src/data/cctvCatalogCap.test.mjs", "src/data/cctvCellCounts.test.mjs", + "src/data/cctvViewPass.test.mjs", "src/data/cctvViewThinning.test.mjs", "src/data/cctvDisplayCode.test.mjs", "src/data/cctvFootprint.js", @@ -645,6 +646,8 @@ "src/data/cctvTxdotSource.test.mjs", "src/layers/cctv/source.test.mjs", "src/layers/cctv/frames.test.mjs", + "src/layers/cctv/countMarkers.test.mjs", + "src/layers/cctv/ground.test.mjs", "src/layers/cctv/rendering.test.mjs", "src/data/alprCameras.js", "src/data/alprCameras.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 93ccb828cb..0a617d4732 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3282,6 +3282,7 @@ "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cameraFraming.js", "src/data/cctvCellCounts.js", "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", diff --git a/src/app/layers/cctv.js b/src/app/layers/cctv.js index 99bf3fa6fd..8c599c6166 100644 --- a/src/app/layers/cctv.js +++ b/src/app/layers/cctv.js @@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js'; import * as credits from '../../data/dataCredits.js'; import * as sprites from '../../data/spriteOrder.js'; import * as activation from '../../cctvFocusRequest.js'; +import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js'; import * as overlays from '../../overlays/worldOverlay.js'; import { CITY_POIS } from '../../cityPois.js'; import * as picking from '../../data/pickRegistry.js'; @@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) { credits, sprites, activation, - overlays, + overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry }, locations: { CITY_POIS }, picking, terrain, diff --git a/src/data/cameraFraming.js b/src/data/cameraFraming.js index af2ee7fc5f..26ac769eea 100644 --- a/src/data/cameraFraming.js +++ b/src/data/cameraFraming.js @@ -1,4 +1,4 @@ -import { toRadians } from '../geo/index.js'; +import { toRadians } from '../geo/vector.js'; import { findCamera } from '../render/rendererOf.js'; /** The camera port's pose, or null when there is none to read. */ diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index fa9ee0eea1..a2306e6efd 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -87,6 +87,7 @@ import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, IDLE_CAMERA_COLOR, + IDLE_CAMERA_ICON, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; @@ -387,9 +388,8 @@ test('camera icons are violet for video feeds, green for stills, amber when acti assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); assert.equal(icons.item(idleVideo.camera.id).scale, 1); const image = (record) => icons.item(record.camera.id).image; - assert.deepEqual(IDLE_CAMERA_COLOR, [93 / 255, 1, 143 / 255, 1]); const idleImage = image(idleStill); - assert.match(atob(idleImage.split(',')[1]), /stroke="#fff"/); + assert.equal(idleImage, IDLE_CAMERA_ICON); assert.equal(image(activeVideo), CAMERA_ICON); assert.equal(image(idleVideo), CAMERA_ICON); idleStill.camera.feedType = 'hls'; diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index bbafd051ad..9a551413a8 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -1,6 +1,6 @@ import { fromDegrees } from '../geo/ellipsoid.js'; -/** Exact camera counts below a thousand, then rounded thousands with a K suffix. */ +/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */ export function formatCameraCount(count) { if (count < 1000) return String(count); const thousands = @@ -43,10 +43,12 @@ export function addCellCamera(cell, camera) { cell.high = Math.max(cell.high, height); } +const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180; + /** Mean longitude and latitude of a cell's mounts, in degrees. */ export function cellLonLat(cell) { return { - lon: cell.lonSum / (1e7 * cell.count), + lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)), lat: cell.latSum / (1e7 * cell.count), }; } @@ -68,57 +70,62 @@ export function cellCenter(cell) { ); } -/** A padded sphere around the group's geographic rectangle and mount heights. */ +/** A padded sphere over the rectangle and every mount, centred at groundM + * when set, otherwise at the mid mount height. */ export function cellBounds(cell) { const lat = (cell.north + cell.south) / 2; - const lon = (cell.east + cell.west) / 2; + const lon = wrapLongitude((cell.east + cell.west) / 2); const height = Number.isFinite(cell.groundM) ? cell.groundM : (cell.high + cell.low) / 2; // The parallel nearest the equator bounds the width of every row. const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180; - // Half the diagonal plus 20% padding on every side. - const radius = - 0.6 * + const halfWidth = + 0.5 * Math.hypot( (cell.east - cell.west) * 111_320 * Math.cos(parallel), (cell.north - cell.south) * 111_320, - cell.high - cell.low, ); + const vertical = Math.max(cell.high - height, height - cell.low); + const radius = 1.2 * Math.hypot(halfWidth, vertical); return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) }; } /** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */ function addCell(target, cell) { + // Across the antimeridian a cell joins on the side of the group's mean. + const shift = target.count + ? 360 * + Math.round( + (target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9, + ) + : 0; target.count += cell.count; target.latSum += cell.latSum; - target.lonSum += cell.lonSum; + target.lonSum += cell.lonSum + shift * 1e7 * cell.count; target.heightSum += cell.heightSum; target.south = Math.min(target.south, cell.south); target.north = Math.max(target.north, cell.north); - target.west = Math.min(target.west, cell.west); - target.east = Math.max(target.east, cell.east); + target.west = Math.min(target.west, cell.west + shift); + target.east = Math.max(target.east, cell.east + shift); target.low = Math.min(target.low, cell.low); target.high = Math.max(target.high, cell.high); } -/** Claim the touching pills in this marker's bucket and its eight neighbors. */ -function collectNeighbors(marker, grid, members, gap) { +/** Visit the touching pills in this marker's bucket and its eight neighbors. */ +function visitNeighbors(marker, grid, gap, visit) { for (let col = -1; col <= 1; col++) { for (let row = -1; row <= 1; row++) { const bucket = grid.get(`${marker.col + col},${marker.row + row}`); if (!bucket) continue; for (const other of bucket) { - // Lone cameras join a count beside them, never each other. - if (marker.cell.count === 1 && other.cell.count === 1) continue; // Distance between the horizontal centre segments of the two pills. const extra = marker.halfSegment + other.halfSegment; const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); const dy = marker.y - other.y; const reach = marker.radius + other.radius + gap; if (dx * dx + dy * dy >= reach * reach) continue; - bucket.delete(other); - members.push(other); + visit(other, dx * dx + dy * dy, reach); } } } @@ -128,7 +135,8 @@ function collectNeighbors(marker, grid, members, gap) { * Merge connected groups of overlapping horizontal pills. Each marker occupies * one grid bucket. Even the widest pill can only touch its eight neighbors. * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and - * joins a count it touches; two such cells alone stay apart. + * joins the nearest count it touches. Lone cameras never join each other + * or bridge two counts. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { @@ -136,7 +144,7 @@ export function mergeCountCells(cells, project, sizeFor, gap) { let rowHeight = 0; const markers = cells.map((cell) => { const screen = project(cellCenter(cell)); - const { width, height } = sizeFor(cell.count); + const { width, height } = sizeFor(cell.count, cell); columnWidth = Math.max(columnWidth, width + gap); rowHeight = Math.max(rowHeight, height + gap); // The view projector reuses its result object. @@ -156,29 +164,57 @@ export function mergeCountCells(cells, project, sizeFor, gap) { const key = `${marker.col},${marker.row}`; if (!grid.has(key)) grid.set(key, new Set()); marker.bucket = grid.get(key); - marker.bucket.add(marker); + if (marker.cell.count > 1) marker.bucket.add(marker); + } + + for (const marker of markers) { + if (marker.cell.count !== 1 || !marker.bucket) continue; + let best = Infinity; + visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => { + const clearance = Math.sqrt(distanceSquared) - reach; + if (clearance < best) { + best = clearance; + marker.nearest = other; + } + }); + } + + // Only counts were candidates for nearest. Now they can claim lone cameras. + for (const marker of markers) + if (marker.cell.count === 1) marker.bucket?.add(marker); + + const members = []; + for (const seed of markers) { + if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue; + members.length = 0; + members.push(seed); + for (const marker of members) { + if (marker.cell.count === 1) continue; + visitNeighbors(marker, grid, gap, (other) => { + if (other.cell.count === 1 && other.nearest !== marker) return; + other.bucket.delete(other); + members.push(other); + }); + } + if (members.length === 1) { + seed.result = seed.cell; + } else { + const group = createCameraCell(seed.cell.key); + group.lone = []; + for (const { cell } of members) { + addCell(group, cell); + if (cell.count === 1) group.lone.push(cell); + else if (cell.lone) group.lone.push(...cell.lone); + } + seed.result = group; + } } const groups = []; - const members = []; - for (const seed of markers) { - if (!seed.bucket) { - groups.push(seed.cell); - continue; - } - if (!seed.bucket.delete(seed)) continue; - members.length = 0; - members.push(seed); - for (let i = 0; i < members.length; i++) - collectNeighbors(members[i], grid, members, gap); - - if (members.length === 1) { - groups.push(seed.cell); - } else { - const group = createCameraCell(seed.cell.key); - for (const member of members) addCell(group, member.cell); - groups.push(group); - } + for (const marker of markers) { + if (marker.result) groups.push(marker.result); + else if (!marker.bucket || marker.bucket.has(marker)) + groups.push(marker.cell); } return groups; } diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index 66d9702c36..1a42b37280 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -12,7 +12,7 @@ import { mergeCountCells, } from './cctvCellCounts.js'; -test('camera counts use the same Latin digits and K notation in every UI language', () => { +test('camera counts use Latin digits and K notation whatever the UI language', () => { const previous = getLocale(); const examples = [ [2, '2'], @@ -27,11 +27,9 @@ test('camera counts use the same Latin digits and K notation in every UI languag [1000000, '1000K'], ]; try { - for (const locale of ['en', 'ru', 'ja', 'ar']) { - setLocale(locale); - for (const [count, label] of examples) - assert.equal(formatCameraCount(count), label, `${locale}: ${count}`); - } + setLocale('ar'); + for (const [count, label] of examples) + assert.equal(formatCameraCount(count), label); } finally { setLocale(previous); } @@ -56,24 +54,28 @@ test('the marker mean weights every mount and the flight bounds cover the outlie } }); +function mergeCounts(sizes, counts, positions) { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + 4, + ); + return { cells, groups }; +} + test('stadiums merge by their own radii and segment lengths across grid boundaries', () => { const sizes = { 2: { width: 28, height: 28 }, 7350: { width: 80, height: 48 }, }; - const gap = 4; const check = (counts, positions, expected) => { - const cells = counts.map((count, i) => ({ - ...createCameraCell(String(i)), - count, - })); - let i = 0; - const groups = mergeCountCells( - cells, - () => positions[i++], - (count) => sizes[count], - gap, - ); + const { groups } = mergeCounts(sizes, counts, positions); assert.deepEqual( groups.map((cell) => cell.count), expected, @@ -100,19 +102,8 @@ test('a lone camera joins a count it touches, and lone cameras alone stay apart' 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 }, }; - const gap = 4; const check = (counts, positions, expected) => { - const cells = counts.map((count, i) => ({ - ...createCameraCell(String(i)), - count, - })); - let i = 0; - const groups = mergeCountCells( - cells, - () => positions[i++], - (count) => sizes[count], - gap, - ); + const { cells, groups } = mergeCounts(sizes, counts, positions); assert.deepEqual( groups.map((cell) => cell.count), expected, @@ -135,3 +126,91 @@ test('a lone camera joins a count it touches, and lone cameras alone stay apart' // A lone camera that only touches another lone camera is left alone. check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]); }); + +test('cells merged across the antimeridian stay at the antimeridian', () => { + for (const lon of [179.9, 179.99, 179.999]) { + for (const reversed of [false, true]) { + const east = createCameraCell('e'); + const west = createCameraCell('w'); + for (let i = 0; i < 2; i++) { + addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 }); + addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 }); + } + const cells = reversed ? [west, east] : [east, west]; + const screens = [ + { x: 100, y: 100 }, + { x: 120, y: 100 }, + ]; + let i = 0; + const [group, ...rest] = mergeCountCells( + cells, + () => screens[i++], + () => ({ width: 40, height: 40 }), + 4, + ); + assert.equal(rest.length, 0); + assert.equal(group.count, 4); + const expected = fromDegrees(180, 0, 0); + assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`); + const bounds = cellBounds(group); + assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`); + for (const l of [lon, -lon]) + assert.ok( + distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius, + ); + } + } +}); + +test('flight bounds on drawn ground still contain every mount', () => { + // Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m. + const flat = createCameraCell('k'); + addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 }); + addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 }); + flat.groundM = 0; + const fb = cellBounds(flat); + assert.ok( + distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius, + 'flat', + ); + // Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them. + const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180)); + const ravine = createCameraCell('r'); + addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 }); + addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 }); + ravine.groundM = 0; + const rb = cellBounds(ravine); + for (const lon of [10, east]) + assert.ok( + distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius, + 'ravine', + ); +}); + +test('a lone camera between two counts joins one of them and does not merge them', () => { + const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } }; + const run = (counts, xs) => + mergeCounts( + sizes, + counts, + xs.map((x) => ({ x, y: 100 })), + ) + .groups.map((cell) => cell.count) + .sort((a, b) => a - b); + assert.deepEqual(run([9, 9], [70, 130]), [9, 9]); + for (const [counts, xs] of [ + [ + [9, 1, 9], + [70, 100, 130], + ], + [ + [1, 9, 9], + [100, 70, 130], + ], + [ + [9, 9, 1], + [70, 130, 100], + ], + ]) + assert.deepEqual(run(counts, xs), [9, 10], String(counts)); +}); diff --git a/src/data/cctvViewPass.test.mjs b/src/data/cctvViewPass.test.mjs new file mode 100644 index 0000000000..07e49ec1cd --- /dev/null +++ b/src/data/cctvViewPass.test.mjs @@ -0,0 +1,254 @@ +import { afterEach, beforeEach, test } from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import cctvLayer, { + _cctvIconsForTest, + _setCctvCoverageStateForTest, + refreshHorizonCulling, +} from './cctv.js'; + +const WIDTH = 800; +const HEIGHT = 600; +const bindings = []; +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + measureText: (text) => ({ + width: text.length * 8, + actualBoundingBoxAscent: 4, + actualBoundingBoxDescent: 4, + }), + }), + }), + }; +}); +afterEach(() => { + delete globalThis.document; + for (const unbind of bindings.splice(0)) unbind(); +}); + +function recordsAt(lonLats, height = 10) { + return lonLats.map(([lon, lat], index) => { + const position = Cesium.Cartesian3.fromDegrees(lon, lat, height); + return { + camera: { + id: `cam-${String(index).padStart(4, '0')}`, + name: `Camera ${index}`, + city: 'Test', + lat, + lon, + headingDeg: 0, + pitchDeg: -18, + fovDeg: 44, + rangeM: 145, + mountHeightM: 8, + absoluteHeightM: height, + }, + position: { x: position.x, y: position.y, z: position.z }, + groundSamples: {}, + groundResolved: {}, + coverageEntities: [], + projection: null, + }; + }); +} + +const plain = ({ x, y, z }) => ({ x, y, z }); + +function lookingAt(eye, target, ports = {}) { + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + return { + viewer: viewerWithAxes(eye, direction, right, up, ports), + direction, + right, + up, + }; +} + +function topDown(height, ports = {}) { + const eye = Cesium.Cartesian3.fromDegrees(0, 0, height); + return viewerWithAxes( + eye, + { x: -1, y: 0, z: 0 }, + { x: 0, y: 1, z: 0 }, + { x: 0, y: 0, z: 1 }, + ports, + ); +} + +function viewerWithAxes(eye, direction, right, up, ports) { + const carto = Cesium.Cartographic.fromCartesian(eye); + const { port } = fakeCameraPort({ + pose: { + lon: Cesium.Math.toDegrees(carto.longitude), + lat: Cesium.Math.toDegrees(carto.latitude), + height: carto.height, + position: plain(eye), + direction: plain(direction), + up: plain(up), + right: plain(right), + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, + }, + }); + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, + canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + draw: fakeDrawPort(), + ...ports, + }), + ); + return viewer; +} + +/** Pinhole projection, as the layer's projector. */ +function project(view, eye, point) { + const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3()); + const z = Cesium.Cartesian3.dot(d, view.direction); + const t = Math.tan(Math.PI / 6); + const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT)); + const y = Cesium.Cartesian3.dot(d, view.up) / z / t; + return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z }; +} + +for (const [label, horizontalM, aboveM] of [ + ['100 m approach', 100, 4], + ['800 m approach', 800, 50], +]) { + test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => { + const ground = 1872; + const records = recordsAt([ + [0, 0], + [0, 0], + ]); + // geoid fallback after a 429 + for (const r of records) + r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' }; + const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8); + const eye = Cesium.Cartesian3.fromDegrees( + 0, + -horizontalM / 111_320, + ground + 8 + aboveM, + ); + const reads = []; + const view = lookingAt(eye, mount, { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + reads.push(point); + return ground; + }, + }, + }); + _setCctvCoverageStateForTest({ viewer: view.viewer, records }); + const stale = project(view, eye, records[0].position); + const truth = project(view, eye, mount); + + assert.ok(stale.y > HEIGHT * 2); + assert.ok(truth.y > 0 && truth.y < HEIGHT); + refreshHorizonCulling(); + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, ground); + + assert.ok(reads.length > 0, 'the stale camera was never read'); + }); +} + +test('cameras off the visible screen cannot spend the whole terrain read budget', () => { + // 300 cameras with no prior around the screen edge, tiles not loaded; the + // 301st at the screen centre over a loaded tile. + const lonLats = []; + for (let i = 0; i < 300; i++) { + const a = (i / 300) * 2 * Math.PI; + // ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide) + lonLats.push([ + (Math.cos(a) * 250) / 111_320, + (Math.sin(a) * 190) / 111_320, + ]); + } + lonLats.push([0, 0]); + const records = recordsAt(lonLats); + const perPass = []; + let reads; + const viewer = topDown(200, { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + reads.push(point); + return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9 + ? 40 + : null; + }, + }, + }); + _setCctvCoverageStateForTest({ viewer, records }); + for (let pass = 0; pass < 3; pass++) { + reads = []; + refreshHorizonCulling(); + perPass.push(reads.length); + } + const last = records.at(-1); + + assert.equal(last.groundPrior?.ellipsoid, 40); + assert.ok(perPass.every((n) => n <= 300)); +}); + +test("the active camera's icon moves beside a count that would cover it", () => { + const records = recordsAt([ + [0, 0], + [0, 0], + [0, 0], + ]); + const viewer = topDown(20_000); + _setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const [marker] = cctvLayer._cctvDrawnForTest().counts.markers; + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990; + const apartPx = + Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) / + metresPerPixel; + + assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon'); +}); + +test('a lone camera just inside the grouping threshold joins the count beside it', () => { + const h = 740; + // mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10 + const records = recordsAt([ + [0, 235 / 111_320], + [0, 255 / 111_320], + [0, 255 / 111_320], + ]); + for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' }; + const viewer = topDown(h + 10); + _setCctvCoverageStateForTest({ viewer, records }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const markers = cctvLayer._cctvDrawnForTest().counts.markers; + assert.deepEqual( + markers.map((marker) => marker.cell.count), + [3], + ); + assert.equal( + icons.item('cam-0000').show, + false, + 'the near singleton still draws beside the count', + ); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 7293e1aac8..b3ef110926 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -1,17 +1,20 @@ // src/data/cctvViewThinning.test.mjs — the CCTV view pass: only cameras on or -// near the screen show, a zoomed-out view groups neighboring cameras, and the layer's UI state never rebuilds every camera for a listener +// near the screen show, a zoomed-out view groups neighboring cameras, and +// the layer's UI state never rebuilds every camera for a listener // that does not read the list. import { afterEach, beforeEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { CAMERA_GREEN } from '../layers/cctv/policy.js'; -import { createCameraGlyphCache } from '../layers/cctv/countMarkers.js'; +import { CAMERA_GREEN, COUNT_CAMERA_ICON } from '../layers/cctv/policy.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { createCameraCell } from './cctvCellCounts.js'; -import { bindRenderer } from '../render/rendererOf.js'; +import { bindRenderer, findCamera } from '../render/rendererOf.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, + focusCctvRecord, + CCTV_FOCUS_RESULT, bindCctvWorldClickGesture, applyCctvFocusDeemphasis, reopenNearestCamera, @@ -55,7 +58,7 @@ function recordsAt(lonLats) { * equator, north up, through a camera port: the view pass projects the * cameras from its pose. */ -function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { +function poseAt(heightM, lonDeg) { const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); const down = Cesium.Cartesian3.normalize( Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), @@ -63,23 +66,25 @@ function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { ); const north = { x: 0, y: 0, z: 1 }; const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3()); - const { port } = fakeCameraPort({ - pose: { - lon: lonDeg, - lat: 0, - height: heightM, - position: { x: eye.x, y: eye.y, z: eye.z }, - direction: { x: down.x, y: down.y, z: down.z }, - up: north, - right: { x: right.x, y: right.y, z: right.z }, - fovy: Math.PI / 3, - aspectRatio: WIDTH / HEIGHT, - near: 0.1, - far: 5e8, - }, - }); + return { + lon: lonDeg, + lat: 0, + height: heightM, + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: { x: down.x, y: down.y, z: down.z }, + up: north, + right: { x: right.x, y: right.y, z: right.z }, + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, + }; +} + +function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { + const { port, setPose } = fakeCameraPort({ pose: poseAt(heightM, lonDeg) }); port.flyToBounds = (bounds, options) => flights.push({ bounds, options }); - const viewer = {}; + const viewer = { moveTo: (lon) => setPose(poseAt(heightM, lon)) }; bindings.push( bindRenderer(viewer, { camera: port, @@ -99,12 +104,9 @@ let glyphWidth; let inkHalfHeight; let ctx; const fonts = new EventTarget(); -let rasters; let spriteImages; -/** Model the sprite’s neutral highlights, dark fills and translucent edges. */ function markerCanvas() { - const canvas = {}; const context = { measureText(text) { measured++; @@ -114,40 +116,8 @@ function markerCanvas() { actualBoundingBoxDescent: inkHalfHeight, }; }, - drawImage(image, x, y, width, height) { - assert.equal(image.loaded, true); - assert.deepEqual( - [x, y, width, height], - [0, 0, canvas.width, canvas.height], - ); - canvas.source = image.src; - const h = Math.floor(height / 2); - canvas.ink = [2, 3, Math.floor(h * 1.5), h]; - rasters.push(canvas); - }, - getImageData() { - const data = new Uint8ClampedArray(canvas.width * canvas.height * 4); - const [left, top, width, height] = canvas.ink; - for (let y = top; y < top + height; y++) { - for (let x = left; x < left + width; x++) { - const shade = x === left ? 255 : 64; - data.set( - [shade, shade, shade, y === top ? 1 : 255], - (y * canvas.width + x) * 4, - ); - } - } - return { data }; - }, - putImageData({ data }) { - const [left, top] = canvas.ink; - const start = (top * canvas.width + left) * 4; - canvas.stroke = [...data.slice(start, start + 4)]; - canvas.fill = [...data.slice(start + 4, start + 8)]; - }, }; - canvas.getContext = () => context; - return canvas; + return { getContext: () => context }; } function seedCoverage(options) { @@ -181,7 +151,6 @@ beforeEach(() => { measured = 0; glyphWidth = 8; inkHalfHeight = 4; - rasters = []; globalThis.document = { fonts, createElement: markerCanvas }; const stack = []; ctx = { @@ -205,7 +174,7 @@ beforeEach(() => { beginPath() {}, fill() {}, drawImage(image, left, top, sw, sh, x, y, width, height) { - assert.deepEqual([left, top, sw, sh], image.ink); + assert.ok(image.loaded); assert.ok(Math.abs(width / height - sw / sh) < 1e-9); this.glyphs.push({ image, @@ -556,27 +525,22 @@ test('cameras on one mount draw side by side once they show as icons', () => { test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); - seedCoverage({ - viewer: viewerAt(20_000), - records, - }); + const viewer = viewerAt(20_000); + seedCoverage({ viewer, records }); refreshHorizonCulling(); const before = cctvLayer.getUIState().cameraIndex; const list = _viewRecordIdsForTest(); // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up). for (const shiftM of [90, 330, 600, 1110]) { - seedCoverage({ - viewer: viewerAt(20_000, shiftM / 111_320), - records, - }); + viewer.moveTo(shiftM / 111_320); refreshHorizonCulling(); - assert.deepEqual( + assert.equal( cctvLayer.getUIState().cameraIndex, before, `pan by ${shiftM} m`, ); } - seedCoverage({ viewer: viewerAt(20_000), records }); + viewer.moveTo(0); refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); @@ -864,7 +828,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', assert.deepEqual(markers(), []); }); -test('count markers share the camera focus fade and recover on release', () => { +test('a dimmed count keeps its alpha when its cell changes and recovers on release', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); @@ -888,8 +852,20 @@ test('count markers share the camera focus fade and recover on release', () => { tick(0, target); tick(params.attackMs + 1, target); assert.equal(paint()[0].alpha, params.dimFloor); - tick(params.attackMs + 2, null); - tick(params.attackMs + params.releaseMs + 3, null); + + const record = records[0]; + record.camera.lon += 2 / 111_320; + record.position = Cesium.Cartesian3.fromDegrees( + record.camera.lon, + record.camera.lat, + record.camera.absoluteHeightM, + ); + refreshHorizonCulling(); + tick(params.attackMs + 2, target); + assert.equal(paint()[0].alpha, params.dimFloor); + + tick(params.attackMs + 3, null); + tick(params.attackMs + params.releaseMs + 4, null); assert.equal(paint()[0].alpha, 1); }); @@ -992,72 +968,21 @@ test('the overlay paints narrow count labels as circles and wide labels as pills assert.equal(sw, sh); assert.ok(lw > lh); assert.ok(lw > text.length * glyphWidth); - assert.equal(sh + 4, 48); - assert.equal(lh + 4, 54); - // The four-pixel outer stroke extends two pixels on each side of the path. - assert.equal(sw + 4, short.width); - assert.equal(lw + 4, long.width); assert.equal(sy + sh / 2, HEIGHT / 2); assert.equal(ly + lh / 2, HEIGHT / 2); assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); assert.equal(ctx.glyphs.length, labels.length); - assert.equal(CAMERA_GREEN, '#5dff8f'); assert.deepEqual( ctx.rings.filter((_, i) => i % 2 === 1), labels.map(() => CAMERA_GREEN), ); for (const [i, label] of labels.entries()) { const glyph = ctx.glyphs[i]; - const [left, top, w, h] = ctx.shapes[i]; - const cx = left + w / 2, - cy = top + h / 2; - assert.equal(glyph.x, cx); - assert.equal(label.x, cx); - assert.deepEqual(glyph.image.stroke, [93, 255, 143, 1]); - assert.deepEqual(glyph.image.fill, [23, 64, 36, 1]); + assert.equal(glyph.x, label.x); assert.equal(label.color, CAMERA_GREEN); - const radius = h / 2 - 1; - // 48 and 54 px markers: the glyph and its top gap grow with the marker. - const grown = (h + 4 - 40) / 18; - assert.ok(Math.abs(glyph.height - (7.5 + 2.5 * grown)) < 1e-9); - assert.ok( - Math.abs(glyph.y - glyph.height / 2 - (cy - radius + 3 + grown)) < 1e-9, - ); - // The middle of the digits sits a fifth of the inner radius below centre. - assert.ok(Math.abs(label.y - (cy + 0.2 * radius)) < 1e-9); - assert.ok(label.y - inkHalfHeight - (glyph.y + glyph.height / 2) >= 5); - for (const [width, edgeY, padding] of [ - [glyph.width, glyph.y - glyph.height / 2, 2], - [label.text.length * glyphWidth, label.y + inkHalfHeight, 6], - ]) { - const chord = 2 * Math.sqrt(radius ** 2 - (edgeY - cy) ** 2); - assert.ok((w - h + chord - width) / 2 >= padding - 1e-9); - } + assert.ok(label.y - inkHalfHeight >= glyph.y + glyph.height / 2); } - const builds = rasters.length; - const images = ctx.glyphs.map((glyph) => glyph.image); - assert.notEqual(images[0], images[1]); - const idleCamera = _cctvIconsForTest().item(records.at(-1).camera.id); - assert.equal(idleCamera.show, true); - for (const image of images) assert.equal(image.source, idleCamera.image); - paint(); - assert.deepEqual( - ctx.glyphs.map((glyph) => glyph.image), - images, - ); - assert.equal(rasters.length, builds); - assert.equal(paintRequests, requests + 1); - assert.match(labels[0].font, /JetBrains Mono/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); - assert.equal(ctx.lineWidth, 1); - ctx.drawImage = () => { - throw new Error('glyph paint failed'); - }; - assert.throws(() => paint(), /glyph paint failed/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); }); test('a wide count label merges a horizontal neighbor beyond the circle diameter', () => { @@ -1169,6 +1094,12 @@ test('hits follow paint order and keep the last painted group until the overlay assert.equal(labels.length, 2); const top = counts.pickedCell(point); assert.equal(String(top.count), labels.at(-1).text); + const replacements = counts.markers.map((marker) => ({ + ...marker.cell, + count: 7, + })); + counts.update(replacements, () => null); + assert.equal(counts.pickedCell(point), top); counts.update([], () => null); assert.equal(counts.pickedCell(point), top); assert.deepEqual(paint(), []); @@ -1178,16 +1109,8 @@ test('hits follow paint order and keep the last painted group until the overlay test('paint, HUD exclusions and hit rectangles use the count-scaled height', () => { seedCoverage({ viewer: viewerAt(20_000) }); const counts = cctvLayer._cctvDrawnForTest().counts; - for (const [count, height] of [ - [2, 40], - [10, 44], - [100, 48], - [1000, 54], - [3162, 56], - [3163, 56], - [7350, 58], - [1e8, 58], - ]) { + let previous = 0; + for (const count of [2, 10, 100, 1000, 3162, 3163, 7350, 1e8]) { const cell = { ...createCameraCell('cell'), count }; for (const lon of [0, 0.025]) { counts.update( @@ -1202,10 +1125,11 @@ test('paint, HUD exclusions and hit rectangles use the count-scaled height', () return false; }, }); - if (height === 40 || height === 58) - assert.equal(ctx.glyphs[0].height, height === 40 ? 7.5 : 10); const marker = markers()[0]; - assert.equal(marker.height, height); + const height = marker.height; + assert.ok(height >= previous); + if (count === 2) assert.equal(height, 40); + previous = height; assert.equal(rect.h, height); assert.equal(rect.w, marker.width); const [x, y, w, h] = ctx.shapes[0]; @@ -1222,44 +1146,28 @@ test('paint, HUD exclusions and hit rectangles use the count-scaled height', () ); } } - // Centred 23 px above the canvas: the taller badges still cross the edge. - const matrix = new Float64Array(16); - matrix[13] = 1 + 46 / HEIGHT; - matrix[15] = 1; - assert.equal( - paint({ viewProjectionMatrix: matrix }).length, - height > 46 ? 1 : 0, - ); } + assert.equal(previous, 58); }); -test('measured ink width selects the circle or pill and clears the curved ring', () => { +test('measured ink width selects the circle or pill', () => { const { records } = recordsAt(Array(99).fill([0, 0])); seedCoverage({ viewer: viewerAt(20_000), records }); for (const [width, extent, circle] of [ [7, 4, true], [25, 4, false], - // Width-only metrics reserve the full type height below the baseline. - [6, undefined, true], ]) { glyphWidth = width; inkHalfHeight = extent; fonts.dispatchEvent(new Event('loadingdone')); refreshHorizonCulling(); - const [label] = paint(); - const [, top, pathWidth, pathHeight] = ctx.shapes[0]; - assert.equal(pathHeight + 4, 48); + paint(); + const [, , pathWidth, pathHeight] = ctx.shapes[0]; assert.equal(pathWidth === pathHeight, circle); - // At the top of the ink, the circle ends narrow the usable inner width. - const innerRadius = pathHeight / 2 - 1; - const edge = label.y + (extent ?? 6) - (top + pathHeight / 2); - const clearWidth = - pathWidth - pathHeight + 2 * Math.sqrt(innerRadius ** 2 - edge ** 2); - assert.ok((clearWidth - label.text.length * width) / 2 >= 6); } }); -test('equal-size camera groups share a camera sprite and follow overlay pixel density', () => { +test('count markers draw the green camera sprite once it has loaded', () => { const { records } = recordsAt([ [0, 0], [0, 0], @@ -1268,45 +1176,18 @@ test('equal-size camera groups share a camera sprite and follow overlay pixel de ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - spriteImages[0].finish(); - paint({ dpr: 1 }); - const low = ctx.glyphs[0].image; - assert.equal(ctx.glyphs[1].image, low); - const builds = rasters.length; - paint({ dpr: 2 }); - const high = ctx.glyphs[0].image; - assert.equal(ctx.glyphs[1].image, high); - assert.notEqual(high, low); - // The raster follows the device density; the painted size does not. - assert.deepEqual([low.width, high.width], [16, 30]); - assert.equal(ctx.glyphs[0].height, 7.5); - paint({ dpr: 2 }); - assert.equal(rasters.length, builds + 1); - paint({ dpr: 1 }); - assert.equal(ctx.glyphs[0].image, low); - assert.equal(rasters.length, builds + 1); -}); - -test('the glyph cache draws its supplied map sprite and multiplies its colours', () => { - const source = - 'data:image/svg+xml,' + - encodeURIComponent( - '', - ); - const glyphFor = createCameraGlyphCache(markerCanvas, source); - assert.equal(glyphFor(12, 2, CAMERA_GREEN), null); - assert.equal(spriteImages[0].src, source); - spriteImages[0].finish(); - const green = glyphFor(12, 2, CAMERA_GREEN); - assert.equal(glyphFor(12, 2, CAMERA_GREEN), green); - const white = glyphFor(12, 2, '#ffffff'); - assert.notEqual(white, green); + paint(); + assert.equal(ctx.glyphs.length, 0); + const requests = paintRequests; + const [image] = spriteImages; + assert.equal(image.src, COUNT_CAMERA_ICON); + image.finish(); + assert.equal(paintRequests, requests + 1); + paint(); assert.deepEqual( - rasters.map(({ source: drawn }) => drawn), - [source, source], + ctx.glyphs.map((glyph) => glyph.image), + [image, image], ); - assert.deepEqual(white.canvas.stroke, [255, 255, 255, 1]); - assert.deepEqual(white.canvas.fill, [64, 64, 64, 1]); }); test('a sprite that loads after disposal does not request a paint', () => { @@ -1316,23 +1197,302 @@ test('a sprite that loads after disposal does not request a paint', () => { cctvLayer._cctvDrawnForTest().counts.dispose(); const requests = paintRequests; spriteImages[0].finish(); - assert.equal(rasters.length, 0); assert.equal(paintRequests, requests); }); -test('counts still paint when an offscreen 2D context is unavailable', () => { - document.createElement = () => ({ getContext: () => null }); +test('cameras less than a metre apart spread even across a rounding boundary', () => { + const { records } = recordsAt([ + [0.000004, 0], + [0.000006, 0], + ]); + seedCoverage({ viewer: viewerAt(460), records }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; + const apart = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + assert.ok(Math.abs(apart / metresPerPixel - 30) < 0.5); +}); + +test('a drawn height read before the terrain settled, or on another surface, is read again', () => { const { records } = recordsAt([ [0, 0], - [0, 0], + [0.2, 0], ]); + records[0].groundPrior = { ellipsoid: -20, source: 'geoid-fallback' }; + let settled = false, + version = 1, + terrain = 100; + const ports = { + globe: { + isGlobeVisible: () => true, + isSettled: () => settled, + surfaceVersion: () => version, + }, + query: { sampleHeightNow: () => terrain }, + }; + seedCoverage({ viewer: viewerAt(20000, 0, [], ports), records }); + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 100); + assert.equal(records[0].groundPrior.settled, false); + terrain = 150; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 100); + settled = true; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 150); + terrain = 0; + version++; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 0); +}); + +test('a camera with geometry takes the drawn terrain once, after the pass that read it', async () => { + const { records } = recordsAt([ + [0, 0], + [0.2, 0], + ]); + records[1].groundPrior = { ellipsoid: 2, source: 'reearth' }; + const record = records[0]; + Object.assign(record, { + groundPrior: { ellipsoid: -20, source: 'geoid-fallback' }, + groundSamples: {}, + groundResolved: {}, + }); + const samples = []; + const ports = { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + samples.push(point); + return 1872; + }, + }, + draw: fakeDrawPort(), + }; + seedCoverage({ + viewer: viewerAt(2200, 0, [], ports), + records, + activeCameraId: 'cam-0', + }); + refreshCoverageStyles(); + assert.ok(record.frustumGeometry); + samples.length = 0; + refreshHorizonCulling(); + refreshHorizonCulling(); + assert.equal( + samples.filter((point) => point.lon === 0 && point.lat === 0).length, + 1, + ); + assert.equal(record.groundPrior.source, 'geoid-fallback'); + await Promise.resolve(); + assert.equal(record.groundPrior.source, 'drawn-terrain'); + for (const pos of [record.position, _cctvIconsForTest().item('cam-0').pos]) + assert.ok( + Math.abs(Cesium.Cartographic.fromCartesian(pos).height - 1880) < 0.01, + ); +}); + +/** Painted centre of a count marker in CSS px. */ +function markerCentre(marker) { + const label = paint().find((l) => l.text === marker.text); + return { x: label.x, y: label.y - marker.labelY }; +} + +test('building geometry for spread mount mates keeps their icons beside the mount', () => { + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + const draw = fakeDrawPort(); + seedCoverage({ + viewer: viewerAt(460, 0, [], { draw }), + records, + activeCameraId: 'cam-2', + }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const before = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + + assert.ok(before > 10); + refreshCoverageStyles(); + + const after = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + const callouts = cctvLayer.getDetectableObjects(); + const ca = callouts.find((o) => o.sourceId === 'cam-0').position; + + assert.ok(after > 10, 'icons stay side by side after geometry is built'); + assert.ok( + Cesium.Cartesian3.distance(icons.item('cam-0').pos, ca) < 1e-6, + 'icon and callout agree', + ); +}); + +test('a count click does not fly while the cockpit or a followed target owns the camera', () => { + const { records } = recordsAt(CLUSTER); + // Cockpit + let flights = []; + globalThis.document.body = { + classList: { contains: (c) => c === 'cockpit-mode' }, + }; + let viewer = viewerAt(20_000, 0, flights); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal( + focusCctvRecord(viewer, records[0]), + CCTV_FOCUS_RESULT.COCKPIT_ACTIVE, + ); + assert.equal(flights.length, 0); + clickMarker(markers()[0]); + + assert.equal(flights.length, 0, 'count click must not fly in cockpit mode'); + // Tracking + delete globalThis.document.body; + flights = []; + viewer = viewerAt(20_000, 0, flights); + Object.defineProperty(findCamera(viewer), 'followed', { + value: { key: 'flights:abc' }, + configurable: true, + }); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal( + focusCctvRecord(viewer, records[0]), + CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW, + ); + assert.equal(flights.length, 0); + clickMarker(markers()[0]); + + assert.equal(flights.length, 0, 'count click must not fly while tracking'); +}); + +test('each click on a long dense chain flies closer than the last', () => { + const lons = []; + const n = 200; + const step = 50 / 111_320; + for (let i = 0; i < n; i++) lons.push([(i - (n - 1) / 2) * step, 0]); + const { records } = recordsAt(lons); + const flights = []; + seedCoverage({ viewer: viewerAt(24_000, 0, flights), records }); + refreshHorizonCulling(); + + let marker = markers().find((m) => m.cell.count === n); + assert.ok(marker, 'one count of 200'); + const clickAt = (m) => { + const { x, y } = markerCentre(m); + const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, () => {}); + click({ + screenPosition: { x, y }, + gesture: { travelPx: 0, durationMs: 20 }, + }); + }; + clickAt(marker); + const first = flights.at(-1); + const c1 = Cesium.Cartographic.fromCartesian(first.bounds.center); + + seedCoverage({ + viewer: viewerAt( + c1.height + first.options.offset.range, + Cesium.Math.toDegrees(c1.longitude), + flights, + ), + records, + }); + refreshHorizonCulling(); + + marker = markers().find((m) => m.cell.count === n); + assert.ok(marker, 'the full count of 200 reforms at the destination'); + clickAt(marker); + const second = flights.at(-1); + + assert.ok( + second.options.offset.range < first.options.offset.range - 1, + 'second click makes progress', + ); +}); + +test("a click outside a round count's circle does not hit it", () => { + const { records } = recordsAt(CLUSTER); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - spriteImages[0].finish(); - assert.deepEqual( - paint().map((label) => label.text), - ['2'], + const [marker] = markers(); + assert.equal(marker.width, marker.height, 'a round marker'); + const c = markerCentre(marker); + const counts = cctvLayer._cctvDrawnForTest().counts; + const r = marker.height / 2; + const corner = { x: c.x + r - 1, y: c.y + r - 1 }; + const dist = Math.hypot(r - 1, r - 1); + + assert.ok(dist > r, 'corner is outside the painted circle'); + assert.equal( + counts.pickedCell(corner), + null, + 'a click outside the painted circle must not hit the count', ); - assert.equal(ctx.glyphs.length, 0); - assert.equal(ctx.shapes.length, 1); +}); + +test('an unresolved batch result takes the drawn terrain', () => { + const { records } = recordsAt([ + [0, 0], + [0.2, 0], + ]); + records[0].groundPrior = { ellipsoid: null, source: 'unresolved' }; + const ports = { + globe: { isGlobeVisible: () => true }, + query: { sampleHeightNow: () => 1872 }, + }; + seedCoverage({ viewer: viewerAt(20_000, 0, [], ports), records }); + refreshHorizonCulling(); + const h = (r) => Cesium.Cartographic.fromCartesian(r.position).height; + + assert.ok( + Math.abs(h(records[0]) - 1880) < 0.01, + 'an unresolved camera takes the drawn terrain', + ); + assert.equal(records[1].groundPrior.source, 'drawn-terrain'); +}); + +const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; +const separationPx = () => { + const icons = _cctvIconsForTest(); + return ( + Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ) / metresPerPixel + ); +}; + +test('shared-mount icons stay spread after coverage geometry is built', () => { + // cam-0/cam-1 share a mount, cam-2 is active 11 m away. + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' }; + seedCoverage({ + viewer: viewerAt(460, 0, [], { draw: fakeDrawPort() }), + records, + activeCameraId: 'cam-2', + coverageMode: 'on', + }); + refreshHorizonCulling(); + const before = separationPx(); + + // selection.setActiveCamera order: refreshHorizonCulling, then refreshCoverageStyles. + refreshCoverageStyles(); + const after = separationPx(); + + assert.ok(Math.abs(before - 30) < 0.5); + assert.ok(Math.abs(after - 30) < 0.5, `icons collapsed to ${after} px`); }); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 89fa278bb5..e071f07238 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -7,113 +7,65 @@ import { import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { CAMERA_GREEN, - IDLE_CAMERA_ICON, - COUNT_BASE_PX, - COUNT_PX_PER_DECADE, - COUNT_MIN_HEIGHT_PX, - COUNT_MAX_HEIGHT_PX, - COUNT_TEXT_PADDING_PX, - COUNT_GLYPH_MIN_PX, - COUNT_GLYPH_MAX_PX, - COUNT_GLYPH_TOP_MIN_PX, - COUNT_GLYPH_TOP_MAX_PX, - COUNT_GLYPH_PADDING_PX, - COUNT_LABEL_DROP, + COUNT_CAMERA_ICON, + CAMERA_ICON_PX, COUNT_MERGE_GAP_PX, - COUNT_SINGLE_ICON_PX, - COUNT_MERGE_PASSES, } from './policy.js'; +import { liftedForHorizon } from '../../geo/horizon.js'; +// Diameter at one camera before applying the size limits, in CSS pixels. +const COUNT_BASE_PX = 38; + +// Extra diameter for each tenfold increase in camera count. +const COUNT_PX_PER_DECADE = 5; + +// Minimum height of a count marker in CSS pixels. +const COUNT_MIN_HEIGHT_PX = 40; + +// Maximum height of a count marker in CSS pixels. +const COUNT_MAX_HEIGHT_PX = 58; + +// Clear fill between the count and the inside of the ring, in CSS pixels. +const COUNT_TEXT_PADDING_PX = 6; + +// Height of the camera glyph in the smallest and the largest marker. +const COUNT_GLYPH_MIN_PX = 7.5; +const COUNT_GLYPH_MAX_PX = 10; + +// Clear fill above the glyph in the smallest and the largest marker. +const COUNT_GLYPH_TOP_MIN_PX = 3; +const COUNT_GLYPH_TOP_MAX_PX = 4; + +// Clear fill between the glyph's top corners and the inside of the ring. +const COUNT_GLYPH_PADDING_PX = 2; + +// The middle of the digits sits this share of the inner radius below the +// marker's centre, which leaves the glyph clear of the count. +const COUNT_LABEL_DROP = 0.2; + +// Merge passes per view. A merged centre and wider label can reach a further +// marker. The cap bounds work on motion ticks. +const COUNT_MERGE_PASSES = 3; const FONT = WORLD_OVERLAY_STYLE.fontTitle; // Reserve the camera's landscape slot even while the map sprite is loading. const GLYPH_ASPECT = 1.5; const RING_PX = 2; const RIM_PX = 1; const STROKE_INSET = RIM_PX + RING_PX / 2; -const SINGLE_ICON = Object.freeze({ - width: COUNT_SINGLE_ICON_PX, - height: COUNT_SINGLE_ICON_PX, -}); - -/** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ -function rasterizeGlyph(canvas, image, size, dpr, color) { - if (!canvas) return null; - // The artwork occupies just over half the height of the square SVG viewport. - const side = 2 * Math.ceil(size * dpr); - canvas.width = canvas.height = side; - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - ctx.drawImage(image, 0, 0, side, side); - const pixels = ctx.getImageData(0, 0, side, side); - const { data } = pixels; - const rgb = Number.parseInt(color.slice(1), 16); - const red = (rgb >> 16) / 255; - const green = ((rgb >> 8) & 255) / 255; - const blue = (rgb & 255) / 255; - let left = side, - top = side, - right = -1, - bottom = -1; - for (let y = 0; y < side; y++) { - for (let x = 0; x < side; x++) { - const i = (y * side + x) * 4; - if (!data[i + 3]) continue; - data[i] *= red; - data[i + 1] *= green; - data[i + 2] *= blue; - left = Math.min(left, x); - right = Math.max(right, x); - top = Math.min(top, y); - bottom = y; - } - } - if (right < 0) return null; - ctx.putImageData(pixels, 0, 0); - const width = right - left + 1; - const height = bottom - top + 1; - const scale = Math.min(size / height, (size * GLYPH_ASPECT) / width); - return { - canvas, - left, - top, - width, - height, - drawWidth: width * scale, - drawHeight: height * scale, - }; -} - -/** Load the map artwork once, then share each tinted device-density raster. */ -export function createCameraGlyphCache(createCanvas, source, onLoad) { - const glyphs = new Map(); - let image; - let ready = false; - return (size, dpr, color) => { - if (!image && typeof Image !== 'undefined') { - image = new Image(); - image.onload = () => { - ready = true; - onLoad?.(); - }; - image.src = source; - } - if (!ready) return null; - const key = `${size}:${dpr}:${color}`; - if (!glyphs.has(key)) { - glyphs.set(key, rasterizeGlyph(createCanvas(), image, size, dpr, color)); - } - return glyphs.get(key); - }; -} +// Painted bounds of the camera art, scaled from its viewBox to source pixels. +const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36); +const GLYPH_SOURCE_ASPECT = 28.1 / 19.5; /** Merged camera groups and their last painted hit rectangles in CSS pixels. */ export function createCountMarkers( registerPaintLane, id, refreshView, - createCanvas = () => globalThis.document?.createElement('canvas'), + keyholeAlpha, ) { - let dpr = Math.max(1, Number(globalThis.window?.devicePixelRatio) || 1); + let hardUi = null; + let sprite = null; + let spriteReady = false; const markers = []; const hits = []; const textMetrics = new Map(); @@ -125,15 +77,15 @@ export function createCountMarkers( active: false, target: 'shared', }); - const glyphFor = createCameraGlyphCache( - createCanvas, - IDLE_CAMERA_ICON, - () => { - if (!markers.length) return; - refreshGlyphs(); - lane?.requestPaint(); - }, - ); + function loadSprite() { + if (sprite || typeof Image === 'undefined') return; + sprite = new Image(); + sprite.onload = () => { + spriteReady = true; + if (markers.length) lane?.requestPaint(); + }; + sprite.src = COUNT_CAMERA_ICON; + } fonts?.addEventListener?.('loadingdone', fontsLoaded); /** Font changes can widen a pill enough to merge it with its neighbor. */ @@ -149,14 +101,12 @@ export function createCountMarkers( const text = formatCameraCount(count); let metrics = textMetrics.get(text); if (!metrics) { - measureCtx ??= createCanvas()?.getContext('2d'); - if (measureCtx) { - measureCtx.font = FONT; - measureCtx.textBaseline = 'middle'; - metrics = measureCtx.measureText(text); - } else { - metrics = { width: text.length * 8 }; - } + measureCtx ??= globalThis.document + .createElement('canvas') + .getContext('2d'); + measureCtx.font = FONT; + measureCtx.textBaseline = 'middle'; + metrics = measureCtx.measureText(text); textMetrics.set(text, metrics); } const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count); @@ -175,9 +125,8 @@ export function createCountMarkers( COUNT_GLYPH_TOP_MIN_PX + (COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown - radius; - // Width-only metrics use half the 12 px type size on each side of the baseline. - const ascent = metrics.actualBoundingBoxAscent ?? 6; - const descent = metrics.actualBoundingBoxDescent ?? 6; + const ascent = metrics.actualBoundingBoxAscent; + const descent = metrics.actualBoundingBoxDescent; const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2; // Each row must clear the ring at the edge where the circle is narrowest. const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2)); @@ -204,14 +153,18 @@ export function createCountMarkers( /** * Reuse marker slots in ground-key order, and invalidate only changed frames. - * `groundHeight(lon, lat)` answers the drawn terrain height in metres, or - * null where it is not loaded; with it a count stands on the ground it - * marks whatever heights its cameras hold. + * `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite + * value where it has not loaded. A count stands on that ground when available + * and otherwise uses its cameras' mean mount height. */ function update(cells, project, groundHeight = null) { // Lone cameras take part so that one beside a count joins it. let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); - const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); + const footprint = (count, cell) => { + if (count > 1) return sizeFor(count); + const px = cell.iconPx ?? CAMERA_ICON_PX; + return { width: px, height: px }; + }; /** A lone camera keeps its icon's own position; a count goes to ground. */ const ground = (list) => { if (!groundHeight) return; @@ -224,7 +177,9 @@ export function createCountMarkers( }; for ( let pass = 0; - pass < COUNT_MERGE_PASSES && visible.length > 1; + pass < COUNT_MERGE_PASSES && + visible.length > 1 && + visible.some((cell) => cell.count > 1); pass++ ) { ground(visible); @@ -246,7 +201,7 @@ export function createCountMarkers( let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; - const marker = markers[i] ?? (markers[i] = { focus: 1 }); + const marker = (markers[i] ??= { focus: 1 }); const last = marker.cell; const size = sizeFor(cell.count); if ( @@ -258,16 +213,23 @@ export function createCountMarkers( last.groundM !== cell.groundM ) { marker.pos = cellCenter(cell); + marker.cullPos = liftedForHorizon(marker.pos); + marker.hudHidden = undefined; changed = true; - } else if ( - last.west !== cell.west || - last.east !== cell.east || - last.south !== cell.south || - last.north !== cell.north || - last.low !== cell.low || - last.high !== cell.high - ) { - changed = true; + } + // A count hidden by the HUD leaves its lone cameras visible as icons. + if (hardUi && cell.lone?.length) { + const at = project(marker.pos); + if ( + at && + hardUi({ + x: at.x - size.width / 2, + y: at.y - size.height / 2, + w: size.width, + h: size.height, + }) + ) + for (const lone of cell.lone) lone.absorbed = false; } changed ||= size.text !== marker.text || @@ -276,24 +238,19 @@ export function createCountMarkers( size.labelY !== marker.labelY; marker.cell = cell; Object.assign(marker, size); - marker.glyph = glyphFor(size.glyphHeight, dpr, CAMERA_GREEN); // Paint never grows the hit buffer, even when a pan reveals every group. hits[i] ??= {}; } markers.length = visible.length; + if (markers.length) loadSprite(); // Keep the last frame pickable until the host clears its pixels. lane?.setActive(markers.length > 0 || hitCount > 0); if (changed) lane?.requestPaint(); } - /** Attach the raster for the current overlay density to each visible group. */ - function refreshGlyphs() { - for (const marker of markers) - marker.glyph = glyphFor(marker.glyphHeight, dpr, CAMERA_GREEN); - } - /** Draw at device density using the host's CSS-pixel transform and projection. */ function paint(frame) { + hardUi = frame.overlapsHardUi ?? hardUi; if (!markers.length) { // Deactivating invalidates the host, so finish the shared frame first. if (hitCount) queueMicrotask(deactivateIfEmpty); @@ -302,10 +259,7 @@ export function createCountMarkers( } hitCount = 0; const { ctx, occluder, viewProjectionMatrix: m } = frame; - if (dpr !== frame.dpr) { - dpr = frame.dpr; - refreshGlyphs(); - } + let refresh = false; ctx.save(); try { ctx.font = FONT; @@ -316,7 +270,7 @@ export function createCountMarkers( const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; - if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) + if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos))) continue; const x = (0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) * @@ -333,11 +287,22 @@ export function createCountMarkers( rect.x >= frame.width || rect.y >= frame.height || rect.x + rect.w <= 0 || - rect.y + rect.h <= 0 || - frame.overlapsHardUi(rect) + rect.y + rect.h <= 0 ) continue; - ctx.globalAlpha = marker.focus; + const hidden = Boolean(hardUi?.(rect)); + if (marker.hudHidden !== hidden) { + marker.hudHidden = hidden; + // A first frame or moving HUD can change which lone icons must show. + refresh ||= marker.cell.lone?.some( + (cell) => cell.absorbed === hidden, + ); + } + if (hidden) continue; + const fade = + frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1; + if (!(fade > 0)) continue; + ctx.globalAlpha = marker.focus * fade; ctx.beginPath(); ctx.roundRect( rect.x + STROKE_INSET, @@ -355,18 +320,15 @@ export function createCountMarkers( ctx.lineWidth = RING_PX; ctx.stroke(); ctx.fillStyle = CAMERA_GREEN; - const glyph = marker.glyph; - if (glyph) { + if (spriteReady) { + const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT; ctx.drawImage( - glyph.canvas, - glyph.left, - glyph.top, - glyph.width, - glyph.height, - x - glyph.drawWidth / 2, - y + marker.glyphBottom - glyph.drawHeight, - glyph.drawWidth, - glyph.drawHeight, + sprite, + ...GLYPH_SOURCE, + x - width / 2, + y + marker.glyphBottom - marker.glyphHeight, + width, + marker.glyphHeight, ); } ctx.fillText(marker.text, x, y + marker.labelY); @@ -376,6 +338,7 @@ export function createCountMarkers( } finally { ctx.restore(); } + if (refresh) queueMicrotask(refreshView); } /** Resolve the topmost group actually painted at this screen position. */ @@ -383,13 +346,14 @@ export function createCountMarkers( if (!point) return null; for (let i = hitCount - 1; i >= 0; i--) { const rect = hits[i]; - if ( - point.x >= rect.x && - point.x <= rect.x + rect.w && - point.y >= rect.y && - point.y <= rect.y + rect.h - ) - return rect.cell; + const radius = rect.h / 2; + // Distance from the pill's horizontal centre segment. + const dx = Math.max( + 0, + Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2, + ); + const dy = point.y - (rect.y + radius); + if (dx * dx + dy * dy <= radius * radius) return rect.cell; } return null; } @@ -407,7 +371,7 @@ export function createCountMarkers( /** Unhook this viewer's painter and its font listener. */ function dispose() { - markers.length = hits.length = hitCount = 0; + hide(); fonts?.removeEventListener?.('loadingdone', fontsLoaded); lane?.unregister(); } diff --git a/src/layers/cctv/countMarkers.test.mjs b/src/layers/cctv/countMarkers.test.mjs new file mode 100644 index 0000000000..f3b2398a99 --- /dev/null +++ b/src/layers/cctv/countMarkers.test.mjs @@ -0,0 +1,136 @@ +import { test, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { createCountMarkers } from './countMarkers.js'; +import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; + +const W = 800; +const H = 600; +const A = 6378137; +// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture). +const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 }); +const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI; +const matrix = new Float64Array([ + 0, + 0, + 0, + 0, + 2 / (30 * W), + 0, + 0, + 0, + 0, + 2 / (30 * H), + 0, + 0, + 0, + 0, + 0, + 1, +]); + +function cellAt(key, x, count, height = 0) { + const cell = createCameraCell(key); + for (let i = 0; i < count; i++) + addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height }); + return cell; +} + +let painter; +function makeCtx() { + return { + labels: [], + globalAlpha: 1, + save() {}, + restore() {}, + beginPath() {}, + roundRect() {}, + stroke() {}, + fill() {}, + drawImage() {}, + fillText(text, x, y) { + this.labels.push({ text, x, y, alpha: this.globalAlpha }); + }, + }; +} +function paint(overrides = {}) { + const ctx = makeCtx(); + painter({ + ctx, + width: W, + height: H, + dpr: 1, + viewProjectionMatrix: matrix, + occluder: { isPointVisible: () => true }, + overlapsHardUi: () => false, + ...overrides, + }); + return ctx.labels; +} +function counts(refresh = () => {}, keyholeAlpha) { + return createCountMarkers( + (_lane, paintFn) => { + painter = paintFn; + return { requestPaint() {}, setActive() {}, unregister() {} }; + }, + 'counts', + refresh, + keyholeAlpha, + ); +} + +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + measureText: (text) => ({ + width: text.length * 7, + actualBoundingBoxAscent: 4, + actualBoundingBoxDescent: 4, + }), + }), + }), + }; +}); +afterEach(() => { + delete globalThis.document; +}); +test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => { + const m = counts(); + m.update([cellAt('a', 400, 2, -20)], project, () => -30); + const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid + const horizon = horizonFrom(eye); + assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true); + assert.equal(paint({ occluder: horizon }).length, 1); +}); + +test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => { + const hud = { overlapsHardUi: (rect) => rect.x < 200 }; + for (const paintedFirst of [true, false]) { + const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)]; + const m = counts(() => m.update(cells, project)); + if (paintedFirst) paint(hud); + m.update(cells, project); + const labels = paint(hud); + await Promise.resolve(); + assert.ok(!cells[1].absorbed || labels.length > 0); + // Moving the HUD at rest also changes whether the lone icon is needed. + paint(); + await Promise.resolve(); + assert.equal(cells[1].absorbed, true); + paint(hud); + await Promise.resolve(); + assert.equal(cells[1].absorbed, false); + m.dispose(); + } +}); + +test('counts fade with the Scope keyhole like the callouts', () => { + const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha); + m.update([cellAt('a', 400, 2)], project); + assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25); + assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []); + assert.equal(m.pickedCell({ x: 400, y: 300 }), null); + assert.equal(paint()[0].alpha, 1); +}); diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 84db00b13e..194be38cc0 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -1,4 +1,4 @@ -import { fromDegrees } from '../../geo/ellipsoid.js'; +import { fromDegreesInto } from '../../geo/ellipsoid.js'; import { findGlobe } from '../../render/rendererOf.js'; import { SUPPORT_KEYS, @@ -233,6 +233,12 @@ export function createGround({ state: layerState, services, parts, source }) { // Stale-record guard: init() may have re-run (destroy/init cycle) while // the batch was in flight — only touch records still live in the map. if (layerState._recordById.get(record.camera.id) !== record) return null; + // The drawn terrain beats a fallback. Only a real batch answer replaces it. + if ( + prior.source === 'geoid-fallback' && + record.groundPrior?.source === 'drawn-terrain' + ) + return null; record.groundPrior = prior; // Keep the cheap pre-enable altitude consistent for records whose // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). @@ -247,14 +253,12 @@ export function createGround({ state: layerState, services, parts, source }) { if (!record.frustumGeometry) { if (!record.position) return null; // In place: the record keeps its position object. - const { x, y, z } = fromDegrees( + fromDegreesInto( record.camera.lon, record.camera.lat, record.camera.absoluteHeightM, + record.position, ); - record.position.x = x; - record.position.y = y; - record.position.z = z; parts.rendering.moveCameraIcon(record); return 'moved'; } @@ -274,19 +278,17 @@ export function createGround({ state: layerState, services, parts, source }) { } /** - * A camera the height batch never answered for (a failed or rate-limited - * chunk leaves it on the catalog's fabricated ground) takes the terrain - * the globe draws under it as its prior, so that it stands on the surface - * the user sees. `rangeM` is how far the eye was when the terrain was - * read: a closer look reads finer terrain and replaces it, and so does a - * batch answer that arrives later. + * Applies drawn terrain as a drawn-terrain prior. The read records the eye + * distance (rangeM), globe surface version (surface) and whether terrain + * loading had finished (settled). Reading from under half that range or + * receiving a later Re:Earth answer replaces the height. * @returns {'moved'|'applied'|null} As `applyGroundPrior`. */ - function adoptDrawnGround(record, heightM, rangeM) { + function adoptDrawnGround(record, heightM, read) { return applyGroundPrior(record, { ellipsoid: heightM, source: 'drawn-terrain', - rangeM, + ...read, }); } diff --git a/src/layers/cctv/ground.test.mjs b/src/layers/cctv/ground.test.mjs new file mode 100644 index 0000000000..c804460f19 --- /dev/null +++ b/src/layers/cctv/ground.test.mjs @@ -0,0 +1,64 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createGround } from './ground.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; + +function setup(record) { + const calls = { culling: 0, geometry: [], notify: 0 }; + const state = { + _viewer: null, + _recordById: new Map([[record.camera.id, record]]), + }; + const parts = { + rendering: { + refreshHorizonCulling: () => (calls.culling++, true), + moveCameraIcon() {}, + }, + geometryQueue: { enqueueViewGeometry() {} }, + presentation: { notifyListeners: () => calls.notify++ }, + geometry: { + // Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell. + updateRecordGeometry(r) { + calls.geometry.push( + ground.groundPriorAltFor(r) + r.camera.mountHeightM, + ); + }, + }, + }; + const ground = createGround({ + state, + services: { + ground: { resolveGroundFloorCells: async () => {} }, + terrain: { resolveEllipsoidalGround: async () => [] }, + }, + parts, + }); + return { ground, calls }; +} + +test('a late geoid fallback leaves a drawn-terrain height in place', () => { + const camera = { + id: 'a', + lat: 42, + lon: -118, + mountHeightM: 8, + absoluteHeightM: 1880, + }; + const record = { + camera, + position: fromDegrees(camera.lon, camera.lat, 1880), + frustumGeometry: {}, + frustumPositions: {}, + groundSamples: {}, + groundResolved: {}, + groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 }, + }; + const { ground, calls } = setup(record); + ground.applyLateGroundPriors( + [record], + [{ ellipsoid: 0, source: 'geoid-fallback' }], + ); + + assert.equal(record.groundPrior.source, 'drawn-terrain'); + assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback'); +}); diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index b20592d396..7dbdcc0fca 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -1,6 +1,6 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { distance, dot } from '../../geo/vector.js'; -import { canvasOf, findCamera } from '../../render/rendererOf.js'; +import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js'; import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js'; import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js'; @@ -103,6 +103,30 @@ export function createLifecycle({ * listeners to its camera; one against the same viewer keeps them. */ function attachViewListeners() { + const globe = findGlobe(layerState._viewer); + if (layerState._surfaceListenerGlobe !== globe) { + layerState._surfaceListener?.(); + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = globe; + } + if (!layerState._surfaceListener && globe?.on) { + // Refresh drawn heights when terrain finishes loading or the surface changes. + let version = globe.surfaceVersion?.(); + let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0; + layerState._surfaceListener = globe.on('progress', (progress) => { + const next = globe.surfaceVersion?.(); + const loaded = progress?.terrainPending === 0 && terrainPending !== 0; + const swapped = next !== version; + version = next; + terrainPending = progress?.terrainPending ?? terrainPending; + if ( + (loaded || swapped) && + layerState._enabled && + !layerState._cameraMoving + ) + settleView(); + }); + } const viewCamera = findCamera(layerState._viewer); if ( layerState._viewListenerCamera && @@ -140,6 +164,9 @@ export function createLifecycle({ /** Drop the move listeners; nothing reports the end of a move after it. */ function detachViewListeners() { + layerState._surfaceListener?.(); + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = null; layerState._horizonCullListener?.(); layerState._horizonCullListener = null; layerState._moveStartListener?.(); @@ -287,9 +314,8 @@ export function createLifecycle({ coverageEntities: [], projection: null, // Task 5 (height-datum fix): regime-aware ground resolution state. - // groundPrior — { ellipsoid, source } from the Re:Earth batch - // (null until a late batch lands). The prior applies in EVERY - // regime and is the terrain-globe resolution outright. + // groundPrior — { ellipsoid, source } from the Re:Earth batch, or + // drawn-terrain with its read conditions for an unanswered camera. // groundResolved — PER-REGIME one-shot latch (regime key → // boolean): true once this record's resolution completed for that // regime; such records are excluded from the completion pass so diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index 205997721b..080fbcfb47 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -72,3 +72,37 @@ test('the view listeners follow the camera port and let go on teardown', () => { assert.deepEqual(counts(second.camera), [0, 0]); assert.equal(state._viewListenerCamera, null); }); + +test('terrain loading and surface changes rerun the view pass', () => { + const viewer = {}; + let version = 1, + progress, + removed = false; + bindRenderer(viewer, { + camera: fakeCameraPort().port, + globe: { + surfaceVersion: () => version, + on(event, cb) { + assert.equal(event, 'progress'); + progress = cb; + return () => { + removed = true; + }; + }, + }, + }); + const { lifecycle, passes } = lifecycleFor({ + _viewer: viewer, + _enabled: true, + }); + lifecycle.attachViewListeners(); + progress({ terrainPending: 2 }); + assert.equal(passes.length, 0); + progress({ terrainPending: 0 }); + assert.equal(passes.length, 1); + version++; + progress({ terrainPending: 0 }); + assert.equal(passes.length, 2); + lifecycle.detachViewListeners(); + assert.ok(removed); +}); diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index 8e69d9e5e8..a52d419782 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,3 +1,5 @@ +import { distance } from '../../geo/vector.js'; +import { rangeForBoundingSphere } from '../../data/cameraFraming.js'; import { isFollowing } from '../../data/followed.js'; import { cellBounds } from '../../data/cctvCellCounts.js'; import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js'; @@ -64,6 +66,16 @@ export function createNavigation({ return true; } + /** What holds the view instead of a CCTV flight, or null when it is free. */ + function viewHeldBy(viewer) { + if ( + typeof document !== 'undefined' && + document.body?.classList.contains('cockpit-mode') + ) + return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE; + return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null; + } + /** * Flies the viewer's camera to frame the specified CCTV camera, * looking along its heading from above. @@ -75,14 +87,12 @@ export function createNavigation({ function focusCctvRecord(viewer, record, duration = 2.2) { if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA; - if ( - typeof document !== 'undefined' && - document.body?.classList.contains('cockpit-mode') - ) { + const held = viewHeldBy(viewer); + if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) { console.debug('[Data:CCTV] focus ignored while cockpit owns the camera'); return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE; } - if (isFollowing(viewer)) { + if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) { console.debug( '[Data:CCTV] focus ignored while a tracked entity owns the camera', ); @@ -108,17 +118,24 @@ export function createNavigation({ /** Frame a group's padded bounds from above, including coincident mounts. */ function zoomToCell(cell) { const viewer = layerState._viewer; + if (!viewer || viewHeldBy(viewer)) return; const camera = cameraOf(viewer); const pose = camera.pose(); const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2); const canvas = canvasOf(viewer); const height = canvas?.clientHeight || canvas?.height || 1; - const halfFov = Math.atan(tanHalfY * Math.min(1, pose.aspectRatio || 1)); const bounds = cellBounds(cell); - // A tight group lands comfortably inside the individual-icon level. + // Half the range where cells stop grouping, so even coincident mounts split. const closeRange = (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); - const range = Math.max(closeRange, bounds.radius / Math.sin(halfFov)); + // Approach long groups in halves so every click gets closer. + const halfway = pose.position + ? distance(pose.position, bounds.center) / 2 + : Infinity; + const range = Math.min( + halfway, + Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)), + ); camera.flyToBounds(bounds, { offset: { heading: 0, pitch: -Math.PI / 2, range }, durationS: 1.2, diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 87fdaf4c32..291cea53e8 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -60,65 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300; export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10; -// View thinning: camera icons show only on or near the screen, and each -// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX -// at its distance from the viewer (in power-of-two metre steps, so a pan -// keeps the same winners until a camera's distance crosses a step). Cells -// smaller than VIEW_MIN_CELL_M do not thin: -// close up every camera shows, co-located ones included. +// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX +// at their distance. Power-of-two metre steps keep cells stable during a pan. +// A cell with several cameras draws one count. Its best-ranked camera represents +// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so +// every camera shows close up. export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; -// Cameras on one mount (the same point to about a metre) draw side by side, +// Cameras within this horizontal distance in metres share a mount. +export const VIEW_SITE_M = 1.5; + +// Cameras on one mount (VIEW_SITE_M) draw side by side, // this many pixels apart, once they show as icons. export const VIEW_SITE_SPREAD_PX = 30; -// Cameras without a ground height that one view pass may read from the drawn -// terrain. The rest wait for the next pass. +// Drawn-terrain reads per view pass for unanswered cameras and for re-reads +// of drawn heights. Off-screen cameras can use at most half of the budget. +// Remaining reads wait for the next pass. export const VIEW_GROUND_READS = 300; -// Diameter at one camera before applying the size limits, in CSS pixels. -export const COUNT_BASE_PX = 38; - -// Extra diameter for each tenfold increase in camera count. -export const COUNT_PX_PER_DECADE = 5; - -// Minimum height of a count marker in CSS pixels. -export const COUNT_MIN_HEIGHT_PX = 40; - -// Maximum height of a count marker in CSS pixels. -export const COUNT_MAX_HEIGHT_PX = 58; - -// Clear fill between the count and the inside of the ring, in CSS pixels. -export const COUNT_TEXT_PADDING_PX = 6; - -// Height of the camera glyph in the smallest and the largest marker. -export const COUNT_GLYPH_MIN_PX = 7.5; -export const COUNT_GLYPH_MAX_PX = 10; - -// Clear fill above the glyph in the smallest and the largest marker. -export const COUNT_GLYPH_TOP_MIN_PX = 3; -export const COUNT_GLYPH_TOP_MAX_PX = 4; - -// Clear fill between the glyph's top corners and the inside of the ring. -export const COUNT_GLYPH_PADDING_PX = 2; - -// The middle of the digits sits this share of the inner radius below the -// marker's centre, which leaves the glyph clear of the count. -export const COUNT_LABEL_DROP = 0.2; +/** + * The camera icon's drawn size (px). Its SVG is 48 px: 1.25× + * near scale on a 2× display draws it at 60 device px, so it is rasterised + * past the drawn size to stay sharp there. + */ +export const CAMERA_ICON_PX = 24; // Minimum gap between the outer rims of two separate markers. export const COUNT_MERGE_GAP_PX = 4; -// On-screen size of a lone camera's icon when testing it against a count -// marker: an icon closer than the merge gap joins that count. -export const COUNT_SINGLE_ICON_PX = 24; - -// Recheck moved centres and wider labels while bounding work on motion ticks. -export const COUNT_MERGE_PASSES = 3; - // Icons this far past the screen edge (fraction of its size) still show, so // a pan does not reveal empty ground before the next view pass. @@ -230,33 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({ /** * Base64-encoded SVG camera icon for the camera icons. Icons rasterise an * SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a - * 2× display draws it at 60 device px, and it stays sharp there. + * 2× display draws it at 60 device px, and it stays sharp there. Active and + * live cameras use cyan art with a billboard tint. Idle cameras use white + * and gray art so the billboard green shows true. The overlay draws the + * green variant directly. */ -function cameraIcon(neutral) { - const tone = (original, gray) => (neutral ? gray : original); - const stroke = tone('#75e7ff', '#fff'); +function cameraIcon(tint = null) { + function tone(original, gray) { + if (!tint) return original; + const shade = parseInt(gray.slice(1, 3), 16) / 255; + return ( + '#' + + tint + .slice(1) + .match(/../g) + .map((channel) => + Math.round(parseInt(channel, 16) * shade) + .toString(16) + .padStart(2, '0'), + ) + .join('') + ); + } + const stroke = tone('#75e7ff', '#ffffff'); const svg = ` - - - + + + - - + + - + `; return 'data:image/svg+xml;base64,' + btoa(svg); } -export const CAMERA_ICON = cameraIcon(false); -export const IDLE_CAMERA_ICON = cameraIcon(true); +export const CAMERA_ICON = cameraIcon(); +export const IDLE_CAMERA_ICON = cameraIcon('#ffffff'); /** * Seed camera definitions used when no live sources are available. @@ -496,6 +487,7 @@ export const CAMERA_SEEDS = [ /** Shared accent for idle still cameras and grouped cameras. */ export const CAMERA_GREEN = '#5dff8f'; +export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN); export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN); diff --git a/src/layers/cctv/presentation.js b/src/layers/cctv/presentation.js index ed8a715ebd..1b25cef84d 100644 --- a/src/layers/cctv/presentation.js +++ b/src/layers/cctv/presentation.js @@ -229,9 +229,12 @@ export function createPresentation({ // separately from the currently applied frustum ground. Google-3D may // legitimately refine the latter to the rendered mesh, so callers must // not infer the prior by subtracting mount height from live geometry. - groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid) - ? record.groundPrior.ellipsoid - : null, + // A height read from drawn terrain is unavailable as a Re:Earth prior. + groundPriorM: + Number.isFinite(record.groundPrior?.ellipsoid) && + record.groundPrior.source !== 'drawn-terrain' + ? record.groundPrior.ellipsoid + : null, intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null, extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null, anchor: camera.anchor ? { ...camera.anchor } : null, @@ -310,11 +313,11 @@ export function createPresentation({ } /** - * `{ id, city, name }` for the active camera, then every camera the view - * pass shows: what the camera picker lists. A whole catalog would put tens - * of thousands of options in the DOM and slow every layout. The same array - * is returned until the view or the active camera changes, so a consumer - * can compare it by identity. + * `{ id, city, name }` for the active camera, then each camera shown as an + * icon and the best-ranked camera of each visible group. A whole catalog + * would put tens of thousands of options in the DOM and slow every layout. + * Consumers can compare the array by identity until the picker records or + * active camera change. * @returns {{id: string, city: string, name: string}[]} */ diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index a2d5a7663c..4fee5ce9cb 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -4,6 +4,9 @@ import { isHeadingEstimated } from './headingConfidence.js'; import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, + CAMERA_ICON_PX, + COUNT_MERGE_GAP_PX, + VIEW_SITE_M, IDLE_CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, @@ -30,11 +33,16 @@ import { findQuery, } from '../../render/rendererOf.js'; import { heightsOf } from '../../queries/heights.js'; -import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js'; +import { + fromDegrees, + fromDegreesInto, + toLonLatH, + WGS84, +} from '../../geo/ellipsoid.js'; import { eastNorthUp } from '../../geo/frames.js'; import { poseProjector } from '../../geo/frustum.js'; import { horizonFrom } from '../../geo/horizon.js'; -import { distance } from '../../geo/vector.js'; +import { add, distance, dot, scale, sub } from '../../geo/vector.js'; const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR }; const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR }; @@ -56,12 +64,6 @@ const samePoint = (a, b) => /** Degrees to radians. */ const toRadians = (degrees) => (degrees * Math.PI) / 180; -/** - * The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25× - * near scale on a 2× display draws it at 60 device px, so it is rasterised - * past the drawn size to stay sharp there. - */ -const CAMERA_ICON_PX = 24; const CAMERA_SCALE_BY_DISTANCE = Object.freeze({ near: 350, nearValue: 1.25, @@ -153,6 +155,7 @@ export function createRendering({ services.overlays?.registerWorldOverlayPaintLane, `cctv:${iconSets}:counts`, refreshHorizonCulling, + services.overlays?.keyholeAlpha, ); return set.id; } @@ -170,7 +173,7 @@ export function createRendering({ const id = record.camera.id; return { id, - pos: copyPoint(record.position), + pos: copyPoint(record.spreadPosition ?? record.position), ...cameraIconStyleFor(record), size: [CAMERA_ICON_PX, CAMERA_ICON_PX], scale: 1, @@ -211,14 +214,18 @@ export function createRendering({ function moveCameraIcon(record) { const icons = layerState._icons; if (!icons || !record.position) return; + // A camera drawn beside its mount mates keeps its offset from the mount. + if (record.spreadOffset) + record.spreadPosition = add(record.position, record.spreadOffset); + const pos = record.spreadPosition ?? record.position; const item = icons.item(record.camera.id); // A camera whose icon waited for a position is drawn now. if (!item) { icons.put(cameraIconItem(record)); return; } - if (samePoint(item.pos, record.position)) return; - icons.put({ ...item, pos: copyPoint(record.position) }); + if (samePoint(item.pos, pos)) return; + icons.put({ ...item, pos: copyPoint(pos) }); } /** Select the sprite and tint together when a camera changes state. */ @@ -235,7 +242,10 @@ export function createRendering({ focusPassIsNeeded, advanceSpriteFocus, focusAlphaNeedsWrite, + nearFarScalarValueAtDistance, } = services.focus; + const iconScaleAt = (range) => + nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1; /** * Focus modulation rides the layer's existing animation loop; no additional @@ -292,9 +302,14 @@ export function createRendering({ let writes = 0; let transitioning = false; let activeCount = 0; - /** A changed focus factor for a camera icon or a painted count. */ + /** + * A changed focus factor for an icon or count. CCTV publishes no tracked + * focus target, so every icon is ambient. + */ function changedFocus(owner, position, shown, width, height, current) { const focus = advanceSpriteFocus(owner, { + // Keep hidden owners in the active count until their dim alpha clears, + // so the focus pass keeps running while they recover. screenPosition: shown && position ? screenPositionFor(position) : null, cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, @@ -342,13 +357,16 @@ export function createRendering({ } /** - * Group horizon-visible mounts by ground cell. Every cell with a member - * near the screen contributes a representative to the picker. Singletons - * and the active camera also enter the icon, geometry and card working set. + * Cull far-side cameras on the CPU because the hidden globe writes no depth. + * Group the rest by ground cell. _viewRecords holds the active camera and + * every nearby icon outside a count for geometry and cards. Cells smaller + * than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the + * best-ranked camera of each visible cell. Both arrays keep their identity + * while their contents are unchanged. * * Runs on camera settle, throttled during motion, on resize, enable and * activation changes — never per frame. - * @returns {boolean} Whether the shown set changed. + * @returns {boolean} Whether the shown set or the picker list changed. */ function refreshHorizonCulling() { @@ -386,15 +404,26 @@ export function createRendering({ const picker = []; const cells = new Map(); const visibleCells = []; - // The terrain the globe draws, where it is the surface (not on the - // photoreal stack) and loaded: null elsewhere. + // Drawn terrain where the globe is the surface. The photoreal stack has + // no reader, and unloaded tiles return a non-finite height. const heights = heightsOf(layerState._viewer); + const globe = findGlobe(layerState._viewer); const groundHeight = - findQuery(layerState._viewer) && - findGlobe(layerState._viewer)?.isGlobeVisible?.() === true + findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true ? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' }) : null; + const surface = globe?.surfaceVersion?.() ?? 0; + const terrainSettled = globe?.isSettled?.('terrain') ?? true; let groundReads = groundHeight ? VIEW_GROUND_READS : 0; + let offscreenReads = groundReads / 2; + let eyeGround; + const column = { x: 0, y: 0, z: 0 }; + const inReadWindow = (s) => + s && + s.x >= -width && + s.x <= 2 * width && + s.y >= -height && + s.y <= 2 * height; const regrounded = []; for (const record of layerState._records) { const position = record.position; @@ -412,39 +441,66 @@ export function createRendering({ continue; let screen = project(position); let range = distance(position, viewer); - // A camera the height batch never answered for (no prior, or the - // geoid fallback a failed chunk leaves) sits near sea level, which can - // be kilometres under the terrain: it would project to the wrong - // place, drift as the view moves and measure too far for its cell. - // Anywhere near the screen, it takes the drawn terrain. + // Missing, unresolved and fallback priors can put a mount kilometres + // below the terrain, shifting its projection and inflating its cell. + // Read nearby mounts again from under half the range, on finer terrain + // after loading, or on a different surface. const prior = record.groundPrior; const drawn = prior?.source === 'drawn-terrain'; + const unanswered = + !Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback'; if ( groundReads > 0 && - (!prior || - prior.source === 'geoid-fallback' || - (drawn && prior.rangeM > 2 * range)) && - screen && - screen.x >= -width && - screen.x <= 2 * width && - screen.y >= -height && - screen.y <= 2 * height + !record.regroundPending && + (unanswered || + (drawn && + (prior.rangeM > 2 * range || + prior.surface !== surface || + (!prior.settled && terrainSettled)))) ) { - groundReads--; - const ground = groundHeight(record.camera.lon, record.camera.lat); - if (Number.isFinite(ground)) { - if (drawn && Math.abs(ground - prior.ellipsoid) < 1) { - prior.rangeM = range; - } else if (record.frustumGeometry) { - // Recomputing geometry writes draw sets: after this pass. - regrounded.push([record, ground, range]); - } else if ( - parts.ground.adoptDrawnGround(record, ground, range) === 'moved' - ) { - screen = project(position); - range = distance(position, viewer); + let probe = inReadWindow(screen) ? screen : null; + if (!probe && unanswered) { + // Its height is a guess. Try the ground under the eye instead. + if (eyeGround === undefined) { + const eye = toLonLatH(viewer); + eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null; + groundReads--; + } + if (Number.isFinite(eyeGround)) { + fromDegreesInto( + record.camera.lon, + record.camera.lat, + eyeGround + (record.camera.mountHeightM || 0), + column, + ); + const at = project(column); + if (inReadWindow(at)) probe = at; } } + const onScreen = + probe && + probe.x >= 0 && + probe.x <= width && + probe.y >= 0 && + probe.y <= height; + if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) { + groundReads--; + if (!onScreen) offscreenReads--; + const ground = groundHeight(record.camera.lon, record.camera.lat); + if (Number.isFinite(ground)) { + const read = { rangeM: range, surface, settled: terrainSettled }; + if (drawn && Math.abs(ground - prior.ellipsoid) < 1) + Object.assign(prior, read); + else if (record.frustumGeometry) { + // Recomputing geometry writes draw sets after this pass. + record.regroundPending = true; + regrounded.push([record, ground, read]); + } else parts.ground.adoptDrawnGround(record, ground, read); + } + } + // The probe reuses the projector's result, and the mount may have moved. + screen = project(position); + range = distance(position, viewer); } const nearScreen = screen && @@ -453,13 +509,25 @@ export function createRendering({ screen.y >= minY && screen.y <= maxY; const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range; - if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) { + if (record.camera.id === activeId) { if (!nearScreen) continue; record.viewPass = record.pickerPass = pass; shown.push(record); picker.push(record); continue; } + if (!(cellM >= VIEW_MIN_CELL_M)) { + if (!nearScreen) continue; + // Too close to group, but a count beside it can still take it in. + const cell = createCameraCell(`near:${record.camera.id}`); + addCellCamera(cell, record.camera); + cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range); + cell.winner = record; + cell.rank = 0; + record.viewCell = cell; + visibleCells.push(cell); + continue; + } const key = worldCellKey(record, cellM); let cell = cells.get(key); if (!cell) { @@ -467,6 +535,7 @@ export function createRendering({ cells.set(key, cell); } addCellCamera(cell, record.camera); + if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range); record.viewCell = cell; if (!nearScreen) continue; // The picker ranks only candidates that were in its padded viewport. @@ -491,6 +560,7 @@ export function createRendering({ } } spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); + clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; let cardsChanged = false; @@ -514,6 +584,7 @@ export function createRendering({ fields.pos = copyPoint(record.spreadPosition); } else if (record.spreadPosition) { // No longer beside a mount mate: back onto its own position. + record.spreadOffset = null; record.spreadPosition = null; fields.pos = copyPoint(record.position); } @@ -543,10 +614,11 @@ export function createRendering({ */ function reground(entries) { let changed = false; - for (const [record, ground, range] of entries) + for (const [record, ground, read] of entries) { + record.regroundPending = false; changed = - parts.ground.adoptDrawnGround(record, ground, range) !== null || - changed; + parts.ground.adoptDrawnGround(record, ground, read) !== null || changed; + } if (!changed) return; if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); parts.presentation.notifyListeners(); @@ -554,7 +626,7 @@ export function createRendering({ /** * Cameras on one mount would draw as one icon with several callouts. Among - * the cameras shown, those that share a point to about a metre get draw + * the cameras shown, those within VIEW_SITE_M horizontally get draw * positions side by side along the screen's horizontal, in id order, * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The * record's own position is untouched: geometry and cards keep the mount. @@ -562,15 +634,31 @@ export function createRendering({ function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { const { right, direction, position: eye } = pose; if (!right || !direction || shown.length < 2) return; - const mounts = new Map(); + const grid = new Map(); + const mounts = []; + const axes = eastNorthUp(eye); for (const record of shown) { - const { lat, lon } = record.camera; - const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`; - const mates = mounts.get(key); - if (mates) mates.push(record); - else mounts.set(key, [record]); + // Sea-level coordinates compare horizontal distance across longitude + // and latitude boundaries, including the antimeridian. + const p = fromDegrees(record.camera.lon, record.camera.lat, 0); + const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M); + const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M); + let mount; + for (let i = col - 1; !mount && i <= col + 1; i++) + for (let j = row - 1; !mount && j <= row + 1; j++) + mount = grid + .get(`${i}:${j}`) + ?.find((site) => distance(p, site.p) <= VIEW_SITE_M); + if (!mount) { + mount = { p, mates: [] }; + mounts.push(mount); + const key = `${col}:${row}`; + if (!grid.has(key)) grid.set(key, []); + grid.get(key).push(mount); + } + mount.mates.push(record); } - for (const mates of mounts.values()) { + for (const { mates } of mounts) { if (mates.length < 2) continue; mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id)); for (let i = 0; i < mates.length; i++) { @@ -586,16 +674,63 @@ export function createRendering({ VIEW_SITE_SPREAD_PX * metresPerPixelPerMetre * depth; - record.spreadPosition = { - x: p.x + right.x * metres, - y: p.y + right.y * metres, - z: p.z + right.z * metres, - }; + record.spreadOffset = scale(right, metres); + record.spreadPosition = add(p, record.spreadOffset); record.spreadPass = pass; } } } + /** Move the active camera's icon beside any count marker that would cover it. */ + function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) { + if (!layerState._activeCameraId) return; + const record = layerState._recordById.get(layerState._activeCameraId); + const markers = layerState._counts?.markers; + if ( + record?.viewPass !== pass || + !markers?.length || + !pose.right || + !pose.direction + ) + return; + const spread = record.spreadPass === pass; + const p = spread ? record.spreadPosition : record.position; + const screen = project(p); + if (!screen) return; + const { x, y } = screen; + const half = + (CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2; + const spans = []; + for (const marker of markers) { + const at = project(marker.pos); + if ( + !at || + Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX + ) + continue; + const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX; + spans.push([at.x - reach, at.x + reach]); + } + // Leave the entire overlapping interval, including an adjacent count. + spans.sort((a, b) => a[0] - b[0]); + let left = Infinity, + right = -Infinity; + for (const [start, end] of spans) { + if (start >= right) { + if (left < x && x < right) break; + left = start; + right = end; + } else right = Math.max(right, end); + } + if (!(left < x && x < right)) return; + const shift = x - left < right - x ? left - x : right - x; + const depth = dot(sub(p, pose.position), pose.direction); + const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth); + record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset; + record.spreadPosition = add(record.position, record.spreadOffset); + record.spreadPass = pass; + } + /** * Canvas coordinates for world positions, from the eye's pose by the * renderer's perspective projection (geo/frustum.js): one pose read per diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 6d4600ec3b..f2548d9aff 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -153,6 +153,7 @@ test('the icons go with the viewer that drew them, whichever tears down', () => name, paint, options, + setActive() {}, unregister() { this.disposed = true; }, diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 6948b2a8a2..9364911537 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -1,3 +1,4 @@ +import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { isTrackingClickGesture } from '../../data/trackingClickGesture.js'; export function createSelection({ @@ -7,7 +8,7 @@ export function createSelection({ source, }) { const { CCTV_ACTIVATION_RESULT } = services.activation; - const { resolvePickId } = services.picking; + const { resolvePickId, findPickOwner } = services.picking; /** * Returns the camera record for the currently active camera. A stale ID falls @@ -29,6 +30,23 @@ export function createSelection({ return fallback; } + /** A card painted above the count, or another layer's object, owns the click. */ + function countYields(event) { + const { x, y } = event.screenPosition; + if ( + layerState._cctvOverlayHost?.hitTest(x, y, { + sourceId: CCTV_OVERLAY_SOURCE_ID, + })?.entryId + ) + return true; + const top = event.topHit; + if (!top) return false; + const drawHit = event.drawHit; + if (drawHit) return !parts.rendering.extractPickedCameraId(drawHit); + const id = resolvePickId(top); + return id !== null && findPickOwner?.(id) !== 'cctv'; + } + /** * Bind CCTV activation to clean taps. Drag-like and long-press gestures do * not reach camera activation or focus dispatch. @@ -44,7 +62,7 @@ export function createSelection({ const cell = layerState._enabled && layerState._counts?.pickedCell(event.screenPosition); - if (cell) { + if (cell && !countYields(event)) { parts.navigation.zoomToCell(cell); return; } @@ -146,9 +164,9 @@ export function createSelection({ // is looking at ever asks. void parts.ground.resolveFootprintGround(record); record.activationDone = true; - // The active camera's icon always shows; the previously active one - // competes for its cell again. Its coverage neighbours join the working - // set and are queued for grounding. + // The active icon always shows and the previous one rejoins its cell. + // Restyle coverage after the view pass sets grouping. Its coverage + // neighbours join the working set and are queued for grounding. parts.rendering.refreshHorizonCulling(); parts.rendering.refreshCoverageStyles(); parts.geometryQueue.enqueueViewGeometry(); diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index f03ded5ceb..297a2f674f 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -1,3 +1,4 @@ +import * as picking from '../../data/pickRegistry.js'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js'; @@ -103,3 +104,49 @@ test('a count click preserves the provisional opening pick until the view settle unbind(); } }); + +test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => { + let zooms = 0, + clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: () => ({}) }, + _cctvOverlayHost: { + hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null), + }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { + extractPickedCameraId: (hit) => + hit?.set === 'cctv-icons' ? hit.id : null, + }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + picking.registerPickOwner('cctv', (id) => id.startsWith('cam-')); + try { + for (const [x, topHit, expected] of [ + [14, null, [0, 1]], + [20, { set: 'flights', id: 'abc' }, [0, 2]], + [20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]], + [20, null, [2, 2]], + [20, { set: 'flights', id: 'cam-2' }, [2, 3]], + ]) { + click({ + screenPosition: { x, y: 26 }, + topHit, + drawHit: topHit, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.deepEqual([zooms, clicks], expected); + } + } finally { + picking.unregisterPickOwner('cctv'); + } +}); diff --git a/src/layers/cctv/state.js b/src/layers/cctv/state.js index a6778de8f3..95c08e2f13 100644 --- a/src/layers/cctv/state.js +++ b/src/layers/cctv/state.js @@ -96,13 +96,14 @@ export function createState({ services }) { // work over these, not the whole catalog. layerState._viewRecords = []; - // Includes a health-ranked representative for each visible group. + // The view records plus the best-ranked camera of each visible cell. layerState._pickerRecords = []; - // Coverage ids refreshCoverageStyles last drew: part of the geometry - // working set even when their icons are thinned out. - + // The active camera's coverage neighbours, including grouped ones. A + // grouping change in this cohort requires a coverage refresh. layerState._coverageCohort = null; + // The cohort minus grouped cameras, last drawn by refreshCoverageStyles. + // These belong to the geometry working set even off screen. layerState._coverageVisibleIds = new Set(); // View pass triggers besides camera settle: an interval while the camera @@ -117,6 +118,9 @@ export function createState({ services }) { // The camera port the moveStart/moveEnd listeners are on. layerState._viewListenerCamera = null; + // Reruns the view pass when terrain loads or the surface changes. + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = null; // A motion pass changed the shown set and the settle pass has not yet told // subscribers; the camera pose the last view pass ran at. From f6982dc934e7e7c8062ad44662504486eed9fa93 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 17:52:50 +0400 Subject: [PATCH 8/9] fix(cctv): a count click yields to what is on top and keeps its group in frame - A count click stands aside when an overlay label or another layer's card already took the click, and CCTV now claims a count click in the shared pick registry, so the flights layer no longer reads it as an empty-map click and keeps tracking its aircraft. - The flight to a group halves the distance only while the group stays in frame; otherwise it flies to the nearest ground cell of the group, so a tilted click no longer ends with no camera on screen. - Counts hidden under the HUD no longer push the active icon aside, and a lone camera that would move a merged count under the HUD leaves the original count and its icon as they were. - Cameras on one mount are spread before counts merge, so a spread icon no longer slides under a neighbouring count. - The ground module comment says how a camera without a batch height takes the drawn terrain. --- docs/CURRENT-STATE.md | 16 +++-- scripts/format-scope.json | 2 + src/data/cctvCards.js | 2 + src/data/cctvCellCounts.js | 17 ++++- src/data/pickRegistry.js | 40 ++++++++++-- src/data/pickRegistry.test.mjs | 41 ++++++++++++ src/layers/cctv/countMarkers.js | 51 +++++++++------ src/layers/cctv/countMarkers.test.mjs | 19 ++++++ src/layers/cctv/count_click_framing.test.mjs | 67 ++++++++++++++++++++ src/layers/cctv/count_click_overlay.test.mjs | 65 +++++++++++++++++++ src/layers/cctv/ground.js | 5 +- src/layers/cctv/lifecycle.js | 13 +++- src/layers/cctv/navigation.js | 37 ++++++++--- src/layers/cctv/rendering.js | 31 +++++---- src/layers/cctv/selection.js | 55 +++++++++++----- src/layers/cctv/selection.test.mjs | 61 ++++++++++++++++++ 16 files changed, 452 insertions(+), 70 deletions(-) create mode 100644 src/layers/cctv/count_click_framing.test.mjs create mode 100644 src/layers/cctv/count_click_overlay.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4f2b6e34a6..76c142c7b3 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1998,10 +1998,13 @@ middle. The marker grows with the count and paints on the world overlay at callout resolution. The count covers the whole cell up to the horizon, including its off-screen cameras. Overlapping markers merge and add their counts. A lone camera whose icon would touch a marker joins the nearest one, unless the HUD -hides that marker. The active camera keeps its own icon beside any marker that -would cover it and stays out of the count. A click on a marker zooms in on its -group, at least halving the distance each time. The view stays put while the -cockpit or a tracked object holds it. Ambient cards and coverage attach only to +hides the merged marker. In that case the lone camera keeps its icon and the +count stays where it was before the merge. The active camera keeps its own icon +beside any marker that would cover it and stays out of the count. A click on a +marker zooms in on its group, at least halving the distance each time. If halving +would leave the group wider than the frame, the view zooms in on the group's +ground cell nearest the eye. The cockpit or a tracked object holds the view +in place. Ambient cards and coverage attach only to cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A camera the height batch never answered for takes the drawn terrain as its ground once it is near the screen. It reads that height again from much closer, once @@ -2131,7 +2134,10 @@ trail, a route. A layer under another layer's card or label (`isUnderOtherCard`) does nothing: it neither acts on its item there nor treats the click as empty space, so a tracked aircraft stays tracked and a selection stays selected. Context (`src/ui/entityContextBridge.js`) names -nothing under a card. With no card on top, the scene rules are unchanged. +nothing under a card. A layer can claim a target it paints outside the overlay's +entries (`registerClickClaim`) where no card or label is on top. A CCTV count +claims each click that zooms to it, so a tracked aircraft stays tracked. +With no card or claim on top, the scene rules are unchanged. World-overlay hit rectangles are what is painted on screen until the next paint: an overlay change (a click subscriber publishing its selection card) no longer clears them mid-click, and a paint that draws nothing clears them diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 3cfaf54072..8f1f106931 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -662,6 +662,8 @@ "src/layers/cctv/source.test.mjs", "src/layers/cctv/frames.test.mjs", "src/layers/cctv/countMarkers.test.mjs", + "src/layers/cctv/count_click_overlay.test.mjs", + "src/layers/cctv/count_click_framing.test.mjs", "src/layers/cctv/ground.test.mjs", "src/layers/cctv/rendering.test.mjs", "src/data/alprCameras.js", diff --git a/src/data/cctvCards.js b/src/data/cctvCards.js index 63b08fa441..caa13c9dfe 100644 --- a/src/data/cctvCards.js +++ b/src/data/cctvCards.js @@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000; const RETRY_MAX_MS = 5 * 60 * 1000; export const CCTV_OVERLAY_SOURCE_ID = 'cctv'; +/** The source a CCTV count marker takes clicks as. */ +export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count'; export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({ fullEnd: CCTV_CARD_SCALE_FULL_M, midEnd: CCTV_CARD_SCALE_MID_M, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 9a551413a8..558f675b61 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -136,7 +136,8 @@ function visitNeighbors(marker, grid, gap, visit) { * one grid bucket. Even the widest pill can only touch its eight neighbors. * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and * joins the nearest count it touches. Lone cameras never join each other - * or bridge two counts. + * or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways. + * A merged group lists its ground cells in `parts`. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { @@ -150,7 +151,7 @@ export function mergeCountCells(cells, project, sizeFor, gap) { // The view projector reuses its result object. return { cell, - x: screen?.x, + x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined, y: screen?.y, halfSegment: (width - height) / 2, radius: height / 2, @@ -201,8 +202,10 @@ export function mergeCountCells(cells, project, sizeFor, gap) { } else { const group = createCameraCell(seed.cell.key); group.lone = []; + group.parts = []; for (const { cell } of members) { addCell(group, cell); + group.parts.push(...(cell.parts ?? [cell])); if (cell.count === 1) group.lone.push(cell); else if (cell.lone) group.lone.push(...cell.lone); } @@ -218,3 +221,13 @@ export function mergeCountCells(cells, project, sizeFor, gap) { } return groups; } + +/** Rebuild a group's count under its original key, excluding lone cameras. */ +export function withoutLoneCameras(group) { + const counts = (group.parts ?? []).filter((cell) => cell.count > 1); + if (!counts.length) return null; + const core = createCameraCell(group.key); + core.parts = counts; + for (const cell of counts) addCell(core, cell); + return core; +} diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index f11f6e8553..f9868e90df 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) { let _overlayHitTest = null; /** @type {WeakMap} */ const clickCards = new WeakMap(); +const _clickClaims = new Map(); + +/** + * Register a target drawn outside the world overlay's entries, such as a CCTV + * count. A claim runs once per click where no card or label is painted above + * it and must not call `clickCard`. + * @param {string} layerId + * @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim + */ +export function registerClickClaim(layerId, claim) { + if (!layerId || typeof claim !== 'function') return; + _clickClaims.set(layerId, claim); +} + +/** Remove a layer's claim when it is disabled or destroyed. */ +export function unregisterClickClaim(layerId) { + _clickClaims.delete(layerId); +} /** * Sets (or with null, clears) the hit test that names the card or label @@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) { } /** - * The topmost interactive card or label painted at a click, read once per - * click so every handler of it sees the same one whatever ran first. + * The topmost interactive card or label painted at a click, or a target a + * layer claims (`registerClickClaim`). All handlers share one result per click. * @param {{screenPosition?: {x: number, y: number}}|null|undefined} click * @returns {{sourceId: string, entryId: string}|null} */ @@ -179,14 +197,28 @@ export function clickCard(click) { try { card = _overlayHitTest?.(at?.x, at?.y) ?? null; } catch { - // a broken hit test must never break click handling + clickCards.set(click, null); + return null; + } + if (!card) { + // A claim that reads this click again cannot re-enter the claims loop. + clickCards.set(click, null); + for (const claim of _clickClaims.values()) { + try { + card = claim(click) ?? null; + } catch { + card = null; + } + if (card) break; + } } clickCards.set(click, card); return card; } /** - * True when another layer's card or label is painted on top at a click. The + * True when another layer has the top card, label, or claimed target + * (`registerClickClaim`) at a click. The * card on top takes the click: a scene item under it does not act, and is * not empty space either, so the layer leaves its selection alone. * @param {object} click The shared dispatcher event. diff --git a/src/data/pickRegistry.test.mjs b/src/data/pickRegistry.test.mjs index eb3347fe8c..90b4d3824c 100644 --- a/src/data/pickRegistry.test.mjs +++ b/src/data/pickRegistry.test.mjs @@ -20,6 +20,8 @@ import { clickCard, isUnderOtherCard, setClickCardHitTest, + registerClickClaim, + unregisterClickClaim, } from './pickRegistry.js'; // --------------------------------------------------------------------------- @@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun setClickCardHitTest(null); } }); + +test('a click claim is the card on top only where no card or label is painted', () => { + const event = (x) => ({ screenPosition: { x, y: 5 } }); + let calls = 0; + registerClickClaim('counts', (click) => { + calls++; + return click.screenPosition.x === 4 + ? { sourceId: 'counts', entryId: 'k' } + : null; + }); + try { + registerClickClaim('counts', null); + const click = event(4); + assert.equal(isUnderOtherCard(click), true); + assert.equal(isUnderOtherCard(click, ['counts']), false); + assert.equal(calls, 1); + assert.equal(clickCard(event(9)), null); + const quake = { sourceId: 'quake-card', entryId: 'q1' }; + setClickCardHitTest(() => quake); + assert.deepEqual(clickCard(event(4)), quake); + assert.equal(calls, 2); + setClickCardHitTest(() => { + throw new Error('broken overlay hit test'); + }); + assert.equal(clickCard(event(4)), null); + assert.equal(calls, 2); + setClickCardHitTest(null); + + unregisterClickClaim('counts'); + assert.equal(clickCard(event(4)), null); + registerClickClaim('counts', () => { + throw new Error('broken claim'); + }); + assert.equal(clickCard(event(4)), null); + } finally { + unregisterClickClaim('counts'); + setClickCardHitTest(null); + } +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index e071f07238..20cc73174d 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -3,6 +3,7 @@ import { cellLonLat, formatCameraCount, mergeCountCells, + withoutLoneCameras, } from '../../data/cctvCellCounts.js'; import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { @@ -200,7 +201,27 @@ export function createCountMarkers( ground(visible); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { - const cell = visible[i]; + let cell = visible[i]; + // If the merged count is under the HUD, restore the count and its lone icons. + if (hardUi && cell.lone?.length) { + const at = project(cellCenter(cell)); + const { width, height } = sizeFor(cell.count); + const rect = at && { + x: at.x - width / 2, + y: at.y - height / 2, + w: width, + h: height, + }; + if (rect && hardUi(rect)) { + for (const lone of cell.lone) lone.absorbed = false; + const core = withoutLoneCameras(cell); + if (core) { + core.releasedAt = rect; + ground([core]); + cell = core; + } + } + } const marker = (markers[i] ??= { focus: 1 }); const last = marker.cell; const size = sizeFor(cell.count); @@ -217,20 +238,6 @@ export function createCountMarkers( marker.hudHidden = undefined; changed = true; } - // A count hidden by the HUD leaves its lone cameras visible as icons. - if (hardUi && cell.lone?.length) { - const at = project(marker.pos); - if ( - at && - hardUi({ - x: at.x - size.width / 2, - y: at.y - size.height / 2, - w: size.width, - h: size.height, - }) - ) - for (const lone of cell.lone) lone.absorbed = false; - } changed ||= size.text !== marker.text || size.width !== marker.width || @@ -267,6 +274,8 @@ export function createCountMarkers( ctx.textBaseline = 'middle'; for (let i = 0; i < markers.length; i++) { const marker = markers[i]; + // The core can stay visible while the HUD uncovers the merged count. + if (marker.cell.releasedAt) refresh ||= !hardUi(marker.cell.releasedAt); const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; @@ -291,12 +300,14 @@ export function createCountMarkers( ) continue; const hidden = Boolean(hardUi?.(rect)); - if (marker.hudHidden !== hidden) { + const previous = marker.hudHidden; + if (previous !== hidden) { marker.hudHidden = hidden; - // A first frame or moving HUD can change which lone icons must show. - refresh ||= marker.cell.lone?.some( - (cell) => cell.absorbed === hidden, - ); + // The active icon steps aside only for visible counts. + refresh ||= + hidden || + previous !== undefined || + marker.cell.lone?.some((cell) => cell.absorbed === hidden); } if (hidden) continue; const fade = diff --git a/src/layers/cctv/countMarkers.test.mjs b/src/layers/cctv/countMarkers.test.mjs index f3b2398a99..b3d3461b71 100644 --- a/src/layers/cctv/countMarkers.test.mjs +++ b/src/layers/cctv/countMarkers.test.mjs @@ -126,6 +126,25 @@ test('a lone camera clear of the HUD keeps its icon when the count beside it is } }); +test('a count stays visible when a lone camera would move it under the HUD', async () => { + const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)]; + const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 225 }; + const m = counts(() => m.update(cells, project)); + paint(hud); + m.update(cells, project); + assert.equal(paint(hud)[0]?.text, '2'); + assert.equal(cells[1].absorbed, false); + await Promise.resolve(); + paint(hud); + await Promise.resolve(); + + paint(); + await Promise.resolve(); + assert.equal(cells[1].absorbed, true); + assert.equal(paint()[0]?.text, '3'); + m.dispose(); +}); + test('counts fade with the Scope keyhole like the callouts', () => { const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha); m.update([cellAt('a', 400, 2)], project); diff --git a/src/layers/cctv/count_click_framing.test.mjs b/src/layers/cctv/count_click_framing.test.mjs new file mode 100644 index 0000000000..5667d51c99 --- /dev/null +++ b/src/layers/cctv/count_click_framing.test.mjs @@ -0,0 +1,67 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { distance } from '../../geo/vector.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +// A count of four merged in a tilted view: two pairs 10 km and 40 km north of +// an eye 800 m up. After the click, at least one member must be in frame. +test('a count click from a tilted view keeps the group members in the frame', () => { + const viewer = {}; + const flights = []; + const fovy = Math.PI / 3; + const aspectRatio = 800 / 600; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: 800 }, + }); + try { + const metresPerDegree = 111_320; + const members = []; + const cells = [10_000, 40_000].map((start) => { + const cell = createCameraCell(String(start)); + for (const northM of [start, start + 10]) { + const lat = northM / metresPerDegree; + addCellCamera(cell, { lat, lon: 0, absoluteHeightM: 8 }); + members.push(fromDegrees(0, lat, 8)); + } + return cell; + }); + const screens = [ + { x: 400, y: 300 }, + { x: 433, y: 300 }, + ]; + const groups = mergeCountCells( + cells, + () => screens.shift(), + () => ({ width: 40, height: 40 }), + 2, + ); + assert.equal(groups.length, 1); + assert.equal(groups[0].count, 4); + const state = { _viewer: viewer }; + const navigation = createNavigation({ state, parts: {} }); + navigation.zoomToCell(groups[0]); + assert.equal(flights.length, 1); + const { range, pitch } = flights[0].options.offset; + assert.equal(pitch, -Math.PI / 2); + const { center } = flights[0].bounds; + const halfSpanM = range * Math.tan(fovy / 2); + assert.ok( + members.some((point) => distance(point, center) <= halfSpanM), + 'no member of the group is in the final frame', + ); + assert.ok(range < distance(fromDegrees(0, 0, 800), center)); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/count_click_overlay.test.mjs b/src/layers/cctv/count_click_overlay.test.mjs new file mode 100644 index 0000000000..69fb55d541 --- /dev/null +++ b/src/layers/cctv/count_click_overlay.test.mjs @@ -0,0 +1,65 @@ +import * as picking from '../../data/pickRegistry.js'; +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createSelection } from './selection.js'; + +function setup() { + let zooms = 0, + clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: () => ({}) }, + _cctvOverlayHost: { hitTest: () => null }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { extractPickedCameraId: () => null }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + return { click, counts: () => [zooms, clicks] }; +} + +test('a click a painted overlay target took (Space Missions label) does not fly to the count', () => { + const { click, counts } = setup(); + // What the dispatcher hands subscribers after an onOverlayClick handler returned true. + click({ + screenPosition: { x: 20, y: 26 }, + overlay: true, + topHit: { set: '', id: null, surface: false }, + drawHit: null, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.equal( + counts()[0], + 0, + 'count flight ran although an overlay target handled the click', + ); +}); + +test("another layer's world-overlay card on top (clickCard) takes the click from the count", () => { + const { click, counts } = setup(); + picking.setClickCardHitTest(() => ({ + sourceId: 'earthquakes', + entryId: 'eq-1', + })); + try { + click({ + screenPosition: { x: 20, y: 26 }, + topHit: null, + drawHit: null, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.ok( + picking.isUnderOtherCard({ screenPosition: { x: 1, y: 1 } }, ['cctv']), + ); + assert.equal(counts()[0], 0, 'count flight ran under another layer card'); + } finally { + picking.setClickCardHitTest(null); + } +}); diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 194be38cc0..cec1798036 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -22,11 +22,12 @@ export function createGround({ state: layerState, services, parts, source }) { * - `google-3d` — photoreal stack: globe hidden, the visible Google 3D * tileset IS the surface → one-shot scene sampling refines. * - `terrain-globe` — any globe stack: the Re:Earth point-height prior IS the - * resolution (zero scene queries). + * resolution. A camera the batch left unanswered takes the + * drawn terrain from the view pass (`adoptDrawnGround`). * * Only an explicit `false` (the photoreal stack hides the globe) selects * `google-3d`; undefined/null (no viewer / torn down) must fall to the regime - * that never touches the scene. Pure — exported for the unit suite. + * that never samples the scene's tiles. Pure — exported for the unit suite. * @param {boolean|undefined|null} globeShow - Whether the renderer shows the * globe (`globe.isGlobeVisible()`). * @returns {'google-3d'|'terrain-globe'} diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index bfe194197b..8230b7457c 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -23,8 +23,14 @@ export function createLifecycle({ source, }) { const { activateCctvCameraFromWorldClick } = services.activation; - const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } = - services.picking; + const { + resolvePickId, + registerPickOwner, + unregisterPickOwner, + clickCard, + registerClickClaim, + unregisterClickClaim, + } = services.picking; const { onFocusTargetAppear } = services.focus; const { releaseContinuousRender } = services.render; @@ -510,6 +516,7 @@ export function createLifecycle({ ); return Boolean(coverage && layerState._recordById.has(coverage[1])); }); + registerClickClaim?.('cctv', parts.selection.countClickCard); if (!layerState._activeCameraId && layerState._records.length) { layerState._activeCameraId = parts.navigation.openingCameraId(); layerState._autoHopSuspended = false; @@ -546,6 +553,7 @@ export function createLifecycle({ services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv'); layerState._enabled = false; unregisterPickOwner('cctv'); + unregisterClickClaim?.('cctv'); // ADJUST mode does not survive a layer toggle — predictable re-entry. layerState._calibrationMode = false; releaseContinuousRender('cctv-adjust'); @@ -580,6 +588,7 @@ export function createLifecycle({ parts.cards.handleVisibilityChange, ); unregisterPickOwner('cctv'); + unregisterClickClaim?.('cctv'); if (layerState._mapStackListener && typeof window !== 'undefined') { window.removeEventListener( 'gev:map-stack-changed', diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index 6590cc32da..9bd0014a80 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,7 +1,7 @@ import { distance } from '../../geo/vector.js'; import { rangeForBoundingSphere } from '../../data/cameraFraming.js'; import { isFollowing } from '../../data/followed.js'; -import { cellBounds } from '../../data/cctvCellCounts.js'; +import { cellBounds, cellCenter } from '../../data/cctvCellCounts.js'; import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js'; import { cameraOf, canvasOf } from '../../render/rendererOf.js'; @@ -131,6 +131,20 @@ export function createNavigation({ return CCTV_FOCUS_RESULT.FOCUSED; } + /** The ground cell of a group nearest the eye, or the group itself if unmerged. */ + function nearestPart(cell, eye) { + let nearest = cell; + let best = Infinity; + for (const part of cell.parts ?? []) { + const d = distance(eye, cellCenter(part)); + if (d < best) { + best = d; + nearest = part; + } + } + return nearest; + } + /** Frame a group's padded bounds from above, including coincident mounts. */ function zoomToCell(cell) { const viewer = layerState._viewer; @@ -140,18 +154,23 @@ export function createNavigation({ const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2); const canvas = canvasOf(viewer); const height = canvas?.clientHeight || canvas?.height || 1; - const bounds = cellBounds(cell); // Half the range where cells stop grouping, so even coincident mounts split. const closeRange = (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); + const fitRange = (bounds) => + Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)); // Approach long groups in halves so every click gets closer. - const halfway = pose.position - ? distance(pose.position, bounds.center) / 2 - : Infinity; - const range = Math.min( - halfway, - Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)), - ); + const halfway = (bounds) => + pose.position ? distance(pose.position, bounds.center) / 2 : Infinity; + let bounds = cellBounds(cell); + const fit = fitRange(bounds); + let range = Math.min(halfway(bounds), fit); + // If the group exceeds the narrower side of the frame, approach its nearest part. + const tanHalf = tanHalfY * Math.min(1, pose.aspectRatio || 1); + if (range < fit && range * tanHalf < bounds.radius) { + bounds = cellBounds(nearestPart(cell, pose.position)); + range = Math.min(halfway(bounds), fitRange(bounds)); + } camera.flyToBounds(bounds, { offset: { heading: 0, pitch: -Math.PI / 2, range }, durationS: 1.2, diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 4fee5ce9cb..2d5166d395 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -546,6 +546,17 @@ export function createRendering({ cell.rank = rank; } } + // Check each mount mate against counts where its icon will be drawn. + const lone = visibleCells.filter((cell) => cell.count === 1); + spreadSharedMounts( + shown.concat(lone.map((cell) => cell.winner)), + pose, + metresPerPixelPerMetre, + pass, + ); + for (const cell of lone) + cell.offsetPx = + cell.winner.spreadPass === pass ? cell.winner.spreadPx : 0; // A count stands on the drawn terrain too: its cell may be too far for // its cameras to have been read. Marks each lone camera that a count // marker beside it has taken in. @@ -559,7 +570,6 @@ export function createRendering({ shown.push(record); } } - spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; @@ -626,10 +636,10 @@ export function createRendering({ /** * Cameras on one mount would draw as one icon with several callouts. Among - * the cameras shown, those within VIEW_SITE_M horizontally get draw - * positions side by side along the screen's horizontal, in id order, - * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The - * record's own position is untouched: geometry and cards keep the mount. + * icon candidates, those within VIEW_SITE_M horizontally get draw positions + * side by side in id order, `VIEW_SITE_SPREAD_PX` apart on screen. A mate + * absorbed by a count keeps its place in the row. Geometry and cards stay + * on the mount. */ function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { const { right, direction, position: eye } = pose; @@ -669,11 +679,9 @@ export function createRendering({ (p.x - eye.x) * direction.x + (p.y - eye.y) * direction.y + (p.z - eye.z) * direction.z; - const metres = - (i - (mates.length - 1) / 2) * - VIEW_SITE_SPREAD_PX * - metresPerPixelPerMetre * - depth; + const px = (i - (mates.length - 1) / 2) * VIEW_SITE_SPREAD_PX; + record.spreadPx = px; + const metres = px * metresPerPixelPerMetre * depth; record.spreadOffset = scale(right, metres); record.spreadPosition = add(p, record.spreadOffset); record.spreadPass = pass; @@ -681,7 +689,7 @@ export function createRendering({ } } - /** Move the active camera's icon beside any count marker that would cover it. */ + /** Only counts visible outside the HUD push the active icon aside. */ function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) { if (!layerState._activeCameraId) return; const record = layerState._recordById.get(layerState._activeCameraId); @@ -702,6 +710,7 @@ export function createRendering({ (CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2; const spans = []; for (const marker of markers) { + if (marker.hudHidden) continue; const at = project(marker.pos); if ( !at || diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 9364911537..a8cb724abe 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -1,4 +1,7 @@ -import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; +import { + CCTV_COUNT_CARD_SOURCE_ID, + CCTV_OVERLAY_SOURCE_ID, +} from '../../data/cctvCards.js'; import { isTrackingClickGesture } from '../../data/trackingClickGesture.js'; export function createSelection({ @@ -8,7 +11,8 @@ export function createSelection({ source, }) { const { CCTV_ACTIVATION_RESULT } = services.activation; - const { resolvePickId, findPickOwner } = services.picking; + const { resolvePickId, findPickOwner, isUnderOtherCard } = services.picking; + const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID]; /** * Returns the camera record for the currently active camera. A stale ID falls @@ -30,15 +34,8 @@ export function createSelection({ return fallback; } - /** A card painted above the count, or another layer's object, owns the click. */ - function countYields(event) { - const { x, y } = event.screenPosition; - if ( - layerState._cctvOverlayHost?.hitTest(x, y, { - sourceId: CCTV_OVERLAY_SOURCE_ID, - })?.entryId - ) - return true; + /** Whether another layer's scene object owns the click at this count. */ + function sceneTakesCountClick(event) { const top = event.topHit; if (!top) return false; const drawHit = event.drawHit; @@ -47,6 +44,34 @@ export function createSelection({ return id !== null && findPickOwner?.(id) !== 'cctv'; } + /** Leave other layers' cards to the caller since clickCard also calls this. */ + function clickedCount(event) { + if ( + !isTrackingClickGesture(event.gesture) || + !layerState._enabled || + event.overlay + ) + return null; + const cell = layerState._counts?.pickedCell(event.screenPosition); + if (!cell) return null; + const { x, y } = event.screenPosition; + if ( + layerState._cctvOverlayHost?.hitTest(x, y, { + sourceId: CCTV_OVERLAY_SOURCE_ID, + })?.entryId + ) + return null; + return sceneTakesCountClick(event) ? null : cell; + } + + /** The count marker as the card on top of a click it takes, for every layer's clickCard. */ + function countClickCard(event) { + const cell = clickedCount(event); + return cell + ? { sourceId: CCTV_COUNT_CARD_SOURCE_ID, entryId: String(cell.key ?? '') } + : null; + } + /** * Bind CCTV activation to clean taps. Drag-like and long-press gestures do * not reach camera activation or focus dispatch. @@ -59,10 +84,9 @@ export function createSelection({ function bindCctvWorldClickGesture(input, onClick) { return input.onClick((event) => { if (!isTrackingClickGesture(event.gesture)) return; - const cell = - layerState._enabled && - layerState._counts?.pickedCell(event.screenPosition); - if (cell && !countYields(event)) { + const cell = clickedCount(event); + // Another layer's card or label painted above the count takes the click. + if (cell && !isUnderOtherCard?.(event, OWN_CARD_SOURCES)) { parts.navigation.zoomToCell(cell); return; } @@ -243,6 +267,7 @@ export function createSelection({ return { getActiveRecord, bindCctvWorldClickGesture, + countClickCard, setActiveCamera, deactivateActiveCamera, cctvEmptyClickDeselects, diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 297a2f674f..6882eeff53 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -1,4 +1,5 @@ import * as picking from '../../data/pickRegistry.js'; +import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js'; @@ -150,3 +151,63 @@ test("a count click yields to a card above it and to another layer's object, not picking.unregisterPickOwner('cctv'); } }); + +test('a count click is the card on top for every layer, unless the count yields', () => { + let zooms = 0; + let clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: (p) => (p?.x === 20 ? { key: 'g' } : null) }, + _cctvOverlayHost: { hitTest: () => null }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { + extractPickedCameraId: (hit) => + hit?.set === 'cctv-icons' ? hit.id : null, + }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + const event = (topHit = null, x = 20, durationMs = 20) => ({ + screenPosition: { x, y: 26 }, + topHit, + drawHit: topHit, + gesture: { travelPx: 0, durationMs }, + }); + picking.registerClickClaim('cctv', selection.countClickCard); + try { + const aircraftFirst = event(); + assert.equal(picking.isUnderOtherCard(aircraftFirst), true); + assert.deepEqual(picking.clickCard(aircraftFirst), { + sourceId: CCTV_COUNT_CARD_SOURCE_ID, + entryId: 'g', + }); + click(aircraftFirst); + assert.deepEqual([zooms, clicks], [1, 0]); + + const cctvFirst = event(); + click(cctvFirst); + assert.equal(picking.isUnderOtherCard(cctvFirst), true); + assert.deepEqual([zooms, clicks], [2, 0]); + + for (const [e, claimed, expected] of [ + [event({ set: 'flights', id: 'abc' }), false, [2, 1]], + [event({ set: 'cctv-icons', id: 'cam-2' }), true, [3, 1]], + [event(null, 20, 1000), false, [3, 1]], + [event(null, 60), false, [3, 2]], + [{ ...event(), overlay: true }, false, [3, 3]], + ]) { + assert.equal(picking.isUnderOtherCard(e), claimed); + click(e); + assert.deepEqual([zooms, clicks], expected); + } + } finally { + picking.unregisterClickClaim('cctv'); + } +}); From aba4c9e53353ed46ce0b677726ad9ec41afd1777 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 02:02:06 +0400 Subject: [PATCH 9/9] fix(cctv): keep a clicked group in frame and let counts take clicks over plain fills - The flight after a count click checks the frame on both axes and at the height of the highest mount, so a group on a slope or in a very wide window stays in view; when it cannot, it flies to the nearest cell with two or more cameras, never to a lone camera that joined the count. - A count takes a click over a background fill no layer owns (earthquake discs, fire perimeters), and still yields to a scene item another layer registered. - A count crossing the HUD edge refreshes the view only when the active icon or a lone camera depends on it, and never mid-motion, so panning no longer runs extra full view passes. - A count restored at the HUD edge keeps the lone cameras its outline covers, and leaves the others as icons. --- docs/CURRENT-STATE.md | 14 +- src/data/cctvCellCounts.js | 29 ++-- src/layers/cctv/countMarkers.js | 46 +++++- src/layers/cctv/countMarkers.test.mjs | 24 +++ .../cctv/count_click_east_west.test.mjs | 76 +++++++++ .../cctv/count_click_near_lone.test.mjs | 69 +++++++++ src/layers/cctv/count_click_relief.test.mjs | 96 ++++++++++++ .../cctv/count_click_ultrawide.test.mjs | 84 ++++++++++ src/layers/cctv/count_hud_pan.test.mjs | 145 ++++++++++++++++++ .../cctv/count_over_quake_disc.test.mjs | 59 +++++++ src/layers/cctv/navigation.js | 42 +++-- src/layers/cctv/rendering.js | 13 +- src/layers/cctv/selection.js | 14 +- src/layers/cctv/selection.test.mjs | 4 + 14 files changed, 674 insertions(+), 41 deletions(-) create mode 100644 src/layers/cctv/count_click_east_west.test.mjs create mode 100644 src/layers/cctv/count_click_near_lone.test.mjs create mode 100644 src/layers/cctv/count_click_relief.test.mjs create mode 100644 src/layers/cctv/count_click_ultrawide.test.mjs create mode 100644 src/layers/cctv/count_hud_pan.test.mjs create mode 100644 src/layers/cctv/count_over_quake_disc.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 76c142c7b3..d941e17f9b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1999,12 +1999,14 @@ callout resolution. The count covers the whole cell up to the horizon, including its off-screen cameras. Overlapping markers merge and add their counts. A lone camera whose icon would touch a marker joins the nearest one, unless the HUD hides the merged marker. In that case the lone camera keeps its icon and the -count stays where it was before the merge. The active camera keeps its own icon -beside any marker that would cover it and stays out of the count. A click on a -marker zooms in on its group, at least halving the distance each time. If halving -would leave the group wider than the frame, the view zooms in on the group's -ground cell nearest the eye. The cockpit or a tracked object holds the view -in place. Ambient cards and coverage attach only to +count stays where it was before the merge. If the marker there would still cover +the icon, the camera stays in its count when the label fits. The active camera +keeps its own icon beside any marker that would cover it and stays out of the +count. A click on a marker zooms in on its group, at least halving the distance +each time. If halving would leave the group wider or taller than the frame, the +view zooms in on the nearest of the group's ground cells with two or more +cameras. The cockpit or a tracked object holds the view in place. Ambient cards +and coverage attach only to cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A camera the height batch never answered for takes the drawn terrain as its ground once it is near the screen. It reads that height again from much closer, once diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 558f675b61..c7d59b4cc7 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -70,6 +70,16 @@ export function cellCenter(cell) { ); } +/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */ +export function cellHalfExtents(cell) { + // The parallel nearest the equator bounds the width of every row. + const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180; + return { + halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel), + halfHeightM: 0.5 * (cell.north - cell.south) * 111_320, + }; +} + /** A padded sphere over the rectangle and every mount, centred at groundM * when set, otherwise at the mid mount height. */ export function cellBounds(cell) { @@ -78,14 +88,8 @@ export function cellBounds(cell) { const height = Number.isFinite(cell.groundM) ? cell.groundM : (cell.high + cell.low) / 2; - // The parallel nearest the equator bounds the width of every row. - const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180; - const halfWidth = - 0.5 * - Math.hypot( - (cell.east - cell.west) * 111_320 * Math.cos(parallel), - (cell.north - cell.south) * 111_320, - ); + const { halfWidthM, halfHeightM } = cellHalfExtents(cell); + const halfWidth = Math.hypot(halfWidthM, halfHeightM); const vertical = Math.max(cell.high - height, height - cell.low); const radius = 1.2 * Math.hypot(halfWidth, vertical); return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) }; @@ -222,12 +226,13 @@ export function mergeCountCells(cells, project, sizeFor, gap) { return groups; } -/** Rebuild a group's count under its original key, excluding lone cameras. */ -export function withoutLoneCameras(group) { +/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */ +export function withoutLoneCameras(group, keep = []) { const counts = (group.parts ?? []).filter((cell) => cell.count > 1); if (!counts.length) return null; const core = createCameraCell(group.key); - core.parts = counts; - for (const cell of counts) addCell(core, cell); + core.parts = [...counts, ...keep]; + if (keep.length) core.lone = [...keep]; + for (const cell of core.parts) addCell(core, cell); return core; } diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 20cc73174d..a04018dad8 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -152,6 +152,36 @@ export function createCountMarkers( }; } + /** Keep covered icons in the restored count if its new label clears the HUD. */ + function retainCoveredCameras(group, core, project) { + const anchor = cellCenter(core); + const at = project(anchor); + if (!at) return core; + const { x, y } = at; // The projector reuses its result. + const size = sizeFor(core.count); + const halfSegment = (size.width - size.height) / 2; + const covered = group.lone.filter((lone) => { + const p = project(cellCenter(lone)); + if (!p) return false; + // The pill outline that merging measures, without its gap. + const dx = Math.max( + 0, + Math.abs(p.x + (lone.offsetPx ?? 0) - x) - halfSegment, + ); + const reach = (size.height + (lone.iconPx ?? CAMERA_ICON_PX)) / 2; + return dx * dx + (p.y - y) ** 2 < reach * reach; + }); + if (!covered.length) return core; + const { width, height } = sizeFor(core.count + covered.length); + if (hardUi({ x: x - width / 2, y: y - height / 2, w: width, h: height })) + return core; + const held = withoutLoneCameras(group, covered); + held.anchor = anchor; + held.groundM = core.groundM; + for (const lone of covered) lone.absorbed = true; + return held; + } + /** * Reuse marker slots in ground-key order, and invalidate only changed frames. * `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite @@ -216,9 +246,9 @@ export function createCountMarkers( for (const lone of cell.lone) lone.absorbed = false; const core = withoutLoneCameras(cell); if (core) { - core.releasedAt = rect; ground([core]); - cell = core; + cell = retainCoveredCameras(cell, core, project); + cell.releasedAt = rect; } } } @@ -231,9 +261,12 @@ export function createCountMarkers( last.latSum !== cell.latSum || last.lonSum !== cell.lonSum || last.heightSum !== cell.heightSum || - last.groundM !== cell.groundM + last.groundM !== cell.groundM || + last.anchor?.x !== cell.anchor?.x || + last.anchor?.y !== cell.anchor?.y || + last.anchor?.z !== cell.anchor?.z ) { - marker.pos = cellCenter(cell); + marker.pos = cell.anchor ?? cellCenter(cell); marker.cullPos = liftedForHorizon(marker.pos); marker.hudHidden = undefined; changed = true; @@ -303,10 +336,9 @@ export function createCountMarkers( const previous = marker.hudHidden; if (previous !== hidden) { marker.hudHidden = hidden; - // The active icon steps aside only for visible counts. + // The active icon steps aside only for visible counts beside it. refresh ||= - hidden || - previous !== undefined || + ((hidden || previous !== undefined) && marker.besideActive) || marker.cell.lone?.some((cell) => cell.absorbed === hidden); } if (hidden) continue; diff --git a/src/layers/cctv/countMarkers.test.mjs b/src/layers/cctv/countMarkers.test.mjs index b3d3461b71..c4391ef5e1 100644 --- a/src/layers/cctv/countMarkers.test.mjs +++ b/src/layers/cctv/countMarkers.test.mjs @@ -145,6 +145,30 @@ test('a count stays visible when a lone camera would move it under the HUD', asy m.dispose(); }); +test('a restored count includes the lone camera it still covers at the HUD edge', async () => { + const cells = [cellAt('a', 200, 2), cellAt('b', 206, 1)]; + const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 221 }; + const scratch = {}; + const update = () => + m.update(cells, (p) => Object.assign(scratch, project(p))); + const m = counts(update); + update(); + assert.equal(Math.round(paint()[0].x), 202); + + paint(hud); + await Promise.resolve(); + const [marker] = paint(hud); + assert.equal(marker?.text, '3'); + assert.equal(Math.round(marker.x), 200); + assert.equal(cells[1].absorbed, true); + assert.ok(m.pickedCell({ x: 206, y: 300 }).parts.includes(cells[1])); + + paint(); + await Promise.resolve(); + assert.equal(Math.round(paint()[0].x), 202); + m.dispose(); +}); + test('counts fade with the Scope keyhole like the callouts', () => { const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha); m.update([cellAt('a', 400, 2)], project); diff --git a/src/layers/cctv/count_click_east_west.test.mjs b/src/layers/cctv/count_click_east_west.test.mjs new file mode 100644 index 0000000000..c62402f0b3 --- /dev/null +++ b/src/layers/cctv/count_click_east_west.test.mjs @@ -0,0 +1,76 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +const M = 111_320; + +// Cesium's default 60 degree field of view spans the wider side, so a 4:3 +// window has a vertical fovy of about 46.8 degrees. Two pairs 50 km and 80 km +// east of an eye 800 m up merge into one count. At half the distance all four +// fit in the frame (the group is wide, not tall), so the flight must keep all +// four in frame instead of approaching only the near pair. +test('a count click on an east-west group that fits keeps every member in the frame', () => { + const viewer = {}; + const flights = []; + const aspectRatio = 800 / 600; + const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio); + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: 800 }, + }); + try { + const members = []; + const cells = [50_000, 80_000].map((start) => { + const cell = createCameraCell(String(start)); + for (const eastM of [start, start + 10]) { + const lon = eastM / M; + addCellCamera(cell, { lat: 0, lon, absoluteHeightM: 8 }); + members.push(lon); + } + return cell; + }); + const screens = [ + { x: 400, y: 300 }, + { x: 433, y: 300 }, + ]; + const groups = mergeCountCells( + cells, + () => screens.shift(), + () => ({ width: 40, height: 40 }), + 2, + ); + assert.equal(groups.length, 1); + assert.equal(groups[0].count, 4); + // Reference: a north-up top-down frame at half the distance holds all four. + const halfwayM = 65_005 / 2; + const refHalfX = halfwayM * Math.tan(fovy / 2) * aspectRatio; + assert.ok(members.every((lon) => Math.abs(lon * M - 65_005) <= refHalfX)); + createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell( + groups[0], + ); + assert.equal(flights.length, 1); + const { range } = flights[0].options.offset; + const center = toLonLatH(flights[0].bounds.center); + const halfX = range * Math.tan(fovy / 2) * aspectRatio; + const inFrame = members.filter( + (lon) => Math.abs((lon - center.lon) * M) <= halfX, + ); + assert.equal( + inFrame.length, + 4, + `only ${inFrame.length} of 4 members in frame (range ${Math.round(range)} m)`, + ); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/count_click_near_lone.test.mjs b/src/layers/cctv/count_click_near_lone.test.mjs new file mode 100644 index 0000000000..db9975e333 --- /dev/null +++ b/src/layers/cctv/count_click_near_lone.test.mjs @@ -0,0 +1,69 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +const M = 111_320; + +// A count of 40 cameras 40 km north of an eye 800 m up takes in a lone camera +// 10 km north that is drawn just below it. The click must not land on the lone +// camera alone: at least one of the 40 counted cameras must be in the frame. +test('a count click does not fly to a lone camera that joined the count', () => { + const viewer = {}; + const flights = []; + const fovy = Math.PI / 3; + const aspectRatio = 800 / 600; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: 800 }, + }); + try { + const crowd = createCameraCell('crowd'); + const counted = []; + for (let i = 0; i < 40; i++) { + const lat = (40_000 + i / 4) / M; + addCellCamera(crowd, { lat, lon: 0, absoluteHeightM: 8 }); + counted.push(lat); + } + const lone = createCameraCell('lone'); + addCellCamera(lone, { lat: 10_000 / M, lon: 0, absoluteHeightM: 8 }); + const screens = [ + { x: 400, y: 300 }, + { x: 400, y: 330 }, + ]; + const groups = mergeCountCells( + [crowd, lone], + () => screens.shift(), + (count) => + count > 1 ? { width: 40, height: 40 } : { width: 24, height: 24 }, + 2, + ); + assert.equal(groups.length, 1); + assert.equal(groups[0].count, 41); + createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell( + groups[0], + ); + assert.equal(flights.length, 1); + const { range } = flights[0].options.offset; + const center = toLonLatH(flights[0].bounds.center); + const halfY = range * Math.tan(fovy / 2); + const inFrame = counted.filter( + (lat) => Math.abs((lat - center.lat) * M) <= halfY, + ); + assert.ok( + inFrame.length > 0, + `none of the 40 counted cameras is in the frame (range ${Math.round(range)} m, centre ${Math.round(center.lat * M)} m north)`, + ); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/count_click_relief.test.mjs b/src/layers/cctv/count_click_relief.test.mjs new file mode 100644 index 0000000000..63023810ad --- /dev/null +++ b/src/layers/cctv/count_click_relief.test.mjs @@ -0,0 +1,96 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +const M = 111_320; + +function run({ aspectRatio, fovy, eye, pairs, groundM }) { + const viewer = {}; + const flights = []; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: eye }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) }, + }); + try { + const members = []; + const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => { + const cell = createCameraCell(String(i)); + for (const d of [0, 10]) { + const m = { lon: (eastM + d) / M, lat: northM / M, h }; + addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h }); + members.push(m); + } + cell.groundM = h; + return cell; + }); + const screens = [ + { x: 400, y: 300 }, + { x: 420, y: 300 }, + ]; + const groups = mergeCountCells( + cells, + () => screens.shift(), + () => ({ width: 40, height: 40 }), + 2, + ); + assert.equal(groups.length, 1); + groups[0].groundM = groundM; + createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell( + groups[0], + ); + const { range } = flights[0].options.offset; + const c = toLonLatH(flights[0].bounds.center); + const eyeH = c.height + range; + const tanY = Math.tan(fovy / 2); + const inFrame = members.filter((m) => { + const depth = eyeH - m.h; + if (!(depth > 0)) return false; + return ( + Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio && + Math.abs((m.lat - c.lat) * M) <= depth * tanY + ); + }); + return { range, inFrame: inFrame.length, centerH: c.height }; + } finally { + unbind(); + } +} + +test('a count click on pairs 300 m above the ground under the group centre keeps a member in the frame', () => { + const aspectRatio = 4 / 3; + const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio); + const r = run({ + aspectRatio, + fovy, + eye: fromDegrees(0, 0, 900), + pairs: [ + { eastM: 3000, h: 800 }, + { eastM: 5000, h: 800 }, + ], + groundM: 500, + }); + + const flat = run({ + aspectRatio, + fovy, + eye: fromDegrees(0, 0, 900), + pairs: [ + { eastM: 3000, h: 500 }, + { eastM: 5000, h: 500 }, + ], + groundM: 500, + }); + + assert.equal(flat.inFrame, 4); + assert.ok(r.inFrame > 0, `no member in frame: ${JSON.stringify(r)}`); +}); diff --git a/src/layers/cctv/count_click_ultrawide.test.mjs b/src/layers/cctv/count_click_ultrawide.test.mjs new file mode 100644 index 0000000000..00bfb84c2a --- /dev/null +++ b/src/layers/cctv/count_click_ultrawide.test.mjs @@ -0,0 +1,84 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +const M = 111_320; + +function run({ aspectRatio, fovy, eye, pairs, groundM }) { + const viewer = {}; + const flights = []; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: eye }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) }, + }); + try { + const members = []; + const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => { + const cell = createCameraCell(String(i)); + for (const d of [0, 10]) { + const m = { lon: (eastM + d) / M, lat: northM / M, h }; + addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h }); + members.push(m); + } + cell.groundM = h; + return cell; + }); + const screens = [ + { x: 400, y: 300 }, + { x: 420, y: 300 }, + ]; + const groups = mergeCountCells( + cells, + () => screens.shift(), + () => ({ width: 40, height: 40 }), + 2, + ); + assert.equal(groups.length, 1); + groups[0].groundM = groundM; + createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell( + groups[0], + ); + const { range } = flights[0].options.offset; + const c = toLonLatH(flights[0].bounds.center); + const eyeH = c.height + range; + const tanY = Math.tan(fovy / 2); + const inFrame = members.filter((m) => { + const depth = eyeH - m.h; + if (!(depth > 0)) return false; + return ( + Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio && + Math.abs((m.lat - c.lat) * M) <= depth * tanY + ); + }); + return { range, inFrame: inFrame.length, centerH: c.height }; + } finally { + unbind(); + } +} + +test('a count click on a north-south group in a 32:9 window keeps every member in the frame', () => { + const aspectRatio = 32 / 9; + const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio); + const r = run({ + aspectRatio, + fovy, + eye: fromDegrees(0, 0, 800), + pairs: [ + { northM: 15_000, h: 8 }, + { northM: 17_000, h: 8 }, + ], + groundM: 8, + }); + + assert.equal(r.inFrame, 4, JSON.stringify(r)); +}); diff --git a/src/layers/cctv/count_hud_pan.test.mjs b/src/layers/cctv/count_hud_pan.test.mjs new file mode 100644 index 0000000000..fd9b8e0c93 --- /dev/null +++ b/src/layers/cctv/count_hud_pan.test.mjs @@ -0,0 +1,145 @@ +import { test, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { createCountMarkers } from './countMarkers.js'; +import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; + +const W = 800; +const H = 600; +const A = 6378137; +// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture). +const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 }); +const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI; +const matrix = new Float64Array([ + 0, + 0, + 0, + 0, + 2 / (30 * W), + 0, + 0, + 0, + 0, + 2 / (30 * H), + 0, + 0, + 0, + 0, + 0, + 1, +]); + +function cellAt(key, x, count, height = 0, y = H / 2) { + const cell = createCameraCell(key); + for (let i = 0; i < count; i++) + addCellCamera(cell, { + lon: lonFor(x), + lat: (Math.asin(((H / 2 - y) * 30) / A) * 180) / Math.PI, + absoluteHeightM: height, + }); + return cell; +} + +let painter; +function makeCtx() { + return { + labels: [], + globalAlpha: 1, + save() {}, + restore() {}, + beginPath() {}, + roundRect() {}, + stroke() {}, + fill() {}, + drawImage() {}, + fillText(text, x, y) { + this.labels.push({ text, x, y, alpha: this.globalAlpha }); + }, + }; +} +function paint(overrides = {}) { + const ctx = makeCtx(); + painter({ + ctx, + width: W, + height: H, + dpr: 1, + viewProjectionMatrix: matrix, + occluder: { isPointVisible: () => true }, + overlapsHardUi: () => false, + ...overrides, + }); + return ctx.labels; +} +function counts(refresh = () => {}, keyholeAlpha) { + return createCountMarkers( + (_lane, paintFn) => { + painter = paintFn; + return { requestPaint() {}, setActive() {}, unregister() {} }; + }, + 'counts', + refresh, + keyholeAlpha, + ); +} + +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + measureText: (text) => ({ + width: text.length * 7, + actualBoundingBoxAscent: 4, + actualBoundingBoxDescent: 4, + }), + }), + }), + }; +}); +afterEach(() => { + delete globalThis.document; +}); + +// 75 counts in five staggered rows, no lone cameras and no active camera, +// pan right 7 CSS px per frame for 60 frames past a left HUD rail. Counts must +// still hide and reappear at the rail, but the paint must not start a full +// view pass on almost every frame: the motion timer passes the view every +// 250 ms, about 4 times in these 60 frames at 60 Hz. +test('a pan past the HUD edge does not pass the view on every frame', async () => { + const run = async (hud) => { + const cells = []; + for (let row = 0; row < 5; row++) + for (let col = 0; col < 15; col++) + cells.push( + cellAt( + `r${row}c${String(col).padStart(2, '0')}`, + 30 + col * 50 + row * 10, + 2, + 0, + 120 + row * 60, + ), + ); + let refreshes = 0; + let hiddenFrames = 0; + const m = counts(() => refreshes++); + m.update(cells, project); + for (let f = 0; f < 60; f++) { + const panned = matrix.slice(); + panned[12] = (2 * (f * 7)) / W; + const labels = paint({ ...hud, viewProjectionMatrix: panned }); + if (labels.length < 75) hiddenFrames++; + await Promise.resolve(); + } + m.dispose(); + return { refreshes, hiddenFrames }; + }; + const control = await run({}); + const withHud = await run({ overlapsHardUi: (rect) => rect.x < 150 }); + assert.equal(control.refreshes, 0); + assert.ok(withHud.hiddenFrames > 0, 'the HUD hides no count'); + assert.ok( + withHud.refreshes <= 4, + `${withHud.refreshes} full view passes from paint in 60 frames`, + ); +}); diff --git a/src/layers/cctv/count_over_quake_disc.test.mjs b/src/layers/cctv/count_over_quake_disc.test.mjs new file mode 100644 index 0000000000..2350b3f567 --- /dev/null +++ b/src/layers/cctv/count_over_quake_disc.test.mjs @@ -0,0 +1,59 @@ +import * as picking from '../../data/pickRegistry.js'; +import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js'; +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createSelection } from './selection.js'; + +// Earthquake discs (like fire perimeters and drone airspace) are deliberately +// unowned background fills. A clean tap on a count painted over a disc must +// zoom to the count and be the card on top for every layer, so Earthquakes +// opens no card. An owned scene object (an aircraft) still takes the click. +test('a count over an earthquake disc takes the click', () => { + let zooms = 0; + let clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: () => ({ key: 'g' }) }, + _cctvOverlayHost: { hitTest: () => null }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { + extractPickedCameraId: (hit) => + hit?.set === 'cctv-icons' ? hit.id : null, + }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + const event = (hit) => ({ + screenPosition: { x: 20, y: 26 }, + topHit: hit, + drawHit: hit, + hit, + gesture: { travelPx: 0, durationMs: 20 }, + }); + picking.registerClickClaim('cctv', selection.countClickCard); + picking.registerPickOwner('flights', (id) => id.startsWith('aircraft:')); + try { + const disc = event({ set: 'earthquakes:1:discs', id: 'earthquake:abc' }); + assert.deepEqual(picking.clickCard(disc), { + sourceId: CCTV_COUNT_CARD_SOURCE_ID, + entryId: 'g', + }); + click(disc); + assert.deepEqual([zooms, clicks], [1, 0]); + + const aircraft = event({ set: 'flights:icons', id: 'aircraft:abc' }); + assert.equal(picking.clickCard(aircraft), null); + click(aircraft); + assert.deepEqual([zooms, clicks], [1, 1]); + } finally { + picking.unregisterClickClaim('cctv'); + picking.unregisterPickOwner('flights'); + } +}); diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index 9bd0014a80..f6f445b86e 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,7 +1,12 @@ import { distance } from '../../geo/vector.js'; +import { toLonLatH } from '../../geo/ellipsoid.js'; import { rangeForBoundingSphere } from '../../data/cameraFraming.js'; import { isFollowing } from '../../data/followed.js'; -import { cellBounds, cellCenter } from '../../data/cctvCellCounts.js'; +import { + cellBounds, + cellCenter, + cellHalfExtents, +} from '../../data/cctvCellCounts.js'; import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js'; import { cameraOf, canvasOf } from '../../render/rendererOf.js'; @@ -131,11 +136,12 @@ export function createNavigation({ return CCTV_FOCUS_RESULT.FOCUSED; } - /** The ground cell of a group nearest the eye, or the group itself if unmerged. */ + /** The nearest ground cell with two or more cameras, or the group itself if unmerged. */ function nearestPart(cell, eye) { let nearest = cell; let best = Infinity; for (const part of cell.parts ?? []) { + if (part.count < 2) continue; const d = distance(eye, cellCenter(part)); if (d < best) { best = d; @@ -157,19 +163,33 @@ export function createNavigation({ // Half the range where cells stop grouping, so even coincident mounts split. const closeRange = (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); - const fitRange = (bounds) => - Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)); + const tanHalfX = tanHalfY * (pose.aspectRatio || 1); + // Range where a cell's ground extent, times `pad`, fits the frame at the + // depth of its highest mount above the bounds centre. + const extentRange = (target, bounds, pad = 1) => { + const { halfWidthM, halfHeightM } = cellHalfExtents(target); + const rise = Math.max(0, target.high - toLonLatH(bounds.center).height); + return ( + rise + pad * Math.max(halfWidthM / tanHalfX, halfHeightM / tanHalfY) + ); + }; + // The sphere fit spans the wider side, so a very wide window also needs the extent. + const fitRange = (target, bounds) => + Math.max( + closeRange, + rangeForBoundingSphere(viewer, bounds.radius), + extentRange(target, bounds, 1.2), + ); // Approach long groups in halves so every click gets closer. const halfway = (bounds) => pose.position ? distance(pose.position, bounds.center) / 2 : Infinity; let bounds = cellBounds(cell); - const fit = fitRange(bounds); - let range = Math.min(halfway(bounds), fit); - // If the group exceeds the narrower side of the frame, approach its nearest part. - const tanHalf = tanHalfY * Math.min(1, pose.aspectRatio || 1); - if (range < fit && range * tanHalf < bounds.radius) { - bounds = cellBounds(nearestPart(cell, pose.position)); - range = Math.min(halfway(bounds), fitRange(bounds)); + let range = Math.min(halfway(bounds), fitRange(cell, bounds)); + // If the group overflows the frame at that range, approach its nearest counted cell. + if (range < extentRange(cell, bounds)) { + const part = nearestPart(cell, pose.position); + bounds = cellBounds(part); + range = Math.min(halfway(bounds), fitRange(part, bounds)); } camera.flyToBounds(bounds, { offset: { heading: 0, pitch: -Math.PI / 2, range }, diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 2d5166d395..a2f8f1b665 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -154,7 +154,7 @@ export function createRendering({ layerState._counts = createCountMarkers( services.overlays?.registerWorldOverlayPaintLane, `cctv:${iconSets}:counts`, - refreshHorizonCulling, + refreshViewFromCounts, services.overlays?.keyholeAlpha, ); return set.id; @@ -356,6 +356,11 @@ export function createRendering({ return { writes, transitioning, activeCount, ran: true }; } + /** During camera motion the timer and settle pass refresh the counts. */ + function refreshViewFromCounts() { + if (!layerState._cameraMoving) refreshHorizonCulling(); + } + /** * Cull far-side cameras on the CPU because the hidden globe writes no depth. * Group the rest by ground cell. _viewRecords holds the active camera and @@ -691,9 +696,10 @@ export function createRendering({ /** Only counts visible outside the HUD push the active icon aside. */ function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) { + const markers = layerState._counts?.markers; + for (const marker of markers ?? []) marker.besideActive = false; if (!layerState._activeCameraId) return; const record = layerState._recordById.get(layerState._activeCameraId); - const markers = layerState._counts?.markers; if ( record?.viewPass !== pass || !markers?.length || @@ -710,13 +716,14 @@ export function createRendering({ (CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2; const spans = []; for (const marker of markers) { - if (marker.hudHidden) continue; const at = project(marker.pos); if ( !at || Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX ) continue; + marker.besideActive = true; + if (marker.hudHidden) continue; const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX; spans.push([at.x - reach, at.x + reach]); } diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index a8cb724abe..157d2606bc 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -11,7 +11,12 @@ export function createSelection({ source, }) { const { CCTV_ACTIVATION_RESULT } = services.activation; - const { resolvePickId, findPickOwner, isUnderOtherCard } = services.picking; + const { + resolvePickId, + findPickOwner, + isOwnedByOtherLayer, + isUnderOtherCard, + } = services.picking; const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID]; /** @@ -39,7 +44,12 @@ export function createSelection({ const top = event.topHit; if (!top) return false; const drawHit = event.drawHit; - if (drawHit) return !parts.rendering.extractPickedCameraId(drawHit); + if (drawHit) { + // Unowned fills, such as earthquake discs, let the count take the click. + if (parts.rendering.extractPickedCameraId(drawHit)) return false; + const id = resolvePickId(drawHit); + return id !== null && Boolean(isOwnedByOtherLayer?.('cctv', id)); + } const id = resolvePickId(top); return id !== null && findPickOwner?.(id) !== 'cctv'; } diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 6882eeff53..a68755711f 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -131,6 +131,7 @@ test("a count click yields to a card above it and to another layer's object, not () => clicks++, ); picking.registerPickOwner('cctv', (id) => id.startsWith('cam-')); + picking.registerPickOwner('flights', (id) => id === 'abc' || id === 'cam-2'); try { for (const [x, topHit, expected] of [ [14, null, [0, 1]], @@ -149,6 +150,7 @@ test("a count click yields to a card above it and to another layer's object, not } } finally { picking.unregisterPickOwner('cctv'); + picking.unregisterPickOwner('flights'); } }); @@ -181,6 +183,7 @@ test('a count click is the card on top for every layer, unless the count yields' gesture: { travelPx: 0, durationMs }, }); picking.registerClickClaim('cctv', selection.countClickCard); + picking.registerPickOwner('flights', (id) => id === 'abc'); try { const aircraftFirst = event(); assert.equal(picking.isUnderOtherCard(aircraftFirst), true); @@ -209,5 +212,6 @@ test('a count click is the card on top for every layer, unless the count yields' } } finally { picking.unregisterClickClaim('cctv'); + picking.unregisterPickOwner('flights'); } });