Draw radio, transit and CCTV through one display each

- Radio: stations, clusters, the selection and its brackets are point
  and sprite sets; clusters come from the layer's engine-neutral screen
  clusterer with Cesium's EntityCluster rules, and clicks go through the
  selection dispatcher. One style module holds the sizes and colours.
- Transit: vehicles are two sprite sets from an up-front atlas, rotated
  with Cesium's projected-rotation maths. The selected vehicle's trail is
  engine.lines in two lanes and 29 age bands, so trails are no longer
  draped over terrain until the contract has ground corridors. The
  Cesium contact trail renderer and its re-export go.
- CCTV: markers, wedges, the plane outline and the calibration gizmo
  (rings, arrows, handles, drags through engine.input) draw on the
  contract. The textured monitor plane and the viewshed volume, which no
  primitive expresses yet, sit behind one seam, render/meshes.js, with a
  Cesium backend and a Navara backend the Navara mode passes in.

Known gaps against Cesium: transit trails are not draped, and the
surveillance-lens click correction runs only where the engine reports
its style stage (Navara).

Coupling: layer renderer lines fall from 2638/8735 to 1636/6953
(Cesium/Navara), ScreenSpaceEventHandler files from 15 to 10, `viewer`
lines from 2014 to 1901.
This commit is contained in:
German Khokhlov committed 2026-11-07 04:29:50 +04:00
1 parent fc75e245a6
commit dc1144b947
68 files changed
+6216 -5326

No files matched your search

