Draw the CCTV calibration gizmo through the renderer ports and take it off the Cesium list

The gizmo's rings and move arrows are draw-port lines that dim where
geometry hides them, and its handles and arrow tips are depth-test-free
draw-port points; their item ids keep the cctv-gizmo-<part> scheme the
layer's pick owner matches. Picks, rays and the cursor go through the query
port and the renderer's canvas, and the drag math runs on plain vectors.
The layer reports what the gizmo draws for the QA harness, which reads the
parts there instead of from the viewer's entities.
This commit is contained in:
Sameh Khamis committed 2026-11-08 07:55:30 -08:00
1 parent 393f1686f2
commit bbad02b73e
6 files changed
+507 -278

No files matched your search

+220 -206
View File
@@ -8,7 +8,7 @@
* - Pure drag math (this top section): ray↔axis closest-point, ray↔plane
* intersection with a grazing-angle guard, ring angles. All unit-tested
* under node:test with zero scene dependencies.
* - createCalibrationGizmo (below): the entity + pointer-input
* - createCalibrationGizmo (below): the draw-set + pointer-input
* controller that renders grab-able handles on the ACTIVE camera and turns
* drags into calibration patches through a narrow callback interface. It
* never touches the layer's records/stores directly.
@@ -23,8 +23,10 @@
* throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query
* invariant is untouched.
*/
import * as Cesium from 'cesium';
import { inputFor } from '../input/dispatcher.js';
import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js';
import { eastNorthUp } from '../geo/frames.js';
import { add, dot, scale, sub } from '../geo/vector.js';
// Grazing guard (spec §5): reject plane intersections when the view ray is
// nearly parallel to the constraint plane — the hit point races to infinity
@@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08;
// Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²).
const PARALLEL_EPS = 1e-6;
const scratchW = new Cesium.Cartesian3();
/**
* Parameter t (metres) along an axis line of the point on that axis closest
* to a mouse ray. Both directions must be normalized.
@@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3();
* t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin,
* d = rayDir·w, e = axisDir·w.
*
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} axisOrigin
* @param {Cesium.Cartesian3} axisDir - Unit.
* Vectors are ECEF `{x, y, z}`.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} axisOrigin
* @param {{x: number, y: number, z: number}} axisDir - Unit.
* @returns {number|null} Axis parameter in metres, or null when near-parallel.
*/
export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) {
const b = Cesium.Cartesian3.dot(rayDir, axisDir);
const b = dot(rayDir, axisDir);
const denom = 1 - b * b;
if (Math.abs(denom) < PARALLEL_EPS) return null;
const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW);
const d = Cesium.Cartesian3.dot(rayDir, w);
const e = Cesium.Cartesian3.dot(axisDir, w);
const w = sub(rayOrigin, axisOrigin);
const d = dot(rayDir, w);
const e = dot(axisDir, w);
return (e - b * d) / denom;
}
/**
* Intersects a mouse ray with a plane, refusing grazing configurations
* (|rayDir·normal| < 0.08) and hits behind the ray origin.
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} planeOrigin
* @param {Cesium.Cartesian3} planeNormal - Unit.
* @returns {Cesium.Cartesian3|null} Hit point (new instance), or null.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} planeOrigin
* @param {{x: number, y: number, z: number}} planeNormal - Unit.
* @returns {{x: number, y: number, z: number}|null} Hit point (new), or null.
*/
export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
const denom = Cesium.Cartesian3.dot(rayDir, planeNormal);
const denom = dot(rayDir, planeNormal);
if (Math.abs(denom) < GRAZING_DOT_MIN) return null;
const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW);
const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom;
const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom;
if (s < 0) return null;
const hit = Cesium.Cartesian3.multiplyByScalar(
rayDir,
s,
new Cesium.Cartesian3(),
);
return Cesium.Cartesian3.add(rayOrigin, hit, hit);
return add(rayOrigin, scale(rayDir, s));
}
/**
* Angle (radians, atan2 convention) of a point around a ring center in the
* plane spanned by two orthonormal basis vectors.
* @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane.
* @param {Cesium.Cartesian3} center - Ring center.
* @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0).
* @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°).
* @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane.
* @param {{x: number, y: number, z: number}} center - Ring center.
* @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0).
* @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°).
* @returns {number} Angle in (−π, π].
*/
export function ringAngle(hitPoint, center, basisA, basisB) {
const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW);
return Math.atan2(
Cesium.Cartesian3.dot(v, basisB),
Cesium.Cartesian3.dot(v, basisA),
);
const v = sub(hitPoint, center);
return Math.atan2(dot(v, basisB), dot(v, basisA));
}
/**
@@ -117,8 +109,8 @@ export function signedAngleDelta(fromRad, toRad) {
// Gizmo controller
// ---------------------------------------------------------------------------
/** Entity id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo entities NEVER get a camera id in
/** Item id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo parts NEVER get a camera id in
* the layer's pick store, so the layer's selection path ignores them. */
export const GIZMO_ID_PREFIX = 'cctv-gizmo-';
@@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6;
const DRAG_THROTTLE_MS = 16;
const HOVER_THROTTLE_MS = 120;
const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff');
const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0');
const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252');
const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a');
const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff');
const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a');
/** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */
function rgba(hex, alpha = 1) {
const n = Number.parseInt(hex.slice(1), 16);
return [
((n >> 16) & 255) / 255,
((n >> 8) & 255) / 255,
(n & 255) / 255,
alpha,
];
}
const COLOR_RING_HEADING = '#35d8ff';
const COLOR_RING_PITCH = '#ff5fd0';
const COLOR_MOVE_EAST = '#ff5252';
const COLOR_MOVE_NORTH = '#52ff7a';
const COLOR_MOVE_UP = '#5b8cff';
const COLOR_HANDLE = '#ffd97a';
const HANDLE_OUTLINE = [0, 0, 0, 0.7];
const toRadians = (deg) => (deg * Math.PI) / 180;
const toDeg = (rad) => (rad * 180) / Math.PI;
/**
* Local ENU unit axes at an ECEF position.
* @param {Cesium.Cartesian3} position
* @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}}
* @param {{x: number, y: number, z: number}} position
* @returns {{east: object, north: object, up: object}}
*/
function enuAxes(position) {
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3());
return {
east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()),
north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()),
up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()),
};
const frame = eastNorthUp(position);
return { east: frame.x, north: frame.y, up: frame.z };
}
/** a*sa + b*sb (fresh Cartesian3). */
/** a*sa + b*sb. */
function combine2(a, sa, b, sb) {
const out = Cesium.Cartesian3.multiplyByScalar(
a,
sa,
new Cesium.Cartesian3(),
);
const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3());
return Cesium.Cartesian3.add(out, t, out);
return add(scale(a, sa), scale(b, sb));
}
/** The midpoint of two points. */
const midpoint = (a, b) => scale(add(a, b), 0.5);
/**
* View-frame unit vectors for a pose within a local ENU frame: horizontal
* forward, viewer-right, and the full pitched view axis.
@@ -192,25 +188,57 @@ function ringPositions(center, radius, basisA, basisB) {
const positions = [];
for (let i = 0; i <= RING_SEGMENTS; i++) {
const angle = (i / RING_SEGMENTS) * 2 * Math.PI;
const offset = combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
positions.push(
add(
center,
combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
),
),
);
positions.push(Cesium.Cartesian3.add(center, offset, offset));
}
return positions;
}
/** The ring and arrow parts: their colour, width and whether an arrow. */
const LINE_PARTS = Object.freeze([
['ring-heading', COLOR_RING_HEADING, 3, false],
['ring-pitch', COLOR_RING_PITCH, 3, false],
['move-east', COLOR_MOVE_EAST, 12, true],
['move-north', COLOR_MOVE_NORTH, 12, true],
['move-up', COLOR_MOVE_UP, 12, true],
]);
/** The point parts (an arrow's tip included): colour and first size. */
const POINT_PARTS = Object.freeze([
['move-east', COLOR_MOVE_EAST, 14],
['move-north', COLOR_MOVE_NORTH, 14],
['move-up', COLOR_MOVE_UP, 14],
['handle-range', COLOR_HANDLE, 13],
['handle-fov-l', COLOR_HANDLE, 10],
['handle-fov-r', COLOR_HANDLE, 10],
]);
/** Every part a pick can grab. */
const PARTS = new Set([
...LINE_PARTS.map(([part]) => part),
...POINT_PARTS.map(([part]) => part),
]);
let gizmoInstances = 0;
/**
* Creates the calibration gizmo controller (design §3c). Renders grab-able
* handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags
* into calibration patches through a narrow callback interface — the gizmo
* never touches layer records/stores directly.
* never touches layer records/stores directly. It draws through the
* renderer's draw port (a line set for the rings and arrows, a point set
* for the handles and arrow tips, each item `cctv-gizmo-<part>`) and picks
* and casts rays through its query port.
*
* @param {Object} deps
* @param {Cesium.Viewer} deps.viewer
* @param {object} deps.viewer - The viewer whose renderer draws it.
* @param {function(): Object|null} deps.getActiveRecord - Returns the record
* the gizmo should attach to, or null to hide (layer decides: enabled +
* calibration mode + active camera).
@@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) {
* end, for the PINNED drag record.
* @returns {{setEnabled: function(boolean): void, refresh: function(): void,
* destroy: function(): void, isDragging: function(): boolean,
* isEnabled: function(): boolean}}
* isEnabled: function(): boolean, partsForTest: function(): Object}}
*/
export function createCalibrationGizmo({
viewer,
@@ -234,74 +262,70 @@ export function createCalibrationGizmo({
let hoveredId = null;
let lastDragAt = 0;
let lastHoverAt = 0;
const entities = new Map(); // part -> Entity
// Whether the parts are drawn now, and each point part's pixel size.
let shown = false;
const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size]));
// The parts' geometry as last drawn: ECEF line positions and point spots.
const linePositions = new Map();
const pointPositions = new Map();
const scene = viewer.scene;
const input = inputFor(viewer);
let releaseCamera = null;
/** 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) viewer.entities.remove(stale);
const entity = viewer.entities.add({ id, show: false, ...options });
entities.set(part, entity);
return entity;
}
const instance = ++gizmoInstances;
const draw = drawOf(viewer);
const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` });
const points = draw.points({ id: `cctv-gizmo:${instance}:points` });
function polylinePart(part, color, width, arrow = false) {
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),
/** The rings and arrows as they now are. */
function lineItems() {
const items = [];
for (const [part, color, widthPx, arrow] of LINE_PARTS) {
const positions = linePositions.get(part);
if (!positions) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
positions,
widthPx,
mode: '3d',
style: arrow
? { kind: 'arrow', color: rgba(color) }
: { kind: 'solid', color: rgba(color, 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),
},
});
depthFailColor: rgba(color, 0.45),
show: shown,
});
}
return items;
}
function pointPart(part, color, pixelSize) {
addEntity(part, {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
/** The handles and arrow tips as they now are. */
function pointItems() {
const items = [];
for (const [part, color] of POINT_PARTS) {
const pos = pointPositions.get(part);
if (!pos) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
pos,
pixelSize: pointSizes.get(part),
color: rgba(color),
outlineColor: HANDLE_OUTLINE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
disableDepthTest: Number.POSITIVE_INFINITY,
show: shown,
});
}
return items;
}
polylinePart('ring-heading', COLOR_RING_HEADING, 3);
polylinePart('ring-pitch', COLOR_RING_PITCH, 3);
polylinePart('move-east', COLOR_MOVE_EAST, 12, true);
polylinePart('move-north', COLOR_MOVE_NORTH, 12, true);
polylinePart('move-up', COLOR_MOVE_UP, 12, true);
pointPart('handle-range', COLOR_HANDLE, 13);
pointPart('handle-fov-l', COLOR_HANDLE, 10);
pointPart('handle-fov-r', COLOR_HANDLE, 10);
function hideAll() {
for (const entity of entities.values()) entity.show = false;
if (!shown) return;
shown = false;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Recomputes every handle's geometry from the active record's CURRENT pose
@@ -329,69 +353,52 @@ export function createCalibrationGizmo({
);
const arrowLen = radius * ARROW_LENGTH_FACTOR;
entities.get('ring-heading').polyline.positions = ringPositions(
mount,
radius,
axes.north,
axes.east,
linePositions.set(
'ring-heading',
ringPositions(mount, radius, axes.north, axes.east),
);
entities.get('ring-pitch').polyline.positions = ringPositions(
mount,
radius,
forwardHoriz,
axes.up,
linePositions.set(
'ring-pitch',
ringPositions(mount, radius, forwardHoriz, axes.up),
);
const arrowTo = (dir) => [
mount,
Cesium.Cartesian3.add(
mount,
Cesium.Cartesian3.multiplyByScalar(
dir,
arrowLen,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
];
const eastArrow = arrowTo(axes.east);
const northArrow = arrowTo(axes.north);
const upArrow = arrowTo(axes.up);
entities.get('move-east').polyline.positions = eastArrow;
entities.get('move-east').position = eastArrow[1];
entities.get('move-north').polyline.positions = northArrow;
entities.get('move-north').position = northArrow[1];
entities.get('move-up').polyline.positions = upArrow;
entities.get('move-up').position = upArrow[1];
entities.get('handle-range').position = positions.capCenter;
entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint(
positions.tl,
positions.bl,
new Cesium.Cartesian3(),
);
entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint(
positions.tr,
positions.br,
new Cesium.Cartesian3(),
);
for (const entity of entities.values()) entity.show = true;
const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))];
for (const [part, dir] of [
['move-east', axes.east],
['move-north', axes.north],
['move-up', axes.up],
]) {
const arrow = arrowTo(dir);
linePositions.set(part, arrow);
pointPositions.set(part, arrow[1]);
}
pointPositions.set('handle-range', positions.capCenter);
pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl));
pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br));
shown = true;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Extracts a gizmo part name from a pick result, or null. */
function gizmoPartFrom(picked) {
const id = picked?.id?.id ?? picked?.id;
/** The gizmo part a pick hit is, or null. */
function gizmoPartFrom(hit) {
if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null;
const id = hit.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null;
return id.slice(GIZMO_ID_PREFIX.length);
const part = id.slice(GIZMO_ID_PREFIX.length);
return PARTS.has(part) ? part : null;
}
function pickGizmoPart(windowPosition) {
const query = findQuery(viewer);
if (!query || !windowPosition) return null;
const { x, y } = 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;
const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 }));
if (part && shown) return part;
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] pick threw:', err?.message || err);
@@ -400,7 +407,8 @@ export function createCalibrationGizmo({
let results = [];
try {
results = scene.drillPick(windowPosition, 6, 14, 14) || [];
results =
query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || [];
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err);
@@ -410,52 +418,54 @@ export function createCalibrationGizmo({
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug(
'[CCTV:gizmo] drillPick @',
windowPosition?.x,
windowPosition?.y,
x,
y,
'→',
JSON.stringify(
results.map((r) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name),
results.map((hit) =>
hit.surface ? '(surface)' : `${hit.set}/${hit.id}`,
),
),
);
}
for (const picked of results) {
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
for (const hit of results) {
const part = gizmoPartFrom(hit);
if (part && shown) return part;
}
return null;
}
function pickRay(windowPosition) {
try {
return viewer.camera.getPickRay(windowPosition) || null;
return (
findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null
);
} catch {
return null;
}
}
function setCursor(value) {
if (scene.canvas?.style) scene.canvas.style.cursor = value;
const style = canvasOf(viewer)?.style;
if (style) style.cursor = value;
}
function setHovered(part) {
const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null;
if (nextId === hoveredId) return;
hoveredId = nextId;
// Hover feedback must NEVER touch polyline geometry: a width change makes
// Cesium rebuild the batched polyline primitive, and until the next render
// the part vanishes from the pick buffer — so the very hover that finds a
// ring makes the following LEFT_DOWN miss it (root-caused via the QA
// harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback
// only; point handles are PointPrimitives (live-updatable, no rebuild), so
// they keep the size bump.
for (const [name, entity] of entities.entries()) {
if (!entity.point) continue;
// Hover feedback must NEVER touch line geometry: a width change rebuilds
// the line, and until the next render the part vanishes from the pick
// buffer — so the very hover that finds a ring makes the following
// LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag,
// 2026-07-05). Rings/arrows get cursor feedback only; point handles
// (an arrow's tip included) change size in place, so they keep the size
// bump.
for (const [name] of POINT_PARTS) {
const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`;
entity.point.pixelSize =
(name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0));
}
points.upsert(pointItems());
setCursor(hoveredId ? 'grab' : '');
}
@@ -469,8 +479,8 @@ export function createCalibrationGizmo({
const ray = pickRay(windowPosition);
if (!ray) return false;
const mount = Cesium.Cartesian3.clone(positions.mount);
const capCenter = Cesium.Cartesian3.clone(positions.capCenter);
const mount = { ...positions.mount };
const capCenter = { ...positions.capCenter };
const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg,
@@ -595,12 +605,7 @@ export function createCalibrationGizmo({
if (part === 'handle-fov-l' || part === 'handle-fov-r') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view);
if (!hit) return null;
const lateral = Math.abs(
Cesium.Cartesian3.dot(
Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()),
right,
),
);
const lateral = Math.abs(dot(sub(hit, capCenter), right));
const halfW = Math.max(0.5, lateral);
const fovDeg = toDeg(
2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)),
@@ -692,13 +697,22 @@ export function createCalibrationGizmo({
offDown();
offMove();
offUp();
for (const entity of entities.values()) {
viewer.entities.remove(entity);
}
entities.clear();
lines.dispose();
points.dispose();
setCursor('');
},
isDragging: () => !!drag,
isEnabled: () => enabled,
/**
* The parts as last drawn, by item id, for the QA harness: whether each
* shows, a line's `positions` and a point's `pos` (an arrow has both).
*/
partsForTest() {
const parts = {};
for (const item of [...lineItems(), ...pointItems()])
parts[item.id] = { ...parts[item.id], ...item };
for (const item of lineItems()) parts[item.id].show = item.show;
return parts;
},
};
}
+272 -65
View File
@@ -12,7 +12,6 @@
// - the controller ends an open drag, and its camera hold, on the next press.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
GIZMO_ID_PREFIX,
closestParamOnAxis,
@@ -22,8 +21,11 @@ import {
signedAngleDelta,
} from './cctvGizmo.js';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fromDegrees } from '../geo/ellipsoid.js';
import { add, distance, negate, normalize, scale } from '../geo/vector.js';
const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z);
const c3 = (x, y, z) => ({ x, y, z });
test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => {
// Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5):
@@ -40,10 +42,7 @@ test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', ()
test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => {
// Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the
// axis around x=10 (it reaches y=0 at x=10).
const dir = Cesium.Cartesian3.normalize(
c3(1, -1, 0),
new Cesium.Cartesian3(),
);
const dir = normalize(c3(1, -1, 0));
const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0));
assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`);
});
@@ -63,10 +62,7 @@ test('closestParamOnAxis: near-parallel ray/axis returns null', () => {
closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)),
null,
);
const nearly = Cesium.Cartesian3.normalize(
c3(1, 1e-9, 0),
new Cesium.Cartesian3(),
);
const nearly = normalize(c3(1, 1e-9, 0));
assert.equal(
closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)),
null,
@@ -81,25 +77,19 @@ test('rayPlaneIntersect: straight-on hit lands at the expected point', () => {
c3(0, 0, 1),
);
assert.ok(hit, 'expected a hit');
assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9);
assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9);
});
test('rayPlaneIntersect: oblique hit resolves correctly', () => {
const dir = Cesium.Cartesian3.normalize(
c3(1, 0, -1),
new Cesium.Cartesian3(),
);
const dir = normalize(c3(1, 0, -1));
const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1));
assert.ok(hit);
assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`);
assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`);
});
test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => {
// dir almost in-plane: z component 0.05 < 0.08 threshold.
const dir = Cesium.Cartesian3.normalize(
c3(1, 0, -0.05),
new Cesium.Cartesian3(),
);
const dir = normalize(c3(1, 0, -0.05));
assert.equal(
rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)),
null,
@@ -136,60 +126,133 @@ test('signedAngleDelta: shortest-path wrap', () => {
assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9);
});
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
/**
* A viewer double drawing through a fake draw port, whose query port picks
* `picked` and casts the ray `ray` (a ray,
* or a function of the window position).
*/
function gizmoViewer(t, { picked, ray }) {
const viewer = {
entities: {
byId: new Map(),
getById(id) {
return this.byId.get(id);
},
add(options) {
this.byId.set(options.id, options);
return options;
},
remove(entity) {
this.byId.delete(entity.id);
},
},
scene: {
canvas: { style: {} },
screenSpaceCameraController: { enableInputs: true },
pick: () => ({ id: { id: `${GIZMO_ID_PREFIX}move-up` } }),
drillPick: () => [],
},
};
const mount = Cesium.Cartesian3.fromDegrees(0, 0, 10);
const east = new Cesium.Cartesian3(0, 1, 0); // east at lon 0, lat 0
viewer.camera = {
getPickRay: () => ({
origin: Cesium.Cartesian3.add(
mount,
Cesium.Cartesian3.multiplyByScalar(east, 100, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
),
direction: Cesium.Cartesian3.negate(east, new Cesium.Cartesian3()),
const queries = [];
const { draw, unbind } = bindFakeDraw(viewer, {
query: {
pick: (x, y, window) => (queries.push(['pick', window]), picked()),
drillPick: (x, y, options) => (queries.push(['drill', options]), []),
pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray),
},
});
t.after(unbind);
return { viewer, draw, queries };
}
const mount = fromDegrees(0, 0, 10);
const east = c3(0, 1, 0); // east at lon 0, lat 0
const gizmoRecord = () => ({
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
});
test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => {
const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
const lines = draw.find('cctv-gizmo:');
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
assert.equal(lines.kind, 'lines');
assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
assert.deepEqual(
[...lines.items.keys()],
['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map(
(part) => GIZMO_ID_PREFIX + part,
),
);
assert.deepEqual(
[...points.items.keys()],
[
'move-east',
'move-north',
'move-up',
'handle-range',
'handle-fov-l',
'handle-fov-r',
].map((part) => GIZMO_ID_PREFIX + part),
);
const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`);
assert.equal(ring.mode, '3d');
assert.equal(ring.widthPx, 3);
assert.equal(ring.positions.length, 97, 'a closed 96-segment ring');
assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12);
assert.ok(Math.abs(ring.depthFailColor[3] - 0.45) < 1e-12);
const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.equal(arrow.style.kind, 'arrow');
assert.equal(arrow.widthPx, 12);
// The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up.
assert.ok(
distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6,
);
const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.deepEqual(tip.pos, arrow.positions[1]);
assert.equal(tip.pixelSize, 14);
assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => item.show,
),
);
gizmo.setEnabled(false);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => !item.show,
),
'hidden off ADJUST',
);
gizmo.destroy();
assert.equal(lines.disposed, true);
assert.equal(points.disposed, true);
});
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
let lineSet = null;
const { viewer, draw, queries } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-up`,
surface: false,
}),
};
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = {
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
};
const record = gizmoRecord();
const ended = [];
const gizmo = createCalibrationGizmo({
viewer,
@@ -198,11 +261,13 @@ test('a press after a release Cesium never reported ends the open drag and its c
endPatch: (r) => ended.push(r),
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
const controller = viewer.scene.screenSpaceCameraController;
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]);
assert.equal(controller.enableInputs, false);
// The release came with a modifier key held: Cesium raised no LEFT_UP.
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
@@ -211,3 +276,145 @@ test('a press after a release Cesium never reported ends the open drag and its c
assert.equal(gizmo.isDragging(), false);
assert.equal(controller.enableInputs, true, 'no hold was stranded');
});
test('a pick of another set or a stray id is no gizmo part', (t) => {
let picked = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => picked,
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
gizmo.setEnabled(true);
picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false };
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'another set');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
picked = {
set: draw.find('cctv-gizmo:').spec.id,
id: `${GIZMO_ID_PREFIX}nothing`,
surface: false,
};
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'no such part');
});
test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => {
const up = c3(1, 0, 0); // up at lon 0, lat 0
let lineSet = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-east`,
surface: false,
}),
// Straight down onto the east axis, `x` metres east of the mount.
ray: (x) => ({
origin: add(add(mount, scale(east, x)), scale(up, 100)),
direction: negate(up),
}),
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
record.camera.calibration = { offsetEastM: 2 };
const patches = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch: (patch, pinned) => patches.push([patch, pinned]),
endPatch() {},
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.equal(viewer.scene.canvas.style.cursor, 'grabbing');
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 12, y: 5 },
});
assert.equal(patches.length, 1);
const [patch, pinned] = patches[0];
assert.equal(pinned, record, 'patched on the record dragged');
assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`);
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } });
assert.equal(gizmo.isDragging(), false);
});
test('hovering a handle grows it and shows the grab cursor', (t) => {
let pointSet = null;
let over = true;
const { viewer, draw } = gizmoViewer(t, {
picked: () =>
over
? {
set: pointSet,
id: `${GIZMO_ID_PREFIX}handle-range`,
surface: false,
}
: null,
ray: null,
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
pointSet = points.spec.id;
gizmo.setEnabled(true);
const size = () =>
points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize;
assert.equal(size(), 13);
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 6, y: 5 },
});
assert.equal(size(), 17);
assert.equal(viewer.scene.canvas.style.cursor, 'grab');
});
test('the harness reads each part as drawn, an arrow with its line and tip', (t) => {
const { viewer } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
const parts = gizmo.partsForTest();
const arrow = parts[`${GIZMO_ID_PREFIX}move-east`];
assert.equal(arrow.positions.length, 2, 'its line');
assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip');
assert.equal(arrow.show, true);
assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true);
assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos);
gizmo.setEnabled(false);
assert.ok(
Object.values(gizmo.partsForTest()).every((part) => part.show === false),
);
});
+1
View File
@@ -111,6 +111,7 @@ export function createCctvLayer({ services, source }) {
parts.testing._extractPickedCameraIdForTest,
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
_cctvIconsForTest: parts.testing._cctvIconsForTest,
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
focusCctvRecord: parts.navigation.focusCctvRecord,
maybeAutoHop: parts.navigation.maybeAutoHop,
cctvCycleIndex: parts.navigation.cctvCycleIndex,
+7
View File
@@ -122,6 +122,12 @@ export function createTesting({ state: layerState, services, parts, source }) {
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
/** What the layer draws now, for the QA harness: the gizmo's parts. */
function _cctvDrawnForTest() {
return { gizmo: layerState._gizmo?.partsForTest() ?? {} };
}
/** The layer's icon set, for tests that read what the rows draw. */
function _cctvIconsForTest() {
@@ -135,5 +141,6 @@ export function createTesting({ state: layerState, services, parts, source }) {
_extractPickedCameraIdForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_cctvDrawnForTest,
};
}
-1
View File
@@ -7,7 +7,6 @@
"src/cockpitCloudEffects.js",
"src/cyberSonarGpu.js",
"src/cyberSonarScene.js",
"src/data/cctvGizmo.js",
"src/data/geoImportPins.js",
"src/input/dispatcher.js",
"src/input/sensorPick.js",