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.
This commit is contained in:
German Khokhlov committed 2026-11-19 03:07:04 +04:00
1 parent 2e18673df8
commit 81fe7f88cc
26 files changed
+1608 -638

No files matched your search

+2 -1
View File
@@ -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,
+1 -1
View File
@@ -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. */
+2 -2
View File
@@ -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';
+75 -39
View File
@@ -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;
}
+109 -30
View File
@@ -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));
});
+254
View File
@@ -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',
);
});
+366 -206
View File
@@ -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(
'<svg xmlns="http://www.w3.org/2000/svg"><circle r="5"/></svg>',
);
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`);
});
+124 -160
View File
@@ -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();
}
+136
View File
@@ -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);
});
+15 -13
View File
@@ -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,
});
}
+64
View File
@@ -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');
});
+30 -4
View File
@@ -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
+34
View File
@@ -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);
});
+25 -8
View File
@@ -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,
+49 -57
View File
@@ -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 = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="${tone('#c9f6ff', '#fff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#ddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666')}"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#fff')}" stroke-width="0.8"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#ccc')}" stroke-width="0.8"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</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);
+11 -8
View File
@@ -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}[]}
*/
+198 -63
View File
@@ -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
+1
View File
@@ -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;
},
+23 -5
View File
@@ -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();
+47
View File
@@ -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');
}
});
+8 -4
View File
@@ -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.