refactor(cctv): isolate calibration handles and stop idle poll frames

Move native gizmo entities and input into an owned renderer. Restore the
captured camera-input flag, handle cancellation and duplicate presses, and
reject foreign handle identities. Preserve native geometry and picking.

Avoid no-op sync-chip mutations and let unchanged CCTV polls complete
without publishing scene changes. Keep health/UI polling and real geometry,
auto-hop and media updates. Extend browser idle samples across two polls.

Validated full Node24 unit/allocation, boundaries, scoped format, production,
panel and QA builds; native legacy parity, real media/GPU picks on dev and
preview, engine contracts and production shell. Retain failed evidence.
This commit is contained in:
German Khokhlov committed 2026-10-28 22:44:27 +04:00
1 parent a72cfc4098
commit 311e178d0c
14 files changed
+649 -197

No files matched your search

+1 -1
View File
@@ -306,7 +306,7 @@ export function createCalibration({
? record
: null;
layerState._gizmo = createCalibrationGizmo({
viewer: layerState._viewer,
renderer: services.createGizmoRenderer(layerState._viewer),
getActiveRecord: () =>
layerState._enabled && layerState._calibrationMode
? parts.selection.getActiveRecord()
+233
View File
@@ -0,0 +1,233 @@
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);
});
+11 -2
View File
@@ -19,7 +19,9 @@ export function createIngestion({
* tick ever samples anything again.
*/
async update() {
if (!layerState._enabled) return;
if (!layerState._enabled) return { changed: false };
let changed = false;
const previousActiveId = layerState._activeCameraId;
const now = Date.now();
layerState._lastUpdate = now;
if (
@@ -35,12 +37,19 @@ export function createIngestion({
const unresolved = layerState._records.filter(
(record) => !parts.ground.isGroundResolved(record),
);
if (unresolved.length)
if (unresolved.length) {
parts.geometryQueue.enqueueGeometryRefresh(unresolved);
changed = true;
}
}
await parts.health.syncHealthState();
parts.navigation.maybeAutoHop(now);
parts.presentation.notifyListeners();
// Health and frame URL notifications update the panel directly. Media
// requests its own frames; only actual scene changes need a tick frame.
return {
changed: changed || previousActiveId !== layerState._activeCameraId,
};
},
};
+76
View File
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { createIngestion } from './ingestion.js';
function setup() {
const record = { camera: { id: 'a' } };
const state = {
_enabled: true,
_activeCameraId: 'a',
_tilesReadyReenqueued: true,
_records: [record],
};
const calls = { health: 0, notify: 0, queues: [] };
const parts = {
model: { projectionTilesReady: () => true },
ground: { isGroundResolved: () => false },
geometryQueue: {
enqueueGeometryRefresh: (records) => calls.queues.push(records),
},
health: {
async syncHealthState() {
calls.health++;
},
},
navigation: { maybeAutoHop() {} },
presentation: {
notifyListeners() {
calls.notify++;
},
},
};
const layer = createIngestion({ state, parts }).methods;
return { state, parts, calls, layer, record };
}
test('CCTV health-only ticks update the panel without claiming scene changes', async () => {
const h = setup();
for (let i = 0; i < 3; i++)
assert.deepEqual(await h.layer.update(), { changed: false });
assert.equal(h.calls.health, 3);
assert.equal(h.calls.notify, 3);
assert.ok(h.state._lastUpdate > 0);
});
test('CCTV completion refresh publishes geometry work exactly once', async () => {
const h = setup();
h.state._tilesReadyReenqueued = false;
assert.deepEqual(await h.layer.update(), { changed: true });
assert.deepEqual(h.calls.queues, [[h.record]]);
assert.deepEqual(await h.layer.update(), { changed: false });
assert.equal(h.calls.queues.length, 1);
});
test('a ready surface with no unresolved records does not claim geometry work', async () => {
const h = setup();
h.state._tilesReadyReenqueued = false;
h.parts.ground.isGroundResolved = () => true;
assert.deepEqual(await h.layer.update(), { changed: false });
assert.equal(h.calls.queues.length, 0);
});
test('CCTV auto-hop still publishes its changed active camera', async () => {
const h = setup();
h.parts.navigation.maybeAutoHop = () => {
h.state._activeCameraId = 'b';
};
assert.deepEqual(await h.layer.update(), { changed: true });
assert.deepEqual(await h.layer.update(), { changed: false });
});
test('disabled CCTV does no polling or presentation work', async () => {
const h = setup();
h.state._enabled = false;
await h.layer.update();
assert.equal(h.calls.health + h.calls.notify + h.calls.queues.length, 0);
});
-3
View File
@@ -453,9 +453,6 @@ export function createLifecycle({
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
if (teardownViewer?.scene?.screenSpaceCameraController) {
teardownViewer.scene.screenSpaceCameraController.enableInputs = true;
}
parts.projection.stopProjectionLoop();
parts.geometryQueue.stopGeometryLoadQueue();
parts.cards.teardownAmbientCards();
+193
View File
@@ -0,0 +1,193 @@
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('');
},
};
}