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'); } });