Merge branch 'main' into exp/cctv-target-navigation

# Conflicts:
#	docs/CURRENT-STATE.md
#	src/layers/cctv/navigation.js
This commit is contained in:
German Khokhlov committed 2026-11-18 16:36:41 +04:00
commit 6e70793f66
2056 files changed
+320064 -46450

No files matched your search

+2
View File
@@ -261,6 +261,8 @@ export function createCalibration({
// §9.1: touching range takes manual control — clear the activation clamp.
if ('rangeScale' in patch) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
}
const anchorMoved = calibrationPatchMovesAnchor(patch);
if (options.transient === true && anchorMoved) {
+24 -28
View File
@@ -1,3 +1,4 @@
import { findFrame } from '../../render/rendererOf.js';
import {
createFrameSlot,
CCTV_OVERLAY_SOURCE_ID,
@@ -8,8 +9,6 @@ import {
CCTV_FRAME_CANVAS_H,
applyFrameResult,
} from '../../data/cctvCards.js';
import * as Cesium from 'cesium';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { selectCctvLod, applyEvictionGrace } from '../../data/cctvLod.js';
import {
CCTV_OVERLAY_SOURCE_OPTIONS,
@@ -35,7 +34,7 @@ export function createCards({ state: layerState, services, parts, source }) {
} = {}) {
layerState._activeCameraCardEnabled = activeCameraCardEnabled === true;
if (layerState._enabled) pushAmbientCardEntries();
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-cards');
return { activeCameraCardEnabled: layerState._activeCameraCardEnabled };
}
@@ -83,17 +82,16 @@ export function createCards({ state: layerState, services, parts, source }) {
);
return;
}
const scene = layerState._viewer.scene;
const carto = layerState._viewer.camera.positionCartographic;
const viewerLat = carto ? Cesium.Math.toDegrees(carto.latitude) : 0;
const viewerLon = carto ? Cesium.Math.toDegrees(carto.longitude) : 0;
// An eye with no geographic position (the earth's centre) measures from 0, 0.
const pose = parts.model.eyePose();
const viewerLat = pose ? pose.lat : 0;
const viewerLon = pose ? pose.lon : 0;
// The active camera is excluded from ambient selection ALWAYS (not just
// after its async activation settles). It is published separately in the
// protected lane below, and grace never applies to it.
const activeId = layerState._activeCameraId;
const occluder = horizonOccluder(layerState._viewer.camera);
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
const view = parts.rendering.cardView();
const { width, height } = view;
const marginX = width * CARD_VIEW_MARGIN;
const marginY = height * CARD_VIEW_MARGIN;
@@ -106,22 +104,20 @@ export function createCards({ state: layerState, services, parts, source }) {
let inView = false;
let sx = NaN;
let sy = NaN;
if (occluder.isPointVisible(record.position)) {
const screen = scene.cartesianToCanvasCoordinates(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
const screen = view.screenOf(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
candidates.push({
id,
@@ -148,7 +144,7 @@ export function createCards({ state: layerState, services, parts, source }) {
// the budget fill through the screen-distribution grid, so periphery
// cells hold cards instead of everything clustering at screen center.
const { cardIds, budgets } = selectCctvLod(candidates, {
cameraHeightM: carto?.height,
cameraHeightM: pose?.height,
incumbentIds: layerState._cardIds,
viewW: width,
viewH: height,
@@ -335,7 +331,7 @@ export function createCards({ state: layerState, services, parts, source }) {
slot,
applyFrameResult(slot, { ok: !!frame, frame }, Date.now()),
);
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-card-frame');
};
image.onload = () => settle(true);
image.onerror = () => settle(false);
+1 -1
View File
@@ -202,7 +202,7 @@ export function createControls({ state: layerState, services, parts, source }) {
* @param {Object} [options={}]
* @param {number} [options.maxCount] - Maximum number of objects to return.
* @param {number} [options.seed] - Offset seed for deterministic stride sampling.
* @returns {{ position: Cesium.Cartesian3, id: string, type: string }[]}
* @returns {{ position: {x: number, y: number, z: number}, id: string, type: string }[]}
*/
getDetectableObjects(options = {}) {
// The cameras the view pass shows, not icons it has hidden.
+195
View File
@@ -0,0 +1,195 @@
/**
* @module layers/cctv/drawSets
* @description The CCTV layer's draw sets: the frustum wireframes
* (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the
* active camera's monitor plane (`plane`, a quad), made through the draw
* port of the viewer the layer is on. They are made when first drawn into
* and made again on another viewer. Item ids keep the layer's
* `cctv-<cameraId>-<role>` scheme the shared pick registry reads, and each
* line's and plane's `meta.cameraId` names its camera (volumes are never
* picked and carry none).
*
* Coverage lines and the plane are written from handles the layer keeps
* (a record's `coverageEntities`, a projection runtime's `plane`): plain
* objects the layer changes and then writes, only what changed reaching
* the set.
*
* Meshes and quads are capabilities: on a renderer without them there are
* no viewshed volumes or monitor plane, and the lines still draw.
*/
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
let instances = 0;
/** A line handle's item, or null for a handle that names no line yet. */
function lineItemOf(handle) {
if (!handle?.id || !Array.isArray(handle.positions)) return null;
const color = handle.color;
return {
id: handle.id,
positions: handle.positions,
widthPx: handle.widthPx,
// As a polyline entity runs: along the ellipsoid between its positions.
mode: 'geodesic',
style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color },
depthFail: handle.depthFailColor
? { kind: 'solid', color: handle.depthFailColor }
: null,
meta: { cameraId: handle.cameraId },
show: handle.show !== false,
};
}
/** What a line item draws, as a key: an unchanged key is not written. */
const lineKey = (item) =>
[
item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'),
item.widthPx,
item.style.kind,
item.style.color.join(','),
item.depthFail ? item.depthFail.color.join(',') : '',
item.show,
].join('|');
/** The plane handle's quad item. */
function quadItemOf(plane) {
return {
id: plane.id,
center: plane.center,
orientation: plane.orientation,
size: plane.size,
source: plane.source,
alpha: plane.alpha,
outline: plane.outline,
meta: { cameraId: plane.cameraId },
show: plane.show === true,
};
}
export function createDrawSets({ state: layerState }) {
/** The live sets and the viewer they draw on, or null. */
let current = null;
/** Viewshed volumes written, ever (the QA harness checks for churn). */
let volumeWrites = 0;
/** The layer's sets on its viewer now, made if need be; null with none. */
function sets() {
const viewer = layerState._viewer;
if (!viewer) return null;
if (current?.viewer === viewer) return current;
dispose();
const draw = drawOf(viewer);
const n = ++instances;
current = {
viewer,
coverage: draw.lines({ id: `cctv:${n}:coverage` }),
viewshed:
draw.meshes?.({ id: `cctv:${n}:viewshed`, pickable: false }) ?? null,
plane: draw.quads?.({ id: `cctv:${n}:plane` }) ?? null,
// What each line item was last written as, by id.
lineKeys: new Map(),
};
return current;
}
/** The live sets, without making them. */
const live = () =>
current && current.viewer === layerState._viewer ? current : null;
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set?.dispose();
} catch {
// Its viewer went first.
}
current = null;
}
/** The ids of the sets that draw the layer's lines and plane. */
function pickableSetIds() {
const s = live();
if (!s) return [];
return s.plane ? [s.coverage.id, s.plane.id] : [s.coverage.id];
}
/** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */
function roleOfSet(setId) {
const s = live();
if (!s) return null;
if (setId === s.coverage.id) return 'coverage';
if (setId === s.plane?.id) return 'plane';
return null;
}
/** Write line handles that changed since they were last written. */
function writeLines(handles) {
if (!handles?.length) return;
const s = handles.some((h) => h?.id) ? sets() : null;
if (!s) return;
const changed = [];
for (const handle of handles) {
const item = lineItemOf(handle);
if (!item) continue;
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
}
/** Take every line out. */
function clearLines() {
const s = live();
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
sets()?.plane?.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
if (plane?.id) live()?.plane?.remove([plane.id]);
}
/** Write a viewshed volume. */
function writeVolume(item) {
const s = sets();
if (!s?.viewshed) return;
s.viewshed.upsert([item]);
volumeWrites += 1;
}
/** Take a viewshed volume out. */
function removeVolume(id) {
if (id) live()?.viewshed?.remove([id]);
}
/** How many viewshed volumes were written, for the QA harness. */
const volumeWritesForTest = () => volumeWrites;
return {
sets,
dispose,
pickableSetIds,
roleOfSet,
writeLines,
clearLines,
writePlane,
removePlane,
writeVolume,
removeVolume,
volumeWritesForTest,
};
}
+135
View File
@@ -0,0 +1,135 @@
// The CCTV layer's draw sets: lines written only as they change, dashed for
// an estimated bearing, the depth-fail colour passed as it is; the sets made
// again on another viewer and let go on dispose.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDrawSets } from './drawSets.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const line = (id, fields = {}) => ({
id,
cameraId: 'cam',
role: 'edge',
positions: [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
],
widthPx: 1.2,
color: [0.1, 0.2, 0.3, 0.4],
dashed: false,
depthFailColor: null,
show: true,
...fields,
});
test('lines are written as they change, and drawn as their handles say', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
const a = line('cctv-cam-ray-tl');
const b = line('cctv-cam-cap', { role: 'cap' });
drawSets.writeLines([a, b]);
const coverage = draw.find('cctv:');
assert.equal(coverage.kind, 'lines');
assert.equal(coverage.writes, 1);
assert.deepEqual(coverage.items.get(a.id), {
id: a.id,
positions: a.positions,
widthPx: 1.2,
mode: 'geodesic',
style: { kind: 'solid', color: a.color },
depthFail: null,
meta: { cameraId: 'cam' },
show: true,
});
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 1, 'unchanged handles write nothing');
b.dashed = true;
b.depthFailColor = [1, 1, 1, 0.2];
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 2);
const cap = coverage.items.get(b.id);
assert.deepEqual(cap.style, {
kind: 'dash',
color: b.color,
length: 16,
pattern16: 255,
});
assert.deepEqual(cap.depthFail, { kind: 'solid', color: [1, 1, 1, 0.2] });
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null);
drawSets.clearLines();
assert.equal(coverage.items.size, 0);
drawSets.writeLines([a]);
assert.ok(coverage.items.has(a.id), 'a cleared line is written again');
} finally {
unbind();
}
});
test('another viewer gets sets of its own; dispose lets them go', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
const old = one.draw.find('cctv:');
assert.equal(drawSets.volumeWritesForTest(), 1);
state._viewer = second;
assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet');
drawSets.writeLines([a]);
assert.ok(old.disposed, 'the old viewer’s sets are let go');
const now = two.draw.find('cctv:');
assert.ok(now.items.has(a.id), 'the line is written anew');
const [coverage, plane] = drawSets.pickableSetIds();
assert.equal(two.draw.set(coverage).kind, 'lines');
assert.equal(two.draw.set(plane).kind, 'quads');
assert.equal(drawSets.roleOfSet(plane), 'plane');
drawSets.dispose();
assert.ok(
[...two.draw.sets.values()].every((set) => set.disposed),
'every set is let go',
);
assert.equal(drawSets.roleOfSet(coverage), null);
} finally {
one.unbind();
two.unbind();
}
});
test('a renderer without meshes or quads still draws the lines', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
delete draw.meshes;
delete draw.quads;
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
drawSets.writeLines([line('cctv-cam-ray-tl')]);
const coverage = draw.find('cctv:');
assert.equal(coverage.items.size, 1);
// No viewshed volumes and no monitor plane: their writes do nothing.
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
drawSets.removeVolume('cctv-cam-viewshed');
const plane = { id: 'cctv-cam-plane', cameraId: 'cam', show: true };
drawSets.writePlane(plane);
drawSets.removePlane(plane);
assert.equal(drawSets.volumeWritesForTest(), 0);
assert.deepEqual(drawSets.pickableSetIds(), [coverage.spec.id]);
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
drawSets.dispose();
} finally {
unbind();
}
});
+8 -8
View File
@@ -106,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Blits the latest projection canvas into the next of two alternating
* offscreen buffer canvases and returns it (H5).
*
* Two buffers are required because Cesium's Material image path re-uploads a
* canvas texture only when the uniform receives a NEW object reference —
* redrawing the same canvas in place is invisible to the GPU. Alternating
* Two buffers are required because the plane re-uploads a canvas texture
* only when it is given a NEW canvas — redrawing the same canvas in place
* is invisible to the GPU. Alternating
* references forces a texture recreate, which at <=1Hz and 1080p is cheap.
*
* @param {Object} runtime - Projection runtime with `.canvas`.
@@ -139,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Pushes fresh pixels into the monitor plane material. Called every
* projection tick.
*
* Video feeds are skipped entirely — their HTMLVideoElement uniform is
* updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap
* Video feeds are skipped entirely — the renderer reads their
* HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap
* the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS.
*
* @param {Object} record - Camera record with an initialized projection runtime.
@@ -156,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
)
return;
const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial);
const planeShowing = !!runtime.plane?.show;
if (!planeShowing) return;
// Only swap when the canvas content actually changed since the last swap.
@@ -170,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
if (!buffer) return;
runtime.lastTextureSwapAt = now;
runtime.lastSwappedCanvasStamp = runtime.canvasStamp;
runtime.planeMaterial.image = buffer;
parts.projection.setPlaneSource(runtime, { canvas: buffer });
}
/**
@@ -355,7 +355,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
// camera republished once in 5 minutes, an Austin one not at all.
// Redrawing regardless bumped canvasStamp, which forced a buffer swap
// and a fresh 1920x1080 texture upload; the plane renders its white
// base color (planeMaterial color = WHITE, alpha .95) for the frame or
// base color (white, alpha .95) for the frame or
// two Cesium needs to rebind, which IS the periodic white flash from the
// owner field tests (2026-07-04 and 2026-07-30).
const fit = fitToProjection(
+114 -221
View File
@@ -1,12 +1,12 @@
import * as Cesium from 'cesium';
import { createFrustumVolumePrimitive } from '../../data/cctvViewshed.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp, frameVector } from '../../geo/frames.js';
import { distance, vec } from '../../geo/vector.js';
import {
FRUSTUM_GROUND_CLEARANCE_M,
PROBE_MIN_RANGE_M,
PROBE_CLEARANCE_M,
COVERAGE_NEIGHBOR_RADIUS_KM,
COVERAGE_NEIGHBOR_LIMIT,
IDLE_COVERAGE_COLOR,
PLANE_FOOTPRINT_LIFT_CAP_M,
} from './policy.js';
@@ -261,30 +261,18 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
/**
* Converts a computeFrustumGeometry result into the Cartesian3 positions the
* entities consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and entities must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: Cesium.Cartesian3, capCenter: Cesium.Cartesian3,
* tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, br: Cesium.Cartesian3,
* bl: Cesium.Cartesian3, label: Cesium.Cartesian3 }}
* Distance along a pitched-down view axis to flat ground at the mount's own
* ground height, or null for an axis at or above the horizon.
* @param {number} mountHeightM Mount height above its ground.
* @param {number} pitchDeg Axis pitch (negative looks down).
* @returns {number|null}
*/
function frustumCartesians(geometry) {
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
tl: at(geometry.corners.tl),
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: Cesium.Cartesian3.fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
),
};
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
const height = Number(mountHeightM);
const pitch = Number(pitchDeg);
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
return height / Math.sin((Math.min(89, -pitch) * Math.PI) / 180);
}
/**
@@ -292,40 +280,35 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* Used by the plane orientation and the activation obstruction probe — both
* need the UNCLAMPED axis, so it comes from the pose, not from clamped points.
* @param {Object} camera - Camera pose (headingDeg, pitchDeg).
* @param {Cesium.Cartesian3} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: Cesium.Cartesian3, up: Cesium.Cartesian3 }} View axis + the
* @param {{x: number, y: number, z: number}} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: {x: number, y: number, z: number}, up: {x: number, y: number, z: number} }} View axis + the
* frame's in-plane "up" (both unit, mutually perpendicular).
*/
function frustumFrameEcef(camera, atPos) {
const h = parts.model.toRad(camera.headingDeg);
const p = parts.model.toRad(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const enu = eastNorthUp(atPos);
// ENU components: view axis + the perpendicular "up" of the pitched cap.
const dirEnu = new Cesium.Cartesian3(
const dirEnu = vec(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
const upEnu = vec(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
return {
dir: Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
),
up: Cesium.Matrix3.multiplyByVector(rot, upEnu, new Cesium.Cartesian3()),
dir: frameVector(enu, dirEnu),
up: frameVector(enu, upEnu),
};
}
/**
* Recomputes the pure frustum geometry from the camera pose + the given ground
* altitude and writes it into the scene: billboard position, the 5 wireframe
* altitude and writes it into the scene: icon position, the 5 wireframe
* polylines (4 corner rays + closed far-plane rectangle), and the monitor
* plane placement. This is the ONLY place v2 geometry is written — called on
* slider input / save / activation / the one-shot ground snap, never per frame.
@@ -340,38 +323,16 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
footprintGroundFor(record),
);
const positions = frustumCartesians(geometry);
const positions = parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
record.camera.absoluteHeightM = geometry.mount.alt;
if (record.billboard) {
record.billboard.position = positions.mount;
}
parts.rendering.moveCameraIcon(record);
record.groundAltM = groundAltM;
if (record.coverageEntities?.length >= 5) {
record.coverageEntities[0].polyline.positions = [
positions.mount,
positions.tl,
];
record.coverageEntities[1].polyline.positions = [
positions.mount,
positions.tr,
];
record.coverageEntities[2].polyline.positions = [
positions.mount,
positions.br,
];
record.coverageEntities[3].polyline.positions = [
positions.mount,
positions.bl,
];
record.coverageEntities[4].polyline.positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
parts.rendering.placeCoverageLines(record.coverageEntities, positions);
parts.drawSets.writeLines(record.coverageEntities);
}
// A live viewshed volume tracks its wireframe: rebuild from the SAME fresh
// positions (weld invariant). Only records currently showing a volume pay
@@ -379,8 +340,8 @@ export function createGeometry({ state: layerState, services, parts, source }) {
// Tint derives from the live active id, not the cached viewshedActiveTint —
// during an activation switch this runs BEFORE refreshCoverageStyles, and
// the cache is stale for exactly that window.
if (record.viewshedPrimitive) {
rebuildViewshedVolume(
if (record.viewshedVolume) {
parts.rendering.rebuildViewshedVolume(
record,
record.camera.id === layerState._activeCameraId,
);
@@ -453,19 +414,12 @@ export function createGeometry({ state: layerState, services, parts, source }) {
if (sampleGround && parts.model.projectionTilesReady()) {
record.groundMeshSampleRequestCount =
(record.groundMeshSampleRequestCount || 0) + 1;
const viewerCarto = layerState._viewer?.camera?.positionCartographic;
const excludeObjects = [...(record.coverageEntities || [])];
if (record.billboard) excludeObjects.push(record.billboard);
if (record.projection?.planeEntity)
excludeObjects.push(record.projection.planeEntity);
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
excludeObjects: excludeObjects.filter(Boolean),
viewerLat: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.latitude)
: undefined,
viewerLon: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.longitude)
: undefined,
const eye = parts.model.eyePose();
// The layer's own lines and plane are not ground; named all the same.
sampleMeshFloorCells(layerState._viewer, [point], {
sets: parts.drawSets.pickableSetIds(),
viewerLat: eye ? eye.lat : undefined,
viewerLon: eye ? eye.lon : undefined,
});
}
@@ -525,52 +479,6 @@ export function createGeometry({ state: layerState, services, parts, source }) {
return new Set(chosen);
}
/**
* Removes (and destroys) a record's viewshed volume primitive, if any.
* @param {Object} record - Camera record.
*/
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedPrimitive && layerState._viewer) {
layerState._viewer.scene.primitives.remove(record.viewshedPrimitive);
}
record.viewshedPrimitive = null;
}
/**
* (Re)builds a record's translucent viewshed volume from its CURRENT
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
* is welded to the cone by construction. Called only where the wireframe
* already rewrites (style refresh on mode/visible-set/active changes,
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
* queries (viewshed design §3b).
* @param {Object} record - Camera record.
* @param {boolean} isActive - Active camera gets the brighter fill.
*/
function rebuildViewshedVolume(record, isActive) {
destroyViewshedVolume(record);
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
)
return;
const color = isActive
? record.viewshedColors.fillActive
: record.viewshedColors.fill;
const primitive = createFrustumVolumePrimitive(
record.frustumPositions,
color,
);
// QA tag: the harness counts viewshed volumes by this marker.
primitive._gevViewshed = record.camera.id;
record.viewshedPrimitive =
layerState._viewer.scene.primitives.add(primitive);
record.viewshedActiveTint = !!isActive;
}
/**
* Counts how many other cameras have overlapping coverage with the target.
* Overlap is approximated by comparing inter-camera distance against the
@@ -611,47 +519,94 @@ export function createGeometry({ state: layerState, services, parts, source }) {
/**
* §9.1 activation obstruction probe (LOCKED owner decision): on camera
* ACTIVATION only, fire ONE scene.pickFromRay along the frustum axis
* ACTIVATION only, cast ONE ray against the scene along the frustum axis
* (mount → cap-center direction). If it hits the tiles closer than the pose
* range, clamp the plane's effective range just short of the first hit so the
* "big and dramatic" true end cap never clips into downtown buildings.
*
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
* never per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range.
* On a globe map it also casts along the same axis against the globe's
* terrain (flat ground at the mount's ground when terrain is missed or met
* beyond the range) and clamps at the nearer end. These are the ONLY
* raycasts in the whole CCTV subsystem — once per activation, never
* per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips
* the probe entirely. A miss on the photoreal stack or a probe failure
* keeps the unclamped range.
*
* The casts are made now, against the scene as it is, and answer a
* microtask later: the clamp then lands by rewriting the geometry from the
* ground it was last written at, before the next frame draws. A newer
* activation, or the camera's deactivation, drops an answer still to come.
* @param {Object} record - Camera record being activated.
* @returns {Promise<void>} Settled once the clamp (if any) has landed.
*/
function runActivationObstructionProbe(record) {
record.probeClampRangeM = null;
const scene = layerState._viewer?.scene;
if (!scene || typeof scene.pickFromRay !== 'function') return;
const token = (record.probeToken = (record.probeToken || 0) + 1);
const viewer = layerState._viewer;
if (!parts.rendering.canPickFromRay()) return Promise.resolve();
const camera = record.camera;
const rangeScale = parts.calibration.normalizeCalibration(
camera.calibration,
).rangeScale;
if (Math.abs(rangeScale - 1) > 0.0001) return; // slider overrides the clamp
// The slider overrides the clamp.
if (Math.abs(rangeScale - 1) > 0.0001) return Promise.resolve();
try {
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
const mountPos = Cesium.Cartesian3.fromDegrees(
camera.lon,
camera.lat,
mountAlt,
);
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
const { dir } = frustumFrameEcef(camera, mountPos);
// Exclude everything the layer itself draws so the probe can only hit the
// world (3D tiles), not our own billboards/polylines/planes.
const exclude = [layerState._billboards, ...layerState._coverageEntities];
for (const runtime of layerState._projectionEntities) {
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
}
const hit = scene.pickFromRay(new Cesium.Ray(mountPos, dir), exclude);
if (!hit?.position) return;
const dist = Cesium.Cartesian3.distance(mountPos, hit.position);
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
// The casts see through everything the layer draws. The surface cast
// meets what is drawn on the globe (the photoreal tiles); on a globe
// map the axis also ends on the globe's terrain, the nearer of that and
// any surface hit. A hit at or beyond the range counts as none. Terrain
// still loading at a coarse level can be missed or met beyond the
// range; then flat ground at the mount's own ground stands in for it.
const inRange = (d) => Number.isFinite(d) && d > 0 && d < camera.rangeM;
return Promise.all([
parts.rendering.obstructionHit(mountPos, dir),
parts.rendering.terrainHit?.(mountPos, dir) ?? null,
])
.then(([hit, terrain]) => {
if (record.probeToken !== token) return;
if (record.camera.id !== layerState._activeCameraId) return;
// A layer torn down or re-initialised since (another viewer, or
// a new record for the same camera) is not the one it asked for.
if (layerState._viewer !== viewer) return;
if (layerState._recordById?.get(record.camera.id) !== record) return;
const hitDist = hit ? distance(mountPos, hit) : NaN;
const distances = inRange(hitDist) ? [hitDist] : [];
if (terrain) {
const terrainDist = terrain.hit
? distance(mountPos, terrain.hit)
: NaN;
const ground = inRange(terrainDist)
? terrainDist
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
}
if (!distances.length) return;
const clamp = activationProbeClampRange(
camera.rangeM,
Math.min(...distances),
);
if (!Number.isFinite(clamp)) return;
record.probeClampRangeM = clamp;
if (Number.isFinite(record.groundAltM))
applyFrustumGeometry(record, record.groundAltM);
// The activation asked for the ground under the unclamped plane's
// footprint; the clamped plane's is asked for now, and the layer
// restyles and tells its listeners, as that answer will.
void parts.ground.resolveFootprintGround(record);
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
})
.catch(() => {
// probe failure → keep the unclamped range
});
} catch {
// probe failure → keep the unclamped range
return Promise.resolve();
}
}
@@ -664,77 +619,17 @@ export function createGeometry({ state: layerState, services, parts, source }) {
*/
function clearProbeClampOnDeactivation(record, rewriteGeometry) {
if (record) record.probeToken = (record.probeToken || 0) + 1;
if (!record || !Number.isFinite(record.probeClampRangeM)) return false;
record.probeClampRangeM = null;
rewriteGeometry?.(record);
return true;
}
/**
* Creates the five Cesium polyline entities that visualize a camera's pitched
* frustum: 4 corner rays (mount → far-plane corner) + the closed far-plane
* rectangle. Entity ids stay in the `cctv-<id>-<role>` scheme (pick-owner
* regex depends on it): roles ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Cesium.Entity[]} Array of five coverage entities.
*/
function buildCoverageEntities(record) {
const { camera } = record;
// Prefer the record's already-refined geometry. Lazy creation commonly
// happens after the staggered ground pass; recomputing from the catalog
// prior here would regress the camera to its pre-sampled datum.
let geometry = record.frustumGeometry;
let positions = record.frustumPositions;
if (!geometry || !positions) {
geometry = computeFrustumGeometry(
camera,
parts.ground.groundPriorAltFor(record),
record.probeClampRangeM,
);
positions = frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
}
const addPolyline = (role, linePositions) =>
layerState._viewer.entities.add({
id: `cctv-${camera.id}-${role}`,
properties: { cctvCameraId: camera.id },
polyline: {
positions: linePositions,
width: 1.2,
material: IDLE_COVERAGE_COLOR,
},
});
const entities = [
addPolyline('ray-tl', [positions.mount, positions.tl]),
addPolyline('ray-tr', [positions.mount, positions.tr]),
addPolyline('ray-br', [positions.mount, positions.br]),
addPolyline('ray-bl', [positions.mount, positions.bl]),
addPolyline('cap', [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
]),
];
entities[0]._coverageRole = 'edge';
entities[1]._coverageRole = 'edge';
entities[2]._coverageRole = 'edge';
entities[3]._coverageRole = 'edge';
entities[4]._coverageRole = 'cap';
return entities;
}
/**
* Materializes coverage entities for eligible records exactly once.
* The helper is dependency-injected so unit tests can prove the enable policy
* without constructing Cesium entities.
* without constructing entities.
*
* @param {Object[]} records CCTV runtime records.
* @param {(record: Object) => boolean} [isEligible] Eligibility predicate.
@@ -792,7 +687,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function ensureActiveCoverageEntities(record) {
return registerCoverageEntities(
materializeCctvActiveCoverageEntities(record, buildCoverageEntities),
materializeCctvActiveCoverageEntities(
record,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -801,7 +699,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
materializeCctvVisibleCoverageEntities(
records,
visibleIds,
buildCoverageEntities,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -812,13 +710,11 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function destroyCoverageEntities() {
if (!layerState._viewer) return;
for (const entity of layerState._coverageEntities) {
layerState._viewer.entities.remove(entity);
}
parts.rendering.removeCoverageEntities();
layerState._coverageEntities = [];
for (const record of layerState._records) {
destroyViewshedVolume(record);
parts.rendering.destroyViewshedVolume(record);
}
for (const runtime of layerState._projectionEntities) {
@@ -831,17 +727,14 @@ export function createGeometry({ state: layerState, services, parts, source }) {
hasShippedFootprint,
footprintPose,
activationProbeClampRange,
frustumCartesians,
flatGroundAxisDistance,
frustumFrameEcef,
applyFrustumGeometry,
updateRecordGeometry,
buildCoverageVisibleSet,
destroyViewshedVolume,
rebuildViewshedVolume,
coverageNeighborCount,
runActivationObstructionProbe,
clearProbeClampOnDeactivation,
buildCoverageEntities,
materializeCctvCoverageEntities,
materializeCctvActiveCoverageEntities,
materializeCctvVisibleCoverageEntities,
+182
View File
@@ -0,0 +1,182 @@
// src/layers/cctv/geometry.test.mjs
// The frustum's view axis and the monitor plane's orientation are computed
// with the shared geo helpers; they must give what the renderer's own transforms
// gave, bit for bit, so frustums, probes and planes land where they did.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createGeometry } from './geometry.js';
import { createModel } from './model.js';
function parts() {
const p = {};
const context = {
state: {},
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
p.model = createModel(context);
p.geometry = createGeometry(context);
return p;
}
/** The renderer's own frame, as the layer computed it before. */
function cesiumFrame(camera, atPos) {
const h = Cesium.Math.toRadians(camera.headingDeg);
const p = Cesium.Math.toRadians(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const dirEnu = new Cesium.Cartesian3(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
const dir = Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
);
const up = Cesium.Matrix3.multiplyByVector(
rot,
upEnu,
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.cross(dir, up, new Cesium.Cartesian3());
const normal = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
const orientation = Cesium.Quaternion.fromRotationMatrix(
new Cesium.Matrix3(
right.x,
up.x,
normal.x,
right.y,
up.y,
normal.y,
right.z,
up.z,
normal.z,
),
);
return { dir, up, orientation };
}
const xyz = (v) => [v.x, v.y, v.z];
test('the frustum axis and plane orientation match the renderer transforms exactly', () => {
const { geometry, model } = parts();
let seed = 7;
const random = () => {
seed = (seed * 16807) % 2147483647;
return seed / 2147483647;
};
for (let i = 0; i < 500; i++) {
const camera = {
headingDeg: random() * 360,
pitchDeg: -89 + random() * 120,
};
const atPos = Cesium.Cartesian3.fromDegrees(
-180 + random() * 360,
-89 + random() * 178,
random() * 3000,
);
const expected = cesiumFrame(camera, atPos);
const frame = geometry.frustumFrameEcef(camera, atPos);
assert.deepEqual(xyz(frame.dir), xyz(expected.dir));
assert.deepEqual(xyz(frame.up), xyz(expected.up));
const q = model.planeOrientationFor(camera, atPos);
const e = expected.orientation;
assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]);
}
});
test('the activation probe clamps the range once its ray answers, unless the camera moved on', async () => {
const { createRendering } = await import('./rendering.js');
const p = {};
const state = { _activeCameraId: 'cam', _viewer: {} };
const context = {
state,
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
const written = [];
const footprints = [];
let restyles = 0;
let notices = 0;
let hitAtM = 80;
p.model = createModel(context);
p.geometry = createGeometry(context);
p.rendering = {
...createRendering(context),
canPickFromRay: () => true,
refreshCoverageStyles: () => (restyles += 1),
// The first surface `hitAtM` metres along the axis.
obstructionHit: async (origin, direction) => ({
x: origin.x + direction.x * hitAtM,
y: origin.y + direction.y * hitAtM,
z: origin.z + direction.z * hitAtM,
}),
};
p.calibration = { normalizeCalibration: () => ({ rangeScale: 1 }) };
p.ground = {
groundAltFor: () => 100,
resolveFootprintGround: async (r) =>
footprints.push(p.geometry.footprintPose(r)),
};
p.presentation = { notifyListeners: () => (notices += 1) };
p.drawSets = { writeLines: (lines) => written.push(lines) };
p.projection = { updatePlanePlacement() {} };
const record = {
camera: {
id: 'cam',
lon: -97.74,
lat: 30.27,
headingDeg: 90,
pitchDeg: -10,
fovDeg: 60,
rangeM: 200,
mountHeightM: 8,
},
coverageEntities: [],
};
state._recordById = new Map([['cam', record]]);
p.geometry.applyFrustumGeometry(record, 100);
assert.equal(record.frustumGeometry.rangeM, 200, 'unclamped at first');
const landed = p.geometry.runActivationObstructionProbe(record);
assert.equal(record.probeClampRangeM, null, 'the answer is still to come');
await landed;
const clamp = p.geometry.activationProbeClampRange(200, 80);
assert.ok(Math.abs(record.probeClampRangeM - clamp) < 1e-6);
assert.ok(
Math.abs(record.frustumGeometry.rangeM - clamp) < 1e-6,
'the geometry is rewritten at the clamp, from the ground it had',
);
assert.equal(record.frustumGeometry.mount.alt, 108);
assert.deepEqual(
footprints,
[p.geometry.footprintPose(record)],
"the clamped plane's footprint ground is asked for",
);
assert.ok(
Math.abs(footprints[0].rangeM - clamp) < 1e-6,
'at the clamped pose',
);
assert.deepEqual([restyles, notices], [1, 1]);
// A probe whose camera is deactivated before it answers lands nothing.
hitAtM = 50;
const stale = p.geometry.runActivationObstructionProbe(record);
p.geometry.clearProbeClampOnDeactivation(record, () => {});
await stale;
assert.equal(record.probeClampRangeM, null);
// Nor does one whose record a re-init replaced for the same camera.
const replaced = p.geometry.runActivationObstructionProbe(record);
state._recordById = new Map([['cam', { ...record }]]);
await replaced;
assert.equal(record.probeClampRangeM, null);
});
+8 -12
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { followedOf } from '../../data/followed.js';
import {
GEO_PROGRESS_NOTIFY_INTERVAL_MS,
GEO_PROGRESS_NOTIFY_BATCH_LIMIT,
@@ -125,16 +125,16 @@ export function createGeometryQueue({
* throughput without restarting the queue.
*
* @param {Object} [ownership={}] Current camera-ownership state.
* @param {*} [ownership.trackedEntity] Cesium tracked entity, if any.
* @param {*} [ownership.followed] What the camera follows, if anything.
* @param {boolean} [ownership.cockpitActive] Whether cockpit owns the camera.
* @returns {{ batchSize: number, delayMs: number }} Drain pacing.
*/
function cctvGeometryDrainPacing({
trackedEntity = null,
followed = null,
cockpitActive = false,
} = {}) {
if (trackedEntity || cockpitActive) {
if (followed || cockpitActive) {
return {
batchSize: GEO_TRACKING_BATCH_SIZE,
delayMs: GEO_TRACKING_BATCH_DELAY_MS,
@@ -213,7 +213,7 @@ export function createGeometryQueue({
const batchResult = processCctvGeometryDrainBatch({
queue: layerState._geoQueue,
readOwnership: () => ({
trackedEntity: layerState._viewer.trackedEntity,
followed: followedOf(layerState._viewer),
cockpitActive:
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode'),
@@ -303,13 +303,9 @@ export function createGeometryQueue({
layerState._tilesReadyReenqueued = false;
if (!layerState._records.length) return;
const active = parts.selection.getActiveRecord();
const carto = layerState._viewer?.camera?.positionCartographic;
const refLat = carto
? Cesium.Math.toDegrees(carto.latitude)
: (active?.camera.lat ?? 0);
const refLon = carto
? Cesium.Math.toDegrees(carto.longitude)
: (active?.camera.lon ?? 0);
const pose = parts.model.eyePose();
const refLat = pose ? pose.lat : (active?.camera.lat ?? 0);
const refLon = pose ? pose.lon : (active?.camera.lon ?? 0);
const pending = geometryWorkingSet()
.filter((record) => record !== active)
.map((record) => ({
+14 -10
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
planeSupportPoints,
@@ -13,7 +14,7 @@ export function createGround({ state: layerState, services, parts, source }) {
const { resolveEllipsoidalGround } = services.terrain;
/**
* Task 5 (height-datum fix): maps the scene's `globe.show` flag to the surface
* Task 5 (height-datum fix): maps whether the renderer shows the globe to the surface
* regime key the per-camera ground cache is keyed by (spec §2 "cache by
* surface regime", collapsed to two keys — ion World Terrain and Re:Earth
* globe terrain get the same handling):
@@ -26,7 +27,8 @@ export function createGround({ state: layerState, services, parts, source }) {
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - `viewer.scene.globe.show`.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
*/
@@ -36,15 +38,15 @@ export function createGround({ state: layerState, services, parts, source }) {
/**
* Task 5: the surface regime the scene is CURRENTLY rendering, derived live
* from `globe.show` (mapStackController's `_activatePhotoreal` /
* `_activateGlobeStack` flip exactly this flag). Reading scene state directly
* from whether the renderer shows the globe (mapStackController's
* `_activatePhotoreal` / `_activateGlobeStack` flip exactly this). Reading it live
* — rather than caching the map-stack id — means the regime is correct even
* for stack changes this module never got an event for.
* @returns {'google-3d'|'terrain-globe'}
*/
function currentSurfaceRegime() {
return surfaceRegimeKey(layerState._viewer?.scene?.globe?.show);
return surfaceRegimeKey(findGlobe(layerState._viewer)?.isGlobeVisible?.());
}
/**
@@ -231,14 +233,16 @@ export function createGround({ state: layerState, services, parts, source }) {
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
Cesium.Cartesian3.fromDegrees(
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
undefined,
record.position,
);
if (record.billboard) record.billboard.position = record.position;
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
+2 -8
View File
@@ -10,7 +10,7 @@ export function createHover({ state: layerState, services, parts, source }) {
* Throttled MOUSE_MOVE hover pass (owner round 2, item B): pointing at a
* camera icon that has no card summons its card immediately. This is
* EVENT-DRIVEN picking on a user gesture, not steady-state work — the
* ≥120 ms throttle caps it at ~8 scene.pick calls/s while the pointer is
* ≥120 ms throttle caps it at ~8 scene picks/s while the pointer is
* actually moving (a still pointer costs nothing), so it can never approach
* per-frame cost. Skipped while the camera is in motion, while ADJUST mode
* owns the pointer (gizmo drags), and while the layer is disabled.
@@ -29,13 +29,7 @@ export function createHover({ state: layerState, services, parts, source }) {
const now = Date.now();
if (now - layerState._hoverLastPickAt < HOVER_PICK_THROTTLE_MS) return;
layerState._hoverLastPickAt = now;
let picked = null;
try {
picked = layerState._viewer.scene.pick(position);
} catch {
picked = null;
}
const cameraId = parts.selection.extractPickedCameraId(picked);
const cameraId = parts.rendering.pickCameraIdAt(position);
if (cameraId && cameraId === layerState._hoverCardId) {
// Still on the hovered camera — keep the card alive.
cancelHoverRelease();
+5
View File
@@ -18,6 +18,7 @@ import { createHealth } from './health.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
import { createDrawSets } from './drawSets.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createCctvLayer({ services, source }) {
@@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) {
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.drawSets = createDrawSets(context);
parts.calibration = createCalibration(context);
parts.testing = createTesting(context);
parts.projection = createProjection(context);
@@ -73,6 +75,7 @@ export function createCctvLayer({ services, source }) {
deriveCalBadge: parts.calibration.deriveCalBadge,
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
activationProbeClampRange: parts.geometry.activationProbeClampRange,
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
_createCctvProjectionPlaneForTest:
parts.testing._createCctvProjectionPlaneForTest,
@@ -110,6 +113,8 @@ export function createCctvLayer({ services, source }) {
_extractPickedCameraIdForTest:
parts.testing._extractPickedCameraIdForTest,
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
_cctvIconsForTest: parts.testing._cctvIconsForTest,
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
focusCctvRecord: parts.navigation.focusCctvRecord,
maybeAutoHop: parts.navigation.maybeAutoHop,
openingCameraId: parts.navigation.openingCameraId,
+2 -2
View File
@@ -29,8 +29,8 @@ export function createIngestion({
layerState._tilesReadyReenqueued = true;
// Per-regime resolution (Task 5): only records unresolved for the
// CURRENT surface regime need the completion pass. On globe stacks
// projectionTilesReady() is false while a (hidden) Google tileset
// exists, so this latch effectively fires for the google-3d regime —
// projectionTilesReady() is false (only drawn photoreal tiles can be
// ready), so this latch fires for the google-3d regime alone —
// terrain-globe records resolve from the prior in their drain pass.
const unresolved = parts.geometryQueue
.geometryWorkingSet()
+113 -153
View File
@@ -1,11 +1,12 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } 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';
import { inputFor } from '../../input/dispatcher.js';
import {
GROUND_PRIOR_INIT_WAIT_MS,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
CALIBRATION_RANGE_FLOOR_M,
VIEW_MOTION_REFRESH_MS,
VIEW_MOTION_MIN_MOVE_FRACTION,
@@ -21,7 +22,6 @@ export function createLifecycle({
parts,
source,
}) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
services.picking;
@@ -46,12 +46,11 @@ export function createLifecycle({
/** Records the camera pose the last view pass ran at. */
function noteViewPose() {
const camera = layerState._viewer?.camera;
if (!camera?.positionWC) return;
const pose = findCamera(layerState._viewer)?.pose();
if (!pose) return;
layerState._viewPose = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction:
camera.directionWC && Cesium.Cartesian3.clone(camera.directionWC),
position: pose.position,
direction: pose.direction,
};
}
@@ -61,16 +60,14 @@ export function createLifecycle({
* would otherwise rerun the full pass on every tick.
*/
function viewPoseChanged() {
const camera = layerState._viewer?.camera;
const now = findCamera(layerState._viewer)?.pose();
const pose = layerState._viewPose;
if (!pose || !camera?.positionWC) return true;
const height = Math.max(1, camera.positionCartographic?.height ?? 0);
const moved = Cesium.Cartesian3.distance(camera.positionWC, pose.position);
if (!pose || !now) return true;
// An eye with no geographic position (the earth's centre) has no height.
const height = Math.max(1, Number.isFinite(now.height) ? now.height : 0);
const moved = distance(now.position, pose.position);
if (moved > height * VIEW_MOTION_MIN_MOVE_FRACTION) return true;
if (!pose.direction || !camera.directionWC) return false;
return (
Cesium.Cartesian3.dot(camera.directionWC, pose.direction) < MIN_TURN_COS
);
return dot(now.direction, pose.direction) < MIN_TURN_COS;
}
function viewMotionTick() {
@@ -99,6 +96,59 @@ export function createLifecycle({
layerState._viewMotionTimer = 0;
}
/**
* Listen for the camera's moves on the viewer's camera port: hover picking
* pauses while it moves, and the view pass reruns on an interval until the
* move ends, then once more. A re-init against a new viewer moves the
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
layerState._viewListenerCamera !== viewCamera
) {
layerState._horizonCullListener?.();
layerState._moveStartListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener = null;
layerState._cameraMoving = false;
}
layerState._viewListenerCamera = viewCamera;
if (!layerState._horizonCullListener && viewCamera) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = viewCamera.on('moveEnd', () => {
layerState._cameraMoving = false;
stopViewMotionTimer();
parts.navigation.reopenNearestCamera();
settleView();
});
}
if (!layerState._moveStartListener && viewCamera) {
// Item B: hover picking pauses while the camera is in motion. A long
// move (cockpit flight, a drag) never settles, so the view pass also
// reruns on an interval until it does.
layerState._moveStartListener = viewCamera.on('moveStart', () => {
layerState._cameraMoving = true;
// enable() starts it for a move already under way.
if (layerState._enabled) startViewMotionTimer();
});
}
}
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
layerState._moveStartListener = null;
layerState._cameraMoving = false;
layerState._viewListenerCamera = null;
stopViewMotionTimer();
}
/** Resets all module-scoped runtime state to initial values. */
function clearRuntimeState() {
@@ -107,6 +157,9 @@ export function createLifecycle({
// Idempotent — also covers a re-init without a prior destroy().
parts.cards.teardownAmbientCards();
parts.projection.clearProjectionOverlay();
// An activation probe still to answer lands on none of these records.
for (const record of layerState._records || [])
if (record) record.probeToken = (record.probeToken || 0) + 1;
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
@@ -123,9 +176,6 @@ export function createLifecycle({
layerState._lastError = null;
layerState._lastFocusStyleAt = 0;
layerState._activeFocusStyleCount = 0;
// FIX ①/③: the discovered tileset handle is scene-scoped — drop it so a fresh
// init re-discovers against the current scene primitives.
layerState._activeTileset = null;
// Task 5: the applied-regime tracker is record-set-scoped — a fresh init
// recomputes it against the then-current scene.
layerState._lastAppliedRegime = null;
@@ -133,9 +183,9 @@ export function createLifecycle({
const methods = {
/**
* Initializes the CCTV layer: loads camera sources, builds the catalog,
* restores calibration from localStorage, creates billboards, sets up click
* restores calibration from localStorage, creates camera icons, sets up click
* handling, and performs initial health sync. Coverage entities stay lazy.
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
* @param {object} viewer - The viewer.
*/
async init(viewer) {
layerState._sourceAbort?.abort();
@@ -156,16 +206,7 @@ export function createLifecycle({
layerState._lastViewContext = '';
layerState._calibrationById = parts.calibration.loadCalibrationStore();
layerState._billboards = new Cesium.BillboardCollection();
// Cesium switches a property's buffer-usage hint whenever it starts or
// stops changing from one frame to the next, and every switch rewrites
// the vertex data of every billboard. The view pass toggles `show` on a
// few icons of a large catalog at a time, so on a 33K catalog each pass
// cost two full rewrites. With the hint fixed, Cesium uploads only the
// icons that changed.
layerState._billboards.computeNewBuffersUsage = () => false;
layerState._viewer.scene.primitives.add(layerState._billboards);
registerSpriteCollection('cctv', layerState._billboards);
parts.rendering.createCameraIcons(layerState._viewer);
const sources = await parts.catalog.loadCameraSources();
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
@@ -233,32 +274,14 @@ export function createLifecycle({
? groundPrior.ellipsoid
: Number(camera.groundElevationM) || 0;
camera.absoluteHeightM = priorGround + camera.mountHeightM;
const position = Cesium.Cartesian3.fromDegrees(
const position = fromDegrees(
camera.lon,
camera.lat,
camera.absoluteHeightM,
);
const billboard = layerState._billboards.add({
id: camera.id,
image: CAMERA_ICON,
position,
color: IDLE_CAMERA_COLOR,
width: 24,
height: 24,
// Field-test fix (2026-07-06): always-on-top. The old finite value
// (1800 m) re-engaged the depth test at far zoom, where the COARSE
// far-LOD Google-3D mesh sits above the true ground and swallowed
// ground-anchored icons ("submerged" pills over SF). Far-side-of-globe
// icons are handled by refreshHorizonCulling() (the flights-layer
// EllipsoidalOccluder pattern), not by the depth test.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(350, 1.25, 4_000_000, 0.42),
});
const record = {
camera,
position,
billboard,
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
@@ -292,11 +315,12 @@ export function createLifecycle({
viewshedColors: viewshedColors(
cameraHue(hueIndexById.get(camera.id) ?? 0),
),
viewshedPrimitive: null,
viewshedVolume: null,
viewshedActiveTint: false,
};
layerState._records.push(record);
layerState._recordById.set(camera.id, record);
parts.rendering.addCameraIcon(record);
}
layerState._count = layerState._records.length;
@@ -331,57 +355,12 @@ export function createLifecycle({
}
// Field-test fix (2026-07-06): horizon-cull on camera settle (pairs with
// the billboards' always-on-top depth setting) + one initial pass so the
// the icons' always-on-top drawing) + one initial pass so the
// first paint is already culled.
// A re-init against a new viewer moves the move listeners to its camera.
if (
layerState._viewListenerCamera &&
layerState._viewListenerCamera !== layerState._viewer.camera
) {
const previous = layerState._viewListenerCamera;
if (layerState._horizonCullListener)
previous.moveEnd?.removeEventListener(
layerState._horizonCullListener,
);
if (layerState._moveStartListener)
previous.moveStart?.removeEventListener(
layerState._moveStartListener,
);
layerState._horizonCullListener = null;
layerState._moveStartListener = null;
layerState._cameraMoving = false;
}
layerState._viewListenerCamera = layerState._viewer.camera;
if (!layerState._horizonCullListener) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = () => {
layerState._cameraMoving = false;
stopViewMotionTimer();
parts.navigation.reopenNearestCamera();
settleView();
};
layerState._viewer.camera.moveEnd.addEventListener(
layerState._horizonCullListener,
);
}
if (!layerState._moveStartListener) {
// Item B: hover picking pauses while the camera is in motion. A long
// move (cockpit flight, a drag) never settles, so the view pass also
// reruns on an interval until it does.
layerState._moveStartListener = () => {
layerState._cameraMoving = true;
// enable() starts it for a move already under way.
if (layerState._enabled) startViewMotionTimer();
};
layerState._viewer.camera.moveStart.addEventListener(
layerState._moveStartListener,
);
}
attachViewListeners();
// A resize or rotation changes what is on screen without moving the
// camera.
const canvas = layerState._viewer.scene?.canvas;
const canvas = canvasOf(layerState._viewer);
if (layerState._viewResizeCanvas !== canvas) {
// A re-init against a new viewer observes its canvas instead.
layerState._viewResizeObserver?.disconnect();
@@ -406,15 +385,15 @@ export function createLifecycle({
}
parts.rendering.refreshHorizonCulling();
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
layerState._viewer.scene.canvas,
);
parts.selection.bindCctvWorldClickGesture(
layerState._clickHandler,
(click) => {
const input = inputFor(layerState._viewer);
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
if (!layerState._enabled) return;
const picked = layerState._viewer.scene.pick(click.position);
const cameraId = parts.selection.extractPickedCameraId(picked);
const picked = event.topHit;
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
if (cameraId) {
activateCctvCameraFromWorldClick(
cameraId,
@@ -431,11 +410,11 @@ export function createLifecycle({
// Item A (owner round 2): the scene pick found no camera — try the
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Cesium click positions
// its camera exactly like a click on the icon. Click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
click.position.x,
click.position.y,
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
@@ -454,14 +433,15 @@ export function createLifecycle({
parts.selection.deactivateActiveCamera();
}
},
{
// Item B: hover summons a card on a cardless camera icon. The gesture
// classifier owns MOUSE_MOVE too, so chain hover work through its seam
// instead of replacing the travel accumulator's handler.
onMouseMove: (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
},
);
// Item B: hover summons a card on a cardless camera icon.
const unsubscribeHover = input.onPointer('move', (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
);
layerState._clickSubscription = () => {
unsubscribeClick();
unsubscribeHover();
};
await parts.health.syncHealthState(true);
// Health ranks crowded cells: thin again now that it has arrived (a
@@ -472,7 +452,6 @@ export function createLifecycle({
}
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
console.log('[Data:CCTV] Initialized with', layerState._count, 'cameras');
},
@@ -491,7 +470,7 @@ export function createLifecycle({
)
services.credits?.showOsmCredit?.(layerState._viewer, 'cctv');
layerState._lastUpdate = Date.now();
// Pick-ownership (H2): camera billboards use the camera id directly;
// Pick-ownership (H2): camera icons use the camera id directly;
// coverage polyline entities use `cctv-<cameraId>-<role>` entity ids.
registerPickOwner('cctv', (pickedId) => {
if (layerState._recordById.has(pickedId)) return true;
@@ -535,7 +514,6 @@ export function createLifecycle({
parts.cards.startCardFrameLoop();
parts.cards.refreshAmbientCards();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
},
/** Disables the layer: hides entities, stops the projection loop and load queue. */
@@ -564,10 +542,10 @@ export function createLifecycle({
/**
* Tears down the layer: destroys click handler, projection loop, coverage
* entities, billboards, and clears all runtime state and subscribers.
* @param {Cesium.Viewer} [viewer] - Viewer instance (falls back to stored ref).
* entities, icons, and clears all runtime state and subscribers. It
* releases what init attached, whichever viewer it is handed.
*/
destroy(viewer) {
destroy() {
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._sourceAbort?.abort();
if (typeof document !== 'undefined')
@@ -583,23 +561,7 @@ export function createLifecycle({
);
layerState._mapStackListener = null;
}
const teardownViewer = viewer || layerState._viewer;
if (layerState._horizonCullListener && teardownViewer?.camera?.moveEnd) {
teardownViewer.camera.moveEnd.removeEventListener(
layerState._horizonCullListener,
);
layerState._horizonCullListener = null;
}
if (layerState._moveStartListener && teardownViewer?.camera?.moveStart) {
teardownViewer.camera.moveStart.removeEventListener(
layerState._moveStartListener,
);
layerState._moveStartListener = null;
}
// The move listeners are gone; nothing will report the end of a move.
layerState._cameraMoving = false;
layerState._viewListenerCamera = null;
stopViewMotionTimer();
detachViewListeners();
layerState._viewResizeObserver?.disconnect();
layerState._viewResizeObserver = null;
layerState._viewResizeCanvas = null;
@@ -609,21 +571,14 @@ export function createLifecycle({
}
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
if (teardownViewer?.scene?.screenSpaceCameraController) {
teardownViewer.scene.screenSpaceCameraController.enableInputs = true;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
parts.projection.stopProjectionLoop();
parts.geometryQueue.stopGeometryLoadQueue();
parts.cards.teardownAmbientCards();
parts.geometry.destroyCoverageEntities();
if (layerState._billboards && teardownViewer) {
teardownViewer.scene.primitives.remove(layerState._billboards);
layerState._billboards = null;
}
parts.rendering.destroyCameraIcons();
parts.drawSets.dispose();
clearRuntimeState();
layerState._viewer = null;
layerState._enabled = false;
@@ -636,5 +591,10 @@ export function createLifecycle({
},
};
return { clearRuntimeState, methods };
return {
clearRuntimeState,
attachViewListeners,
detachViewListeners,
methods,
};
}
+74
View File
@@ -0,0 +1,74 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
function viewerWithCamera() {
const camera = fakeCameraPort();
const viewer = {};
bindRenderer(viewer, { camera: camera.port });
return { viewer, camera };
}
function lifecycleFor(state) {
const passes = [];
const lifecycle = createLifecycle({
state,
services: {
sprites: {},
activation: {},
picking: {},
focus: {},
render: {},
},
parts: {
rendering: {
refreshHorizonCulling: () => {
passes.push('view');
return false;
},
},
geometryQueue: { enqueueViewGeometry() {} },
cards: { refreshAmbientCards() {} },
presentation: { notifyListeners() {} },
navigation: { reopenNearestCamera() {} },
},
});
return { lifecycle, passes };
}
test('the view listeners follow the camera port and let go on teardown', () => {
const first = viewerWithCamera();
const state = { _viewer: first.viewer, _enabled: false };
const { lifecycle, passes } = lifecycleFor(state);
const counts = (camera) => [
camera.listenerCount('moveStart'),
camera.listenerCount('moveEnd'),
];
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
first.camera.emit('moveStart');
assert.equal(state._cameraMoving, true, 'hover pauses while moving');
first.camera.emit('moveEnd');
assert.equal(state._cameraMoving, false);
assert.deepEqual(passes, ['view'], 'a settled move reruns the view pass');
// A re-init on the same viewer keeps its listeners.
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
// One on a new viewer moves them to its camera.
const second = viewerWithCamera();
state._viewer = second.viewer;
first.camera.emit('moveStart');
lifecycle.attachViewListeners();
assert.equal(state._cameraMoving, false, 'the old move is forgotten');
assert.deepEqual(counts(first.camera), [0, 0]);
assert.deepEqual(counts(second.camera), [1, 1]);
lifecycle.detachViewListeners();
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
+33 -63
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { cross, negate, toDegrees, toRadians } from '../../geo/vector.js';
import { fromAxes } from '../../geo/quaternion.js';
import { findCamera } from '../../render/rendererOf.js';
import { greatCircleKm } from '../../geoDistance.js';
import { staticFrameRefreshMs } from '../../data/cctvLod.js';
import { frameFetchDue, cardFetchPolicy } from '../../data/cctvCards.js';
@@ -14,7 +16,7 @@ export function createModel({ state: layerState, services, parts, source }) {
*/
function toRad(deg) {
return Cesium.Math.toRadians(deg);
return toRadians(deg);
}
/**
@@ -308,8 +310,8 @@ export function createModel({ state: layerState, services, parts, source }) {
const lon2 = lon1 + Math.atan2(y, x);
return {
lat: Cesium.Math.toDegrees(lat2),
lon: Cesium.Math.toDegrees(lon2),
lat: toDegrees(lat2),
lon: toDegrees(lon2),
};
}
@@ -345,12 +347,22 @@ export function createModel({ state: layerState, services, parts, source }) {
* @returns {string} Grid key in the form "zoomBucket:latGrid:lonGrid".
*/
/**
* The eye's pose from the camera port, or null when there is no camera or
* the eye has no geographic position (the earth's centre).
* @returns {object|null}
*/
function eyePose() {
const pose = findCamera(layerState._viewer)?.pose();
return Number.isFinite(pose?.lat) ? pose : null;
}
function currentViewContext() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto) return 'none';
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const alt = carto.height || 0;
const pose = eyePose();
if (!pose) return 'none';
const { lat, lon } = pose;
const alt = pose.height || 0;
const zoomBucket =
alt < 1500
? 'street'
@@ -371,43 +383,13 @@ export function createModel({ state: layerState, services, parts, source }) {
}
/**
* Reports whether the active Google Photorealistic 3D Tileset (if any) has
* finished loading the tiles in view. Shared mesh-floor sampling is gated on
* this so a one-shot cell never bakes in a miss from still-streaming tiles.
* Discovers + caches the tileset lazily from scene
* primitives (the CCTV module holds only a `_viewer` reference). When no
* tileset is present (OSM fallback) this returns true so ground sampling is
* not permanently blocked.
*
* Task 5 (review correction, spec §2): a HIDDEN tileset (`show === false`,
* i.e. a globe stack is active) must NOT report ready — Cesium 1.138's
* the shared sampler can only inspect *visible* 3D tilesets, so a sample taken
* against the hidden Google tileset would silently miss.
*
* @returns {boolean} True when tiles are loaded AND visible (or no tileset
* exists to wait on).
* Whether the photoreal tiles in view have finished loading; the rendering
* part, which reads the scene, answers.
* @returns {boolean}
*/
function projectionTilesReady() {
if (
!layerState._activeTileset ||
layerState._activeTileset.isDestroyed?.()
) {
layerState._activeTileset = null;
const primitives = layerState._viewer?.scene?.primitives;
if (primitives && typeof primitives.get === 'function') {
for (let i = 0; i < primitives.length; i++) {
const p = primitives.get(i);
if (p instanceof Cesium.Cesium3DTileset && !p.isDestroyed?.()) {
layerState._activeTileset = p;
break;
}
}
}
}
if (!layerState._activeTileset) return true;
if (layerState._activeTileset.show === false) return false;
return layerState._activeTileset.tilesLoaded === true;
return parts.rendering.projectionTilesReady();
}
/**
@@ -418,30 +400,17 @@ export function createModel({ state: layerState, services, parts, source }) {
* frame-up, so the 16:9 texture maps upright and unmirrored. Static geometry —
* computed only on slider/save/activation, never per frame (§2b).
* @param {Object} camera - Camera pose.
* @param {Cesium.Cartesian3} capCenterPos - Plane center in ECEF.
* @returns {Cesium.Quaternion}
* @param {{x: number, y: number, z: number}} capCenterPos - Plane center in ECEF.
* @returns {{x: number, y: number, z: number, w: number}} The quaternion.
*/
function planeOrientationFor(camera, capCenterPos) {
const frame = parts.geometry.frustumFrameEcef(camera, capCenterPos);
const right = Cesium.Cartesian3.cross(
frame.dir,
frame.up,
new Cesium.Cartesian3(),
);
const normal = Cesium.Cartesian3.negate(frame.dir, new Cesium.Cartesian3());
const m = new Cesium.Matrix3(
right.x,
frame.up.x,
normal.x,
right.y,
frame.up.y,
normal.y,
right.z,
frame.up.z,
normal.z,
);
return Cesium.Quaternion.fromRotationMatrix(m);
return fromAxes({
x: cross(frame.dir, frame.up),
y: frame.up,
z: negate(frame.dir),
});
}
/**
@@ -564,6 +533,7 @@ export function createModel({ state: layerState, services, parts, source }) {
return cameraId !== activeCameraId || record?.activationDone !== true;
}
return {
eyePose,
toRad,
normalizeHeading,
clamp,
+17 -22
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -43,16 +44,13 @@ export function createNavigation({
}
/**
* Finds the camera closest to the Cesium viewer's current position.
* Finds the camera closest to the viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
*/
function nearestCameraIdToViewer() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto) return null;
return nearestCameraIdToPoint(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
);
const pose = parts.model.eyePose();
if (!pose) return null;
return nearestCameraIdToPoint(pose.lat, pose.lon);
}
/**
@@ -86,9 +84,9 @@ export function createNavigation({
}
/**
* Flies the Cesium viewer camera to frame the specified CCTV camera,
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
* @param {Cesium.Viewer|null} viewer Cesium viewer that owns the camera.
* @param {object|null} viewer The viewer that owns the camera.
* @param {Object|null} record CCTV camera runtime record.
* @param {number} [duration=2.2] - Flight duration in seconds.
* @returns {'focused'|'no-active-camera'|'tracking-holds-view'|'cockpit-active'} Focus result.
@@ -103,7 +101,7 @@ export function createNavigation({
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (viewer.trackedEntity) {
if (isFollowing(viewer)) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -111,19 +109,16 @@ export function createNavigation({
}
const { camera } = record;
const range = Math.max(280, camera.rangeM * 1.18);
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
record.position,
Math.max(40, camera.rangeM * 0.36),
),
cameraOf(viewer).flyToBounds(
{ center: record.position, radius: Math.max(40, camera.rangeM * 0.36) },
{
offset: new Cesium.HeadingPitchRange(
parts.model.toRad(camera.headingDeg),
parts.model.toRad(-22),
offset: {
heading: parts.model.toRad(camera.headingDeg),
pitch: parts.model.toRad(-22),
range,
),
duration: Math.max(0.2, duration || 0),
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
},
durationS: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
);
return CCTV_FOCUS_RESULT.FOCUSED;
+6 -14
View File
@@ -8,19 +8,11 @@ function fixture() {
{ camera: { id: 'west', lat: 40, lon: -120 } },
{ camera: { id: 'east', lat: 40, lon: -100 } },
];
const state = {
_records: records,
_viewer: {
camera: {
positionCartographic: {
latitude: (40 * Math.PI) / 180,
longitude: (-101 * Math.PI) / 180,
},
},
},
};
const state = { _records: records };
const eye = { pose: { lat: 40, lon: -101 } };
const parts = {
model: {
eyePose: () => eye.pose,
haversineKm(lat1, lon1, lat2, lon2) {
return Math.hypot(lat1 - lat2, lon1 - lon2);
},
@@ -40,7 +32,7 @@ function fixture() {
parts,
source: {},
});
return { state, navigation, selected };
return { state, eye, navigation, selected };
}
test('nearest camera can be resolved from an explicit WGS84 target', () => {
@@ -69,9 +61,9 @@ test('invalid target coordinates fail closed', () => {
});
test('opening camera keeps viewer-nearest and first-record fallback', () => {
const { state, navigation } = fixture();
const { state, eye, navigation } = fixture();
assert.equal(navigation.openingCameraId(), 'east');
state._viewer = null;
eye.pose = null;
assert.equal(navigation.openingCameraId(), 'west');
state._records = [];
assert.equal(navigation.openingCameraId(), null);
+19 -26
View File
@@ -1,7 +1,7 @@
export { ACTIVE_FRAME_REFRESH_MS } from './sourcePolicy.js';
import * as Cesium from 'cesium';
import { CCTV_CARD_FETCH_BURST_SPACING_MS } from '../../data/cctvCards.js';
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { hexColor } from '../../render/color.js';
// ---------------------------------------------------------------------------
// API endpoints
@@ -179,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
heightM: 0,
});
/** Base64-encoded SVG camera icon for billboard rendering. */
/**
* 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.
*/
export const CAMERA_ICON = (() => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
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="#c9f6ff"/>
@@ -434,44 +438,33 @@ export const CAMERA_SEEDS = [
];
// ---------------------------------------------------------------------------
// Visual style constants
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.88);
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
export const ACTIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#ffd97a').withAlpha(0.95);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
export const LIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#b48cff').withAlpha(0.88);
export const LIVE_CAMERA_COLOR = hexColor('#b48cff', 0.88);
export const IDLE_COVERAGE_COLOR =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.24);
export const IDLE_COVERAGE_COLOR = hexColor('#2fe0ff', 0.24);
export const IDLE_COVERAGE_CENTER_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.2);
export const IDLE_COVERAGE_CENTER_MUTED = hexColor('#2fe0ff', 0.2);
export const IDLE_COVERAGE_EDGE_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.18);
export const IDLE_COVERAGE_EDGE_MUTED = hexColor('#2fe0ff', 0.18);
export const ACTIVE_COVERAGE_EDGE =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.58);
export const ACTIVE_COVERAGE_EDGE = hexColor('#8dff87', 0.58);
export const ACTIVE_COVERAGE_CENTER =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.82);
export const ACTIVE_COVERAGE_CENTER = hexColor('#d7ff8d', 0.82);
// H6: dimmer depth-fail materials let the active frustum wireframe read
// through buildings while in monitor fallback mode.
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.18);
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = hexColor('#8dff87', 0.18);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.26);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = hexColor('#d7ff8d', 0.26);
export const PLANE_OUTLINE_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.55);
export const PLANE_OUTLINE_COLOR = hexColor('#6be8ff', 0.55);
/**
* Card budget while the staggered geometry drain is running — the raised
+90 -63
View File
@@ -1,5 +1,4 @@
import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
@@ -8,6 +7,25 @@ import {
PROJECTION_CANVAS_HEIGHT,
} from './policy.js';
/** The monitor plane's alpha over its frame, as its image material had it. */
const PLANE_ALPHA = 0.95;
/** A plain white image, for a plane with no media (tests). */
const WHITE_IMAGE =
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">' +
'<rect width="1" height="1" fill="#fff"/></svg>',
);
/** Copy a position's coordinates into `out`. */
function copyPosition(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
export function createProjection({
state: layerState,
services,
@@ -18,7 +36,7 @@ export function createProjection({
/**
* Build the protected label associated with one active monitor plane.
* @param {{cameraId: string, name: string, position: Cesium.Cartesian3|Function}} input
* @param {{cameraId: string, name: string, position: object|Function}} input
* @returns {Object} Shared-host presentation entry.
*/
@@ -46,7 +64,7 @@ export function createProjection({
}
/**
* Re-derives the monitor plane entity's placement (position, orientation,
* Re-derives the monitor plane's placement (position, orientation,
* dimensions) + label from the record's current frustum geometry, so the plane
* always caps the wireframe exactly (corner rays terminate on its corners).
* No-op when the record has no plane runtime (idle neighbors have no plane).
@@ -55,7 +73,8 @@ export function createProjection({
function updatePlanePlacement(record) {
const runtime = record?.projection;
if (!runtime?.planeEntity) return;
const plane = runtime?.plane;
if (!plane) return;
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -64,21 +83,33 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeEntity.position = positions.capCenter;
runtime.planeEntity.orientation = parts.model.planeOrientationFor(
record.camera,
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
placePlane(plane, record.camera, geometry, positions);
if (runtime.labelPosition)
copyPosition(positions.label, runtime.labelPosition);
parts.drawSets.writePlane(plane);
}
/** Pose a plane handle on the frustum's far cap. */
function placePlane(plane, camera, geometry, positions) {
plane.center = positions.capCenter;
plane.orientation = parts.model.planeOrientationFor(
camera,
positions.capCenter,
);
if (runtime.planeEntity.plane) {
runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
);
}
if (runtime.labelPosition) {
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
}
plane.size = [geometry.halfW * 2, geometry.halfH * 2];
}
/**
* Give the monitor plane another image: a canvas, or the video element.
* @param {Object} runtime - Projection runtime.
* @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source
*/
function setPlaneSource(runtime, source) {
runtime.planeSource = source;
if (!runtime.plane) return;
runtime.plane.source = source;
parts.drawSets.writePlane(runtime.plane);
}
/**
@@ -102,7 +133,10 @@ export function createProjection({
function setPlaneVisible(runtime, visible) {
if (!runtime) return;
if (runtime.planeEntity) runtime.planeEntity.show = !!visible;
if (runtime.plane && runtime.plane.show !== !!visible) {
runtime.plane.show = !!visible;
parts.drawSets.writePlane(runtime.plane);
}
if (visible && runtime.overlayEntry && runtime.cameraId) {
if (layerState._projectionOverlayOwnerId !== runtime.cameraId) {
layerState._cctvOverlayHost.setEntries(
@@ -121,38 +155,34 @@ export function createProjection({
}
}
/** Create the native monitor plane plus its cached host-label presentation. */
/** A plain white plane image, for a plane with no media (tests). */
function plainPlaneSource() {
return { image: WHITE_IMAGE };
}
/** Create the monitor plane plus its cached host-label presentation. */
function createProjectionPlane(record, runtime, geometry, positions) {
runtime.labelPosition ||= new Cesium.Cartesian3();
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
runtime.labelPosition ||= { x: 0, y: 0, z: 0 };
copyPosition(positions.label, runtime.labelPosition);
runtime.cameraId = String(record.camera.id);
runtime.overlayEntry = createCctvProjectionOverlayEntry({
cameraId: runtime.cameraId,
name: record.camera.name,
position: () => runtime.labelPosition,
});
runtime.planeEntity = layerState._viewer.entities.add({
const plane = {
id: `cctv-${record.camera.id}-plane`,
properties: { cctvCameraId: record.camera.id },
cameraId: record.camera.id,
source: runtime.planeSource || plainPlaneSource(),
alpha: PLANE_ALPHA,
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
show: false,
position: positions.capCenter,
orientation: parts.model.planeOrientationFor(
record.camera,
positions.capCenter,
),
plane: {
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
dimensions: new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
),
material: runtime.planeMaterial,
outline: true,
outlineColor: PLANE_OUTLINE_COLOR,
},
});
return runtime.planeEntity;
};
placePlane(plane, record.camera, geometry, positions);
runtime.plane = plane;
parts.drawSets.writePlane(plane);
return plane;
}
/**
@@ -187,11 +217,11 @@ export function createProjection({
ctx,
image: null,
video: null,
planeEntity: null,
plane: null,
cameraId: String(record.camera.id),
labelPosition: new Cesium.Cartesian3(),
labelPosition: { x: 0, y: 0, z: 0 },
overlayEntry: null,
planeMaterial: null,
planeSource: { canvas },
buffers: null,
bufferIndex: 0,
lastTextureSwapAt: 0,
@@ -222,16 +252,17 @@ export function createProjection({
video.playsInline = true;
video.crossOrigin = 'anonymous';
video.preload = 'auto';
// Cesium sizes the video texture from the element's width/height
// attributes at first upload. Set them from the real stream dimensions
// and rebind on any resolution change (camera switch, adaptive source).
// The plane shows the video once it knows its size (the element's
// width/height follow the real stream dimensions); the renderer reads
// it at a new size on any later resolution change (camera switch,
// adaptive source).
const bindVideoTexture = () => {
if (runtime.video !== video || !runtime.planeMaterial) return;
if (runtime.video !== video || runtime.disposed) return;
if (!(video.videoWidth > 0 && video.videoHeight > 0)) return;
video.width = video.videoWidth;
video.height = video.videoHeight;
runtime.planeMaterial.image = runtime.canvas;
runtime.planeMaterial.image = video;
if (runtime.planeSource?.video !== video)
setPlaneSource(runtime, { video });
};
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
@@ -256,7 +287,7 @@ export function createProjection({
runtime.imageLoading = false;
runtime.imageReady = false;
};
runtime.planeMaterial.image = runtime.canvas;
setPlaneSource(runtime, { canvas: runtime.canvas });
parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners();
},
@@ -279,9 +310,8 @@ export function createProjection({
}
// Monitor plane = the frustum's far cap: video feeds bind the video element
// directly (Cesium updates video-backed entity materials per frame); image
// feeds start on the placeholder canvas and switch to double-buffer swaps
// at <=1Hz.
// directly (the renderer reads it every frame); image feeds start on the
// placeholder canvas and switch to double-buffer swaps at <=1Hz.
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -290,12 +320,7 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
image: canvas,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
createProjectionPlane(record, runtime, geometry, positions);
return runtime;
@@ -340,15 +365,15 @@ export function createProjection({
runtime.video.removeAttribute('src');
runtime.video.load();
}
if (runtime.planeEntity && layerState._viewer) {
layerState._viewer.entities.remove(runtime.planeEntity);
runtime.planeEntity = null;
if (runtime.plane) {
parts.drawSets.removePlane(runtime.plane);
runtime.plane = null;
}
if (layerState._projectionOverlayOwnerId === runtime.cameraId)
clearProjectionOverlay();
runtime.overlayEntry = null;
runtime.labelPosition = null;
runtime.planeMaterial = null;
runtime.planeSource = null;
}
function startProjectionLoop() {
@@ -430,6 +455,8 @@ export function createProjection({
updatePlanePlacement,
clearProjectionOverlay,
setPlaneVisible,
setPlaneSource,
plainPlaneSource,
createProjectionPlane,
createProjectionRuntime,
ensureProjectionRuntime,
+592 -139
View File
@@ -1,7 +1,7 @@
import * as Cesium from 'cesium';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
ACTIVE_COVERAGE_CENTER,
@@ -10,10 +10,88 @@ import {
ACTIVE_COVERAGE_EDGE,
IDLE_COVERAGE_EDGE_MUTED,
ACTIVE_COVERAGE_EDGE_DEPTHFAIL,
IDLE_COVERAGE_COLOR,
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
import {
canvasOf,
drawOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, 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';
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** Icon sets made so far, by every layer: set ids unique to each. */
let iconSets = 0;
/** A point's coordinates, as an item keeps them. */
const copyPoint = (p) => ({ x: p.x, y: p.y, z: p.z });
/** Whether two points are the same, coordinate for coordinate. */
const samePoint = (a, b) =>
!!a && !!b && a.x === b.x && a.y === b.y && a.z === b.z;
/** 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,
far: 4_000_000,
farValue: 0.42,
});
/**
* The translucent frustum volume of one camera, as a mesh item: the same 5
* points the wireframe draws (frustumVolumeGeometryData), in the
* east-north-up frame at the mount. Unlit flat colour, both faces visible
* (the viewer is routinely inside or behind a cone); its set is never
* pickable (clicks fall through to the icon/wireframe/plane, whose pick
* semantics are established).
* @param {string} id - Item id.
* @param {Object} positions - frustumCartesians shape.
* @param {number[]} color - Per-camera fill colour (already alpha'd).
*/
function frustumVolumeItem(id, positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const origin = positions.mount;
const frame = eastNorthUp(origin);
const local = new Float32Array(flat.length);
for (let i = 0; i < flat.length; i += 3) {
const dx = flat[i] - origin.x;
const dy = flat[i + 1] - origin.y;
const dz = flat[i + 2] - origin.z;
local[i] = dx * frame.x.x + dy * frame.x.y + dz * frame.x.z;
local[i + 1] = dx * frame.y.x + dy * frame.y.y + dz * frame.y.z;
local[i + 2] = dx * frame.z.x + dy * frame.z.y + dz * frame.z.z;
}
return {
id,
origin: { x: origin.x, y: origin.y, z: origin.z },
positions: local,
indices,
color,
flat: true,
};
}
/** FNV-1a over a camera id: a stable, well-spread order for crowded cells. */
function idHash(id) {
@@ -31,6 +109,102 @@ export function createRendering({
parts,
source,
}) {
/**
* The catalog's camera icons: an icon draw set, and the book the layer
* reads them back from (`render/motion/iconBook.js`), each item a camera
* by its id. Cameras hold still, so each item's motion is a hold at its
* mount. Items draw depth-test-free (field-test fix 2026-07-06: the old
* finite depth-test distance re-engaged at far zoom, where the COARSE
* far-LOD Google-3D mesh sits above the true ground and swallowed
* ground-anchored icons); the set culls the far side of the globe and
* refreshHorizonCulling thins the rest.
* The set stacks under the other sprite layers (`spriteDrawOrder`).
* @param {object} viewer The layer's viewer.
* @returns {string} The icon set's id.
*/
function createCameraIcons(viewer) {
// A re-init against a new viewer replaces the icons; the old ones go.
destroyCameraIcons();
const set = drawOf(viewer).icons({
id: `cctv:${++iconSets}:icons`,
horizonCull: true,
// Hidden until enable() has thinned and culled them
// (refreshHorizonCulling, then refreshCoverageStyles shows the set):
// shown from the start, every camera in the catalogue drew while the
// layer waited on its health check.
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
return set.id;
}
/** Let the icon draw set go, whichever viewer the caller tears down. */
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
function cameraIconItem(record) {
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
motion: { kind: 'hold' },
meta: { layer: 'cctv', id },
show: true,
};
}
/**
* A camera's icon item with `fields` changed, to write with the pass's
* others in one go (`writeCameraIcons`); null when none of them changes
* or it has no icon, so a large catalog writes only what changed.
*/
function patchedCameraIcon(id, fields) {
const item = layerState._icons?.item(id);
if (!item) return null;
for (const key in fields)
if (item[key] !== fields[key]) return { ...item, ...fields };
return null;
}
/** Write a pass's changed icons, in one write to the set. */
function writeCameraIcons(items) {
if (items.length) layerState._icons?.putMany(items);
}
/** Add a camera record's icon, idle and shown, once it has a position. */
function addCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
icons.put(cameraIconItem(record));
}
/** Hold a camera's icon at its record's current position. */
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
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) });
}
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
function cameraColorFor(record) {
if (record.camera.id === layerState._activeCameraId)
@@ -64,40 +238,36 @@ export function createRendering({
return;
if (nowMs - layerState._lastFocusStyleAt < 80) return;
layerState._lastFocusStyleAt = nowMs;
const scene = layerState._viewer.scene;
const camera = layerState._viewer.camera;
const query = findQuery(layerState._viewer);
const eye = findCamera(layerState._viewer)?.pose()?.position;
if (!query || !eye) return;
const result = applyCctvFocusDeemphasis({
records: layerState._records,
target,
previousActiveCount: layerState._activeFocusStyleCount,
nowMs,
screenPositionFor: (position) =>
Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
layerState._scratchFocusScreen,
),
cameraDistanceFor: (position) =>
Cesium.Cartesian3.distance(camera.positionWC, position),
baseColorFor: cameraColorFor,
screenPositionFor: (position) => query.project(position),
cameraDistanceFor: (position) => distance(eye, position),
});
layerState._activeFocusStyleCount = result.activeCount;
}
/**
* Apply the gated CCTV focus pass through the production color path.
* Apply the gated CCTV focus pass through the set's focus column (the shader
* multiplies it into the base color's alpha).
* @param {object} input
* @param {object} [input.icons] The icon book (defaults to the layer's).
* @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}}
*/
function applyCctvFocusDeemphasis({
records,
icons = layerState._icons,
target,
previousActiveCount = 0,
nowMs,
screenPositionFor,
cameraDistanceFor,
baseColorFor,
params,
}) {
if (!focusPassIsNeeded(target, previousActiveCount)) {
@@ -107,30 +277,30 @@ export function createRendering({
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const bb = record.billboard;
if (!bb) continue;
const position = bb.position;
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(bb, {
const focus = advanceSpriteFocus(item.meta, {
// Keep hidden icons in the state/release pass so the active count cannot
// drop while a stale dim alpha remains waiting to reappear.
screenPosition:
bb.show === false || !position ? null : screenPositionFor(position),
item.show === false || !position ? null : screenPositionFor(position),
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
target,
params,
spriteHalfWidthPx: (bb.width || 24) * (bb.scale || 1) * 0.5,
spriteHalfHeightPx: (bb.height || 24) * (bb.scale || 1) * 0.5,
spriteHalfWidthPx: item.size[0] * scale * 0.5,
spriteHalfHeightPx: item.size[1] * scale * 0.5,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
const base = baseColorFor(record);
const alpha = base.alpha * focus.factor;
if (focusAlphaNeedsWrite(bb.color?.alpha, alpha, params)) {
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
bb.color = base.withAlpha(alpha);
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
writes += 1;
}
}
@@ -138,18 +308,17 @@ export function createRendering({
}
/**
* Updates visual styles (colors, widths, visibility) for all camera billboards,
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera billboards, mirroring the
* flights layer's EllipsoidalOccluder pass. With the Cesium globe hidden
* (Google-3D regime) nothing writes far-side depth, and the billboards are now
* always-on-top (`disableDepthTestDistance: INFINITY` — the far-zoom submerge
* fix), so without this pass London's cluster would shine through the planet
* from a US viewpoint.
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
@@ -168,38 +337,37 @@ export function createRendering({
if (
!layerState._enabled ||
!layerState._viewer ||
layerState._viewer.isDestroyed() ||
!layerState._records.length
)
return false;
const { camera, scene } = layerState._viewer;
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
const pose = findCamera(layerState._viewer)?.pose();
if (!pose?.position) return false;
const canvas = canvasOf(layerState._viewer);
const width = canvas?.clientWidth || canvas?.width || 0;
const height = canvas?.clientHeight || canvas?.height || 0;
const minX = -width * VIEW_ICON_MARGIN;
const maxX = width * (1 + VIEW_ICON_MARGIN);
const minY = -height * VIEW_ICON_MARGIN;
const maxY = height * (1 + VIEW_ICON_MARGIN);
// Ground metres one pixel covers per metre of distance from the viewer.
const fovy = Number.isFinite(camera.frustum?.fovy)
? camera.frustum.fovy
: Math.PI / 3;
const fovy = Number.isFinite(pose.fovy) ? pose.fovy : Math.PI / 3;
const metresPerPixelPerMetre =
(2 * Math.tan(fovy / 2)) / Math.max(1, height);
const viewer = camera.positionWC;
// The horizon test of Cesium's EllipsoidalOccluder, inlined: this loop
const viewer = pose.position;
// The renderer's horizon test (geo/horizon.js), inlined: this loop
// visits every camera in the catalog.
const inverseRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
const inverseRadii = WGS84.oneOverRadii;
const cx = viewer.x * inverseRadii.x;
const cy = viewer.y * inverseRadii.y;
const cz = viewer.z * inverseRadii.z;
const limbSquared = cx * cx + cy * cy + cz * cz - 1;
const activeId = layerState._activeCameraId;
const project = screenProjector(scene, camera, width, height);
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const cells = new Map();
for (const record of layerState._records) {
const position = record.billboard?.position;
const position = record.position;
if (!position) continue;
const vx = position.x * inverseRadii.x - cx;
const vy = position.y * inverseRadii.y - cy;
@@ -240,12 +408,14 @@ export function createRendering({
record.viewPass = pass;
shown.push(record);
}
const writes = [];
for (const record of layerState._records) {
const bb = record.billboard;
if (!bb) continue;
const visible = record.viewPass === pass;
if (bb.show !== visible) bb.show = visible;
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
if (item) writes.push(item);
}
writeCameraIcons(writes);
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
@@ -255,37 +425,21 @@ export function createRendering({
}
/**
* Canvas coordinates for world positions. In 3D the pass multiplies by one
* view-projection matrix per call instead of Cesium's per-point
* cartesianToCanvasCoordinates, which dominated the pass on a large
* catalog; other scene modes keep Cesium's projection.
* @returns {(position: Cesium.Cartesian3) => ({x: number, y: number}|null)}
* Canvas coordinates for world positions, from the eye's pose by the
* renderer's perspective projection (geo/frustum.js): one pose read per
* pass rather than a renderer projection per point, which dominated the
* pass on a large catalog. Null behind the eye or before its near plane.
* A pose with no perspective field of view is projected by the renderer,
* point by point.
* @returns {(position: {x: number, y: number, z: number}) =>
* ({x: number, y: number}|null)}
*/
function screenProjector(scene, camera, width, height) {
const out = layerState._scratchViewScreen;
const projection = camera.frustum?.projectionMatrix;
if (
scene.mode !== Cesium.SceneMode.SCENE3D ||
!projection ||
!camera.viewMatrix
)
return (position) => scene.cartesianToCanvasCoordinates(position, out);
const m = Cesium.Matrix4.multiply(
projection,
camera.viewMatrix,
layerState._scratchViewProjection,
);
return (p) => {
const w = m[3] * p.x + m[7] * p.y + m[11] * p.z + m[15];
const z = m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14];
// Behind the eye or before the near plane: Cesium does not draw it.
if (!(w > 0) || z < 0) return null;
out.x =
((m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12]) / w + 1) * 0.5 * width;
out.y =
(1 - (m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13]) / w) * 0.5 * height;
return out;
};
function screenProjector(pose, width, height) {
if (Number.isFinite(pose.fovy) && Number.isFinite(pose.aspectRatio)) {
return poseProjector(pose, width, height, layerState._scratchViewScreen);
}
const query = findQuery(layerState._viewer);
return (position) => query?.project(position) ?? null;
}
/**
@@ -307,7 +461,7 @@ export function createRendering({
return record.viewCellKey;
const latStep = 2 ** level / 111_320;
const row = Math.floor(lat / latStep);
const rowLat = Cesium.Math.toRadians((row + 0.5) * latStep);
const rowLat = toRadians((row + 0.5) * latStep);
const lonStep = latStep / Math.max(0.05, Math.cos(rowLat));
record.viewCellLevel = level;
record.viewCellLat = lat;
@@ -349,23 +503,29 @@ export function createRendering({
for (const record of Array.isArray(records) ? records : []) {
if (record) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
if (record.camera?.id === activeCameraId) record.activationDone = false;
}
for (const entity of record?.coverageEntities || []) entity.show = false;
if (record?.viewshedPrimitive) destroyVolume?.(record);
if (record?.projection?.planeEntity)
record.projection.planeEntity.show = false;
parts.drawSets.writeLines(record?.coverageEntities);
if (record?.viewshedVolume) destroyVolume?.(record);
const plane = record?.projection?.plane;
if (plane?.show) {
plane.show = false;
parts.drawSets.writePlane(plane);
}
}
}
function hideCctvVisuals() {
hideCctvRecordVisuals(
layerState._records,
parts.geometry.destroyViewshedVolume,
destroyViewshedVolume,
layerState._activeCameraId,
);
parts.projection.clearProjectionOverlay();
if (layerState._billboards) layerState._billboards.show = false;
if (layerState._icons) layerState._icons.show = false;
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -387,19 +547,16 @@ export function createRendering({
coverageVisible,
);
}
// Only changed icons are written, in one go after the pass, so across a
// large catalog only the changed rows upload.
const restyled = [];
for (const record of layerState._records) {
const isActive = record.camera.id === activeId;
if (record.billboard) {
// Unchanged writes still dirty the collection, which then rewrites
// every icon's vertices: across a large catalog, write only changes.
const color = cameraColorFor(record);
if (!Cesium.Color.equals(record.billboard.color, color))
record.billboard.color = color;
const scale = isActive ? 1.25 : 1.0;
if (record.billboard.scale !== scale) record.billboard.scale = scale;
// disableDepthTestDistance stays POSITIVE_INFINITY for every billboard
// (set at creation) — see the field-test far-zoom submerge fix there.
}
const icon = patchedCameraIcon(record.camera.id, {
color: cameraColorFor(record),
scale: isActive ? 1.25 : 1.0,
});
if (icon) restyled.push(icon);
if (
layerState._enabled &&
@@ -426,10 +583,6 @@ export function createRendering({
// rather than rendering identically to a surveyed one (#639). Colors,
// widths, and the active/idle emphasis are unchanged.
const bearingEstimated = isHeadingEstimated(record.camera);
const lineMaterial = (color) =>
bearingEstimated
? new Cesium.PolylineDashMaterialProperty({ color })
: color;
for (const entity of record.coverageEntities || []) {
// The frustum wireframe is part of the projection representation —
// force it on for the active camera and let it read through geometry
@@ -438,45 +591,43 @@ export function createRendering({
layerState._enabled &&
((coverageOn && inVisibleSet) || planeShowing)
);
if (!entity.polyline) continue;
if (!entity.role) continue;
// Viewshed mode swaps the cyan/green scheme for the camera's own hue so
// adjacent cones read as distinct coverage claims (design §3b); the
// active camera keeps its width/alpha emphasis in both schemes.
const hue = viewshedOn ? record.viewshedColors : null;
if (entity._coverageRole === 'cap') {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED,
);
entity.polyline.width = isActive ? 2.2 : 1.0;
entity.polyline.depthFailMaterial = planeShowing
const hue = viewshedOn ? record.viewshedColors || null : null;
entity.dashed = bearingEstimated;
if (entity.role === 'cap') {
entity.color = hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED;
entity.widthPx = isActive ? 2.2 : 1.0;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.26)
? withAlpha(hue.line, 0.26)
: ACTIVE_COVERAGE_CENTER_DEPTHFAIL
: undefined;
: null;
} else {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line.withAlpha(0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED,
);
entity.polyline.width = isActive ? 1.8 : 0.9;
entity.polyline.depthFailMaterial = planeShowing
entity.color = hue
? isActive
? hue.lineActive
: withAlpha(hue.line, 0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED;
entity.widthPx = isActive ? 1.8 : 0.9;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.18)
? withAlpha(hue.line, 0.18)
: ACTIVE_COVERAGE_EDGE_DEPTHFAIL
: undefined;
: null;
}
}
parts.drawSets.writeLines(record.coverageEntities);
// Viewshed volume lifecycle: exists iff enabled + viewshed mode + in the
// visible set. Rebuild on active-tint flips (rare); otherwise leave the
@@ -488,14 +639,11 @@ export function createRendering({
record.frustumPositions
);
if (wantVolume) {
if (
!record.viewshedPrimitive ||
record.viewshedActiveTint !== isActive
) {
parts.geometry.rebuildViewshedVolume(record, isActive);
if (!record.viewshedVolume || record.viewshedActiveTint !== isActive) {
rebuildViewshedVolume(record, isActive);
}
} else if (record.viewshedPrimitive) {
parts.geometry.destroyViewshedVolume(record);
} else if (record.viewshedVolume) {
destroyViewshedVolume(record);
}
if (record.projection) {
@@ -503,11 +651,316 @@ export function createRendering({
}
}
if (layerState._billboards)
layerState._billboards.show = !!layerState._enabled;
writeCameraIcons(restyled);
if (layerState._icons) layerState._icons.show = !!layerState._enabled;
parts.projection.pauseInactiveProjectionFeeds(activeId);
}
/**
* Reports whether the photorealistic tiles the scene draws have finished
* loading the tiles in view. Shared mesh-floor sampling is gated on this so
* a one-shot cell never bakes in a miss from still-streaming tiles.
*
* Only the photoreal regime (the globe hidden under the tiles) can be
* ready: on a globe stack the tiles are hidden, and the shared sampler can
* only inspect tiles that are drawn, so a sample taken against them would
* silently miss (Task 5, spec §2). The tiles' readiness is the globe
* port's (`isSettled('tiles')`), true as well when no tiles are drawn.
*
* @returns {boolean} True when the regime is photoreal and its tiles in
* view have loaded.
*/
function projectionTilesReady() {
const globe = layerState._viewer ? findGlobe(layerState._viewer) : null;
if (!globe || globe.isGlobeVisible?.() !== false) return false;
return globe.isSettled('tiles') === true;
}
/**
* Converts a computeFrustumGeometry result into the ECEF positions the
* drawn items consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and items must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: object, capCenter: object, tl: object, tr: object,
* br: object, bl: object, label: object }} ECEF points with x, y and z.
*/
function frustumCartesians(geometry) {
const at = (p) => fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
tl: at(geometry.corners.tl),
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
),
};
}
/**
* Creates the five lines that visualize a camera's pitched frustum: 4
* corner rays (mount → far-plane corner) + the closed far-plane rectangle,
* as line handles the layer restyles and then writes to its coverage set.
* Item ids stay in the `cctv-<id>-<role>` scheme (pick-owner regex depends
* on it): ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Object[]} Array of five coverage line handles.
*/
function buildCoverageEntities(record) {
const { camera } = record;
// Prefer the record's already-refined geometry. Lazy creation commonly
// happens after the staggered ground pass; recomputing from the catalog
// prior here would regress the camera to its pre-sampled datum.
let geometry = record.frustumGeometry;
let positions = record.frustumPositions;
if (!geometry || !positions) {
geometry = parts.geometry.computeFrustumGeometry(
camera,
parts.ground.groundPriorAltFor(record),
record.probeClampRangeM,
);
positions = frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
moveCameraIcon(record);
}
const line = (name, role) => ({
id: `cctv-${camera.id}-${name}`,
cameraId: camera.id,
role,
positions: null,
widthPx: 1.2,
color: IDLE_COVERAGE_COLOR,
dashed: false,
depthFailColor: null,
show: true,
});
const entities = [
line('ray-tl', 'edge'),
line('ray-tr', 'edge'),
line('ray-br', 'edge'),
line('ray-bl', 'edge'),
line('cap', 'cap'),
];
placeCoverageLines(entities, positions);
parts.drawSets.writeLines(entities);
return entities;
}
/**
* Put a camera's five coverage line handles on its frustum positions (not
* written: the caller writes them).
* @param {Object[]} entities - The record's coverage handles.
* @param {Object} positions - frustumCartesians shape.
*/
function placeCoverageLines(entities, positions) {
if (!(entities?.length >= 5)) return;
entities[0].positions = [positions.mount, positions.tl];
entities[1].positions = [positions.mount, positions.tr];
entities[2].positions = [positions.mount, positions.br];
entities[3].positions = [positions.mount, positions.bl];
entities[4].positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
}
/**
* The activation obstruction probe's one ray cast against the scene: the
* first surface along the ray from `origin`. The layer's own lines, plane
* and volumes are not ground, so the cast sees through them.
* @param {{x: number, y: number, z: number}} origin - ECEF ray origin.
* @param {{x: number, y: number, z: number}} direction - Unit ECEF direction.
* @returns {Promise<{x: number, y: number, z: number}|null>} Null as well
* when the scene cannot cast rays.
*/
async function obstructionHit(origin, direction) {
const query = findQuery(layerState._viewer);
if (!query) return null;
return query.rayCast({ origin, direction }, { against: 'surface' });
}
/**
* On a globe map, where the activation probe's axis meets the globe's
* terrain: `{hit}`, `hit` null on a miss. Null when the globe is not shown
* (the photoreal stack), where only the surface cast counts.
* @returns {Promise<{hit: object|null}|null>}
*/
async function terrainHit(origin, direction) {
const viewer = layerState._viewer;
if (findGlobe(viewer)?.isGlobeVisible?.() !== true) return null;
const query = findQuery(viewer);
if (!query) return null;
return {
hit: await query.rayCast({ origin, direction }, { against: 'terrain' }),
};
}
/** Whether there is a query port to cast the activation probe through. */
function canPickFromRay() {
return typeof findQuery(layerState._viewer)?.rayCast === 'function';
}
/** Removes the layer's coverage lines from the scene. */
function removeCoverageEntities() {
parts.drawSets.clearLines();
}
/**
* The camera a pick (a draw-port `Hit`: `event.drawHit`, `query.pick`)
* names: an item of the layer's own sets that its record still draws.
* @param {{set: string, id: string, meta?: object}|null} hit
* @returns {string|null} Camera ID, or null if the pick is not a CCTV item.
*/
function extractPickedCameraId(hit) {
if (!hit || typeof hit.set !== 'string' || typeof hit.id !== 'string')
return null;
// A camera icon: its item id is the upstream camera id, so a sibling
// may legitimately use the same string. A bare id match is not
// ownership proof: the layer's own icon set must have drawn the pick.
const icons = layerState._icons;
if (icons && hit.set === icons.setId)
return icons.has(hit.id) && layerState._recordById.has(hit.id)
? hit.id
: null;
// A coverage line or monitor plane: an item of the layer's own sets
// that its record still draws.
const role = parts.drawSets.roleOfSet(hit.set);
if (!role) return null;
const value = hit.meta?.cameraId;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
if (!record) return null;
const owns =
role === 'coverage'
? Boolean(record.coverageEntities?.some((h) => h?.id === hit.id))
: record.projection?.plane?.id === hit.id ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.plane?.id === hit.id,
);
return owns ? value : null;
}
/**
* The camera whose icon or coverage is under a screen position (CSS px),
* from one pick; null when none is, or the pick throws.
* @param {{x: number, y: number}} position
* @returns {string|null}
*/
function pickCameraIdAt(position) {
let hit = null;
try {
hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null;
} catch {
hit = null;
}
return extractPickedCameraId(hit);
}
/**
* Where the ambient cards can go this pass: the canvas size, and the
* canvas position of a world point on the near side of the horizon (null
* behind it or off the projection).
* @returns {{width: number, height: number,
* screenOf: (position: object) => ({x: number, y: number}|null)}}
*/
function cardView() {
const viewer = layerState._viewer;
const canvas = canvasOf(viewer);
const query = findQuery(viewer);
const eye = findCamera(viewer)?.pose()?.position;
const horizon = eye ? horizonFrom(eye) : null;
return {
width: canvas?.clientWidth || canvas?.width || 0,
height: canvas?.clientHeight || canvas?.height || 0,
screenOf: (position) =>
query && horizon?.isPointVisible(position)
? query.project(position)
: null,
};
}
/**
* Removes (and destroys) a record's viewshed volume primitive, if any.
* @param {Object} record - Camera record.
*/
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedVolume)
parts.drawSets.removeVolume(record.viewshedVolume);
record.viewshedVolume = null;
}
/**
* (Re)builds a record's translucent viewshed volume from its CURRENT
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
* is welded to the cone by construction. Called only where the wireframe
* already rewrites (style refresh on mode/visible-set/active changes,
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
* queries (viewshed design §3b).
* @param {Object} record - Camera record.
* @param {boolean} isActive - Active camera gets the brighter fill.
*/
function rebuildViewshedVolume(record, isActive) {
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
) {
destroyViewshedVolume(record);
return;
}
const colors = record.viewshedColors;
const id = `cctv-${record.camera.id}-viewshed`;
// Replaced where it is: the volume draws in the frame its old one did.
parts.drawSets.writeVolume(
frustumVolumeItem(
id,
record.frustumPositions,
isActive ? colors.fillActive : colors.fill,
),
);
record.viewshedVolume = id;
record.viewshedActiveTint = !!isActive;
}
return {
projectionTilesReady,
frustumCartesians,
buildCoverageEntities,
placeCoverageLines,
obstructionHit,
terrainHit,
canPickFromRay,
removeCoverageEntities,
extractPickedCameraId,
pickCameraIdAt,
cardView,
destroyViewshedVolume,
rebuildViewshedVolume,
createCameraIcons,
destroyCameraIcons,
addCameraIcon,
moveCameraIcon,
refreshCctvFocusStyles,
applyCctvFocusDeemphasis,
refreshHorizonCulling,
+333 -33
View File
@@ -2,6 +2,7 @@
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
// from the same base color the coverage refresh assigns, so a video-feed camera
// stays violet while it dims instead of falling back to the idle cyan.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRendering } from './rendering.js';
@@ -11,68 +12,367 @@ import {
LIVE_CAMERA_COLOR,
} from './policy.js';
import { isVideoFeedType } from '../../sources/cctvTypes.js';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
const FOCUS_FACTOR = 0.5;
function assertFadedFrom(actual, base, label) {
assert.ok(actual, `${label}: color written`);
assert.deepEqual(
[actual.red, actual.green, actual.blue],
[base.red, base.green, base.blue],
`${label}: hue`,
);
assert.equal(actual.alpha, base.alpha * FOCUS_FACTOR, `${label}: alpha`);
function assertKeepsColor(icons, id, base, label) {
assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`);
assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`);
}
test('focus de-emphasis fades each icon from its own color', () => {
const record = (id, feedType) => ({
camera: { id, feedType },
// No position, so the pass skips screen projection; the focus stub below
// decides the factor on its own.
billboard: { show: true },
position: { x: 6378137, y: 0, z: 0 },
});
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
});
const projected = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
query: {
project: (position) => {
projected.push(position);
return { x: 10, y: 20 };
},
},
});
const state = {
_enabled: true,
_viewer: { scene: {}, camera: {} },
_viewer: viewer,
_records: [idleVideo, idleStill, activeVideo],
_activeCameraId: activeVideo.camera.id,
_activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity,
};
const distances = [];
const focus = {
focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => ({}),
focusPassIsNeeded: () => true,
advanceSpriteFocus: () => ({
factor: FOCUS_FACTOR,
active: true,
transitioning: false,
}),
advanceSpriteFocus: (meta, input) => {
distances.push(input.cameraDistance);
return { factor: FOCUS_FACTOR, active: true, transitioning: false };
},
focusAlphaNeedsWrite: () => true,
};
const { refreshCctvFocusStyles } = createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedCamera: (camera) =>
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedType,
isVideoFeedCamera: (camera) =>
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
},
},
source: {},
});
try {
const setId = createCameraIcons(viewer);
for (const r of state._records) addCameraIcon(r);
refreshCctvFocusStyles(1000);
const icons = state._icons;
assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video');
assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still');
assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video');
assert.equal(state._activeFocusStyleCount, 3);
assert.equal(projected.length, 3, 'each shown icon is projected');
assert.deepEqual(distances, [1000, 1000, 1000], 'from the eye');
// What the set draws: depth-test-free, held at the mount, shrinking
// with distance as before.
const drawn = draw.set(setId).items.get('idle-hls');
assert.equal(drawn.disableDepthTest, Infinity);
assert.deepEqual(drawn.motion, { kind: 'hold' });
assert.deepEqual(drawn.pos, idleVideo.position);
assert.deepEqual(drawn.size, [24, 24]);
assert.deepEqual(drawn.scaleByDistance, {
near: 350,
nearValue: 1.25,
far: 4_000_000,
farValue: 0.42,
});
assert.equal(drawn.focus, FOCUS_FACTOR);
assert.equal(draw.set(setId).spec.horizonCull, true);
// Hidden until enable() has culled and thinned the cameras: the layer
// waits on its health check between drawing them and that pass.
assert.equal(draw.set(setId).show, false);
} finally {
unbind();
}
});
test('the icons go with the viewer that drew them, whichever tears down', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus: {} },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
state._viewer = second;
const current = createCameraIcons(second);
assert.notEqual(old, current);
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
assert.equal(two.draw.sets.get(current).disposed, false);
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
} finally {
one.unbind();
two.unbind();
}
});
test('the obstruction probe casts one ray through the query port', async () => {
const calls = [];
const viewer = {};
const unbind = bindRenderer(viewer, {
query: {
rayCast: async (ray, options) => {
calls.push({ ray, options });
return { x: 1, y: 2, z: 3 };
},
},
});
const state = { _viewer: viewer };
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
try {
assert.equal(rendering.canPickFromRay(), true);
const origin = { x: 0, y: 0, z: 0 };
const direction = { x: 1, y: 0, z: 0 };
assert.deepEqual(await rendering.obstructionHit(origin, direction), {
x: 1,
y: 2,
z: 3,
});
// The layer's own sets are not ground: the cast sees through them
// without naming them.
assert.deepEqual(calls, [
{ ray: { origin, direction }, options: { against: 'surface' } },
]);
} finally {
unbind();
}
state._viewer = {};
assert.equal(rendering.canPickFromRay(), false);
assert.equal(
await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
null,
);
});
test('cards go only where the horizon lets the camera see', () => {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000);
const front = Cesium.Cartesian3.fromDegrees(0, 0);
const back = Cesium.Cartesian3.fromDegrees(180, 0);
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: eye.x, y: eye.y, z: eye.z } },
});
const unbind = bindRenderer(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 0, height: 600 },
query: { project: () => ({ x: 10, y: 20 }) },
});
try {
const view = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
}).cardView();
assert.equal(view.width, 800);
assert.equal(view.height, 600);
assert.deepEqual(view.screenOf(front), { x: 10, y: 20 });
assert.equal(view.screenOf(back), null);
} finally {
unbind();
}
});
test('the projection tiles are ready only when drawn and settled', () => {
const viewer = {};
let globeVisible = true;
let settled = true;
const unbind = bindRenderer(viewer, {
globe: {
isGlobeVisible: () => globeVisible,
isSettled: (kind) => kind === 'tiles' && settled,
},
});
try {
const { projectionTilesReady } = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
});
assert.equal(projectionTilesReady(), false, 'a globe stack hides them');
globeVisible = false;
assert.equal(projectionTilesReady(), true);
settled = false;
assert.equal(projectionTilesReady(), false, 'still streaming');
} finally {
unbind();
}
const bare = createRendering({
state: { _viewer: {} },
services: { focus: {} },
parts: {},
});
assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles');
});
test('a view pass writes only the icons it changes, in one write', () => {
const viewer = {};
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 2000);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const camera = fakeCameraPort({
pose: {
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: { x: 0, y: 0, z: 1 },
fovy: Math.PI / 3,
aspectRatio: 4 / 3,
near: 0.1,
far: 5e8,
},
});
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
});
const record = (id, lon) => {
const p = Cesium.Cartesian3.fromDegrees(lon, 0, 10);
return {
camera: { id, lat: 0, lon },
position: { x: p.x, y: p.y, z: p.z },
};
};
// One in view, one far off it.
const near = record('near', 0);
const far = record('far', 1);
const state = {
_enabled: true,
_viewer: viewer,
_records: [near, far],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
drawSets: { roleOfSet: () => null },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
const set = draw.set(setId);
const writes = set.writes;
refreshCctvFocusStyles(1000);
assert.equal(rendering.refreshHorizonCulling(), true);
assert.equal(set.writes, writes + 1, 'one write for the pass');
assert.equal(set.items.get('near').show, true);
assert.equal(set.items.get('far').show, false);
assertFadedFrom(idleVideo.billboard.color, LIVE_CAMERA_COLOR, 'idle video');
assertFadedFrom(idleStill.billboard.color, IDLE_CAMERA_COLOR, 'idle still');
assertFadedFrom(
activeVideo.billboard.color,
ACTIVE_CAMERA_COLOR,
'active video',
);
assert.equal(state._activeFocusStyleCount, 3);
assert.equal(rendering.refreshHorizonCulling(), false);
assert.equal(set.writes, writes + 1, 'an unchanged view writes nothing');
// Another layer on the same viewer draws its icons in a set of its own.
const other = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
source: {},
});
const otherId = other.createCameraIcons(viewer);
assert.notEqual(otherId, setId);
assert.equal(
rendering.extractPickedCameraId({ set: otherId, id: 'near' }),
null,
"the other layer's icon is not this layer's camera",
);
} finally {
unbind();
}
});
test('a pose with no perspective field of view is projected by the renderer', () => {
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 7e6, y: 0, z: 0 }, fovy: undefined },
});
const asked = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
query: {
project: (position) => {
asked.push(position.y);
return position.y === 0 ? { x: 400, y: 300 } : null;
},
},
});
// On the ground under the eye, in cells of their own.
const record = (id, y) => ({
camera: { id, lat: 0, lon: y / 1000 },
position: { x: 6378137, y, z: 0 },
});
const state = {
_enabled: true,
_viewer: viewer,
_records: [record('on', 0), record('off', 1000)],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
rendering.refreshHorizonCulling();
const set = draw.set(setId);
assert.deepEqual(asked.sort(), [0, 1000]);
assert.equal(set.items.get('on').show, true);
assert.equal(set.items.get('off').show, false);
} finally {
unbind();
}
});
+23 -74
View File
@@ -1,8 +1,4 @@
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../data/trackingClickGesture.js';
import * as Cesium from 'cesium';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
state: layerState,
@@ -34,24 +30,19 @@ export function createSelection({
}
/**
* Bind CCTV activation to clean taps while preserving the layer's hover-move
* callback on the shared Cesium handler. Drag-like and long-press gestures do
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
* @param {Cesium.ScreenSpaceEventHandler|Object} handler - Input handler.
* @param {(click: Object) => void} onClick - Accepted CCTV click callback.
* @param {Object} [options] - Gesture test seams and optional onMouseMove hook.
* @returns {void}
* @param {import('../../input/dispatcher.js').InputDispatcher} input
* @param {(event: import('../../input/dispatcher.js').ClickEvent) => void} onClick
* Accepted CCTV click callback.
* @returns {() => void} Unsubscribe.
*/
function bindCctvWorldClickGesture(handler, onClick, options = {}) {
bindTrackingClickGesture(
handler,
(click, gesture) => {
if (!isTrackingClickGesture(gesture)) return;
onClick(click);
},
options,
);
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
onClick(event);
});
}
/**
@@ -119,12 +110,13 @@ export function createSelection({
layerState._geoQueue.splice(queueIdx, 1);
layerState._geoQueue.unshift(record);
}
// §9.1: one obstruction probe per activation, BEFORE the geometry pass so
// the range clamp lands in the same rewrite. A FIRST-EVER activation (no
// real ground sample yet) probes from the catalog-prior altitude — if that
// prior is off, the clamp is measured from a shifted origin, but a
// re-activation after the one-shot snap lands re-probes from real ground,
// so it self-corrects.
// §9.1: one obstruction probe per activation, cast before the geometry
// pass; its range clamp lands a microtask later, before the next frame,
// rewriting the geometry and asking again for the footprint ground. A
// FIRST-EVER activation (no real ground sample yet) probes from the
// catalog-prior altitude — if that prior is off, the clamp is measured
// from a shifted origin, but a re-activation after the one-shot snap
// lands re-probes from real ground, so it self-corrects.
parts.geometry.runActivationObstructionProbe(record);
// Coverage is activation-lazy even while the mode is OFF: the active
// camera's projection representation must be ready without materializing
@@ -214,57 +206,14 @@ export function createSelection({
}
/**
* Extracts a camera ID from a Cesium pick result by checking billboard IDs,
* primitive IDs, and entity cctvCameraId properties.
* @param {Object|null} picked - Result from scene.pick().
* @returns {string|null} Camera ID, or null if the pick is not a CCTV entity.
* The camera a scene pick result is, or null: read by the rendering part,
* which owns the scene objects the pick names.
* @param {Object|null} picked - Result from a scene pick.
* @returns {string|null}
*/
function extractPickedCameraId(picked) {
if (!picked) return null;
const entity = picked.id?.properties
? picked.id
: picked.primitive?.id?.properties
? picked.primitive.id
: null;
const maybeProp = entity?.properties?.cctvCameraId;
if (maybeProp) {
const value =
typeof maybeProp.getValue === 'function'
? maybeProp.getValue(Cesium.JulianDate.now())
: maybeProp;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
const ownsCoverageEntity = Boolean(
record?.coverageEntities?.includes(entity),
);
const ownsProjectionEntity =
record?.projection?.planeEntity === entity ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.planeEntity === entity,
);
if (record && (ownsCoverageEntity || ownsProjectionEntity)) return value;
}
// Camera billboard IDs are intentionally the upstream camera ID, so a
// sibling may legitimately use the same string. A bare ID match is not
// ownership proof: require this layer's billboard collection or the exact
// billboard stored on the record.
const directId =
typeof picked.id === 'string'
? picked.id
: typeof picked.primitive?.id === 'string'
? picked.primitive.id
: null;
const record =
directId === null ? null : layerState._recordById.get(directId);
if (!record) return null;
return picked.primitive === layerState._billboards ||
picked.primitive === record.billboard
? directId
: null;
return parts.rendering.extractPickedCameraId(picked);
}
return {
getActiveRecord,
+5 -4
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCctvSource, createCctvLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const camera = {
id: 'pack/camera ?x',
@@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
},
sprites: { registerSpriteCollection: noop },
sprites: {},
activation: {},
locations: {},
picking: { unregisterPickOwner: noop },
@@ -134,9 +135,9 @@ test('camera construction is inert and destruction cancels a pending catalog and
const a = createCctvLayer({ services, source });
const b = createCctvLayer({ services, source });
assert.equal(listeners.size, 0);
const viewer = {
scene: { primitives: { add: (value) => value, remove: () => true } },
};
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
t.after(unbind);
const initializing = a.init(viewer);
assert.equal(listeners.size, 1);
assert.equal(signal.aborted, false);
+10 -20
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const {
clearOverlaySource,
@@ -15,7 +13,8 @@ export function createState({ services }) {
layerState._viewer = null;
layerState._billboards = null;
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._records = [];
@@ -58,7 +57,7 @@ export function createState({ services }) {
layerState._lastViewContext = '';
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._count = 0;
@@ -84,11 +83,8 @@ export function createState({ services }) {
layerState._activeFocusStyleCount = 0;
layerState._scratchFocusScreen = new Cesium.Cartesian2();
layerState._scratchViewScreen = new Cesium.Cartesian2();
layerState._scratchViewProjection = new Cesium.Matrix4();
// The view pass's screen-point scratch: its projection writes only x and y.
layerState._scratchViewScreen = { x: 0, y: 0 };
// Counts view passes; a record shown by the latest pass carries its number.
@@ -114,7 +110,7 @@ export function createState({ services }) {
layerState._viewResizeCanvas = null;
// The camera the moveStart/moveEnd listeners are attached to.
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
@@ -174,16 +170,9 @@ export function createState({ services }) {
layerState._lastTransientNotifyAt = 0;
// Cached handle on the active Google Photorealistic 3D Tileset, discovered
// lazily from scene.primitives. Shared mesh-floor sampling is gated on its
// tilesLoaded flag so a coarse-LOD miss is never baked in. Cleared when the
// tileset is destroyed / the layer tears down.
layerState._activeTileset = null;
// Task 5: last surface regime the record geometry was recomputed for. The
// map-stack change listener compares the CURRENT regime (derived live from
// scene.globe.show) against this so bing→osm switches (same 'terrain-globe'
// whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe'
// regime) don't trigger a pointless full-catalog rewrite.
layerState._lastAppliedRegime = null;
@@ -193,8 +182,8 @@ export function createState({ services }) {
layerState._mapStackListener = null;
// Field-test fix (2026-07-06): camera.moveEnd handle for the horizon-culling
// pass (removed in destroy). Event-driven only — never a per-frame loop, so
// Field-test fix (2026-07-06): the Off of the camera's moveEnd listener for
// the horizon-culling pass (called in destroy). Event-driven only — never a per-frame loop, so
// the zero-steady-state-work invariant holds.
layerState._horizonCullListener = null;
@@ -269,6 +258,7 @@ export function createState({ services }) {
layerState._cameraMoving = false;
// The Off of the camera's moveStart listener.
layerState._moveStartListener = null;
layerState._sourceAbort = null;
return layerState;
+54 -7
View File
@@ -1,4 +1,13 @@
import * as Cesium from 'cesium';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
const testIconSet = () => ({
id: 'cctv:test:icons',
show: true,
upsert() {},
remove() {},
dispose() {},
});
export function createTesting({ state: layerState, services, parts, source }) {
/** Test seam: republishes host entries through the real push path, so tests
@@ -19,7 +28,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
/**
* Create the production monitor-plane/host-label pair without media setup.
* @param {Object} viewer Cesium viewer seam.
* @param {Object} viewer Viewer whose renderer draws the plane.
* @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime.
*/
@@ -34,15 +43,16 @@ export function createTesting({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
const runtime = {
cameraId: String(record.camera.id),
planeEntity: null,
labelPosition: new Cesium.Cartesian3(),
plane: null,
// createProjectionPlane gives it its label position.
labelPosition: null,
overlayEntry: null,
planeMaterial: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
planeSource: parts.projection.plainPlaneSource(),
};
parts.projection.createProjectionPlane(
record,
@@ -102,7 +112,6 @@ export function createTesting({ state: layerState, services, parts, source }) {
);
layerState._coverageEntities = [];
layerState._projectionEntities = [];
layerState._billboards = null;
layerState._activeCameraId = activeCameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = !!openingCameraProvisional;
@@ -117,6 +126,42 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
/**
* What the layer draws now, for the QA harness: the gizmo's parts, the
* coverage lines and monitor planes by item id, the viewshed volumes'
* ids, and how many volumes were ever written.
*/
function _cctvDrawnForTest() {
const coverage = {};
for (const record of layerState._records)
for (const line of record.coverageEntities || [])
if (line?.id) coverage[line.id] = line;
const planes = {};
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
viewsheds: layerState._records
.map((record) => record.viewshedVolume)
.filter(Boolean),
viewshedWrites: parts.drawSets.volumeWritesForTest(),
};
}
/** The layer's icon book, for tests that read what the icons draw. */
function _cctvIconsForTest() {
return layerState._icons;
}
return {
_pushAmbientCardEntriesForTest,
@@ -125,5 +170,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
_updateCctvProjectionPlaneForTest,
_extractPickedCameraIdForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_cctvDrawnForTest,
};
}