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