Files
gods-eye-view/src/cameraGroundGuard.test.mjs
T
German Khokhlov 35e70ec280 Draw the aircraft family, Wildlife Sightings and the Cockpit through the contract
The layers that still had one Cesium and one Navara implementation, or
drew on Cesium only, now draw through engine.movers, engine.lines and
engine.camera on both engines, and application code holds the engine
instead of guessing it from a viewer.

- Aircraft family: flights, military and local ADS-B share one display
  (src/layers/aircraft/render/display.js). The Cesium and Navara
  renderers are gone. Where they differed, the display follows Cesium:
  - attach and visibility tracking, live disableDepthTestDistance
    changes, the tracked glyph's distance scale, model ids that change,
    local ADS-B markers hidden until shown and its UAT ring as a point;
  - the trail head's hidden alpha is 0.45, the contract's
    depthFailAlpha scaled by the head's 0.9.
  The tracked glyph stays over the fleet, as on Navara. The movers
  contract reports readiness per model and reads model axes as the
  glTF's own on every engine. Cesium's follow takes any native target
  through a proxy entity in the ENU frame and mirrors its readout fields.
- Wildlife Sightings draws badges and the density glow as sprite sets
  and its privacy cells as line outlines (no fill yet). It takes clicks
  from engine.input and its card anchors to the engine's canvas and
  camera, so the layer is in both engines' catalogs again and a switch
  keeps the session's layer set.
- Cockpit: cockpitHost takes the engine only. The ridden aircraft is the
  engine follow's target, hidden through its sprite; only the Cesium
  Viewer's stock double-click is still routed around.
- About forty camera, navigation, share-link, HUD, voice, detection and
  layer-lifecycle callers take the engine. isGlobeEngine and
  engineFromViewer calls outside src/globe fall from 51 to 14.

The coupling baseline drops accordingly: layer renderer lines from
5239/12331 to 4546/11106 (Cesium/Navara), `viewer` lines from 2424 to
2209, Cesium-importing files from 69 to 66.
2026-11-07 02:34:34 +04:00

215 lines
8.8 KiB
JavaScript

