Files
gods-eye-view/src/testSupport/fakeCameraPort.mjs
T
Sameh Khamis 491c58cdc6 Drive the camera verbs through the camera and frame ports and take them off the Cesium list
The verbs' motions run on the frame port's preUpdate, which Cesium raises
right after the clock tick they used to run on; a renderer bound after the
verbs started is picked up when the next motion starts. They read the camera
from its port's pose, wait for a flight through its `flying`, and frame an
orbit from the pose with the geo maths.

Globe rotation tests the keyhole fit from the pose and the port's projection
matrix (a centred perspective one) instead of Cesium's frustum, and checks
the Globe View preset by computing its pose rather than cloning a Cesium
camera. The contract's renderer is a 3D WGS84 globe, so the scene-mode and
non-WGS84 refusals go with their tests. At the start the captured pose is
written back through setView only when the camera handoff changed it (a
route's bank levelled), instead of copying the basis into Cesium's camera.

The verbs still read the viewer's canvas for its size and listen on it for
the user's input.
2026-11-07 14:37:58 -08:00

198 lines
6.6 KiB
JavaScript

/**
* A camera port for tests of code that reads the camera: a settable pose,
* a settable view rectangle, and events the test raises itself.
*/
import { createCameraEvents } from '../render/camera/events.js';
import { toDegrees } from '../geo/index.js';
import { bindRenderer, rendererOf } from '../render/rendererOf.js';
import { createCesiumCamera } from '../render/cesium/camera.js';
import { fakeCesiumCredits } from './fakeCreditsPort.mjs';
const DEFAULT_POSE = Object.freeze({
lon: 0,
lat: 0,
height: 1000,
heading: 0,
pitch: -Math.PI / 2,
roll: 0,
position: { x: 0, y: 0, z: 0 },
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
near: 1,
far: 5e8,
frameIsIdentity: true,
});
/**
* @param {{pose?: object, viewRectangle?: object|null}} [initial]
*/
export function fakeCameraPort({ pose = {}, viewRectangle = null } = {}) {
let current = { ...DEFAULT_POSE, ...pose };
let rect = viewRectangle;
const events = createCameraEvents({
pose: () => ({ ...current }),
report: (error) => {
throw error;
},
});
const counts = {};
const port = {
pose: () => ({ ...current }),
viewRectangle: () => (rect ? { ...rect } : null),
on(event, cb, options) {
const off = events.on(event, cb, options);
counts[event] = (counts[event] ?? 0) + 1;
let live = true;
return () => {
if (live) counts[event] -= 1;
live = false;
off();
};
},
};
return {
port,
/** Change the pose the port reports. */
setPose: (fields) => (current = { ...current, ...fields }),
setViewRectangle: (next) => (rect = next),
emit: (event) => events.emit(event),
/** Run the contract's `changed` measure, as a frame would. */
stepChanged: () => events.stepChanged(),
listenerCount: (event) => counts[event] ?? 0,
};
}
/**
* Bind to a fake viewer the Cesium renderer's own camera port over its
* Cesium-shaped fake camera, for tests whose code is half on the port: the
* port's commands reach the fake camera as the renderer maps them
* (`flyTo({destination: Cartesian3, ...})`), while poses are read leniently
* from what the fake has (`positionCartographic`, `heading`, `pitch`,
* `roll`, the frustum's `fovy`, `aspectRatio`, `near` and `far`) and events come from the fake's own `changed`, `moveStart` and
* `moveEnd`. A fake with `trackedEntityChanged` and `entities` follows
* through the port, as the renderer does. Its credits are the renderer's
* credits port over the fake's `creditDisplay`, if it has one; `ports`
* adds other ports (a fake draw port, say). Binding a viewer twice keeps the
* first. Returns the viewer.
* @template {{camera: object}} V
* @param {V} viewer
* @param {object} [ports]
* @returns {V}
*/
export function bindFakeCesiumCamera(viewer, ports = {}) {
if (rendererOf(viewer)) return viewer;
const fake = viewer.camera;
const noEvent = { addEventListener: () => () => {} };
// A fake that does not keep Cesium's current flight gets one kept for it,
// as Cesium does: from a flight's start until it completes or cancels.
let current = null;
const flown = (fly) =>
function (...args) {
const options = args.at(-1) ?? {};
const flight = {};
current = flight;
const settle = (cb) => () => {
if (current === flight) current = null;
cb?.();
};
args[args.length - 1] = {
...options,
complete: settle(options.complete),
cancel: settle(options.cancel),
};
return fly.apply(this, args);
};
const keepsFlight = '_currentFlight' in fake;
const camera = new Proxy(fake, {
get(target, key, receiver) {
if ((key === 'moveStart' || key === 'moveEnd') && !target[key])
return noEvent;
if (!keepsFlight) {
if (key === '_currentFlight') return current ?? undefined;
if ((key === 'flyTo' || key === 'flyToBoundingSphere') && target[key])
return flown(target[key]);
if (key === 'cancelFlight' && target[key])
return function (...args) {
current = null;
return target[key].apply(this, args);
};
}
return Reflect.get(target, key, receiver);
},
});
const scene = {
postUpdate: noEvent,
preUpdate: viewer.scene?.preUpdate ?? noEvent,
get screenSpaceCameraController() {
return viewer.scene?.screenSpaceCameraController ?? undefined;
},
requestRender: () => viewer.scene?.requestRender?.(),
};
// A fake with Cesium's entity tracking follows as the renderer does.
const tracks = Boolean(viewer.trackedEntityChanged && viewer.entities);
const real = createCesiumCamera({
scene,
camera,
...(tracks ? { widget: viewer } : {}),
report: (error) => {
throw error;
},
}).port;
const port = Object.create(real, {
pose: {
value() {
const c = fake.positionCartographic;
const p = fake.positionWC;
const v = (w) => ({ x: w.x, y: w.y, z: w.z });
return {
...DEFAULT_POSE,
...(p ? { position: v(p) } : {}),
...(fake.directionWC ? { direction: v(fake.directionWC) } : {}),
...(fake.upWC ? { up: v(fake.upWC) } : {}),
...(fake.rightWC ? { right: v(fake.rightWC) } : {}),
...(Number.isFinite(fake.frustum?.fovy)
? { fovy: fake.frustum.fovy }
: {}),
...(Number.isFinite(fake.frustum?.aspectRatio)
? { aspectRatio: fake.frustum.aspectRatio }
: {}),
...(typeof fake.frustum?.near === 'number'
? { near: fake.frustum.near }
: {}),
...(typeof fake.frustum?.far === 'number'
? { far: fake.frustum.far }
: {}),
lon: c ? toDegrees(c.longitude) : NaN,
lat: c ? toDegrees(c.latitude) : NaN,
height: c ? c.height : NaN,
heading: fake.heading ?? 0,
pitch: fake.pitch ?? -Math.PI / 2,
roll: fake.roll ?? 0,
};
},
},
// A fake that computes a view rectangle answers with it, as the
// renderer does; one that does not has none.
viewRectangle: {
value: () => (fake.computeViewRectangle ? real.viewRectangle() : null),
},
on: {
value(event, cb) {
const source = fake[event];
const off = source?.addEventListener?.(cb);
if (typeof off === 'function') return off;
return () => source?.removeEventListener?.(cb);
},
},
});
bindRenderer(viewer, {
...ports,
camera: port,
credits: fakeCesiumCredits(viewer),
});
return viewer;
}