mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 10:12:18 +00:00
Merge branch 'main' into samehkhamis/start-layers
This commit is contained in:
62 files changed
+5709
-372
No files matched your search
@@ -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. */
|
||||
|
||||
+15
-1
@@ -85,7 +85,9 @@ import {
|
||||
} from '../cctvFocusRequest.js';
|
||||
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';
|
||||
@@ -353,7 +355,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
|
||||
}
|
||||
});
|
||||
|
||||
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
|
||||
test('camera icons are violet for video feeds, green for stills, amber when active', () => {
|
||||
const record = (id, feedType) => ({
|
||||
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
|
||||
// Every catalog record is placed as it is made, and drawn there.
|
||||
@@ -385,6 +387,18 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
|
||||
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
|
||||
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
|
||||
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
|
||||
const image = (record) => icons.item(record.camera.id).image;
|
||||
const idleImage = image(idleStill);
|
||||
assert.equal(idleImage, IDLE_CAMERA_ICON);
|
||||
assert.equal(image(activeVideo), CAMERA_ICON);
|
||||
assert.equal(image(idleVideo), CAMERA_ICON);
|
||||
idleStill.camera.feedType = 'hls';
|
||||
refreshCoverageStyles();
|
||||
assert.equal(image(idleStill), CAMERA_ICON);
|
||||
idleStill.camera.feedType = 'image';
|
||||
refreshCoverageStyles();
|
||||
assert.equal(image(idleStill), idleImage);
|
||||
|
||||
} finally {
|
||||
_setCctvCoverageStateForTest({ enabled: false });
|
||||
unbind();
|
||||
|
||||
@@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000;
|
||||
const RETRY_MAX_MS = 5 * 60 * 1000;
|
||||
|
||||
export const CCTV_OVERLAY_SOURCE_ID = 'cctv';
|
||||
/** The source a CCTV count marker takes clicks as. */
|
||||
export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count';
|
||||
export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
|
||||
fullEnd: CCTV_CARD_SCALE_FULL_M,
|
||||
midEnd: CCTV_CARD_SCALE_MID_M,
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
|
||||
/** 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 =
|
||||
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
|
||||
return `${thousands}K`;
|
||||
}
|
||||
|
||||
/** An empty cell and its on-screen picker candidate. */
|
||||
export function createCameraCell(key) {
|
||||
return {
|
||||
key,
|
||||
count: 0,
|
||||
latSum: 0,
|
||||
lonSum: 0,
|
||||
heightSum: 0,
|
||||
south: Infinity,
|
||||
north: -Infinity,
|
||||
west: Infinity,
|
||||
east: -Infinity,
|
||||
low: Infinity,
|
||||
high: -Infinity,
|
||||
winner: null,
|
||||
rank: Infinity,
|
||||
};
|
||||
}
|
||||
|
||||
/** Accumulate one horizon-visible mount in its ground cell. */
|
||||
export function addCellCamera(cell, camera) {
|
||||
const { lat, lon, absoluteHeightM: height = 0 } = camera;
|
||||
cell.count++;
|
||||
// Integer sums make the mean independent of catalog order, to about a centimetre.
|
||||
cell.latSum += Math.round(lat * 1e7);
|
||||
cell.lonSum += Math.round(lon * 1e7);
|
||||
cell.heightSum += Math.round(height * 100);
|
||||
cell.south = Math.min(cell.south, lat);
|
||||
cell.north = Math.max(cell.north, lat);
|
||||
cell.west = Math.min(cell.west, lon);
|
||||
cell.east = Math.max(cell.east, lon);
|
||||
cell.low = Math.min(cell.low, height);
|
||||
cell.high = Math.max(cell.high, height);
|
||||
}
|
||||
|
||||
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: wrapLongitude(cell.lonSum / (1e7 * cell.count)),
|
||||
lat: cell.latSum / (1e7 * cell.count),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Geographic mean of the mounts. Its height is the drawn ground under it
|
||||
* when the cell carries one (`groundM`), since a camera nobody has looked at
|
||||
* yet may still hold a catalog height far from the terrain; otherwise the
|
||||
* mean mount height.
|
||||
*/
|
||||
export function cellCenter(cell) {
|
||||
const { lon, lat } = cellLonLat(cell);
|
||||
return fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
Number.isFinite(cell.groundM)
|
||||
? cell.groundM
|
||||
: cell.heightSum / (100 * cell.count),
|
||||
);
|
||||
}
|
||||
|
||||
/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */
|
||||
export function cellHalfExtents(cell) {
|
||||
// The parallel nearest the equator bounds the width of every row.
|
||||
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
|
||||
return {
|
||||
halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel),
|
||||
halfHeightM: 0.5 * (cell.north - cell.south) * 111_320,
|
||||
};
|
||||
}
|
||||
|
||||
/** A padded sphere over the rectangle and every mount, centred at groundM
|
||||
* when set, otherwise at the mid mount height. */
|
||||
export function cellBounds(cell) {
|
||||
const lat = (cell.north + cell.south) / 2;
|
||||
const lon = wrapLongitude((cell.east + cell.west) / 2);
|
||||
const height = Number.isFinite(cell.groundM)
|
||||
? cell.groundM
|
||||
: (cell.high + cell.low) / 2;
|
||||
const { halfWidthM, halfHeightM } = cellHalfExtents(cell);
|
||||
const halfWidth = Math.hypot(halfWidthM, halfHeightM);
|
||||
const vertical = Math.max(cell.high - height, height - cell.low);
|
||||
const radius = 1.2 * Math.hypot(halfWidth, vertical);
|
||||
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
|
||||
}
|
||||
|
||||
/** 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 + 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 + 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);
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
// 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;
|
||||
visit(other, dx * dx + dy * dy, reach);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 the nearest count it touches. Lone cameras never join each other
|
||||
* or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways.
|
||||
* A merged group lists its ground cells in `parts`.
|
||||
* Ground cells stay intact for the camera picker and individual-icon pass.
|
||||
*/
|
||||
export function mergeCountCells(cells, project, sizeFor, gap) {
|
||||
let columnWidth = 0;
|
||||
let rowHeight = 0;
|
||||
const markers = cells.map((cell) => {
|
||||
const screen = project(cellCenter(cell));
|
||||
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.
|
||||
return {
|
||||
cell,
|
||||
x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined,
|
||||
y: screen?.y,
|
||||
halfSegment: (width - height) / 2,
|
||||
radius: height / 2,
|
||||
};
|
||||
});
|
||||
const grid = new Map();
|
||||
for (const marker of markers) {
|
||||
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
|
||||
marker.col = Math.floor(marker.x / columnWidth);
|
||||
marker.row = Math.floor(marker.y / rowHeight);
|
||||
const key = `${marker.col},${marker.row}`;
|
||||
if (!grid.has(key)) grid.set(key, new Set());
|
||||
marker.bucket = grid.get(key);
|
||||
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 = [];
|
||||
group.parts = [];
|
||||
for (const { cell } of members) {
|
||||
addCell(group, cell);
|
||||
group.parts.push(...(cell.parts ?? [cell]));
|
||||
if (cell.count === 1) group.lone.push(cell);
|
||||
else if (cell.lone) group.lone.push(...cell.lone);
|
||||
}
|
||||
seed.result = group;
|
||||
}
|
||||
}
|
||||
|
||||
const groups = [];
|
||||
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;
|
||||
}
|
||||
|
||||
/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */
|
||||
export function withoutLoneCameras(group, keep = []) {
|
||||
const counts = (group.parts ?? []).filter((cell) => cell.count > 1);
|
||||
if (!counts.length) return null;
|
||||
const core = createCameraCell(group.key);
|
||||
core.parts = [...counts, ...keep];
|
||||
if (keep.length) core.lone = [...keep];
|
||||
for (const cell of core.parts) addCell(core, cell);
|
||||
return core;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { distance } from '../geo/vector.js';
|
||||
import { getLocale, setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
createCameraCell,
|
||||
addCellCamera,
|
||||
cellCenter,
|
||||
cellBounds,
|
||||
formatCameraCount,
|
||||
mergeCountCells,
|
||||
} from './cctvCellCounts.js';
|
||||
|
||||
test('camera counts use Latin digits and K notation whatever the UI language', () => {
|
||||
const previous = getLocale();
|
||||
const examples = [
|
||||
[2, '2'],
|
||||
[999, '999'],
|
||||
[1000, '1K'],
|
||||
[1150, '1.2K'],
|
||||
[1687, '1.7K'],
|
||||
[9960, '10K'],
|
||||
[10000, '10K'],
|
||||
[12345, '12K'],
|
||||
[12500, '13K'],
|
||||
[1000000, '1000K'],
|
||||
];
|
||||
try {
|
||||
setLocale('ar');
|
||||
for (const [count, label] of examples)
|
||||
assert.equal(formatCameraCount(count), label);
|
||||
} finally {
|
||||
setLocale(previous);
|
||||
}
|
||||
});
|
||||
|
||||
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
|
||||
const cameras = [
|
||||
{ lon: 12, lat: 52, absoluteHeightM: 30 },
|
||||
{ lon: 12, lat: 52, absoluteHeightM: 40 },
|
||||
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
|
||||
];
|
||||
const cell = createCameraCell();
|
||||
for (const camera of cameras) addCellCamera(cell, camera);
|
||||
const expected = fromDegrees(12.001, 52.002, 40);
|
||||
assert.ok(distance(cellCenter(cell), expected) < 0.001);
|
||||
const bounds = cellBounds(cell);
|
||||
for (const { lon, lat, absoluteHeightM } of cameras) {
|
||||
assert.ok(
|
||||
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
|
||||
bounds.radius,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
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 check = (counts, positions, expected) => {
|
||||
const { groups } = mergeCounts(sizes, counts, positions);
|
||||
assert.deepEqual(
|
||||
groups.map((cell) => cell.count),
|
||||
expected,
|
||||
);
|
||||
assert.equal(
|
||||
groups.reduce((sum, cell) => sum + cell.count, 0),
|
||||
counts[0] + counts[1],
|
||||
);
|
||||
};
|
||||
const origin = { x: 35, y: 37 };
|
||||
// Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear.
|
||||
check([2, 7350], [origin, { x: 35, y: 78 }], [7352]);
|
||||
check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]);
|
||||
// The large pill's centre segment extends 16 pixels towards the circle.
|
||||
check([7350, 2], [origin, { x: 92, y: 37 }], [7352]);
|
||||
check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]);
|
||||
check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]);
|
||||
// Large pills can reach across a row boundary at their full diameter.
|
||||
check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]);
|
||||
});
|
||||
|
||||
test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => {
|
||||
const sizes = {
|
||||
1: { width: 24, height: 24 },
|
||||
9: { width: 40, height: 40 },
|
||||
};
|
||||
const check = (counts, positions, expected) => {
|
||||
const { cells, groups } = mergeCounts(sizes, counts, positions);
|
||||
assert.deepEqual(
|
||||
groups.map((cell) => cell.count),
|
||||
expected,
|
||||
);
|
||||
// A lone camera that stays apart is still its own cell object.
|
||||
assert.deepEqual(
|
||||
groups.filter((cell) => cell.count === 1),
|
||||
cells.filter((cell) => groups.includes(cell) && cell.count === 1),
|
||||
);
|
||||
};
|
||||
const at = (x, y = 100) => ({ x, y });
|
||||
// Radii 20 and 12: the four-pixel gap is clear at 36 pixels.
|
||||
check([9, 1], [at(100), at(135)], [10]);
|
||||
check([9, 1], [at(100), at(136)], [9, 1]);
|
||||
check([1, 9], [at(135), at(100)], [10]);
|
||||
// Overlapping icons with no count beside them stay two icons.
|
||||
check([1, 1], [at(100), at(110)], [1, 1]);
|
||||
// A count takes every lone camera it touches, on either side.
|
||||
check([1, 9, 1], [at(70), at(100), at(130)], [11]);
|
||||
// A lone camera that only touches another lone camera is left alone.
|
||||
check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]);
|
||||
});
|
||||
|
||||
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));
|
||||
});
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
+1280
-52
File diff suppressed because it is too large.
Load diff
@@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) {
|
||||
let _overlayHitTest = null;
|
||||
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
|
||||
const clickCards = new WeakMap();
|
||||
const _clickClaims = new Map();
|
||||
|
||||
/**
|
||||
* Register a target drawn outside the world overlay's entries, such as a CCTV
|
||||
* count. A claim runs once per click where no card or label is painted above
|
||||
* it and must not call `clickCard`.
|
||||
* @param {string} layerId
|
||||
* @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim
|
||||
*/
|
||||
export function registerClickClaim(layerId, claim) {
|
||||
if (!layerId || typeof claim !== 'function') return;
|
||||
_clickClaims.set(layerId, claim);
|
||||
}
|
||||
|
||||
/** Remove a layer's claim when it is disabled or destroyed. */
|
||||
export function unregisterClickClaim(layerId) {
|
||||
_clickClaims.delete(layerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets (or with null, clears) the hit test that names the card or label
|
||||
@@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The topmost interactive card or label painted at a click, read once per
|
||||
* click so every handler of it sees the same one whatever ran first.
|
||||
* The topmost interactive card or label painted at a click, or a target a
|
||||
* layer claims (`registerClickClaim`). All handlers share one result per click.
|
||||
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
|
||||
* @returns {{sourceId: string, entryId: string}|null}
|
||||
*/
|
||||
@@ -179,14 +197,28 @@ export function clickCard(click) {
|
||||
try {
|
||||
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
|
||||
} catch {
|
||||
// a broken hit test must never break click handling
|
||||
clickCards.set(click, null);
|
||||
return null;
|
||||
}
|
||||
if (!card) {
|
||||
// A claim that reads this click again cannot re-enter the claims loop.
|
||||
clickCards.set(click, null);
|
||||
for (const claim of _clickClaims.values()) {
|
||||
try {
|
||||
card = claim(click) ?? null;
|
||||
} catch {
|
||||
card = null;
|
||||
}
|
||||
if (card) break;
|
||||
}
|
||||
}
|
||||
clickCards.set(click, card);
|
||||
return card;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when another layer's card or label is painted on top at a click. The
|
||||
* True when another layer has the top card, label, or claimed target
|
||||
* (`registerClickClaim`) at a click. The
|
||||
* card on top takes the click: a scene item under it does not act, and is
|
||||
* not empty space either, so the layer leaves its selection alone.
|
||||
* @param {object} click The shared dispatcher event.
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
clickCard,
|
||||
isUnderOtherCard,
|
||||
setClickCardHitTest,
|
||||
registerClickClaim,
|
||||
unregisterClickClaim,
|
||||
} from './pickRegistry.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
});
|
||||
|
||||
test('a click claim is the card on top only where no card or label is painted', () => {
|
||||
const event = (x) => ({ screenPosition: { x, y: 5 } });
|
||||
let calls = 0;
|
||||
registerClickClaim('counts', (click) => {
|
||||
calls++;
|
||||
return click.screenPosition.x === 4
|
||||
? { sourceId: 'counts', entryId: 'k' }
|
||||
: null;
|
||||
});
|
||||
try {
|
||||
registerClickClaim('counts', null);
|
||||
const click = event(4);
|
||||
assert.equal(isUnderOtherCard(click), true);
|
||||
assert.equal(isUnderOtherCard(click, ['counts']), false);
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(clickCard(event(9)), null);
|
||||
const quake = { sourceId: 'quake-card', entryId: 'q1' };
|
||||
setClickCardHitTest(() => quake);
|
||||
assert.deepEqual(clickCard(event(4)), quake);
|
||||
assert.equal(calls, 2);
|
||||
setClickCardHitTest(() => {
|
||||
throw new Error('broken overlay hit test');
|
||||
});
|
||||
assert.equal(clickCard(event(4)), null);
|
||||
assert.equal(calls, 2);
|
||||
setClickCardHitTest(null);
|
||||
|
||||
unregisterClickClaim('counts');
|
||||
assert.equal(clickCard(event(4)), null);
|
||||
registerClickClaim('counts', () => {
|
||||
throw new Error('broken claim');
|
||||
});
|
||||
assert.equal(clickCard(event(4)), null);
|
||||
} finally {
|
||||
unregisterClickClaim('counts');
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user