// Camera ground-guard policy tests: pure arithmetic plus a fake scene, no network.
//
// Arrival framing is computed before the destination's tiles exist, so it
// works from a predicted ground height. The guard measures the real surface
// after arrival and lifts the eye; these tests pin when it acts.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
MIN_EYE_CLEARANCE_M,
groundClearanceDeficitM,
guardCameraAboveGround,
} from './cameraGroundGuard.js';
import { createCesiumEngine } from './globe/cesium/createCesiumEngine.js';
import { createFakeEngine } from './globe/testing/fakeEngine.js';
test('a buried camera is lifted clear of the surface', () => {
// Framed near sea level, arriving over ground at ~1,609 m (Denver).
const lift = groundClearanceDeficitM(140, 1609);
assert.equal(lift, 1609 + MIN_EYE_CLEARANCE_M - 140);
});
test('a camera resting on the surface is lifted to a usable height', () => {
// Camp Mabry field report: eye 1 m above the mesh at 171 m.
assert.equal(groundClearanceDeficitM(172, 171), MIN_EYE_CLEARANCE_M - 1);
});
test('a well-framed arrival is left alone', () => {
assert.equal(groundClearanceDeficitM(1755, 1609), 0);
assert.equal(groundClearanceDeficitM(2960, 1609), 0);
});
test('sub-metre noise never triggers a nudge', () => {
assert.equal(groundClearanceDeficitM(1609 + MIN_EYE_CLEARANCE_M, 1609), 0);
assert.equal(
groundClearanceDeficitM(1609 + MIN_EYE_CLEARANCE_M - 1, 1609),
0,
);
});
test('an unmeasurable surface is never acted on', () => {
assert.equal(groundClearanceDeficitM(1000, Number.NaN), 0);
assert.equal(groundClearanceDeficitM(Number.NaN, 1609), 0);
assert.equal(groundClearanceDeficitM(1000, undefined), 0);
});
test('the clearance frames a subject without turning into an overflight', () => {
assert.ok(MIN_EYE_CLEARANCE_M >= 60);
assert.ok(MIN_EYE_CLEARANCE_M <= 250);
});
// A viewer double under the real Cesium engine (`viewer.engine`), so the
// guard runs the shell's engine path against Cesium-shaped calls.
function fakeViewer({ cameraHeightM, surfaceM, canvas = null }) {
const flights = [];
const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM);
const viewer = {
flights,
canvas,
scene: {
canvas,
sampleHeightSupported: true,
sampleHeight: (carto) =>
typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM,
},
camera: {
positionCartographic: position,
positionWC: Cesium.Cartographic.toCartesian(position),
frustum: { fovy: 1, aspectRatio: 1.5 },
heading: 0.5,
pitch: -0.55,
roll: 0,
flyTo: (options) => flights.push(options),
},
};
viewer.engine = createCesiumEngine(viewer);
return viewer;
}
test('the guard lifts a buried arrival once the surface answers', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
const lifts = [];
guardCameraAboveGround(
viewer.engine,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 1, onLift: (m) => lifts.push(m) },
);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 1);
const lifted = Cesium.Cartographic.fromCartesian(
viewer.flights[0].destination,
);
assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5);
assert.equal(viewer.flights[0].orientation.heading, 0.5);
assert.equal(lifts.length, 1);
});
test('the guard waits for streaming tiles and yields to a newer arrival', async () => {
let answer = Number.NaN;
let stale = false;
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: () => answer });
guardCameraAboveGround(
viewer.engine,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 2, attempts: 20, isStale: () => stale },
);
await new Promise((resolve) => setTimeout(resolve, 12));
assert.equal(viewer.flights.length, 0, 'no guess while tiles stream in');
stale = true;
answer = 171;
await new Promise((resolve) => setTimeout(resolve, 12));
assert.equal(viewer.flights.length, 0, 'a newer arrival owns the camera');
});
test('the guard leaves a clear view untouched', async () => {
const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 });
guardCameraAboveGround(viewer.engine, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 });
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0);
});
// Handoffs act before the delayed probe, even when the next owner stays low.
import { NavigationController } from './ui/navigationController.js';
import { SceneDirector } from './scenes/director.js';
import { LayerLifecycle } from './data/lifecycle.js';
function handoffFixture(t) {
t.mock.timers.enable({ apis: ['setTimeout'] });
const canvas = new EventTarget();
canvas.ownerDocument = new EventTarget();
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171, canvas });
viewer.trackedEntityChanged = new Cesium.Event();
viewer.camera.cancelFlight = () => {};
viewer.camera.lookAtTransform = () => {};
viewer.camera.flyToBoundingSphere = () => {};
viewer.camera.setView = () => {};
const originalFly = viewer.camera.flyTo;
const navigation = new NavigationController({
viewer,
engine: viewer.engine,
tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer',
'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer',
'rocketLaunchesLayer'].map((key) => [key, {}])),
cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {},
getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {},
isCockpitActive: () => false, showToast() {},
});
guardCameraAboveGround(viewer.engine, { lat: 30.3, lon: -97.7 });
return { viewer, navigation, originalFly };
}
for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) {
test(`arrival guard relinquishes and removes hooks on ${handoff}`, async (t) => {
const { viewer, navigation, originalFly } = handoffFixture(t);
if (handoff === 'Director') {
SceneDirector.prototype._claimCameraOwnership.call({
viewer, engine: viewer.engine, styleManager: { runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn) },
});
} else if (handoff === 'tracking') {
viewer.trackedEntityChanged.raiseEvent({ id: 'contact' });
} else if (handoff === 'follow' || handoff === 'UI') {
navigation._stampNavigation({ cancelPendingSelection: false });
} else if (handoff === 'keyboard') {
viewer.scene.canvas.ownerDocument.dispatchEvent(new Event('keydown'));
} else if (handoff === 'app-stop') navigation.stop();
else if (handoff.startsWith('layer-')) {
const lifecycle = new LayerLifecycle(viewer, { engine: viewer.engine });
lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} });
await lifecycle.setEnabled('test', true);
if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false);
else await lifecycle.destroyLayer('test');
} else viewer.camera[handoff]({});
const priorFlights = viewer.flights.length;
t.mock.timers.tick(10000);
assert.equal(viewer.flights.length, priorFlights, 'the old probe cannot fly');
assert.equal(viewer.camera.flyTo, originalFly, 'direct-call hook is removed');
assert.equal(viewer.trackedEntityChanged.numberOfListeners, 0);
navigation.destroy();
});
}
test('the guard runs on a globe engine alone and yields to its next camera command', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const engine = createFakeEngine();
engine.fake.setPose({
position: Cesium.Cartesian3.fromDegrees(-97.7603, 30.3141, 172),
heading: 0.5,
pitch: -0.55,
roll: 0,
});
engine.fake.script('sampleHeight', 171);
const lifts = [];
guardCameraAboveGround(engine, { lat: 30.3125, lon: -97.765 }, {
onLift: (m) => lifts.push(m),
});
t.mock.timers.tick(600);
const [flight] = engine.fake.callsOf('camera.flyTo')[0].args;
const lifted = Cesium.Cartographic.fromCartesian(flight.destination);
assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5);
assert.ok(Math.abs(flight.orientation.heading - 0.5) < 1e-9);
assert.equal(flight.easing, 'cubicInOut');
assert.equal(lifts.length, 1);
assert.equal(engine.camera.commanded.numberOfListeners, 0);
// A camera command before the first probe ends the guard.
engine.fake.setPose({ position: Cesium.Cartesian3.fromDegrees(-97.7603, 30.3141, 172) });
guardCameraAboveGround(engine, { lat: 30.3125, lon: -97.765 });
engine.camera.cancelFlight();
t.mock.timers.tick(10000);
assert.equal(engine.fake.callsOf('camera.flyTo').length, 1);
assert.equal(engine.camera.commanded.numberOfListeners, 0);
});