-233
View File
@@ -1,233 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createCalibrationGizmo } from '../../data/cctvGizmo.js';
import { createCesiumCctvGizmoRenderer } from './render/cesiumGizmo.js';
function setup(t, initialInputs = true) {
const actions = new Map();
const entities = new Cesium.EntityCollection();
const controller = { enableInputs: initialInputs };
const canvas = new EventTarget();
canvas.style = {};
canvas.ownerDocument = { defaultView: new EventTarget() };
let picked = null;
let destroys = 0;
const viewer = {
entities,
scene: {
canvas,
screenSpaceCameraController: controller,
pick: () => picked,
drillPick: () => [],
},
camera: {
getPickRay: ({ x }) => ({
origin: new Cesium.Cartesian3(6378237, x, 0),
direction: new Cesium.Cartesian3(-1, 0, 0),
}),
},
};
const renderer = createCesiumCctvGizmoRenderer(viewer, {
createEventHandler: () => ({
setInputAction: (listener, type) => actions.set(type, listener),
destroy() {
destroys++;
actions.clear();
},
}),
});
const p = (x, y, z) => new Cesium.Cartesian3(x, y, z);
const record = {
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 100,
calibration: {
headingDeg: 0,
pitchDeg: 0,
offsetEastM: 0,
offsetNorthM: 0,
heightM: 0,
rangeScale: 1,
fovDeg: 0,
},
basePose: { rangeM: 100, fovDeg: 60 },
},
frustumGeometry: { rangeM: 100 },
frustumPositions: {
mount: p(6378137, 0, 0),
capCenter: p(6378137, 0, 100),
tl: p(6378150, -20, 100),
tr: p(6378150, 20, 100),
bl: p(6378124, -20, 100),
br: p(6378124, 20, 100),
},
};
let active = record;
const patches = [],
ends = [];
const gizmo = createCalibrationGizmo({
renderer,
getActiveRecord: () => active,
applyPatch: (patch, pinned) => patches.push({ patch, pinned }),
endPatch: (pinned) => ends.push(pinned),
});
t.after(() => gizmo.destroy());
gizmo.setEnabled(true);
const event = (type, x = 10) =>
actions.get(Cesium.ScreenSpaceEventType[type])?.({
position: { x, y: 0 },
endPosition: { x, y: 0 },
});
return {
gizmo,
renderer,
record,
entities,
controller,
patches,
ends,
canvas,
event,
choose: (entity = entities.getById('cctv-gizmo-move-east')) => {
picked = { id: entity };
},
switchCamera: () => {
active = { ...record };
},
destroys: () => destroys,
};
}
for (const initial of [false, true]) {
for (const ending of ['release', 'disable', 'destroy', 'selection']) {
test(`gizmo ${ending} restores initial camera input ${initial} and ends only the pinned record`, (t) => {
const h = setup(t, initial);
h.choose();
h.event('LEFT_DOWN');
assert.equal(h.gizmo.isDragging(), true);
assert.equal(h.controller.enableInputs, false);
if (ending === 'selection') {
h.switchCamera();
h.event('MOUSE_MOVE', 25);
} else {
h.event('MOUSE_MOVE', 25);
assert.equal(h.patches.length, 1);
assert.equal(h.patches[0].pinned, h.record);
assert.ok(Math.abs(h.patches[0].patch.offsetEastM - 15) < 1e-8);
if (ending === 'release') h.event('LEFT_UP');
if (ending === 'disable') h.gizmo.setEnabled(false);
if (ending === 'destroy') h.gizmo.destroy();
}
assert.equal(h.controller.enableInputs, initial);
assert.deepEqual(h.ends, [h.record]);
assert.equal(h.gizmo.isDragging(), false);
h.event('LEFT_UP');
assert.equal(h.ends.length, 1);
if (ending === 'selection') assert.equal(h.patches.length, 0);
});
}
}
test('native gizmo requires the exact owned entity, not a sibling with its ID', (t) => {
const h = setup(t);
const own = h.entities.getById('cctv-gizmo-move-east');
h.choose({ id: own.id });
h.event('LEFT_DOWN');
assert.equal(h.gizmo.isDragging(), false);
h.choose();
h.event('LEFT_DOWN');
assert.equal(h.gizmo.isDragging(), true);
});
test('gizmo builds eight owned handles with pinned native geometry and releases only those', (t) => {
const h = setup(t);
const now = Cesium.JulianDate.now();
assert.equal(h.entities.values.length, 8);
for (const entity of h.entities.values) assert.equal(entity.show, true);
const heading = h.entities
.getById('cctv-gizmo-ring-heading')
.polyline.positions.getValue(now);
assert.equal(heading.length, 97);
assert.ok(
Math.abs(
Cesium.Cartesian3.distance(heading[0], h.record.frustumPositions.mount) -
12,
) < 1e-8,
);
const east = h.entities.getById('cctv-gizmo-move-east');
assert.equal(east.polyline.width.getValue(now), 12);
assert.equal(east.polyline.material.getType(now), 'PolylineArrow');
assert.ok(Math.abs(east.position.getValue(now).y - 19.2) < 1e-8);
const sibling = h.entities.add({ id: 'foreign' });
h.gizmo.destroy();
h.gizmo.destroy();
assert.deepEqual(h.entities.values, [sibling]);
assert.equal(h.destroys(), 1);
});
for (const event of ['pointercancel', 'blur']) {
test(`gizmo ${event} ends a pinned drag and releases the camera`, (t) => {
const h = setup(t);
h.choose();
h.event('LEFT_DOWN');
const target =
event === 'blur' ? h.canvas.ownerDocument.defaultView : h.canvas;
target.dispatchEvent(new Event(event));
assert.equal(h.gizmo.isDragging(), false);
assert.equal(h.controller.enableInputs, true);
assert.deepEqual(h.ends, [h.record]);
h.gizmo.destroy();
target.dispatchEvent(new Event(event));
assert.equal(h.ends.length, 1);
});
}
test('a duplicate down cannot overwrite the original camera-input state', (t) => {
const h = setup(t);
h.choose();
h.event('LEFT_DOWN');
h.event('LEFT_DOWN');
h.event('LEFT_UP');
assert.equal(h.controller.enableInputs, true);
assert.deepEqual(h.ends, [h.record]);
});
test('native gizmo never deletes an unrelated entity with a reserved handle ID', (t) => {
const h = setup(t);
const id = 'cctv-gizmo-move-east';
const own = h.entities.getById(id);
h.entities.remove(own);
const sibling = h.entities.add({ id });
assert.throws(
() => h.renderer.createPoint('move-east', Cesium.Color.RED, 10),
/owned|already|exists/i,
);
assert.equal(h.entities.getById(id), sibling);
h.choose(own);
h.event('LEFT_DOWN');
assert.equal(h.gizmo.isDragging(), false);
h.gizmo.destroy();
assert.equal(h.entities.getById(id), sibling);
});
test('a handle construction failure releases already-created resources', () => {
const handles = new Set();
let destroys = 0;
const renderer = {
createLine(part) {
if (part === 'move-east') throw new Error('ID already owned');
const handle = { part };
handles.add(handle);
return handle;
},
destroy() {
destroys++;
handles.clear();
},
};
assert.throws(() => createCalibrationGizmo({ renderer }), /already owned/);
assert.equal(handles.size, 0);
assert.equal(destroys, 1);
});
-364
View File
@@ -1,364 +0,0 @@
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import { horizonOccluder } from '../../../data/iconOrientation.js';
import { createFrustumVolumePrimitive } from './cesiumViewshed.js';
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../../data/trackingClickGesture.js';
import { createCesiumCctvGizmoRenderer } from './cesiumGizmo.js';
import {
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_COVERAGE_COLOR,
PLANE_OUTLINE_COLOR,
} from '../policy.js';
/** Native CCTV resources and scene operations owned by one viewer. */
export function createCctvCesiumRenderer({ services, state }) {
let viewer = null;
let billboards = null;
let activeTileset = null;
const entities = new Set();
const volumes = new Set();
const listeners = new Set();
const gizmos = new Set();
const color = (value) => (value ? Cesium.Color.clone(value) : undefined);
function ownListener(remove) {
const release = () => {
if (!listeners.delete(release)) return;
remove();
};
listeners.add(release);
return release;
}
function addEntity(options) {
const entity = viewer.entities.add(options);
entities.add(entity);
return entity;
}
function removeEntity(entity) {
if (!entities.delete(entity)) return;
if (viewer.entities.getById(entity.id) === entity)
viewer.entities.remove(entity);
}
function tilesReady() {
if (!activeTileset || activeTileset.isDestroyed?.()) {
activeTileset = null;
const primitives = 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?.()) {
activeTileset = p;
break;
}
}
}
}
if (!activeTileset) return true;
return activeTileset.show !== false && activeTileset.tilesLoaded === true;
}
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' ? state._recordById.get(value) : null;
const ownsCoverageEntity = Boolean(
record?.coverageEntities?.includes(entity),
);
const ownsProjectionEntity =
record?.projection?.planeEntity === entity ||
state._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 : state._recordById.get(directId);
if (!record) return null;
return picked.primitive === billboards ||
picked.primitive === record.billboard
? directId
: null;
}
return {
extractPickedCameraId,
attach(owner) {
if (viewer && viewer !== owner)
throw new Error('CCTV renderer already has an owner');
viewer = owner;
activeTileset = null;
},
get ready() {
return Boolean(viewer && !viewer.isDestroyed?.());
},
cameraCartographic: () => viewer?.camera?.positionCartographic,
following: () => Boolean(viewer?.trackedEntity),
globeVisible: () => viewer?.scene?.globe?.show,
tilesReady,
project: (position, result) =>
viewer.scene.cartesianToCanvasCoordinates(position, result),
distance: (position) =>
geo.cartesian3.distance(viewer.camera.positionWC, position),
horizonTest() {
const occluder = horizonOccluder(viewer.camera);
return (position) => occluder.isPointVisible(position);
},
viewport() {
const canvas = viewer.scene.canvas;
return {
width: canvas.clientWidth || canvas.width || 0,
height: canvas.clientHeight || canvas.height || 0,
};
},
request: () => viewer?.scene?.requestRender?.(),
pick: (screen) => viewer.scene.pick(screen),
onMoveEnd: (fn) => ownListener(viewer.camera.moveEnd.addEventListener(fn)),
onMoveStart: (fn) =>
ownListener(viewer.camera.moveStart.addEventListener(fn)),
bindClick(onClick, options = {}) {
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
bindTrackingClickGesture(
handler,
(event, gesture) => {
if (isTrackingClickGesture(gesture)) onClick(event);
},
options,
);
return ownListener(() => handler.destroy());
},
createGizmoRenderer() {
const gizmo = createCesiumCctvGizmoRenderer(viewer);
gizmos.add(gizmo);
return gizmo;
},
createMarkers() {
if (billboards) throw new Error('CCTV markers already exist');
billboards = new Cesium.BillboardCollection();
viewer.scene.primitives.add(billboards);
services.sprites.registerSpriteCollection('cctv', billboards);
return billboards;
},
createMarker(camera, position) {
return billboards.add({
id: camera.id,
image: CAMERA_ICON,
position,
color: color(IDLE_CAMERA_COLOR),
width: 24,
height: 24,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(350, 1.25, 4_000_000, 0.42),
});
},
setMarkersVisible(value) {
if (billboards) billboards.show = value;
},
restoreOrder: () => services.sprites.restoreSpriteOrder(viewer),
showCredit: () => services.credits?.showOsmCredit?.(viewer, 'cctv'),
hideCredit: () => services.credits?.hideOsmCredit?.(viewer, 'cctv'),
sampleMeshFloorCells: (points, options) =>
services.mesh.sampleMeshFloorCells(viewer?.scene, points, options),
obstructionRay(origin, direction, exclude, far) {
if (!viewer?.scene?.pickFromRay) return undefined;
const hit = viewer.scene.pickFromRay(
new Cesium.Ray(origin, direction),
[billboards, ...exclude].filter(Boolean),
);
return hit?.position &&
geo.cartesian3.distance(origin, hit.position) <= far
? hit
: undefined;
},
createPlaneMaterial(image) {
return new Cesium.ImageMaterialProperty({
image,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
},
createTestPlaneMaterial: () =>
new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
setPlaneImage(runtime, image) {
runtime.planeMaterial.image = image;
},
createPlane(record, runtime, geometry, positions, orientation) {
return addEntity({
id: `cctv-${record.camera.id}-plane`,
properties: { cctvCameraId: record.camera.id },
show: false,
position: positions.capCenter,
orientation: Cesium.Quaternion.clone(orientation),
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: color(PLANE_OUTLINE_COLOR),
},
});
},
updatePlane(runtime, geometry, positions, orientation) {
const entity = runtime.planeEntity;
entity.position = positions.capCenter;
entity.orientation = Cesium.Quaternion.clone(orientation);
if (entity.plane)
entity.plane.dimensions = new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
);
},
setPlaneVisible(runtime, visible) {
if (runtime.planeEntity) runtime.planeEntity.show = visible;
},
removePlane: (runtime) => removeEntity(runtime.planeEntity),
createCoverage(cameraId, positions) {
const created = [];
try {
for (const [role, points] of [
['ray-tl', [positions.mount, positions.tl]],
['ray-tr', [positions.mount, positions.tr]],
['ray-br', [positions.mount, positions.br]],
['ray-bl', [positions.mount, positions.bl]],
[
'cap',
[
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
],
],
]) {
const entity = addEntity({
id: `cctv-${cameraId}-${role}`,
properties: { cctvCameraId: cameraId },
polyline: {
positions: points,
width: 1.2,
material: color(IDLE_COVERAGE_COLOR),
},
});
entity._coverageRole = role === 'cap' ? 'cap' : 'edge';
created.push(entity);
}
return created;
} catch (error) {
for (const entity of created) removeEntity(entity);
throw error;
}
},
updateCoverage(record, positions) {
const lines = record.coverageEntities;
if (!lines || lines.length < 5) return;
for (const [i, role] of ['tl', 'tr', 'br', 'bl'].entries())
lines[i].polyline.positions = [positions.mount, positions[role]];
lines[4].polyline.positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
},
removeCoverageEntity: removeEntity,
styleLine(entity, { visible, width, tint, dashed, depthFail }) {
entity.show = visible;
if (!entity.polyline) return;
entity.polyline.width = width;
entity.polyline.material = dashed
? new Cesium.PolylineDashMaterialProperty({ color: color(tint) })
: color(tint);
entity.polyline.depthFailMaterial = color(depthFail);
},
hideCoverage(record) {
for (const entity of record.coverageEntities || []) entity.show = false;
},
removeCoverage(record) {
for (const entity of record.coverageEntities || []) removeEntity(entity);
},
createVolume(record, tint) {
const primitive = createFrustumVolumePrimitive(
record.frustumPositions,
color(tint),
);
primitive._gevViewshed = record.camera.id;
viewer.scene.primitives.add(primitive);
volumes.add(primitive);
return primitive;
},
removeVolume(primitive) {
if (volumes.delete(primitive)) viewer.scene.primitives.remove(primitive);
},
focus(record, duration) {
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
record.position,
Math.max(40, record.camera.rangeM * 0.36),
),
{
offset: new Cesium.HeadingPitchRange(
geo.math.toRadians(record.camera.headingDeg),
geo.math.toRadians(-22),
Math.max(280, record.camera.rangeM * 1.18),
),
duration: Math.max(0.2, duration || 0),
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
},
);
},
destroy() {
if (!viewer) return;
services.credits?.hideOsmCredit?.(viewer, 'cctv');
for (const remove of listeners) remove();
for (const gizmo of gizmos) gizmo.destroy();
gizmos.clear();
for (const entity of entities) removeEntity(entity);
for (const volume of volumes) viewer.scene.primitives.remove(volume);
volumes.clear();
if (billboards) {
services.sprites.unregisterSpriteCollection?.('cctv', billboards);
viewer.scene.primitives.remove(billboards);
}
viewer = billboards = activeTileset = null;
},
};
}
export function bindCctvWorldClickGesture(handler, onClick, options = {}) {
bindTrackingClickGesture(
handler,
(click, gesture) => {
if (!isTrackingClickGesture(gesture)) return;
onClick(click);
},
options,
);
}
-158
View File
@@ -1,158 +0,0 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import * as Cesium from 'cesium';
import { createCctvCesiumRenderer } from './cesium.js';
import { viewshedColors } from '../../../data/cctvViewshed.js';
function viewer() {
return {
entities: new Cesium.EntityCollection(),
scene: { primitives: new Cesium.PrimitiveCollection() },
camera: { moveStart: new Cesium.Event(), moveEnd: new Cesium.Event() },
isDestroyed: () => false,
};
}
function setup(t) {
const owner = viewer();
const sprites = [];
const state = { _recordById: new Map(), _projectionEntities: [] };
const renderer = createCctvCesiumRenderer({
state,
services: {
sprites: {
registerSpriteCollection: (...args) => sprites.push(['add', ...args]),
unregisterSpriteCollection: (...args) =>
sprites.push(['remove', ...args]),
},
},
});
renderer.attach(owner);
t.after(() => renderer.destroy());
const p = (x, y, z) => new Cesium.Cartesian3(x, y, z);
const positions = {
mount: p(6378137, 0, 10),
tl: p(6378137, 100, 40),
tr: p(6378137, 140, 40),
br: p(6378137, 140, 0),
bl: p(6378137, 100, 0),
capCenter: p(6378137, 120, 20),
};
return { owner, renderer, sprites, positions, state };
}
test('native CCTV releases only its original viewer resources and listeners', (t) => {
const h = setup(t);
const foreignViewer = viewer();
const foreign = foreignViewer.entities.add({ id: 'cctv-a-cap' });
const neighbor = h.owner.entities.add({ id: 'neighbor' });
const markers = h.renderer.createMarkers();
h.renderer.createMarker({ id: 'a' }, h.positions.mount);
h.renderer.createCoverage('a', h.positions);
const record = { camera: { id: 'a' }, frustumPositions: h.positions };
const volume = h.renderer.createVolume(record, viewshedColors(30).fill);
assert.equal(volume.allowPicking, false);
assert.equal(volume.asynchronous, false);
let moves = 0;
h.renderer.onMoveEnd(() => moves++);
h.owner.camera.moveEnd.raiseEvent();
assert.equal(moves, 1);
assert.throws(() => h.renderer.attach(foreignViewer), /already has an owner/);
h.renderer.destroy(foreignViewer);
h.renderer.destroy();
h.owner.camera.moveEnd.raiseEvent();
assert.equal(moves, 1);
assert.deepEqual(h.owner.entities.values, [neighbor]);
assert.equal(h.owner.scene.primitives.length, 0);
assert.equal(foreignViewer.entities.getById(foreign.id), foreign);
assert.deepEqual(h.sprites, [
['add', 'cctv', markers],
['remove', 'cctv', markers],
]);
});
test('coverage construction rolls back partial entities and can retry', (t) => {
const h = setup(t);
const collision = h.owner.entities.add({ id: 'cctv-a-ray-br' });
assert.throws(() => h.renderer.createCoverage('a', h.positions));
assert.deepEqual(h.owner.entities.values, [collision]);
h.owner.entities.remove(collision);
const lines = h.renderer.createCoverage('a', h.positions);
assert.equal(lines.length, 5);
assert.deepEqual(
lines.map((line) => line._coverageRole),
['edge', 'edge', 'edge', 'edge', 'cap'],
);
});
test('replaced native entity identities survive CCTV teardown', (t) => {
const h = setup(t);
const [line] = h.renderer.createCoverage('a', h.positions);
h.owner.entities.remove(line);
const replacement = h.owner.entities.add({ id: line.id });
h.renderer.destroy();
assert.deepEqual(h.owner.entities.values, [replacement]);
});
test('native materials convert portable colours and keep depth-fail and dash policy', (t) => {
const h = setup(t);
const [line] = h.renderer.createCoverage('a', h.positions);
const tint = viewshedColors(210).line;
h.renderer.styleLine(line, {
visible: true,
width: 1.8,
tint,
dashed: true,
depthFail: tint.withAlpha(0.18),
});
const now = Cesium.JulianDate.now();
assert.equal(line.polyline.material.getType(now), 'PolylineDash');
assert.ok(
Cesium.Color.equals(line.polyline.material.getValue(now).color, tint),
);
assert.equal(line.polyline.depthFailMaterial.getValue(now).color.alpha, 0.18);
h.renderer.styleLine(line, {
visible: false,
width: 0.9,
tint,
dashed: false,
});
assert.equal(line.show, false);
assert.equal(line.polyline.material.getType(now), 'Color');
assert.equal(line.polyline.depthFailMaterial, undefined);
});
test('obstruction queries include the owned marker set and enforce finite range', (t) => {
const h = setup(t);
const markers = h.renderer.createMarkers();
const exclude = [{}];
let query;
h.owner.scene.pickFromRay = (ray, exclusions) => {
query = { ray, exclusions };
return {
position: Cesium.Cartesian3.add(
ray.origin,
new Cesium.Cartesian3(0, 20, 0),
new Cesium.Cartesian3(),
),
};
};
assert.equal(
h.renderer.obstructionRay(
h.positions.mount,
Cesium.Cartesian3.UNIT_Y,
exclude,
10,
),
undefined,
);
assert.ok(
h.renderer.obstructionRay(
h.positions.mount,
Cesium.Cartesian3.UNIT_Y,
exclude,
30,
),
);
assert.deepEqual(query.exclusions, [markers, ...exclude]);
assert.ok(query.ray instanceof Cesium.Ray);
});
-193
View File
@@ -1,193 +0,0 @@
import * as Cesium from 'cesium';
import { GIZMO_ID_PREFIX } from '../../../data/cctvGizmo.js';
/** Native handle resources and input, owned by exactly one viewer. */
export function createCesiumCctvGizmoRenderer(
viewer,
{
createEventHandler = (canvas) => new Cesium.ScreenSpaceEventHandler(canvas),
} = {},
) {
const scene = viewer.scene;
const handler = createEventHandler(scene.canvas);
const entities = new Map();
const removeCancelListeners = [];
let destroyed = false;
/** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */
function addEntity(part, options) {
const id = `${GIZMO_ID_PREFIX}${part}`;
const stale = viewer.entities.getById(id);
if (stale && stale !== entities.get(part))
throw new Error(`CCTV handle ID is already owned: ${id}`);
if (stale) viewer.entities.remove(stale);
const entity = viewer.entities.add({ id, show: false, ...options });
entities.set(part, entity);
return entity;
}
function createLine(part, color, width, arrow = false) {
color = Cesium.Color.clone(color);
return addEntity(part, {
...(arrow
? {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 14,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}
: {}),
polyline: {
positions: [],
width,
material: arrow
? new Cesium.PolylineArrowMaterialProperty(color)
: color.withAlpha(0.9),
// Standard gizmo convention: parts behind geometry stay clearly
// visible, just dimmed (a street-level mount buries half the heading
// ring in sloped photogrammetry tiles — smoke-tested 2026-07-05).
depthFailMaterial: color.withAlpha(0.45),
},
});
}
function createPoint(part, color, pixelSize) {
color = Cesium.Color.clone(color);
return addEntity(part, {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
}
/** Extracts a gizmo part name from a pick result, or null. */
function gizmoPartFrom(picked) {
const id = picked?.id?.id ?? picked?.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null;
const part = id.slice(GIZMO_ID_PREFIX.length);
const entity = entities.get(part);
return entity &&
viewer.entities.getById(id) === entity &&
(picked.id === entity || picked.primitive?.id === entity)
? part
: null;
}
function pickGizmoPart(windowPosition) {
// Gizmo primitives render depth-test-free and should be the topmost pick.
// Take the cheap single-result path first: a full drillPick can stall for
// tens of seconds under software GL even when its first result is already
// the gizmo. Retain drillPick for uncommon overlap/fallback cases.
try {
const picked = scene.pick(windowPosition, 14, 14);
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] pick threw:', err?.message || err);
}
}
let results = [];
try {
results = scene.drillPick(windowPosition, 6, 14, 14) || [];
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err);
}
return null;
}
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug(
'[CCTV:gizmo] drillPick @',
windowPosition?.x,
windowPosition?.y,
'→',
JSON.stringify(
results.map((r) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name),
),
),
);
}
for (const picked of results) {
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
}
return null;
}
function pickRay(windowPosition) {
try {
return viewer.camera.getPickRay(windowPosition) || null;
} catch {
return null;
}
}
function setCursor(value) {
if (scene.canvas?.style) scene.canvas.style.cursor = value;
}
return {
createLine,
createPoint,
pickPart: pickGizmoPart,
pickRay,
setCursor,
on(type, listener) {
if (type === 'cancel') {
for (const [target, event] of [
[scene.canvas, 'pointercancel'],
[scene.canvas.ownerDocument?.defaultView, 'blur'],
]) {
if (!target?.addEventListener) continue;
target.addEventListener(event, listener);
removeCancelListeners.push(() =>
target.removeEventListener(event, listener),
);
}
return;
}
handler.setInputAction(
listener,
{
down: Cesium.ScreenSpaceEventType.LEFT_DOWN,
move: Cesium.ScreenSpaceEventType.MOUSE_MOVE,
up: Cesium.ScreenSpaceEventType.LEFT_UP,
}[type],
);
},
suspendCameraInputs() {
const controller = scene.screenSpaceCameraController;
const previous = controller?.enableInputs;
if (controller) controller.enableInputs = false;
let released = false;
return () => {
if (released) return;
released = true;
if (controller) controller.enableInputs = previous;
};
},
destroy() {
if (destroyed) return;
destroyed = true;
handler.destroy();
for (const remove of removeCancelListeners) remove();
removeCancelListeners.length = 0;
for (const entity of entities.values())
if (viewer.entities.getById(entity.id) === entity)
viewer.entities.remove(entity);
entities.clear();
setCursor('');
},
};
}
+133
View File
@@ -0,0 +1,133 @@
// The CCTV meshes on Cesium (behind render/meshes.js): the monitor plane is
// a plane Entity with an image material, the viewshed volume a synchronous
// Primitive of six triangles in a flat translucent colour, both faces drawn,
// never picked. The activation probe's ray pick lives here too, while the
// Cesium engine has no surface.raycast.
import * as Cesium from 'cesium';
import { frustumVolumeGeometryData } from '../../../data/cctvViewshed.js';
import { PLANE_IMAGE_ALPHA } from './style.js';
const toColor = (tint) => new Cesium.Color(...tint.rgba());
/** The frustum volume's Primitive over positions { mount, tl, tr, br, bl }. */
export function createFrustumVolumePrimitive(positions, tint) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: flat,
}),
},
indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)),
});
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(toColor(tint)),
},
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
// The camera is routinely inside or behind a cone.
renderState: { cull: { enabled: false } },
}),
asynchronous: false,
// Clicks fall through to the markers, wedges and plane.
allowPicking: false,
});
}
/**
* @param {{ viewer: Cesium.Viewer }} cesium The engine's Cesium extension.
*/
export function createCctvCesiumMeshes({ viewer: { entities, scene } }) {
const planes = new Map();
const volumes = new Set();
const dimensions = (shape) =>
new Cesium.Cartesian2(shape.halfW * 2, shape.halfH * 2);
return {
createMaterial(image) {
const property = image
? new Cesium.ImageMaterialProperty({
image,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(PLANE_IMAGE_ALPHA),
})
: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE);
return {
property,
setImage(next) {
property.image = next;
},
dispose() {},
};
},
createPlane(cameraId, material, shape, positions, orientation) {
const entity = entities.add({
id: `cctv-${cameraId}-plane`,
show: false,
position: positions.capCenter,
orientation: Cesium.Quaternion.clone(orientation),
plane: {
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
dimensions: dimensions(shape),
material: material.property,
},
});
const plane = {
entity,
get show() {
return entity.show;
},
set show(value) {
entity.show = value;
},
destroy() {
if (!planes.delete(entity)) return;
if (entities.getById(entity.id) === entity) entities.remove(entity);
},
};
planes.set(entity, plane);
return plane;
},
updatePlane({ entity }, shape, positions, orientation) {
entity.position = positions.capCenter;
entity.orientation = Cesium.Quaternion.clone(orientation);
if (entity.plane) entity.plane.dimensions = dimensions(shape);
},
createVolume(positions, tint) {
const primitive = createFrustumVolumePrimitive(positions, tint);
scene.primitives.add(primitive);
volumes.add(primitive);
return {
primitive,
destroy() {
if (volumes.delete(primitive)) scene.primitives.remove(primitive);
},
};
},
// The engine's pick result keeps Cesium's own id: the plane Entity.
planeFromPick: (picked) => planes.get(picked.id) ?? null,
drawnBy: (native) => native.entity ?? native.primitive,
obstructionRay(origin, direction, far, exclude) {
if (!scene.pickFromRay) return undefined;
const hit = scene.pickFromRay(new Cesium.Ray(origin, direction), exclude);
return hit?.position &&
Cesium.Cartesian3.distance(origin, hit.position) <= far
? hit
: undefined;
},
destroy() {
for (const plane of [...planes.values()]) plane.destroy();
for (const primitive of volumes) scene.primitives.remove(primitive);
volumes.clear();
},
};
}
-45
View File
@@ -1,45 +0,0 @@
import * as Cesium from 'cesium';
import { frustumVolumeGeometryData } from '../../../data/cctvViewshed.js';
/**
* Builds the translucent frustum-volume primitive for one camera.
* Synchronous (6 triangles — cheaper than the async geometry pipeline's
* bookkeeping), unlit flat color, both faces visible (the viewer is routinely
* inside or behind a cone), never pickable (clicks fall through to the
* billboard/wireframe/plane, whose pick semantics are established).
* @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData).
* @param {Cesium.Color} color - Per-camera fill color (already alpha'd).
* @returns {Cesium.Primitive}
*/
export function createFrustumVolumePrimitive(positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: flat,
}),
},
indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)),
});
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
renderState: {
cull: { enabled: false },
},
}),
asynchronous: false,
allowPicking: false,
});
}
+922
View File
@@ -0,0 +1,922 @@
// The CCTV cameras on the globe contract (engine.movers, engine.lines,
// engine.input, engine.picker, engine.camera, engine.projector,
// engine.surface, engine.credits), the same on every engine:
// - the camera markers, one sprite set (24 px, shrinking with distance,
// always on top) of plain handles the layer writes; the writes are
// committed once per frame and before every pick;
// - the coverage wedges (four corner rays and the far rectangle) and the
// monitor plane's outline as engine lines, rebuilt when their width, dash
// or depth fail changes;
// - the calibration gizmo: rings and arrow shafts as lines, arrow tips and
// handles in one point set, drags through engine.input;
// - the monitor plane and the viewshed volume behind render/meshes.js, the
// engine-specific part the contract has no primitive for yet.
// The layer (../index.js) keeps the records, the policy and the style
// choices (../rendering.js, ./style.js).
import * as geo from '../../../geo/index.js';
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../../data/trackingClickGesture.js';
import { GIZMO_ID_PREFIX } from '../../../data/cctvGizmo.js';
import { CAMERA_ICON, IDLE_CAMERA_COLOR } from '../policy.js';
import { createCctvMeshes } from './meshes.js';
import {
COVERAGE_DASH,
COVERAGE_INITIAL,
GIZMO_ARROW_TIP_PX,
GIZMO_DEPTH_FAIL_ALPHA,
GIZMO_DRILL_LIMIT,
GIZMO_LINE_ALPHA,
GIZMO_ORDER,
GIZMO_PICK_PX,
GIZMO_POINT,
LINE_ARC,
MARKER_ORDER,
MARKER_SCALE_BY_DISTANCE,
MARKER_SET_ID,
MARKER_SIZE_PX,
PLANE_OUTLINE,
depthFailAlpha,
} from './style.js';
const GIZMO_POINT_SET_ID = `${GIZMO_ID_PREFIX}points`;
const GIZMO_POINT_CAPACITY = 16;
// The tracking click gesture's handler types, as engine.input types.
const CLICK_EVENT_TYPES = Object.freeze({
LEFT_DOWN: 'down',
MOUSE_MOVE: 'move',
LEFT_UP: 'up',
LEFT_CLICK: 'click',
});
const CORNERS = ['tl', 'tr', 'br', 'bl'];
const capRing = (p) => [p.tl, p.tr, p.br, p.bl, p.tl];
const sameDash = (a, b) =>
a === b || (a && b && a.lengthPx === b.lengthPx && a.gapPx === b.gapPx);
const sameColor = (a, b) =>
a.red === b.red &&
a.green === b.green &&
a.blue === b.blue &&
a.alpha === b.alpha;
const gizmoDebug = () =>
typeof window !== 'undefined' && window.__gevGizmoDebug;
const scratchRotation = geo.matrix3.create();
const scratchCorner = geo.cartesian3.create();
/** The plane's outline: its corners from the centre, size and orientation. */
export function planeOutline(shape, positions, orientation) {
const rotation = geo.matrix3.fromQuaternion(orientation, scratchRotation);
const corner = (x, y) =>
geo.cartesian3.add(
geo.matrix3.multiplyByVector(
rotation,
geo.cartesian3.fromElements(
x * shape.halfW,
y * shape.halfH,
0,
scratchCorner,
),
geo.cartesian3.create(),
),
positions.capCenter,
geo.cartesian3.create(),
);
const tl = corner(-1, 1);
return [tl, corner(1, 1), corner(1, -1), corner(-1, -1), tl];
}
/** The tracking click gesture over engine.input (the CCTV world click). */
export function bindCctvWorldClickGesture(handler, onClick, options = {}) {
bindTrackingClickGesture(
handler,
(click, gesture) => {
if (!isTrackingClickGesture(gesture)) return;
onClick(click);
},
options,
);
}
/**
* @param {import('../../../globe/contract.js').GlobeEngine} engine
* @param {{ state: object, services: object, navaraMeshes?: Function }} options
* The layer's state and services; `navaraMeshes` is the Navara meshes
* backend (render/navaraMeshes.js), which the Navara mode passes in.
*/
export function createCctvDisplay(
engine,
{ state, services = {}, navaraMeshes } = {},
) {
if (!engine) throw new TypeError('The CCTV display needs a globe engine');
const meshes = createCctvMeshes(engine, { navaraMeshes });
const markers = [];
const markerHandles = new WeakSet();
const changedMarkers = new Set();
const lines = new Map();
const planes = new Set();
const planeByMesh = new Map();
const gizmos = new Set();
const removers = new Set();
let markerSet = null,
capacity = 0,
markersVisible = true,
dirty = false,
initialized = false,
destroyed = false;
const request = () => engine.render.request('cctv');
const ownListener = (remove) => {
const release = () => {
if (removers.delete(release)) remove();
};
removers.add(release);
return release;
};
// ── Markers ─────────────────────────────────────────────────────────────
// What changed since the last sync: one marker, or every one (null).
const markDirty = (marker = null) => {
if (destroyed) return;
if (marker) changedMarkers.add(marker);
else for (const each of markers) changedMarkers.add(each);
if (dirty) return;
dirty = true;
request();
};
function syncMarkers() {
if (!dirty || !markerSet || destroyed) return;
dirty = false;
markerSet.setCount(markers.length);
for (const marker of changedMarkers)
markerSet.set(marker.index, {
position: marker.position,
show: markersVisible && marker.show,
scale: marker.scale,
color: marker.color.rgba(),
cell: 'camera',
pickId: marker.id,
});
changedMarkers.clear();
markerSet.commit();
}
function allocateMarkers(count) {
if (markerSet && capacity >= count) return;
markerSet?.destroy();
capacity = Math.max(128, count, capacity * 2);
markerSet = engine.movers.createSet({
id: MARKER_SET_ID,
kind: 'sprite',
capacity,
order: MARKER_ORDER,
pickable: true,
depthTest: 'always',
sharpen: true,
sprite: {
sizePx: MARKER_SIZE_PX,
scaleByDistance: [...MARKER_SCALE_BY_DISTANCE],
atlas: { url: CAMERA_ICON, cells: { camera: [0, 0, 1, 1] } },
},
});
markDirty();
}
/** A marker handle: billboard-like fields the layer reads and writes. */
function createMarkerHandle(camera, position) {
const marker = {
id: camera.id,
index: markers.length,
width: MARKER_SIZE_PX,
height: MARKER_SIZE_PX,
};
const fields = {
position: [geo.cartesian3.clone(position), geo.cartesian3.equals],
color: [IDLE_CAMERA_COLOR, sameColor],
scale: [1, Object.is],
show: [true, Object.is],
};
for (const [key, [initial, equal]] of Object.entries(fields)) {
let value = initial;
Object.defineProperty(marker, key, {
enumerable: true,
get: () => value,
set(next) {
if (equal(next, value)) return;
// A caller cannot move a marker by mutating what it passed.
value = key === 'position' ? geo.cartesian3.clone(next) : next;
markDirty(marker);
},
});
}
markerHandles.add(marker);
return marker;
}
const ownsMarker = (handle) => markerHandles.has(handle);
// ── Lines ───────────────────────────────────────────────────────────────
/**
* A line handle with an entity-like face (`show`, `polyline.positions`):
* the engine line is rebuilt when its width, dash or depth fail changes.
*/
function createLineHandle(id, style, positions, options = {}) {
const {
pickId = id,
shown = true,
order = 0,
arrow = false,
extra = {},
} = options;
let current = {
widthPx: style.widthPx,
color: style.color,
depthFailAlpha: style.depthFailAlpha ?? 0,
dash: style.dash ?? null,
};
let points = positions;
let visible = shown;
let line = null;
let destroyed = false;
const build = () => {
line?.destroy();
line = null;
line = engine.lines.createLine({
id,
pickId,
widthPx: current.widthPx,
color: current.color.rgba(),
depthFailAlpha: current.depthFailAlpha,
dash: current.dash,
arc: LINE_ARC,
order,
...(arrow ? { arrow: true } : {}),
});
line.setPositions(points);
line.show(visible);
};
build();
const handle = {
id,
pickId,
...extra,
get line() {
return line;
},
get show() {
return !destroyed && visible;
},
set show(value) {
if (destroyed || visible === Boolean(value)) return;
visible = Boolean(value);
line.show(visible);
},
polyline: {
get positions() {
return points;
},
set positions(value) {
if (destroyed) return;
points = value;
line.setPositions(value);
},
},
/** { visible, widthPx, color, depthFail?, dash? } (./style.js). */
style(next) {
if (destroyed) return;
const wanted = {
widthPx: next.widthPx,
color: next.color,
depthFailAlpha: depthFailAlpha(next.color, next.depthFail),
dash: next.dash ?? null,
};
const rebuild =
wanted.widthPx !== current.widthPx ||
wanted.depthFailAlpha !== current.depthFailAlpha ||
!sameDash(wanted.dash, current.dash);
const recolor = !sameColor(wanted.color, current.color);
current = wanted;
visible = Boolean(next.visible);
if (rebuild) build();
else {
if (recolor) line.setColor(current.color.rgba());
line.show(visible);
}
},
destroy() {
if (destroyed) return;
destroyed = true;
lines.delete(id);
line.destroy();
},
};
lines.set(id, handle);
return handle;
}
/** Whether a pick result is this live, shown line. */
const lineFromPick = (picked) => {
const handle = lines.get(picked?.owner);
return handle && picked.id === handle.pickId && handle.show ? handle : null;
};
// ── Planes ──────────────────────────────────────────────────────────────
function cameraOwnsPlane(cameraId, plane) {
const record = state._recordById?.get(cameraId);
if (!record) return false;
return (
record.projection?.planeEntity === plane ||
(state._projectionEntities ?? []).some(
(runtime) =>
runtime?.cameraId === cameraId && runtime.planeEntity === plane,
)
);
}
/** The engine objects one of the layer's handles draws with. */
function drawnObjects(handle) {
if (!handle) return [];
if (ownsMarker(handle)) return markerSet ? [markerSet] : [];
if (lines.get(handle.id) === handle) return [handle.line];
if (planes.has(handle))
return [handle.outline.line, meshes.drawnBy(handle.mesh)].filter(Boolean);
return [meshes.drawnBy(handle)].filter(Boolean);
}
/** What the layer's exclusion lists name, as the engine's own objects. */
const engineObjects = (handles = []) => [
...new Set(handles.flatMap(drawnObjects)),
];
/**
* The same for a ray pick that skips objects by pick id (Cesium's): every
* marker, as the whole set was, and the listed lines, planes and volumes.
*/
function rayExclusions(handles = []) {
const exclude = markers.map((marker) => marker.id);
for (const handle of handles) {
if (!handle || ownsMarker(handle)) continue;
if (lines.get(handle.id) === handle) exclude.push(handle.pickId);
else if (planes.has(handle))
exclude.push(
handle.outline.pickId,
...[meshes.drawnBy(handle.mesh)].filter(Boolean),
);
else exclude.push(...[meshes.drawnBy(handle)].filter(Boolean));
}
return exclude;
}
// ── Gizmo ───────────────────────────────────────────────────────────────
function createGizmoRenderer() {
const handles = new Map();
const slots = [];
const gizmoRemovers = [];
let points = null;
let destroyed = false;
const canvas = () => engine.host.canvas;
const setCursor = (value) => {
const style = canvas()?.style;
if (style) style.cursor = value;
};
const assertNew = (part) => {
if (destroyed) throw new Error('CCTV gizmo is destroyed');
if (handles.has(part))
throw new Error(
`CCTV handle ID is already owned: ${GIZMO_ID_PREFIX}${part}`,
);
};
const writePoint = (slot) => {
if (destroyed || !points) return;
points.set(slot.index, {
position: slot.position,
color: slot.color.rgba(),
scale: slot.pixelSize / GIZMO_POINT.sizePx,
show: slot.visible,
pickId: slot.pickId,
});
points.commit();
};
/** A point in the gizmo's set: `position`, `show`, `point.pixelSize`. */
function addPoint(part, color, pixelSize) {
if (slots.length >= GIZMO_POINT_CAPACITY)
throw new Error('CCTV gizmo has no room for another handle');
points ??= engine.movers.createSet({
id: GIZMO_POINT_SET_ID,
kind: 'point',
capacity: GIZMO_POINT_CAPACITY,
order: GIZMO_ORDER,
pickable: true,
depthTest: 'always',
point: {
sizePx: GIZMO_POINT.sizePx,
outlinePx: GIZMO_POINT.outlinePx,
outlineColor: [...GIZMO_POINT.outlineColor],
},
});
const slot = {
index: slots.length,
pickId: `${GIZMO_ID_PREFIX}${part}`,
position: geo.cartesian3.create(),
color,
pixelSize,
visible: false,
};
slots.push(slot);
points.setCount(slots.length);
writePoint(slot);
return slot;
}
/** Gives a handle its point's `position` and `point.pixelSize`. */
const withPoint = (handle, slot) =>
Object.defineProperties(handle, {
position: {
enumerable: true,
get: () => slot.position,
set(value) {
slot.position = geo.cartesian3.clone(value);
writePoint(slot);
},
},
point: {
enumerable: true,
value: {
get pixelSize() {
return slot.pixelSize;
},
set pixelSize(value) {
if (value === slot.pixelSize) return;
slot.pixelSize = value;
writePoint(slot);
},
},
},
});
const setPointShown = (slot, value) => {
if (slot.visible === Boolean(value)) return;
slot.visible = Boolean(value);
writePoint(slot);
};
function partFrom(picked) {
const id = picked?.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX))
return null;
const part = id.slice(GIZMO_ID_PREFIX.length);
const handle = handles.get(part);
return handle?.owns(picked.owner) && handle.show ? part : null;
}
return {
createLine(part, color, width, arrow = false) {
assertNew(part);
const tint = arrow ? color : color.withAlpha(GIZMO_LINE_ALPHA);
const line = createLineHandle(
`${GIZMO_ID_PREFIX}${part}`,
{
widthPx: width,
color: tint,
depthFailAlpha: depthFailAlpha(
tint,
color.withAlpha(GIZMO_DEPTH_FAIL_ALPHA),
),
},
[],
{ shown: false, order: GIZMO_ORDER, arrow },
);
if (!arrow) {
const handle = {
id: line.id,
get show() {
return line.show;
},
set show(value) {
line.show = value;
},
polyline: line.polyline,
owns: (owner) => owner === line.id,
destroy: () => line.destroy(),
};
handles.set(part, handle);
return handle;
}
let slot;
try {
slot = addPoint(part, color, GIZMO_ARROW_TIP_PX);
} catch (error) {
line.destroy();
throw error;
}
const handle = withPoint(
{
id: line.id,
get show() {
return line.show;
},
set show(value) {
line.show = value;
setPointShown(slot, value);
},
polyline: line.polyline,
owns: (owner) => owner === line.id || owner === GIZMO_POINT_SET_ID,
destroy: () => line.destroy(),
},
slot,
);
handles.set(part, handle);
return handle;
},
createPoint(part, color, pixelSize) {
assertNew(part);
const slot = addPoint(part, color, pixelSize);
const handle = withPoint(
{
id: slot.pickId,
get show() {
return slot.visible;
},
set show(value) {
setPointShown(slot, value);
},
owns: (owner) => owner === GIZMO_POINT_SET_ID,
destroy() {},
},
slot,
);
handles.set(part, handle);
return handle;
},
// Handles draw over the scene: the single pick usually finds one,
// and a drill covers what overlaps them.
pickPart(position) {
try {
const part = partFrom(
engine.picker.pick(position, GIZMO_PICK_PX, GIZMO_PICK_PX),
);
if (part) return part;
} catch (error) {
if (gizmoDebug())
console.debug('[CCTV:gizmo] pick threw:', error?.message || error);
}
let results = [];
try {
results =
engine.picker.drillPick(
position,
GIZMO_DRILL_LIMIT,
GIZMO_PICK_PX,
GIZMO_PICK_PX,
) || [];
} catch (error) {
if (gizmoDebug())
console.debug(
'[CCTV:gizmo] drillPick threw:',
error?.message || error,
);
return null;
}
if (gizmoDebug())
console.debug(
'[CCTV:gizmo] drillPick @',
position?.x,
position?.y,
'→',
JSON.stringify(results.map((result) => String(result?.id))),
);
for (const picked of results) {
const part = partFrom(picked);
if (part) return part;
}
return null;
},
pickRay(position) {
try {
return engine.camera.pickRay(position) || null;
} catch {
return null;
}
},
setCursor,
on(type, listener) {
if (destroyed) return;
if (type !== 'cancel') {
gizmoRemovers.push(engine.input.on(type, listener));
return;
}
const target = canvas();
for (const [owner, event] of [
[target, 'pointercancel'],
[target?.ownerDocument?.defaultView, 'blur'],
]) {
if (!owner?.addEventListener) continue;
owner.addEventListener(event, listener);
gizmoRemovers.push(() => owner.removeEventListener(event, listener));
}
},
// The contract sets camera inputs; it cannot read them back, so the
// release turns them on again.
suspendCameraInputs() {
engine.input.setCameraInputs(false);
let released = false;
return () => {
if (released) return;
released = true;
engine.input.setCameraInputs(true);
};
},
destroy() {
if (destroyed) return;
destroyed = true;
gizmos.delete(this);
for (const remove of gizmoRemovers.splice(0)) remove();
for (const handle of handles.values()) handle.destroy();
handles.clear();
points?.destroy();
points = null;
setCursor('');
},
};
}
const removeFrame = engine.frames.preRender.addEventListener(syncMarkers);
let credit = false;
return {
attach() {
if (destroyed) throw new Error('CCTV display is destroyed');
initialized = true;
},
get ready() {
return initialized && !destroyed && !engine.isDestroyed();
},
cameraCartographic: () => engine.camera.pose().cartographic,
following: () => Boolean(engine.camera.following()),
globeVisible: () => !engine.maps.photorealActive(),
// Without shown photoreal tiles there is nothing to wait on.
tilesReady: () =>
!engine.maps.photorealActive() || engine.surface.tilesLoaded(),
project: (position, result) =>
engine.projector.worldToWindow(position, result),
distance: (position) =>
geo.cartesian3.distance(engine.camera.livePosition, position),
horizonTest: () => (position) => engine.projector.horizonVisible(position),
viewport: () => engine.host.size(),
request,
pick(position) {
syncMarkers();
return engine.picker.pick(position);
},
/**
* The camera a pick result belongs to: its marker in this layer's set,
* a shown wedge line or plane the camera's record owns; null for
* anything else, a sibling with the same id included.
*/
extractPickedCameraId(picked) {
if (!picked) return null;
if (picked.owner === MARKER_SET_ID)
return typeof picked.id === 'string' &&
state._recordById?.has(picked.id)
? picked.id
: null;
const line = lineFromPick(picked);
if (line?.cameraId !== undefined) {
const record = state._recordById?.get(line.cameraId);
return record?.coverageEntities?.includes(line) ? line.cameraId : null;
}
const plane =
line?.plane ?? planeByMesh.get(meshes.planeFromPick(picked));
if (plane?.show && cameraOwnsPlane(plane.cameraId, plane))
return plane.cameraId;
return null;
},
onMoveEnd: (fn) => ownListener(engine.camera.moveEnd.addEventListener(fn)),
onMoveStart: (fn) =>
ownListener(engine.camera.moveStart.addEventListener(fn)),
bindClick(onClick, options = {}) {
const removes = [];
bindCctvWorldClickGesture(
{
setInputAction(fn, type) {
removes.push(engine.input.on(type, fn));
},
},
onClick,
{ ...options, eventTypes: CLICK_EVENT_TYPES },
);
return ownListener(() => removes.forEach((remove) => remove()));
},
createGizmoRenderer() {
const gizmo = createGizmoRenderer();
gizmos.add(gizmo);
return gizmo;
},
createMarkers() {
if (markerSet) throw new Error('CCTV markers already exist');
allocateMarkers(1);
return markerSet;
},
createMarker(camera, position) {
const marker = createMarkerHandle(camera, position);
markers.push(marker);
allocateMarkers(markers.length);
markDirty(marker);
return marker;
},
setMarkersVisible(value) {
if (markersVisible === Boolean(value)) return;
markersVisible = Boolean(value);
markDirty();
},
restoreOrder: syncMarkers,
showCredit() {
if (credit) return;
credit = true;
services.credits?.showOsmCredit?.(engine, 'cctv');
},
hideCredit() {
if (!credit) return;
credit = false;
services.credits?.hideOsmCredit?.(engine, 'cctv');
},
sampleMeshFloorCells(points, options = {}) {
syncMarkers();
return services.mesh.sampleMeshFloorCells(engine, points, {
...options,
excludeObjects: engineObjects(options.excludeObjects),
});
},
/** The world (tiles) along the activation probe, within `far` metres. */
obstructionRay(origin, direction, exclude, far) {
syncMarkers();
if (typeof engine.surface.raycast === 'function')
return engine.surface.raycast({
origin,
direction,
far,
exclude: [markerSet, ...engineObjects(exclude)].filter(Boolean),
});
return meshes.obstructionRay(
origin,
direction,
far,
rayExclusions(exclude),
);
},
createPlaneMaterial: (image) => meshes.createMaterial(image),
createTestPlaneMaterial: () => meshes.createMaterial(null),
setPlaneImage(runtime, image) {
runtime.planeMaterial?.setImage(image);
},
createPlane(record, runtime, geometry, positions, orientation) {
const cameraId = record.camera.id;
const mesh = meshes.createPlane(
cameraId,
runtime.planeMaterial,
geometry,
positions,
orientation,
);
let outline;
try {
outline = createLineHandle(
`cctv-${cameraId}-plane-outline`,
PLANE_OUTLINE,
planeOutline(geometry, positions, orientation),
{ pickId: mesh.id, shown: false },
);
} catch (error) {
mesh.destroy();
throw error;
}
const plane = {
id: mesh.id,
cameraId,
mesh,
outline,
get show() {
return mesh.show;
},
set show(value) {
mesh.show = value;
outline.show = mesh.show;
},
};
outline.plane = plane;
planes.add(plane);
planeByMesh.set(mesh, plane);
return plane;
},
updatePlane(runtime, geometry, positions, orientation) {
const plane = runtime.planeEntity;
if (!planes.has(plane)) return;
meshes.updatePlane(plane.mesh, geometry, positions, orientation);
plane.outline.polyline.positions = planeOutline(
geometry,
positions,
orientation,
);
},
setPlaneVisible(runtime, visible) {
if (runtime.planeEntity) runtime.planeEntity.show = visible;
},
removePlane(runtime) {
const plane = runtime?.planeEntity;
if (planes.delete(plane)) {
planeByMesh.delete(plane.mesh);
plane.mesh.destroy();
plane.outline.destroy();
}
runtime?.planeMaterial?.dispose();
},
createCoverage(cameraId, positions) {
const created = [];
try {
for (const [role, points] of [
...CORNERS.map((corner) => [
`ray-${corner}`,
[positions.mount, positions[corner]],
]),
['cap', capRing(positions)],
])
created.push(
createLineHandle(
`cctv-${cameraId}-${role}`,
COVERAGE_INITIAL,
points,
{
extra: {
cameraId,
_coverageRole: role === 'cap' ? 'cap' : 'edge',
},
},
),
);
return created;
} catch (error) {
for (const line of created) line.destroy();
throw error;
}
},
updateCoverage(record, positions) {
const coverage = record.coverageEntities;
if (!coverage || coverage.length < 5) return;
CORNERS.forEach((corner, index) => {
coverage[index].polyline.positions = [
positions.mount,
positions[corner],
];
});
coverage[4].polyline.positions = capRing(positions);
},
removeCoverageEntity(handle) {
if (handle && lines.get(handle.id) === handle) handle.destroy();
},
/** The layer's coverage style ({ visible, width, tint, dashed, depthFail? }). */
styleLine(handle, { visible, width, tint, dashed, depthFail }) {
if (lines.get(handle?.id) !== handle) return;
handle.style({
visible,
widthPx: width,
color: tint,
depthFail,
dash: dashed ? COVERAGE_DASH : null,
});
},
hideCoverage(record) {
for (const handle of record.coverageEntities || []) handle.show = false;
},
removeCoverage(record) {
for (const handle of record.coverageEntities || [])
if (lines.get(handle?.id) === handle) handle.destroy();
},
createVolume: (record, tint) =>
meshes.createVolume(record.frustumPositions, tint),
removeVolume: (volume) => volume?.destroy(),
focus(record, duration) {
engine.camera.flyToSphere(
{
center: record.position,
radius: Math.max(40, record.camera.rangeM * 0.36),
},
{
heading: geo.math.toRadians(record.camera.headingDeg),
pitch: geo.math.toRadians(-22),
range: Math.max(280, record.camera.rangeM * 1.18),
duration: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
);
},
destroy() {
if (destroyed) return;
this.hideCredit();
destroyed = true;
initialized = false;
removeFrame();
for (const remove of [...removers]) remove();
for (const gizmo of [...gizmos]) gizmo.destroy();
for (const handle of [...lines.values()]) handle.destroy();
meshes.destroy();
planes.clear();
planeByMesh.clear();
markerSet?.destroy();
markerSet = null;
markers.length = 0;
},
};
}
+648
View File
@@ -0,0 +1,648 @@
// The CCTV display on the engine contract, on the fake engine and on the
// Cesium engine (Cesium's own collections, primitives and entities over a
// stub scene: they draw nothing but hold what the engine writes): the
// marker set and its batched writes, the coverage wedge lines and their
// styles, picks that need this layer's own objects, the monitor plane and
// its outline, the viewshed volume, the activation probe's ray, the world
// click, the credit, focus and teardown.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import { viewshedColors } from '../../../data/cctvViewshed.js';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { CCTV_HARNESSES } from '../../../testSupport/cctvEngines.mjs';
import {
ACTIVE_CAMERA_COLOR,
IDLE_CAMERA_COLOR,
IDLE_COVERAGE_CENTER_MUTED,
IDLE_COVERAGE_COLOR,
IDLE_COVERAGE_EDGE_MUTED,
PLANE_OUTLINE_COLOR,
} from '../policy.js';
import { createCctvDisplay, planeOutline } from './display.js';
const p = (x, y, z) => geo.cartesian3.fromElements(x, y, z);
const POSITIONS = {
mount: p(6378137, 0, 10),
tl: p(6378137, 100, 40),
tr: p(6378137, 140, 40),
br: p(6378137, 140, 0),
bl: p(6378137, 100, 0),
capCenter: p(6378137, 120, 20),
};
const SHAPE = { halfW: 20, halfH: 11.25 };
const near = (actual, expected, label, tolerance = 1e-6) =>
assert.ok(
Math.abs(actual - expected) < tolerance,
`${label}: ${actual} vs ${expected}`,
);
const sameRgba = (actual, color, label) =>
color
.rgba()
.forEach((value, index) =>
near(actual[index], value, `${label}[${index}]`),
);
function setup(makeHarness, t, services = {}) {
const harness = makeHarness();
const state = { _recordById: new Map(), _projectionEntities: [] };
const display = createCctvDisplay(harness.engine, { state, services });
display.attach();
t.after(() => {
display.destroy();
harness.destroy();
});
return { ...harness, display, state };
}
const recordFor = (state, id, extra = {}) => {
const record = { camera: { id }, coverageEntities: [], ...extra };
state._recordById.set(id, record);
return record;
};
test('the display needs a globe engine', () => {
assert.throws(() => createCctvDisplay(null, { state: {} }), TypeError);
});
for (const makeHarness of CCTV_HARNESSES) {
const { name } = makeHarness();
test(`markers are one always-on-top sprite set written once a frame (${name})`, async (t) => {
const h = setup(makeHarness, t);
h.display.createMarkers();
assert.throws(() => h.display.createMarkers(), /already exist/);
const position = p(6378137, 10, 20);
const marker = h.display.createMarker({ id: 'a' }, position);
const other = h.display.createMarker({ id: 'b' }, POSITIONS.mount);
assert.equal(marker.width, 24);
assert.equal(marker.color, IDLE_CAMERA_COLOR);
position.y = 99;
assert.equal(marker.position.y, 10, 'the marker keeps its own copy');
const [listed] = h.engine.movers.list();
assert.deepEqual(
{ id: listed.id, kind: listed.kind, count: listed.count },
{ id: 'cctv', kind: 'sprite', count: 0 },
'nothing is written before the frame',
);
h.frame();
assert.equal(h.engine.movers.list()[0].count, 2);
marker.color = ACTIVE_CAMERA_COLOR;
marker.scale = 1.25;
h.display.setMarkersVisible(false);
h.display.restoreOrder();
await h.settle();
if (h.cesium) {
const billboards = h.primitive('cctv');
const billboard = billboards.get(0);
assert.equal(billboard.width, 24);
assert.equal(billboard.height, 24);
assert.equal(
billboard.disableDepthTestDistance,
Number.POSITIVE_INFINITY,
);
assert.deepEqual(
[
billboard.scaleByDistance.near,
billboard.scaleByDistance.nearValue,
billboard.scaleByDistance.far,
billboard.scaleByDistance.farValue,
],
[350, 1.25, 4_000_000, 0.42],
);
assert.equal(billboard.id, 'a');
assert.equal(billboard.scale, 1.25);
near(billboard.color.alpha, ACTIVE_CAMERA_COLOR.alpha, 'alpha');
assert.equal(billboard.show, false);
assert.equal(billboards.get(1).show, false);
} else {
const set = h.engine.fake.moverSet('cctv');
assert.equal(set.options.order, 0, 'the bottom of the contact sprites');
assert.equal(set.options.depthTest, 'always');
assert.equal(set.options.pickable, true);
assert.equal(set.options.sprite.sizePx, 24);
assert.deepEqual(
[...set.options.sprite.scaleByDistance],
[350, 1.25, 4_000_000, 0.42],
);
assert.equal(set.store.scales[0], 1.25);
assert.equal(set.store.shows[0], 0);
assert.equal(set.store.pickIds[1], 'b');
const commits = set.commits;
marker.color = marker.color.withAlpha(marker.color.alpha);
marker.position = { ...marker.position };
other.show = true;
h.frame();
assert.equal(
h.engine.fake.moverSet('cctv').commits,
commits,
'unchanged writes commit nothing',
);
}
});
test(`coverage is five lines that roll back a partial build (${name})`, (t) => {
const h = setup(makeHarness, t);
const foreign = h.engine.lines.createLine({
id: 'cctv-a-ray-br',
widthPx: 1,
color: [1, 1, 1, 1],
});
assert.throws(() => h.display.createCoverage('a', POSITIONS), /exists/);
assert.deepEqual(
h.engine.lines.list().map(({ id }) => id),
['cctv-a-ray-br'],
);
foreign.destroy();
const lines = h.display.createCoverage('a', POSITIONS);
assert.deepEqual(
lines.map((line) => [line.id, line._coverageRole, line.cameraId]),
[
['cctv-a-ray-tl', 'edge', 'a'],
['cctv-a-ray-tr', 'edge', 'a'],
['cctv-a-ray-br', 'edge', 'a'],
['cctv-a-ray-bl', 'edge', 'a'],
['cctv-a-cap', 'cap', 'a'],
],
);
assert.ok(
lines.every((line) => line.show),
'shown as created',
);
assert.deepEqual(lines[4].polyline.positions, [
POSITIONS.tl,
POSITIONS.tr,
POSITIONS.br,
POSITIONS.bl,
POSITIONS.tl,
]);
const moved = { ...POSITIONS, tl: p(6378137, 90, 45) };
h.display.updateCoverage({ coverageEntities: lines }, moved);
assert.deepEqual(lines[0].polyline.positions, [moved.mount, moved.tl]);
assert.equal(lines[4].polyline.positions[0], moved.tl);
if (h.cesium) {
const drawn = h.primitive('cctv-a-cap');
assert.equal(
drawn.geometryInstances.geometry._arcType,
Cesium.ArcType.GEODESIC,
);
assert.equal(drawn.geometryInstances.geometry._width, 1.2);
} else {
const line = h.lineState('cctv-a-cap');
assert.equal(line.widthPx, 1.2);
assert.equal(line.arc, 'geodesic');
assert.equal(line.pickId, 'cctv-a-cap');
sameRgba(line.color, IDLE_COVERAGE_COLOR, 'idle colour');
}
h.display.hideCoverage({ coverageEntities: lines });
assert.ok(lines.every((line) => !line.show));
h.display.removeCoverageEntity(lines[0]);
h.display.removeCoverage({ coverageEntities: lines });
assert.equal(h.engine.lines.list().length, 0);
});
test(`coverage styles keep Cesium's widths, dash and depth fail (${name})`, (t) => {
const h = setup(makeHarness, t);
const [edge, , , , cap] = h.display.createCoverage('a', POSITIONS);
const hue = viewshedColors(210);
// The layer's styles (../rendering.js) for an active, viewshed-hued
// estimated bearing behind the plane, then idle ones.
const style = (line, input) =>
h.display.styleLine(line, { visible: true, dashed: false, ...input });
style(edge, {
width: 1.8,
tint: hue.lineActive,
dashed: true,
depthFail: hue.line.withAlpha(0.18),
});
if (h.cesium) {
const drawn = h.primitive(edge.id);
assert.equal(drawn.appearance.material.type, 'PolylineDash');
near(
drawn.appearance.material.uniforms.color.alpha,
hue.lineActive.alpha,
'line alpha',
);
near(
drawn.depthFailAppearance.material.uniforms.color.alpha,
0.18,
'depth-fail alpha',
);
assert.equal(drawn.geometryInstances.geometry._width, 1.8);
} else {
const line = h.lineState(edge.id);
assert.deepEqual(line.dash, { kind: 'pixels', lengthPx: 8, gapPx: 8 });
assert.equal(line.widthPx, 1.8);
near(line.depthFailAlpha, 0.18 / hue.lineActive.alpha, 'depth fail');
sameRgba(line.color, hue.lineActive, 'active hue');
}
style(cap, { visible: false, width: 1, tint: IDLE_COVERAGE_CENTER_MUTED });
assert.equal(cap.show, false);
style(edge, { width: 0.9, tint: IDLE_COVERAGE_EDGE_MUTED });
if (h.cesium) {
const drawn = h.primitive(edge.id);
assert.equal(drawn.appearance.material.type, 'Color');
assert.equal(drawn.depthFailAppearance, undefined);
assert.equal(drawn.geometryInstances.geometry._width, 0.9);
} else {
const line = h.lineState(edge.id);
assert.equal(line.dash, null);
assert.equal(line.depthFailAlpha, 0);
assert.equal(line.widthPx, 0.9);
h.engine.fake.resetCalls();
const before = h.engine.fake.line(edge.id);
style(edge, { width: 0.9, tint: hue.line.withAlpha(0.6) });
assert.equal(
h.engine.fake.line(edge.id),
before,
'a colour change keeps the line',
);
sameRgba(h.lineState(edge.id).color, hue.line.withAlpha(0.6), 'idle hue');
}
});
test(`picks need this layer's own markers, lines and planes (${name})`, async (t) => {
const h = setup(makeHarness, t);
const record = recordFor(h.state, 'a');
h.display.createMarkers();
record.billboard = h.display.createMarker({ id: 'a' }, POSITIONS.mount);
h.frame();
await h.settle();
h.scriptPicks({ set: 'cctv', index: 0 });
assert.equal(
h.display.extractPickedCameraId(h.display.pick({ x: 1, y: 1 })),
'a',
);
assert.equal(
h.display.extractPickedCameraId({ id: 'a', owner: 'sibling' }),
null,
'a sibling with the camera id is not this layer',
);
record.coverageEntities = h.display.createCoverage('a', POSITIONS);
h.scriptPicks({ line: 'cctv-a-cap' });
assert.equal(
h.display.extractPickedCameraId(h.display.pick({ x: 1, y: 1 })),
'a',
);
record.coverageEntities[4].show = false;
assert.equal(
h.display.extractPickedCameraId({
id: 'cctv-a-cap',
owner: 'cctv-a-cap',
}),
null,
'a hidden line is not picked',
);
record.coverageEntities[4].show = true;
const stray = h.display.createCoverage('b', POSITIONS);
assert.equal(
h.display.extractPickedCameraId({ id: stray[0].id, owner: stray[0].id }),
null,
'a line no record owns is not a camera',
);
h.display.removeCoverageEntity(record.coverageEntities[4]);
assert.equal(
h.display.extractPickedCameraId({
id: 'cctv-a-cap',
owner: 'cctv-a-cap',
}),
null,
);
assert.equal(h.display.extractPickedCameraId(undefined), null);
});
test(`the monitor plane, its outline and material (${name})`, (t) => {
const h = setup(makeHarness, t);
const record = recordFor(h.state, 'a');
const orientation = geo.quaternion.fromAxisAngle(
geo.cartesian3.normalize(p(1, 2, 3), geo.cartesian3.create()),
0.75,
geo.quaternion.create(),
);
const runtime = { cameraId: 'a', planeMaterial: null };
runtime.planeMaterial = h.display.createPlaneMaterial({ width: 8 });
const plane = h.display.createPlane(
{ camera: { id: 'a' } },
runtime,
SHAPE,
POSITIONS,
orientation,
);
runtime.planeEntity = plane;
assert.equal(plane.show, false);
assert.equal(plane.outline.show, false);
h.display.setPlaneVisible(runtime, true);
assert.equal(plane.outline.show, true);
const corners = plane.outline.polyline.positions;
const rotation = geo.matrix3.fromQuaternion(
orientation,
geo.matrix3.create(),
);
for (const [index, [x, y]] of [
[-1, 1],
[1, 1],
[1, -1],
[-1, -1],
[-1, 1],
].entries()) {
const expected = geo.cartesian3.add(
geo.matrix3.multiplyByVector(
rotation,
p(x * SHAPE.halfW, y * SHAPE.halfH, 0),
geo.cartesian3.create(),
),
POSITIONS.capCenter,
geo.cartesian3.create(),
);
near(geo.cartesian3.distance(corners[index], expected), 0, 'corner');
}
if (h.cesium) {
const entity = h.viewer.entities.getById('cctv-a-plane');
const now = Cesium.JulianDate.now();
assert.equal(entity.show, true);
assert.deepEqual(
entity.plane.dimensions.getValue(now),
new Cesium.Cartesian2(40, 22.5),
);
assert.equal(entity.plane.outline, undefined, 'the outline is a line');
assert.equal(entity.plane.material.color.getValue(now).alpha, 0.95);
assert.equal(entity.plane.material.transparent.getValue(now), true);
h.scriptPicks({ native: { id: entity, primitive: {} } });
assert.equal(
h.display.extractPickedCameraId(h.display.pick({ x: 1, y: 1 })),
null,
'a plane no record owns is not a camera',
);
record.projection = runtime;
assert.equal(
h.display.extractPickedCameraId(h.display.pick({ x: 1, y: 1 })),
'a',
);
} else {
const outline = h.lineState('cctv-a-plane-outline');
assert.equal(outline.widthPx, 1);
assert.equal(outline.pickId, 'cctv-a-plane');
sameRgba(outline.color, PLANE_OUTLINE_COLOR, 'outline colour');
record.projection = runtime;
}
h.scriptPicks({ line: 'cctv-a-plane-outline' });
assert.equal(
h.display.extractPickedCameraId(h.display.pick({ x: 1, y: 1 })),
'a',
'the outline picks its camera',
);
const moved = { ...POSITIONS, capCenter: p(6378140, 120, 20) };
h.display.updatePlane(runtime, SHAPE, moved, orientation);
near(
plane.outline.polyline.positions[0].x - corners[0].x,
3,
'the outline moves with the plane',
);
const material = runtime.planeMaterial;
h.display.removePlane(runtime);
assert.equal(material.disposed, true);
assert.equal(h.engine.lines.list().length, 0);
if (h.cesium) assert.equal(h.viewer.entities.values.length, 0);
});
test(`the viewshed volume and the activation probe's ray (${name})`, (t) => {
const mesh = [];
const h = setup(makeHarness, t, {
mesh: { sampleMeshFloorCells: (...args) => mesh.push(args) },
});
const record = recordFor(h.state, 'a', { frustumPositions: POSITIONS });
const markerSet = h.display.createMarkers();
record.billboard = h.display.createMarker({ id: 'a' }, POSITIONS.mount);
h.display.createMarker({ id: 'b' }, POSITIONS.tl);
record.coverageEntities = h.display.createCoverage('a', POSITIONS);
const volume = h.display.createVolume(record, viewshedColors(30).fill);
h.display.sampleMeshFloorCells([{ lat: 0, lon: 0 }], {
excludeObjects: [...record.coverageEntities, record.billboard],
});
const [[target, , { excludeObjects }]] = mesh;
assert.equal(target, h.engine);
assert.ok(excludeObjects.includes(markerSet), 'the marker set');
assert.ok(
record.coverageEntities.every(({ line }) =>
excludeObjects.includes(line),
),
'the engine lines',
);
assert.equal(excludeObjects.length, 6);
const direction = p(0, 1, 0);
if (h.cesium) {
const primitive = volume.native.primitive;
assert.equal(primitive.allowPicking, false);
assert.equal(primitive.asynchronous, false);
assert.ok(h.viewer.scene.primitives.contains(primitive));
let query;
h.viewer.scene.pickFromRay = (ray, exclusions) => {
query = { ray, exclusions };
return {
position: Cesium.Cartesian3.add(
ray.origin,
new Cesium.Cartesian3(0, 20, 0),
new Cesium.Cartesian3(),
),
};
};
const exclude = [...record.coverageEntities, volume];
assert.equal(
h.display.obstructionRay(POSITIONS.mount, direction, exclude, 10),
undefined,
'a hit past the range is no obstruction',
);
assert.ok(
h.display.obstructionRay(POSITIONS.mount, direction, exclude, 30),
);
assert.ok(query.ray instanceof Cesium.Ray);
assert.deepEqual(
query.exclusions.slice(0, 2),
['a', 'b'],
'every marker',
);
assert.ok(query.exclusions.includes('cctv-a-ray-tl'));
assert.ok(query.exclusions.includes(primitive));
h.display.removeVolume(volume);
assert.ok(!h.viewer.scene.primitives.contains(primitive));
} else {
assert.equal(
h.display.obstructionRay(POSITIONS.mount, direction, [], 30),
undefined,
'no ray pick on an engine without one',
);
let ray;
h.engine.surface.raycast = (query) => {
ray = query;
return { position: POSITIONS.tl, distance: 5 };
};
assert.ok(
h.display.obstructionRay(
POSITIONS.mount,
direction,
record.coverageEntities,
30,
),
);
assert.equal(ray.far, 30);
assert.equal(ray.exclude.length, 6);
assert.equal(volume.positions, POSITIONS);
}
});
test(`a clean click reaches the layer; a drag does not (${name})`, (t) => {
const h = setup(makeHarness, t);
const clicks = [];
const moves = [];
const remove = h.display.bindClick((click) => clicks.push(click.position), {
onMouseMove: (movement) => moves.push(movement.endPosition),
});
const press = (to) => {
h.fire('down', { position: { x: 10, y: 10 } });
h.fire('move', { startPosition: { x: 10, y: 10 }, endPosition: to });
h.fire('up', { position: to });
h.fire('click', { position: to });
};
press({ x: 12, y: 11 });
press({ x: 60, y: 10 });
assert.equal(clicks.length, 1);
assert.deepEqual({ ...clicks[0] }, { x: 12, y: 11 });
assert.equal(moves.length, 2);
remove();
press({ x: 12, y: 11 });
assert.equal(clicks.length, 1);
});
test(`focus, credit and teardown (${name})`, (t) => {
const credits = [];
const h = setup(makeHarness, t, {
credits: {
showOsmCredit: (...args) => credits.push(['show', ...args]),
hideOsmCredit: (...args) => credits.push(['hide', ...args]),
},
});
let flight;
h.engine.camera.flyToSphere = (sphere, options) => {
flight = { sphere, options };
};
h.display.focus(
{ position: POSITIONS.mount, camera: { headingDeg: 84, rangeM: 126 } },
0.1,
);
assert.deepEqual(flight, {
sphere: { center: POSITIONS.mount, radius: 45.36 },
options: {
heading: (84 * Math.PI) / 180,
pitch: (-22 * Math.PI) / 180,
range: 280,
duration: 0.2,
easing: 'cubicInOut',
},
});
h.display.showCredit();
h.display.showCredit();
assert.deepEqual(credits, [['show', h.engine, 'cctv']]);
let moves = 0;
h.display.onMoveEnd(() => moves++);
h.engine.camera.moveEnd.raiseEvent();
assert.equal(moves, 1);
h.display.createMarkers();
h.display.createMarker({ id: 'a' }, POSITIONS.mount);
h.display.createCoverage('a', POSITIONS);
const runtime = { planeMaterial: h.display.createPlaneMaterial(null) };
runtime.planeEntity = h.display.createPlane(
{ camera: { id: 'a' } },
runtime,
SHAPE,
POSITIONS,
{ x: 0, y: 0, z: 0, w: 1 },
);
h.display.createVolume(
{ frustumPositions: POSITIONS },
viewshedColors(1).fill,
);
h.display.createGizmoRenderer().createPoint('range', IDLE_CAMERA_COLOR, 10);
assert.equal(h.display.ready, true);
h.display.destroy();
h.display.destroy();
assert.equal(h.display.ready, false);
h.engine.camera.moveEnd.raiseEvent();
assert.equal(moves, 1);
assert.deepEqual(credits.at(-1), ['hide', h.engine, 'cctv']);
assert.equal(h.engine.lines.list().length, 0);
assert.equal(h.engine.movers.list().length, 0);
if (h.cesium) {
assert.equal(h.viewer.entities.values.length, 0);
const drawn = [];
for (let i = 0; i < h.viewer.scene.primitives.length; i++)
drawn.push(h.viewer.scene.primitives.get(i));
assert.ok(
drawn.every((primitive) => !(primitive instanceof Cesium.Primitive)),
'the volume is gone',
);
}
});
}
test('the plane outline closes on its first corner', () => {
const corners = planeOutline(
{ halfW: 2, halfH: 1 },
{ capCenter: p(10, 0, 0) },
{ x: 0, y: 0, z: 0, w: 1 },
);
assert.equal(corners.length, 5);
assert.equal(corners[0], corners[4]);
assert.deepEqual({ ...corners[0] }, { x: 8, y: 1, z: 0 });
assert.deepEqual({ ...corners[2] }, { x: 12, y: -1, z: 0 });
});
test('on Navara the display draws its plane through the backend it is given', async (t) => {
const { createCctvNavaraMeshes } = await import('./navaraMeshes.js');
const engine = createFakeEngine({ kind: 'navara' });
const descriptors = new Map();
const view = {
registerMesh: (key, value) => descriptors.set(key, value),
addMesh(config) {
const key = Object.keys(config)[0];
const desc = new (descriptors.get(key))(view, {}, config);
desc.createMesh();
return { delete: () => desc.onDestroy() };
},
};
class MeshDesc {
onDestroy() {}
}
const pickers = new Set();
engine.picker.registerMeshPicker = (pick) => {
pickers.add(pick);
return () => pickers.delete(pick);
};
engine.extensions = { navara: { view, MeshDesc } };
const state = { _recordById: new Map(), _projectionEntities: [] };
const display = createCctvDisplay(engine, {
state,
navaraMeshes: createCctvNavaraMeshes,
});
t.after(() => engine.destroy());
display.attach();
const record = recordFor(state, 'a');
const runtime = { planeMaterial: display.createPlaneMaterial(null) };
runtime.planeEntity = display.createPlane(
{ camera: { id: 'a' } },
runtime,
SHAPE,
POSITIONS,
{ x: 0, y: 0, z: 0, w: 1 },
);
record.projection = runtime;
assert.equal(pickers.size, 1);
const picked = { id: 'cctv-a-plane', owner: 'cctv-a-plane' };
assert.equal(display.extractPickedCameraId(picked), null, 'hidden');
display.setPlaneVisible(runtime, true);
assert.equal(runtime.planeEntity.mesh.native.group.visible, true);
assert.equal(display.extractPickedCameraId(picked), 'a');
display.destroy();
assert.equal(pickers.size, 0);
});
@@ -0,0 +1,369 @@
// The CCTV calibration gizmo drawn by the display, on the fake engine and
// on the Cesium engine: drags through engine.input that patch only the
// pinned record and hand the camera back, picks that need the gizmo's own
// handles, the handles' geometry, hover sizes, cancellation and teardown.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../../geo/index.js';
import { createCalibrationGizmo } from '../../../data/cctvGizmo.js';
import { CCTV_HARNESSES } from '../../../testSupport/cctvEngines.mjs';
import { IDLE_CAMERA_COLOR } from '../policy.js';
import { createCctvDisplay } from './display.js';
const p = (x, y, z) => geo.cartesian3.fromElements(x, y, z);
const near = (actual, expected, label) =>
assert.ok(Math.abs(actual - expected) < 1e-5, `${label}: ${actual}`);
function setup(makeHarness, t) {
const harness = makeHarness();
const display = createCctvDisplay(harness.engine, { state: {} });
display.attach();
// A fixed ray per screen x: along -X from 100 m over the mount.
harness.engine.camera.pickRay = ({ x }) => ({
origin: p(6378237, x, 0),
direction: p(-1, 0, 0),
});
const renderer = display.createGizmoRenderer();
const record = {
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 100,
calibration: {
headingDeg: 0,
pitchDeg: 0,
offsetEastM: 0,
offsetNorthM: 0,
heightM: 0,
rangeScale: 1,
fovDeg: 0,
},
basePose: { rangeM: 100, fovDeg: 60 },
},
frustumGeometry: { rangeM: 100 },
frustumPositions: {
mount: p(6378137, 0, 0),
capCenter: p(6378137, 0, 100),
tl: p(6378150, -20, 100),
tr: p(6378150, 20, 100),
bl: p(6378124, -20, 100),
br: p(6378124, 20, 100),
},
};
let active = record;
const patches = [];
const ends = [];
const gizmo = createCalibrationGizmo({
renderer,
getActiveRecord: () => active,
applyPatch: (patch, pinned) => patches.push({ patch, pinned }),
endPatch: (pinned) => ends.push(pinned),
});
t.after(() => {
gizmo.destroy();
display.destroy();
harness.destroy();
});
gizmo.setEnabled(true);
const event = (type, x = 10) =>
harness.fire(type, {
position: { x, y: 0 },
startPosition: { x, y: 0 },
endPosition: { x, y: 0 },
});
return {
...harness,
display,
gizmo,
renderer,
record,
patches,
ends,
event,
choose: (target = { line: 'cctv-gizmo-move-east' }) =>
harness.scriptPicks(target),
switchCamera: () => {
active = { ...record };
},
};
}
for (const makeHarness of CCTV_HARNESSES) {
const { name } = makeHarness();
for (const ending of ['release', 'disable', 'destroy', 'selection']) {
test(`a gizmo ${ending} hands the camera back and ends only the pinned record (${name})`, (t) => {
const h = setup(makeHarness, t);
h.choose();
h.event('down');
assert.equal(h.gizmo.isDragging(), true);
assert.deepEqual(h.cameraInputs(), [false]);
if (ending === 'selection') {
h.switchCamera();
h.event('move', 25);
} else {
h.event('move', 25);
assert.equal(h.patches.length, 1);
assert.equal(h.patches[0].pinned, h.record);
assert.ok(Math.abs(h.patches[0].patch.offsetEastM - 15) < 1e-8);
if (ending === 'release') h.event('up');
if (ending === 'disable') h.gizmo.setEnabled(false);
if (ending === 'destroy') h.gizmo.destroy();
}
assert.deepEqual(h.cameraInputs(), [false, true]);
assert.deepEqual(h.ends, [h.record]);
assert.equal(h.gizmo.isDragging(), false);
h.event('up');
assert.equal(h.ends.length, 1);
if (ending === 'selection') assert.equal(h.patches.length, 0);
});
}
test(`the gizmo needs its own handle, not a sibling with its id (${name})`, (t) => {
const h = setup(makeHarness, t);
const sibling = h.engine.lines.createLine({
id: 'sibling',
pickId: 'cctv-gizmo-move-east',
widthPx: 1,
color: [1, 1, 1, 1],
});
sibling.setPositions([p(6378137, 0, 0), p(6378137, 1, 0)]);
h.choose({ line: 'sibling' });
h.event('down');
assert.equal(h.gizmo.isDragging(), false);
h.choose({ set: 'cctv-gizmo-points', index: 0 });
h.event('down');
assert.equal(h.gizmo.isDragging(), true, 'an arrow tip drags its arrow');
sibling.destroy();
});
test(`the gizmo draws eight handles and releases only those (${name})`, (t) => {
const h = setup(makeHarness, t);
const foreign = h.engine.lines.createLine({
id: 'foreign',
widthPx: 1,
color: [1, 1, 1, 1],
});
const lines = h.engine.lines.list().filter(({ id }) => id !== 'foreign');
assert.deepEqual(
lines.map(({ id }) => id),
[
'cctv-gizmo-ring-heading',
'cctv-gizmo-ring-pitch',
'cctv-gizmo-move-east',
'cctv-gizmo-move-north',
'cctv-gizmo-move-up',
],
);
assert.ok(lines.every(({ shown }) => shown));
assert.equal(lines[0].points, 97);
const [points] = h.engine.movers.list();
assert.deepEqual(
{ id: points.id, kind: points.kind, count: points.count },
{ id: 'cctv-gizmo-points', kind: 'point', count: 6 },
);
if (h.cesium) {
const ring = h.primitive('cctv-gizmo-ring-heading');
const first = ring.geometryInstances.geometry._positions[0];
assert.ok(
Math.abs(
geo.cartesian3.distance(first, h.record.frustumPositions.mount) - 12,
) < 1e-6,
);
const east = h.primitive('cctv-gizmo-move-east');
assert.equal(east.geometryInstances.geometry._width, 12);
assert.equal(east.appearance.material.type, 'PolylineArrow');
assert.ok(
Math.abs(
east.depthFailAppearance.material.uniforms.color.alpha - 0.45,
) < 1e-6,
);
const heading = h.primitive('cctv-gizmo-ring-heading');
assert.ok(
Math.abs(heading.appearance.material.uniforms.color.alpha - 0.9) < 1e-6,
);
assert.ok(
Math.abs(
heading.depthFailAppearance.material.uniforms.color.alpha - 0.45,
) < 1e-6,
);
const tips = h.primitive('cctv-gizmo-points');
const tip = tips.get(0);
near(tip.pixelSize, 14, 'tip size');
assert.equal(tip.outlineWidth, 2);
assert.ok(Math.abs(tip.outlineColor.alpha - 0.7) < 1e-6);
assert.equal(tip.disableDepthTestDistance, Number.POSITIVE_INFINITY);
assert.ok(Math.abs(tip.position.y - 19.2) < 1e-6);
near(tips.get(3).pixelSize, 13, 'range handle size');
} else {
const ring = h.engine.fake.line('cctv-gizmo-ring-heading');
assert.ok(
Math.abs(
geo.cartesian3.distance(
p(...ring.positions.slice(0, 3)),
h.record.frustumPositions.mount,
) - 12,
) < 1e-6,
);
const east = h.lineState('cctv-gizmo-move-east');
assert.equal(east.widthPx, 12);
assert.equal(east.arrow, true);
assert.ok(Math.abs(east.depthFailAlpha - 0.45) < 1e-6);
const heading = h.lineState('cctv-gizmo-ring-heading');
assert.ok(Math.abs(heading.color[3] - 0.9) < 1e-6);
assert.ok(Math.abs(heading.depthFailAlpha - 0.5) < 1e-6);
const set = h.engine.fake.moverSet('cctv-gizmo-points');
assert.equal(set.options.depthTest, 'always');
assert.equal(set.options.order, 100);
assert.deepEqual(set.options.point.outlineColor, [0, 0, 0, 0.7]);
assert.equal(set.options.point.outlinePx, 2);
assert.equal(set.store.pickIds[0], 'cctv-gizmo-move-east');
assert.ok(Math.abs(set.store.positions[1] - 19.2) < 1e-6);
near(set.store.scales[0] * set.options.point.sizePx, 14, 'tip size');
near(set.store.scales[3] * set.options.point.sizePx, 13, 'range size');
}
h.gizmo.destroy();
h.gizmo.destroy();
assert.deepEqual(
h.engine.lines.list().map(({ id }) => id),
['foreign'],
);
assert.equal(h.engine.movers.list().length, 0);
assert.equal(h.canvas.style.cursor, '');
foreign.destroy();
});
test(`hovering a handle grows it and shows the grab cursor (${name})`, (t) => {
const h = setup(makeHarness, t);
h.choose({ set: 'cctv-gizmo-points', index: 3 });
h.event('move');
assert.equal(h.canvas.style.cursor, 'grab');
const size = (index) =>
h.cesium
? h.primitive('cctv-gizmo-points').get(index).pixelSize
: h.engine.fake.moverSet('cctv-gizmo-points').store.scales[index] * 10;
near(size(3), 17, 'the hovered range handle');
near(size(0), 10, 'an arrow tip takes the handle size');
near(size(4), 10, 'a field-of-view handle');
});
for (const cancel of ['pointercancel', 'blur']) {
test(`a ${cancel} ends a pinned drag and releases the camera (${name})`, (t) => {
const h = setup(makeHarness, t);
h.choose();
h.event('down');
const target =
cancel === 'blur' ? h.canvas.ownerDocument.defaultView : h.canvas;
target.dispatchEvent(new Event(cancel));
assert.equal(h.gizmo.isDragging(), false);
assert.deepEqual(h.cameraInputs(), [false, true]);
assert.deepEqual(h.ends, [h.record]);
h.gizmo.destroy();
target.dispatchEvent(new Event(cancel));
assert.equal(h.ends.length, 1);
});
}
test(`a second down cannot start another drag (${name})`, (t) => {
const h = setup(makeHarness, t);
h.choose();
h.event('down');
h.event('down');
h.event('up');
assert.deepEqual(h.cameraInputs(), [false, true]);
assert.deepEqual(h.ends, [h.record]);
});
test(`a handle id another owner holds stops the gizmo cleanly (${name})`, (t) => {
const h = setup(makeHarness, t);
assert.throws(
() => h.renderer.createPoint('move-east', IDLE_CAMERA_COLOR, 10),
/already owned/,
);
h.gizmo.destroy();
const sibling = h.engine.lines.createLine({
id: 'cctv-gizmo-move-east',
widthPx: 1,
color: [1, 1, 1, 1],
});
assert.throws(
() =>
createCalibrationGizmo({
renderer: h.display.createGizmoRenderer(),
getActiveRecord: () => null,
applyPatch() {},
endPatch() {},
}),
/already exists/,
);
assert.deepEqual(
h.engine.lines.list().map(({ id }) => id),
['cctv-gizmo-move-east'],
);
assert.equal(h.engine.movers.list().length, 0);
sibling.destroy();
});
test(`a destroyed gizmo drops its input and listeners (${name})`, (t) => {
const h = setup(makeHarness, t);
let cancels = 0;
let moves = 0;
h.renderer.on('cancel', () => cancels++);
h.renderer.on('move', () => moves++);
h.canvas.dispatchEvent(new Event('pointercancel'));
h.canvas.ownerDocument.defaultView.dispatchEvent(new Event('blur'));
h.event('move');
assert.equal(cancels, 2);
assert.equal(moves, 1);
h.renderer.setCursor('grabbing');
h.gizmo.destroy();
h.canvas.dispatchEvent(new Event('pointercancel'));
h.event('move');
assert.equal(cancels, 2);
assert.equal(moves, 1);
assert.equal(h.canvas.style.cursor, '');
assert.throws(
() => h.renderer.createPoint('new', IDLE_CAMERA_COLOR, 10),
/destroyed/,
);
});
}
test("an arrow's shaft goes when its tip cannot be drawn", (t) => {
const [makeHarness] = CCTV_HARNESSES;
const harness = makeHarness();
t.after(() => harness.destroy());
const display = createCctvDisplay(harness.engine, { state: {} });
harness.engine.movers.createSet = () => {
throw new Error('allocation failed');
};
const renderer = display.createGizmoRenderer();
const color = { withAlpha: () => color, rgba: () => [1, 1, 1, 1], alpha: 1 };
assert.throws(
() => renderer.createLine('east', color, 8, true),
/allocation failed/,
);
assert.equal(harness.engine.lines.list().length, 0);
display.destroy();
});
test('a handle construction failure releases already-created resources', () => {
const handles = new Set();
let destroys = 0;
const renderer = {
createLine(part) {
if (part === 'move-east') throw new Error('ID already owned');
const handle = { part };
handles.add(handle);
return handle;
},
destroy() {
destroys++;
handles.clear();
},
};
assert.throws(() => createCalibrationGizmo({ renderer }), /already owned/);
assert.equal(handles.size, 0);
assert.equal(destroys, 1);
});
+171
View File
@@ -0,0 +1,171 @@
// The CCTV meshes the globe contract has no primitive for yet, behind one
// seam: the monitor plane (a quad textured with a live canvas or video) and
// the viewshed volume (the frustum pyramid in a flat translucent colour,
// both faces, not pickable). Movers draw a glTF per instance at a uniform
// scale and lines draw strips, so neither carries a texture that changes
// every frame or a pyramid whose corners move independently.
//
// This is the only CCTV module that reads engine.extensions. Each engine
// draws through its own backend: render/cesiumMeshes.js (Cesium entities and
// primitives) and render/navaraMeshes.js (three meshes in Navara's view),
// which the Navara mode loads and passes in, as Navara modules reach the app
// only through its import(). The handles here keep what the layer asked
// for, so an engine with no backend (the fake engine) draws nothing and
// still answers. The plane's outline is an engine line, drawn by the display.
import { createCctvCesiumMeshes } from './cesiumMeshes.js';
/**
* @param {import('../../../globe/contract.js').GlobeEngine} engine
* @param {{ navaraMeshes?: (engine: object, navara: object) => object }} [options]
* The Navara backend's factory (render/navaraMeshes.js).
*/
export function createCctvMeshes(engine, { navaraMeshes } = {}) {
const cesium = engine.extensions?.cesium;
const navara = engine.extensions?.navara;
const materials = new Set();
const planes = new Set();
const volumes = new Set();
const planeByNative = new Map();
const backend = cesium
? createCctvCesiumMeshes(cesium)
: navara && navaraMeshes
? navaraMeshes(engine, navara)
: null;
let destroyed = false;
const alive = () => {
if (destroyed) throw new Error('CCTV meshes are destroyed');
};
return {
/** A plane material showing `image` (a canvas or video), or plain white. */
createMaterial(image) {
alive();
const material = {
image: image ?? null,
native: null,
disposed: false,
setImage(next) {
if (material.disposed) return;
material.image = next;
material.native?.setImage(next);
},
dispose() {
if (material.disposed) return;
material.disposed = true;
materials.delete(material);
material.native?.dispose();
material.native = null;
},
};
material.native = backend?.createMaterial(material.image) ?? null;
materials.add(material);
return material;
},
/**
* The monitor plane, hidden: `shape` { halfW, halfH } metres, centred on
* positions.capCenter, its local +Z along `orientation`'s normal.
*/
createPlane(cameraId, material, shape, positions, orientation) {
alive();
if (!materials.has(material))
throw new Error('CCTV plane material is not owned');
const plane = {
id: `cctv-${cameraId}-plane`,
cameraId,
material,
shape,
positions,
orientation,
visible: false,
native: null,
destroyed: false,
get show() {
return !plane.destroyed && plane.visible;
},
set show(value) {
if (plane.destroyed) return;
plane.visible = Boolean(value);
if (plane.native) plane.native.show = plane.visible;
},
destroy() {
if (plane.destroyed) return;
plane.destroyed = true;
planes.delete(plane);
if (plane.native) {
planeByNative.delete(plane.native);
plane.native.destroy();
plane.native = null;
}
},
};
if (backend) {
plane.native = backend.createPlane(
cameraId,
material.native,
shape,
positions,
orientation,
);
planeByNative.set(plane.native, plane);
}
planes.add(plane);
return plane;
},
updatePlane(plane, shape, positions, orientation) {
if (!planes.has(plane)) return;
Object.assign(plane, { shape, positions, orientation });
if (plane.native)
backend.updatePlane(plane.native, shape, positions, orientation);
},
/** The viewshed volume over positions { mount, tl, tr, br, bl }. */
createVolume(positions, tint) {
alive();
const volume = {
positions,
tint,
native: null,
destroyed: false,
destroy() {
if (volume.destroyed) return;
volume.destroyed = true;
volumes.delete(volume);
volume.native?.destroy();
volume.native = null;
},
};
volume.native = backend?.createVolume(positions, tint) ?? null;
volumes.add(volume);
return volume;
},
/** The live, shown plane an engine pick result names, or null. */
planeFromPick(picked) {
if (!backend || !picked) return null;
const plane = planeByNative.get(backend.planeFromPick(picked));
return plane?.show ? plane : null;
},
/** What draws a plane or volume, for an engine `exclude` list. */
drawnBy(handle) {
return backend && handle?.native
? backend.drawnBy(handle.native)
: undefined;
},
/**
* The first scene object along a ray within `far` metres, skipping
* `exclude` (pick ids and drawn objects), on an engine without
* surface.raycast; undefined where the backend has no ray pick.
*/
obstructionRay(origin, direction, far, exclude) {
return backend?.obstructionRay?.(origin, direction, far, exclude);
},
destroy() {
if (destroyed) return;
destroyed = true;
for (const plane of [...planes]) plane.destroy();
for (const volume of [...volumes]) volume.destroy();
for (const material of [...materials]) material.dispose();
backend?.destroy();
},
};
}
+124
View File
@@ -0,0 +1,124 @@
// The CCTV meshes seam: what an engine without a backend keeps, and the
// Navara backend the Navara mode passes in.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { viewshedColors } from '../../../data/cctvViewshed.js';
import { createCctvMeshes } from './meshes.js';
const shape = { halfW: 8, halfH: 4.5 };
const positions = {
mount: { x: 6378137, y: 0, z: 0 },
tl: { x: 6378147, y: -1, z: 1 },
tr: { x: 6378147, y: 1, z: 1 },
br: { x: 6378147, y: 1, z: -1 },
bl: { x: 6378147, y: -1, z: -1 },
capCenter: { x: 6378147, y: 0, z: 0 },
};
const identity = { x: 0, y: 0, z: 0, w: 1 };
/** A backend that records what it is asked to draw. */
function recordingBackend(calls) {
const native = (kind, args) => {
const object = {
kind,
args,
show: false,
destroy: () => calls.push(['destroy', kind]),
};
calls.push(['create', kind, object]);
return object;
};
return {
createMaterial: (image) => ({
...native('material', [image]),
setImage: (image) => calls.push(['image', image]),
dispose: () => calls.push(['dispose', 'material']),
}),
createPlane: (...args) => native('plane', args),
updatePlane: (plane, ...args) => calls.push(['update', ...args]),
createVolume: (...args) => native('volume', args),
planeFromPick: (picked) => picked.native,
drawnBy: (object) => object,
destroy: () => calls.push(['destroy', 'backend']),
};
}
test('an engine without a backend keeps the handles and draws nothing', () => {
const engine = createFakeEngine();
const meshes = createCctvMeshes(engine);
const material = meshes.createMaterial(null);
const plane = meshes.createPlane('a', material, shape, positions, identity);
assert.equal(plane.id, 'cctv-a-plane');
assert.equal(plane.show, false);
plane.show = true;
assert.equal(plane.show, true);
assert.equal(meshes.planeFromPick({ id: plane.id }), null);
assert.equal(meshes.drawnBy(plane), undefined);
assert.equal(
meshes.obstructionRay(positions.mount, positions.tl, 10, []),
undefined,
);
assert.throws(
() => meshes.createPlane('b', { image: null }, shape, positions, identity),
/not owned/,
);
meshes.destroy();
assert.equal(plane.show, false);
assert.equal(material.disposed, true);
assert.throws(() => meshes.createMaterial(null), /destroyed/);
});
test('the Navara backend the Navara mode passes in draws the meshes', () => {
const engine = createFakeEngine({ kind: 'navara' });
const navara = { view: {}, MeshDesc: class {} };
engine.extensions = { navara };
const calls = [];
let given;
const meshes = createCctvMeshes(engine, {
navaraMeshes(target, extension) {
given = { target, extension };
return recordingBackend(calls);
},
});
assert.equal(given.target, engine);
assert.equal(given.extension, navara);
const material = meshes.createMaterial('canvas');
material.setImage('video');
const plane = meshes.createPlane('a', material, shape, positions, identity);
const volume = meshes.createVolume(positions, viewshedColors(4).fill);
const created = calls.filter(([type]) => type === 'create');
assert.deepEqual(
created.map(([, kind]) => kind),
['material', 'plane', 'volume'],
);
assert.deepEqual(calls[1], ['image', 'video']);
const [, , drawnPlane] = created[1];
assert.equal(drawnPlane.args[1], material.native, 'its drawn material');
plane.show = true;
assert.equal(drawnPlane.show, true);
assert.equal(meshes.planeFromPick({ native: drawnPlane }), plane);
plane.show = false;
assert.equal(meshes.planeFromPick({ native: drawnPlane }), null);
meshes.updatePlane(plane, shape, positions, identity);
assert.deepEqual(calls.at(-1), ['update', shape, positions, identity]);
assert.equal(meshes.drawnBy(volume), created[2][2]);
meshes.destroy();
meshes.destroy();
assert.deepEqual(calls.slice(-4), [
['destroy', 'plane'],
['destroy', 'volume'],
['dispose', 'material'],
['destroy', 'backend'],
]);
});
test('a Navara engine without the backend draws nothing', () => {
const engine = createFakeEngine({ kind: 'navara' });
engine.extensions = { navara: {} };
const meshes = createCctvMeshes(engine);
const volume = meshes.createVolume(positions, viewshedColors(4).fill);
assert.equal(meshes.drawnBy(volume), undefined);
meshes.destroy();
});
-338
View File
@@ -1,338 +0,0 @@
import * as geo from '../../../geo/index.js';
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../../data/trackingClickGesture.js';
import { createCctvNavaraMeshes } from './navaraMeshes.js';
import { createCctvNavaraLine } from './navaraLine.js';
import { createNavaraCctvGizmoRenderer } from './navaraGizmo.js';
import {
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_COVERAGE_COLOR,
} from '../policy.js';
export function createCctvNavaraRenderer(
engine,
{ state, services, view, MeshDesc },
) {
const meshes = createCctvNavaraMeshes(engine, { view, MeshDesc });
const markers = [];
const coverage = new Set();
const planes = new Set();
const gizmos = new Set();
const removers = new Set();
let initialized = false,
destroyed = false,
visible = true,
dirty = false;
let set = null,
capacity = 0,
credit = null;
const request = () => engine.render.request('cctv');
const markDirty = () => {
if (dirty || destroyed) return;
dirty = true;
request();
};
function syncMarkers() {
if (!dirty || !set || destroyed) return;
dirty = false;
set.setCount(markers.length);
markers.forEach((marker, index) =>
set.set(index, {
position: marker.position,
show: visible && marker.show,
scale: marker.scale,
color: marker.color.rgba(),
cell: 'camera',
pickId: marker.id,
}),
);
set.commit();
}
function allocateMarkers(count) {
if (set && capacity >= count) return;
set?.destroy();
capacity = Math.max(128, count, capacity * 2);
set = engine.movers.createSet({
id: 'cctv',
kind: 'sprite',
capacity,
order: 50,
pickable: true,
depthTest: 'always',
sharpen: true,
sprite: {
sizePx: 24,
scaleByDistance: [350, 1.25, 4_000_000, 0.42],
atlas: { url: CAMERA_ICON, cells: { camera: [0, 0, 1, 1] } },
},
});
markDirty();
}
const ownListener = (remove) => {
const release = () => {
if (removers.delete(release)) remove();
};
removers.add(release);
return release;
};
function pickedCameraId(picked) {
if (!picked) return null;
if (picked.owner === 'cctv' && state._recordById.has(picked.id))
return picked.id;
for (const entity of [...coverage, ...planes])
if (picked.id === entity.id && picked.owner === entity.id && entity.show)
return entity.cameraId;
return null;
}
const removeMeshPicker = engine.picker.registerMeshPicker((at) => {
const hit = meshes.pickPlane(engine.camera.pickRay(at));
if (!hit) return [];
// The rendered depth includes terrain, tiles and foreground models.
const surface = engine.picker.pickPosition(at);
if (
surface &&
geo.cartesian3.distance(engine.camera.livePosition, surface) + 0.1 <
hit.distance
)
return [];
return [
{
onTop: 0,
order: 0,
depth: hit.distance,
result: { id: hit.plane.id, owner: hit.plane.id },
},
];
});
const removeFrame = engine.frames.preRender.addEventListener(syncMarkers);
const removePlane = (runtime) => {
const plane = runtime?.planeEntity;
if (planes.delete(plane)) plane.destroy();
runtime?.planeMaterial?.dispose();
};
const points = (p) => [p.tl, p.tr, p.br, p.bl, p.tl];
return {
attach() {
if (destroyed) throw new Error('CCTV renderer is destroyed');
initialized = true;
},
get ready() {
return initialized && !destroyed && !engine.isDestroyed();
},
cameraCartographic: () => engine.camera.pose().cartographic,
following: () => Boolean(engine.camera.following()),
globeVisible: () => !engine.maps.photorealActive(),
tilesReady: () => engine.surface.tilesLoaded(),
project: (position, result) =>
engine.projector.worldToWindow(position, result),
distance: (position) =>
geo.cartesian3.distance(engine.camera.livePosition, position),
horizonTest: () => (position) => engine.projector.horizonVisible(position),
viewport: () => engine.host.size(),
request,
pick(position) {
syncMarkers();
return engine.picker.pick(position);
},
extractPickedCameraId: pickedCameraId,
onMoveEnd: (fn) => ownListener(engine.camera.moveEnd.addEventListener(fn)),
onMoveStart: (fn) =>
ownListener(engine.camera.moveStart.addEventListener(fn)),
bindClick(onClick, options = {}) {
const removes = [];
bindTrackingClickGesture(
{
setInputAction(fn, type) {
removes.push(engine.input.on(type, fn));
},
},
(event, gesture) => {
if (isTrackingClickGesture(gesture)) onClick(event);
},
{
...options,
eventTypes: {
LEFT_DOWN: 'down',
MOUSE_MOVE: 'move',
LEFT_UP: 'up',
LEFT_CLICK: 'click',
},
},
);
return ownListener(() => removes.forEach((remove) => remove()));
},
createGizmoRenderer() {
const gizmo = createNavaraCctvGizmoRenderer(engine);
gizmos.add(gizmo);
return gizmo;
},
createMarkers() {
allocateMarkers(1);
return set;
},
createMarker(camera, position) {
const marker = { id: camera.id };
for (const [key, initial] of Object.entries({
position,
color: IDLE_CAMERA_COLOR,
scale: 1,
show: true,
})) {
const copy = (item) => (key === 'position' ? { ...item } : item);
const equal = (a, b) =>
key === 'position'
? a.x === b.x && a.y === b.y && a.z === b.z
: key === 'color'
? a.red === b.red &&
a.green === b.green &&
a.blue === b.blue &&
a.alpha === b.alpha
: a === b;
let value = copy(initial);
Object.defineProperty(marker, key, {
enumerable: true,
get: () => value,
set(next) {
if (!equal(next, value)) {
value = copy(next);
markDirty();
}
},
});
}
markers.push(marker);
allocateMarkers(markers.length);
markDirty();
return marker;
},
setMarkersVisible(value) {
if (visible !== Boolean(value)) {
visible = Boolean(value);
markDirty();
}
},
restoreOrder: syncMarkers,
showCredit() {
credit ??= engine.credits.addStatic(
'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors',
);
},
hideCredit() {
credit?.();
credit = null;
},
sampleMeshFloorCells: (p, options) =>
services.mesh.sampleMeshFloorCells(engine, p, options),
obstructionRay: (origin, direction, exclude, far) =>
engine.surface.raycast({ origin, direction, exclude, far }),
createPlaneMaterial: meshes.createMaterial,
createTestPlaneMaterial: () => meshes.createMaterial(null),
setPlaneImage: (runtime, image) => runtime.planeMaterial.setImage(image),
createPlane(record, runtime, geometry, p, orientation) {
const plane = meshes.createPlane(
record.camera.id,
runtime.planeMaterial,
geometry,
p,
orientation,
);
planes.add(plane);
return plane;
},
updatePlane: (runtime, geometry, p, orientation) =>
meshes.updatePlane(runtime.planeEntity, geometry, p, orientation),
setPlaneVisible(runtime, value) {
if (runtime.planeEntity) runtime.planeEntity.show = value;
},
removePlane,
createCoverage(cameraId, p) {
const created = [];
try {
for (const [role, positions] of [
['ray-tl', [p.mount, p.tl]],
['ray-tr', [p.mount, p.tr]],
['ray-br', [p.mount, p.br]],
['ray-bl', [p.mount, p.bl]],
['cap', points(p)],
]) {
const line = createCctvNavaraLine(
engine,
`cctv-${cameraId}-${role}`,
{ width: 1.2, tint: IDLE_COVERAGE_COLOR },
positions,
);
line.cameraId = cameraId;
line._coverageRole = role === 'cap' ? 'cap' : 'edge';
coverage.add(line);
created.push(line);
}
return created;
} catch (error) {
for (const line of created) {
coverage.delete(line);
line.destroy();
}
throw error;
}
},
updateCoverage(record, p) {
const lines = record.coverageEntities;
if (!lines || lines.length < 5) return;
['tl', 'tr', 'br', 'bl'].forEach((role, i) => {
lines[i].polyline.positions = [p.mount, p[role]];
});
lines[4].polyline.positions = points(p);
},
removeCoverageEntity(entity) {
if (coverage.delete(entity)) entity.destroy();
},
styleLine: (entity, style) => entity.style(style),
hideCoverage(record) {
for (const entity of record.coverageEntities || []) entity.show = false;
},
removeCoverage(record) {
for (const entity of record.coverageEntities || [])
if (coverage.delete(entity)) entity.destroy();
},
createVolume: (record, tint) =>
meshes.createVolume(record.frustumPositions, tint),
removeVolume: (volume) => volume?.destroy(),
focus(record, duration) {
engine.camera.flyToSphere(
{
center: record.position,
radius: Math.max(40, record.camera.rangeM * 0.36),
},
{
heading: geo.math.toRadians(record.camera.headingDeg),
pitch: geo.math.toRadians(-22),
range: Math.max(280, record.camera.rangeM * 1.18),
duration: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
);
},
destroy() {
if (destroyed) return;
destroyed = true;
initialized = false;
removeFrame();
removeMeshPicker();
for (const remove of [...removers]) remove();
for (const gizmo of gizmos) gizmo.destroy();
for (const line of coverage) line.destroy();
meshes.destroy();
set?.destroy();
set = null;
credit?.();
credit = null;
markers.length = 0;
coverage.clear();
planes.clear();
gizmos.clear();
},
};
}
-119
View File
@@ -1,119 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { createCctvNavaraRenderer } from './navara.js';
function fixture(t) {
const engine = createFakeEngine({ kind: 'navara' });
const pickers = new Set();
engine.picker.registerMeshPicker = (pick) => {
pickers.add(pick);
return () => pickers.delete(pick);
};
const descriptors = new Map();
const view = {
registerMesh: (key, value) => descriptors.set(key, value),
addMesh(config) {
const key = Object.keys(config)[0];
const desc = new (descriptors.get(key))(view, {}, config);
desc.createMesh();
return { delete: () => desc.onDestroy() };
},
};
class MeshDesc {
onDestroy() {}
}
const state = { _recordById: new Map() };
const renderer = createCctvNavaraRenderer(engine, {
state,
services: {},
view,
MeshDesc,
});
renderer.attach();
t.after(() => renderer.destroy());
return { engine, renderer, state, pickers };
}
test('CCTV focus uses the engine sphere-flight fields and native range/pitch', (t) => {
const { engine, renderer } = fixture(t);
let flight;
engine.camera.flyToSphere = (sphere, options) => {
flight = { sphere, options };
};
const position = { x: 100, y: 200, z: 300 };
renderer.focus({ position, camera: { headingDeg: 84, rangeM: 126 } }, 0.2);
assert.deepEqual(flight, {
sphere: { center: position, radius: 45.36 },
options: {
heading: (84 * Math.PI) / 180,
pitch: (-22 * Math.PI) / 180,
range: 280,
duration: 0.2,
easing: 'cubicInOut',
},
});
});
test('CCTV markers own position snapshots and batch mutations without idle writes', (t) => {
const { engine, renderer } = fixture(t);
renderer.createMarkers();
const position = { x: 6378137, y: 10, z: 20 };
const marker = renderer.createMarker({ id: 'camera' }, position);
renderer.restoreOrder();
const store = engine.fake.moverSet('cctv').store;
position.y = 35;
marker.position = position;
engine.fake.frame();
assert.equal(store.positions[1], 35);
position.y = 42;
assert.equal(
marker.position.y,
35,
'a caller cannot mutate the retained position',
);
engine.fake.resetCalls();
marker.position = { ...marker.position };
marker.color = marker.color.withAlpha(marker.color.alpha);
renderer.restoreOrder();
assert.equal(engine.fake.callsOf('render.request').length, 0);
renderer.setMarkersVisible(false);
renderer.restoreOrder();
assert.equal(store.shows[0], 0);
});
test('CCTV picking requires actual owned primitives, and destroy removes its picker', (t) => {
const { engine, renderer, state, pickers } = fixture(t);
renderer.createMarkers();
const position = { x: 6378137, y: 10, z: 20 };
renderer.createMarker({ id: 'a' }, position);
state._recordById.set('a', {});
assert.equal(
renderer.extractPickedCameraId({ id: 'a', owner: 'sibling' }),
null,
);
assert.equal(renderer.extractPickedCameraId({ id: 'a', owner: 'cctv' }), 'a');
const p = {
mount: position,
tl: position,
tr: position,
br: position,
bl: position,
};
const lines = renderer.createCoverage('a', p);
lines[0].show = true;
assert.equal(
renderer.extractPickedCameraId({ id: lines[0].id, owner: lines[0].id }),
'a',
);
renderer.removeCoverageEntity(lines[0]);
assert.equal(
renderer.extractPickedCameraId({ id: lines[0].id, owner: lines[0].id }),
null,
);
renderer.destroy();
renderer.destroy();
assert.equal(pickers.size, 0);
assert.equal(engine.lines.list().length, 0);
assert.equal(engine.movers.list().length, 0);
});
-150
View File
@@ -1,150 +0,0 @@
import { GIZMO_ID_PREFIX } from '../../../data/cctvGizmo.js';
import { createCctvNavaraLine } from './navaraLine.js';
export function createNavaraCctvGizmoRenderer(engine) {
const entities = new Map();
const removers = [];
let destroyed = false;
const pointSets = new Set();
const makePoint = (part, color, size) => {
const id = `${GIZMO_ID_PREFIX}${part}`;
const set = engine.movers.createSet({
id,
kind: 'point',
capacity: 1,
pickable: true,
depthTest: 'always',
order: 100,
point: { sizePx: size, outlinePx: 2, outlineColor: [0, 0, 0, 0.7] },
});
pointSets.add(set);
let position = { x: 0, y: 0, z: 0 };
let visible = false;
let pixelSize = size;
const sync = () => {
if (destroyed) return;
set.setCount(1);
set.set(0, {
position,
show: visible,
scale: pixelSize / size,
color: color.rgba(),
pickId: id,
});
set.commit();
};
return {
id,
get position() {
return position;
},
set position(value) {
position = value;
sync();
},
get show() {
return visible;
},
set show(value) {
if (visible !== Boolean(value)) {
visible = Boolean(value);
sync();
}
},
point: {
get pixelSize() {
return pixelSize;
},
set pixelSize(value) {
if (value !== pixelSize) {
pixelSize = value;
sync();
}
},
},
};
};
const add = (part, entity) => {
entities.set(part, entity);
return entity;
};
const assertNew = (part) => {
if (destroyed) throw new Error('CCTV gizmo is destroyed');
if (entities.has(part))
throw new Error(`CCTV handle is already owned: ${part}`);
};
return {
createPoint(part, color, size) {
assertNew(part);
return add(part, makePoint(part, color, size));
},
createLine(part, color, width, arrow = false) {
assertNew(part);
const line = createCctvNavaraLine(engine, `${GIZMO_ID_PREFIX}${part}`, {
tint: color.withAlpha(arrow ? 1 : 0.9),
depthFail: color.withAlpha(0.45),
width,
arrow,
order: 100,
});
if (!arrow) return add(part, line);
let point;
try {
point = makePoint(part, color, 14);
} catch (error) {
line.destroy();
throw error;
}
const visibility = Object.getOwnPropertyDescriptor(point, 'show');
Object.defineProperty(point, 'show', {
get: visibility.get,
set(value) {
visibility.set(value);
line.show = value;
},
});
point.polyline = line.polyline;
point.destroy = () => line.destroy();
return add(part, point);
},
pickPart(position) {
for (const hit of engine.picker.drillPick(position, 6)) {
if (typeof hit?.id !== 'string' || !hit.id.startsWith(GIZMO_ID_PREFIX))
continue;
const part = hit.id.slice(GIZMO_ID_PREFIX.length);
if (hit.owner === hit.id && entities.get(part)?.show) return part;
}
return null;
},
pickRay: (position) => engine.camera.pickRay(position),
setCursor(value) {
if (engine.host.canvas.style) engine.host.canvas.style.cursor = value;
},
suspendCameraInputs: () => engine.input.suspendCameraInputs(),
on(type, listener) {
if (type !== 'cancel') {
removers.push(engine.input.on(type, listener));
return;
}
const canvas = engine.host.canvas;
for (const [target, event] of [
[canvas, 'pointercancel'],
[canvas.ownerDocument?.defaultView, 'blur'],
]) {
if (!target?.addEventListener) continue;
target.addEventListener(event, listener);
removers.push(() => target.removeEventListener(event, listener));
}
},
destroy() {
if (destroyed) return;
destroyed = true;
for (const remove of removers.splice(0)) remove();
for (const entity of entities.values()) entity.destroy?.();
for (const set of pointSets) set.destroy();
entities.clear();
pointSets.clear();
if (engine.host.canvas.style) engine.host.canvas.style.cursor = '';
},
};
}
@@ -1,61 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { viewshedColors } from '../../../data/cctvViewshed.js';
import { createNavaraCctvGizmoRenderer } from './navaraGizmo.js';
const color = viewshedColors(30).fill;
test('Navara gizmo releases arrow resources, input and cancellation listeners', () => {
const engine = createFakeEngine({ kind: 'navara' });
const canvas = new EventTarget();
const window = new EventTarget();
canvas.style = {};
canvas.ownerDocument = { defaultView: window };
engine.host.canvas = canvas;
const renderer = createNavaraCctvGizmoRenderer(engine);
renderer.createLine('east', color, 8, true);
renderer.createLine('heading', color, 3);
renderer.createPoint('range', color, 10);
let cancels = 0;
let moves = 0;
renderer.on('cancel', () => cancels++);
renderer.on('move', () => moves++);
canvas.dispatchEvent(new Event('pointercancel'));
window.dispatchEvent(new Event('blur'));
engine.fake.input('move', { position: { x: 1, y: 1 } });
assert.equal(cancels, 2);
assert.equal(moves, 1);
assert.throws(
() => renderer.createLine('east', color, 8, true),
/already owned/,
);
assert.equal(engine.lines.list().length, 2);
assert.equal(engine.movers.list().length, 2);
renderer.setCursor('grabbing');
renderer.destroy();
renderer.destroy();
canvas.dispatchEvent(new Event('pointercancel'));
window.dispatchEvent(new Event('blur'));
engine.fake.input('move', { position: { x: 1, y: 1 } });
assert.equal(cancels, 2);
assert.equal(moves, 1);
assert.equal(engine.lines.list().length, 0);
assert.equal(engine.movers.list().length, 0);
assert.equal(canvas.style.cursor, '');
assert.throws(() => renderer.createPoint('new', color, 10), /destroyed/);
});
test('Navara gizmo rolls back the arrow shaft if its tip cannot be allocated', () => {
const engine = createFakeEngine({ kind: 'navara' });
engine.movers.createSet = () => {
throw new Error('allocation failed');
};
const renderer = createNavaraCctvGizmoRenderer(engine);
assert.throws(
() => renderer.createLine('east', color, 8, true),
/allocation failed/,
);
assert.equal(engine.lines.list().length, 0);
renderer.destroy();
});
-68
View File
@@ -1,68 +0,0 @@
/** Mutable CCTV line backed by the existing engine ribbon renderer. */
export function createCctvNavaraLine(engine, id, initial, points = []) {
let style = { ...initial };
let positions = points;
let visible = false;
let destroyed = false;
let line = null;
const build = () => {
line?.destroy();
line = engine.lines.createLine({
id,
pickId: id,
widthPx: style.width,
color: style.tint.rgba(),
depthFailAlpha: style.depthFail
? style.depthFail.alpha / Math.max(style.tint.alpha, 1e-6)
: 0,
dash: style.dashed ? { lengthPx: 8, gapPx: 8 } : null,
arrow: Boolean(style.arrow),
order: style.order ?? 0,
});
line.setPositions(positions);
line.show(visible);
};
build();
return {
id,
get show() {
return !destroyed && visible;
},
set show(value) {
if (destroyed || visible === Boolean(value)) return;
visible = Boolean(value);
line.show(visible);
},
polyline: {
get positions() {
return positions;
},
set positions(value) {
if (destroyed) return;
positions = value;
line.setPositions(value);
},
},
style(next) {
if (destroyed) return;
const depth = (s) =>
s.depthFail ? s.depthFail.alpha / Math.max(s.tint.alpha, 1e-6) : 0;
const rebuild =
next.width !== style.width ||
Boolean(next.dashed) !== Boolean(style.dashed) ||
depth(next) !== depth(style);
const colorChanged = next.tint
.rgba()
.some((v, i) => v !== style.tint.rgba()[i]);
style = { ...style, ...next };
if (rebuild) build();
else if (colorChanged) line.setColor(style.tint.rgba());
this.show = next.visible;
},
destroy() {
if (destroyed) return;
destroyed = true;
line.destroy();
},
};
}
+71 -67
View File
@@ -1,3 +1,8 @@
// The CCTV meshes on Navara (behind render/meshes.js, loaded through
// import()): the monitor plane and the viewshed volume as three meshes in
// Navara's view, depth-tested against the scene, and a mesh picker for the
// plane's own triangles.
import {
BufferAttribute,
BufferGeometry,
@@ -13,8 +18,9 @@ import {
Vector3,
VideoTexture,
} from 'three';
import * as geo from '../../../geo/index.js';
import { frustumVolumeGeometryData } from '../../../data/cctvViewshed.js';
import { PLANE_OUTLINE_COLOR } from '../policy.js';
import { PLANE_IMAGE_ALPHA } from './style.js';
const KIND = 'gevCctvMesh';
const registered = new WeakSet();
@@ -34,7 +40,11 @@ function placeGeometry(mesh, positions, indices, origin) {
mesh.matrixWorldNeedsUpdate = true;
}
/** CCTV owns these resources; media playback remains in shared projection. */
/**
* @param {import('../../../globe/contract.js').GlobeEngine} engine
* @param {{ view: object, MeshDesc: Function }} navara The engine's Navara
* extension.
*/
export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
if (!view?.addMesh || !MeshDesc)
throw new TypeError('CCTV requires Navara MeshDesc support');
@@ -79,7 +89,7 @@ export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
const material = new MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.95,
opacity: PLANE_IMAGE_ALPHA,
side: DoubleSide,
depthWrite: false,
toneMapped: false,
@@ -178,9 +188,9 @@ export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
}
}
function updatePlane(plane, geometry, positions, orientation) {
function updatePlane(plane, shape, positions, orientation) {
if (!planes.has(plane)) return;
// Match the native plane's quaternion and dimensions, including its UVs.
// The native plane's quaternion and dimensions, including its UVs.
const q = new Quaternion(
orientation.x,
orientation.y,
@@ -194,25 +204,55 @@ export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
[-1, -1],
[1, -1],
]) {
const p = new Vector3(x * geometry.halfW, y * geometry.halfH, 0)
const p = new Vector3(x * shape.halfW, y * shape.halfH, 0)
.applyQuaternion(q)
.add(positions.capCenter);
flat.push(p.x, p.y, p.z);
}
placeGeometry(plane.mesh, flat, [0, 2, 1, 2, 3, 1], positions.capCenter);
plane.outline.setPositions(
[0, 1, 3, 2, 0].map((i) => ({
x: flat[i * 3],
y: flat[i * 3 + 1],
z: flat[i * 3 + 2],
})),
);
request();
}
/** The nearest shown plane's triangles along a ray, from either side. */
function pickPlane(ray) {
if (destroyed || !ray) return undefined;
raycaster.ray.origin.copy(ray.origin);
raycaster.ray.direction.copy(ray.direction).normalize();
let nearest;
for (const plane of planes) {
if (!plane.show) continue;
plane.group.updateWorldMatrix(true, true);
const hit = raycaster.intersectObject(plane.mesh, false)[0];
if (hit && (!nearest || hit.distance < nearest.distance))
nearest = { ...hit, plane };
}
return nearest;
}
const removeMeshPicker = engine.picker.registerMeshPicker((at) => {
const hit = pickPlane(engine.camera.pickRay(at));
if (!hit) return [];
// The rendered depth includes terrain, tiles and foreground models.
const surface = engine.picker.pickPosition(at);
if (
surface &&
geo.cartesian3.distance(engine.camera.livePosition, surface) + 0.1 <
hit.distance
)
return [];
return [
{
onTop: 0,
order: 0,
depth: hit.distance,
result: { id: hit.plane.id, owner: hit.plane.id },
},
];
});
return {
createMaterial,
createPlane(cameraId, material, geometry, positions, orientation) {
createPlane(cameraId, material, shape, positions, orientation) {
alive();
if (!materials.has(material) || material.disposed)
throw new Error('CCTV plane material is not owned');
@@ -221,45 +261,15 @@ export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
'uv',
new BufferAttribute(new Float32Array([0, 1, 1, 1, 0, 0, 1, 0]), 2),
);
let outline;
let plane;
let transferred = false;
try {
outline = engine.lines.createLine({
id: `cctv-${cameraId}-plane-outline`,
widthPx: 1,
color: PLANE_OUTLINE_COLOR.rgba(),
});
transferred = true;
plane = ownMesh(mesh, () => {
outline.destroy();
material.dispose();
planes.delete(plane);
});
plane.id = `cctv-${cameraId}-plane`;
plane.cameraId = cameraId;
plane.outline = outline;
const visibility = Object.getOwnPropertyDescriptor(plane, 'show');
Object.defineProperty(plane, 'show', {
get: visibility.get,
set(value) {
visibility.set(value);
if (planes.has(plane)) outline.show(plane.show);
},
});
planes.add(plane);
updatePlane(plane, geometry, positions, orientation);
plane.show = false;
return plane;
} catch (error) {
plane?.destroy();
if (!transferred) {
mesh.geometry.dispose();
outline?.destroy();
material.dispose();
}
throw error;
}
// A failed descriptor disposes the geometry; the material stays its own.
let plane = null;
plane = ownMesh(mesh, () => planes.delete(plane));
plane.id = `cctv-${cameraId}-plane`;
plane.cameraId = cameraId;
planes.add(plane);
updatePlane(plane, shape, positions, orientation);
plane.show = false;
return plane;
},
updatePlane,
createVolume(positions, tint) {
@@ -277,24 +287,18 @@ export function createCctvNavaraMeshes(engine, { view, MeshDesc }) {
placeGeometry(mesh, data.positions, data.indices, positions.mount);
return ownMesh(mesh, () => material.dispose());
},
/** Actual plane triangles, not a projected rectangle or marker proxy. */
pickPlane(ray) {
if (destroyed || !ray) return undefined;
raycaster.ray.origin.copy(ray.origin);
raycaster.ray.direction.copy(ray.direction).normalize();
let nearest;
for (const plane of planes) {
if (!plane.show) continue;
plane.group.updateWorldMatrix(true, true);
const hit = raycaster.intersectObject(plane.mesh, false)[0];
if (hit && (!nearest || hit.distance < nearest.distance))
nearest = { ...hit, plane };
}
return nearest;
pickPlane,
// The mesh picker's result names the plane by its id.
planeFromPick(picked) {
for (const plane of planes)
if (picked.id === plane.id && picked.owner === plane.id) return plane;
return null;
},
drawnBy: (native) => native.group,
destroy() {
if (destroyed) return;
destroyed = true;
removeMeshPicker();
for (const resource of [...owned]) resource.destroy();
for (const material of [...materials]) material.dispose();
},
+45 -17
View File
@@ -9,7 +9,6 @@ function harness() {
const scene = new Group();
const kinds = new Map();
const handles = new Set();
const lines = new Set();
let requests = 0;
let fail = false;
let failedGeometryDisposals = 0;
@@ -43,27 +42,25 @@ function harness() {
return handle;
},
};
const pickers = new Set();
const engine = {
render: { request: () => requests++ },
lines: {
createLine(options) {
const line = {
options,
setPositions: (value) => (line.positions = value),
show: (value) => (line.visible = value),
destroy: () => lines.delete(line),
};
lines.add(line);
return line;
camera: { livePosition: { x: 0, y: 0, z: 0 }, pickRay: () => null },
picker: {
pickPosition: () => undefined,
registerMeshPicker(pick) {
pickers.add(pick);
return () => pickers.delete(pick);
},
},
};
const owner = createCctvNavaraMeshes(engine, { view, MeshDesc });
return {
owner,
engine,
scene,
handles,
lines,
pickers,
requests: () => requests,
failedGeometryDisposals: () => failedGeometryDisposals,
fail: () => (fail = true),
@@ -111,9 +108,9 @@ test('Navara CCTV plane preserves native rotated geometry, UVs and metre precisi
assert.equal(uv.getY(i), (y + 1) / 2);
}
assert.equal(plane.show, false);
assert.equal(plane.outline.visible, false);
assert.equal(plane.id, 'cctv-a-plane');
plane.show = true;
assert.equal(plane.outline.visible, true);
assert.equal(plane.group.visible, true);
assert.equal(material.material.opacity, 0.95);
assert.equal(material.material.depthWrite, false);
});
@@ -188,12 +185,13 @@ test('Navara CCTV releases replaced video textures and ignores retired image upd
const plane = h.owner.createPlane('a', material, shape, positions, identity);
plane.destroy();
plane.destroy();
assert.equal(finalDisposed, 0, 'the plane leaves its material to its owner');
material.dispose();
const requests = h.requests();
material.setImage(video);
assert.equal(h.requests(), requests);
assert.equal(finalDisposed, 1);
assert.equal(h.handles.size, 0);
assert.equal(h.lines.size, 0);
h.owner.destroy();
h.owner.destroy();
assert.equal(finalDisposed, 1);
@@ -209,11 +207,11 @@ test('Navara CCTV rolls back a failed descriptor and rejects new resources after
() => h.owner.createPlane('a', material, shape, positions, identity),
/descriptor failed/,
);
assert.equal(releases, 1);
assert.equal(releases, 0, 'the material stays with its owner');
assert.equal(h.failedGeometryDisposals(), 1);
assert.equal(h.handles.size, 0);
assert.equal(h.lines.size, 0);
h.owner.destroy();
assert.equal(releases, 1);
assert.throws(() => h.owner.createMaterial(canvas()), /destroyed/);
});
@@ -244,3 +242,33 @@ test('Navara CCTV volume preserves native world vertices and releases geometry/m
assert.equal(materialReleases, 1);
assert.equal(h.handles.size, 0);
});
test('Navara CCTV plane picks go through a mesh picker that defers to nearer depth', () => {
const h = harness();
const plane = h.owner.createPlane(
'a',
h.owner.createMaterial(canvas()),
shape,
positions,
identity,
);
plane.show = true;
const [pick] = h.pickers;
h.engine.camera.livePosition = { ...positions.capCenter, z: 5800 };
h.engine.camera.pickRay = () => ({
origin: { ...positions.capCenter, z: 5800 },
direction: { x: 0, y: 0, z: -1 },
});
const [hit] = pick({ x: 1, y: 1 });
assert.deepEqual(hit.result, { id: 'cctv-a-plane', owner: 'cctv-a-plane' });
assert.equal(hit.depth, 122);
assert.equal(h.owner.planeFromPick(hit.result), plane);
assert.equal(
h.owner.planeFromPick({ id: 'cctv-a-plane', owner: 'sibling' }),
null,
);
h.engine.picker.pickPosition = () => ({ ...positions.capCenter, z: 5750 });
assert.deepEqual(pick({ x: 1, y: 1 }), [], 'a wall in front hides it');
h.owner.destroy();
assert.equal(h.pickers.size, 0);
});
+59
View File
@@ -0,0 +1,59 @@
// The CCTV display's look on the globe contract: the camera markers, the
// coverage lines as created, the monitor plane's outline and material and
// the calibration gizmo's handles, in contract terms (CSS pixels, a
// depth-fail alpha factor). Values are Cesium's, the reference look; the
// per-camera coverage styles are the layer's (../rendering.js). No engine
// imports.
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
import { IDLE_COVERAGE_COLOR, PLANE_OUTLINE_COLOR } from '../policy.js';
/** The camera markers: one sprite set, the bottom of the contact sprites. */
export const MARKER_SET_ID = 'cctv';
export const MARKER_SIZE_PX = 24;
export const MARKER_SCALE_BY_DISTANCE = Object.freeze([
350, 1.25, 4_000_000, 0.42,
]);
export const MARKER_ORDER = SPRITE_LAYER_ORDER.indexOf('cctv');
/** A coverage line as created, before the first style pass. */
export const COVERAGE_INITIAL = Object.freeze({
widthPx: 1.2,
color: IDLE_COVERAGE_COLOR,
});
// Cesium's PolylineDashMaterialProperty defaults: 16 px, half dash.
export const COVERAGE_DASH = Object.freeze({ lengthPx: 8, gapPx: 8 });
// Entity polylines follow the ellipsoid (Cesium's default arc type).
export const LINE_ARC = 'geodesic';
/** The monitor plane: its image at 95 % and a 1 px outline. */
export const PLANE_IMAGE_ALPHA = 0.95;
export const PLANE_OUTLINE = Object.freeze({
widthPx: 1,
color: PLANE_OUTLINE_COLOR,
});
/** The calibration gizmo, drawn over the markers. */
export const GIZMO_ORDER = 100;
export const GIZMO_LINE_ALPHA = 0.9;
// Parts behind geometry stay visible, dimmed: a street-level mount buries
// half the heading ring in sloped photogrammetry tiles.
export const GIZMO_DEPTH_FAIL_ALPHA = 0.45;
export const GIZMO_ARROW_TIP_PX = 14;
export const GIZMO_POINT = Object.freeze({
sizePx: 10,
outlinePx: 2,
outlineColor: Object.freeze([0, 0, 0, 0.7]),
});
// Pick boxes around the pointer, as Cesium's gizmo picked.
export const GIZMO_PICK_PX = 14;
export const GIZMO_DRILL_LIMIT = 6;
/**
* A depth-fail colour as the contract's alpha factor of the line colour (the
* contract keeps the line's hue where the scene hides it).
*/
export const depthFailAlpha = (tint, depthFail) =>
depthFail
? Math.min(1, Math.max(0, depthFail.alpha / Math.max(tint.alpha, 1e-6)))
: 0;
+2 -2
View File
@@ -337,8 +337,8 @@ export function createRendering({
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.
// Every marker draws over the scene (the marker set's depth test is
// 'always') — see the field-test far-zoom submerge fix there.
}
if (
+10 -17
View File
@@ -1,7 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCctvSource, createCctvLayer } from './index.js';
import { createCctvCesiumRenderer } from './render/cesium.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
import { createCctvDisplay } from './render/display.js';
const camera = {
id: 'pack/camera ?x',
@@ -111,7 +112,6 @@ test('camera construction is inert and destruction cancels a pending catalog and
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
},
sprites: { registerSpriteCollection: noop },
activation: {},
locations: {},
picking: { unregisterPickOwner: noop },
@@ -132,24 +132,17 @@ test('camera construction is inert and destruction cancels a pending catalog and
});
},
};
const a = createCctvLayer({
services,
source,
rendererFactory: createCctvCesiumRenderer,
});
const b = createCctvLayer({
services,
source,
rendererFactory: createCctvCesiumRenderer,
});
const rendererFactory = ({ engine, ...context }) =>
createCctvDisplay(engine, context);
const a = createCctvLayer({ services, source, rendererFactory });
const b = createCctvLayer({ services, source, rendererFactory });
assert.equal(listeners.size, 0);
const viewer = {
scene: { primitives: { add: (value) => value, remove: () => true } },
};
const initializing = a.init(viewer);
const engine = createFakeEngine();
const initializing = a.init(null, { engine });
assert.equal(listeners.size, 1);
assert.equal(signal.aborted, false);
a.destroy(viewer);
a.destroy();
assert.equal(engine.movers.list().length, 0, 'the markers go with it');
assert.equal(listeners.size, 0);
assert.equal(signal.aborted, true);
resolveCatalog({ sources: [] });
+14 -11
View File
@@ -7,18 +7,21 @@ export function createTesting({
source,
rendererFactory,
}) {
let testViewer;
function useRenderer(viewer) {
if (parts.renderer && testViewer === viewer) return;
let testEngine;
function useRenderer(engine) {
if (parts.renderer && testEngine === engine) return;
parts.renderer?.destroy();
parts.renderer = null;
testEngine = engine;
if (!engine) return;
parts.renderer = rendererFactory({
state: layerState,
services,
parts,
source,
engine,
});
parts.renderer.attach(viewer);
testViewer = viewer;
parts.renderer.attach();
}
/** Test seam: republishes host entries through the real push path, so tests
@@ -39,13 +42,13 @@ export function createTesting({
/**
* Create the production monitor-plane/host-label pair without media setup.
* @param {Object} viewer Cesium viewer seam.
* @param {Object} engine Globe engine.
* @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime.
*/
function _createCctvProjectionPlaneForTest(viewer, record) {
useRenderer(viewer);
function _createCctvProjectionPlaneForTest(engine, record) {
useRenderer(engine);
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -93,7 +96,7 @@ export function createTesting({
* Primes the minimum module state needed to exercise the production coverage
* refresh path in unit tests.
* @param {Object} [options={}] Test state values.
* @param {Object|null} [options.viewer] Viewer-like entity owner.
* @param {Object|null} [options.engine] Globe engine the display draws on.
* @param {Object[]} [options.records] Seeded CCTV records.
* @param {string|null} [options.activeCameraId] Active record id.
* @param {boolean} [options.enabled=true] Layer enabled state.
@@ -104,7 +107,7 @@ export function createTesting({
*/
function _setCctvCoverageStateForTest({
viewer = null,
engine = null,
records = [],
activeCameraId = null,
enabled = true,
@@ -112,7 +115,7 @@ export function createTesting({
showProjection = false,
healthById = new Map(),
} = {}) {
useRenderer(viewer);
useRenderer(engine);
layerState._records = Array.isArray(records) ? records : [];
layerState._recordById = new Map(
layerState._records