Read the HUD and share-link camera through the renderer's camera port

The first camera-family slice. The camera port's events move into a
shared module (render/camera/events.js) that the stub and the Cesium
port both use: listener lists, delivery with errors reported, and the
contract's per-listener `changed` measure.

The Cesium port gains:
- camera.on: `changed` measured per listener on every tick, where Cesium
  measures its single threshold (the counts match Cesium's own at each
  threshold); moveStart and moveEnd relayed from Cesium's camera;
- camera.viewRectangle, in degrees (now in CESIUM_CHECKS);
- lon and lat in pose, and NaN where Cesium has no cartographic position.

Code that still holds the viewer reaches the renderer through
rendererOf(viewer); the application renderer binds it on create and
unbinds on destroy.

The HUD reads its telemetry from the camera port and no longer imports
Cesium (off the allow-list). The share link writes the hash from the
pose. Its restore path stays on the viewer's camera for a later slice.

Behaviour changes:
- The share link listens to `changed` at its own 0.5 threshold, not at
  whatever global threshold layers had set, and also to moveEnd, so the
  hash always catches up with where the camera comes to rest.
- The HUD's and share link's camera callbacks run from the port's single
  relay, ahead of other moveStart/moveEnd listeners, and a throw in one
  is reported to the renderer's error listeners instead of escaping from
  Cesium's render.
This commit is contained in:
Sameh Khamis committed 2026-11-05 19:48:58 -08:00
1 parent 910185bfe0
commit b5900b4178
28 files changed
+688 -243

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
/**
* @module render/camera/events
* @description The camera port's events, shared by the Cesium port and the stub: the
* listener lists, delivery (a throwing listener is reported, the rest still
* run), and the contract's per-listener `changed` measure. A renderer calls
* `stepChanged()` once per frame and `emit()` for the events its engine
* raises.
*/
import { acosClamped, distance, dot } from '../../geo/index.js';
const TWO_PI = Math.PI * 2;
/** The contract's camera events. */
export const CAMERA_EVENTS = Object.freeze([
'changed',
'moveStart',
'moveEnd',
'followChanged',
'flightEnd',
]);
/** How far an angle moved, as a fraction of π, the short way round. */
const angleDelta = (a, b) => {
const d = Math.abs(a - b) % TWO_PI;
return (d > Math.PI ? TWO_PI - d : d) / Math.PI;
};
/**
* @param {{pose: () => import('../contract/camera').CameraPose,
* report: (error: unknown) => void}} options `pose` is read only while a
* `changed` listener is registered.
*/
export function createCameraEvents({ pose, report }) {
const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []]));
function deliver(entry) {
if (!entry.live) return;
try {
entry.cb();
} catch (error) {
report(error);
}
}
function emit(event) {
for (const entry of listeners[event].slice()) deliver(entry);
}
/**
* @param {string} event
* @param {() => void} cb
* @param {{threshold?: number}} [options]
* @returns {() => void}
*/
function on(event, cb, options = {}) {
const list = listeners[event];
if (!list) throw new Error(`Unknown camera event: ${event}`);
const entry = { cb, live: true, threshold: options.threshold ?? 0.5 };
list.push(entry);
return () => {
entry.live = false;
const i = list.indexOf(entry);
if (i >= 0) list.splice(i, 1);
};
}
/**
* Per listener, the reference camera's formula: heading and roll each
* against their own last reported value, then direction and position
* against the last reported view. Each can report in the same frame.
*/
function stepChanged() {
const list = listeners.changed;
if (!list.length) return;
const current = pose();
for (const entry of list.slice()) {
if (!entry.live) continue;
const t = entry.threshold;
entry.heading ??= current.heading;
entry.roll ??= current.roll;
const headingF = angleDelta(entry.heading, current.heading);
const rollF = angleDelta(entry.roll, current.roll);
if (headingF > t) entry.heading = current.heading;
if (rollF > t) entry.roll = current.roll;
if (headingF > t || rollF > t) deliver(entry);
if (!entry.view) {
entry.view = {
position: current.position,
direction: current.direction,
};
continue;
}
const dirF =
acosClamped(dot(current.direction, entry.view.direction)) /
(current.fovy * 0.5);
const heightF =
distance(current.position, entry.view.position) / current.height;
if (dirF > t || heightF > t) {
entry.view = {
position: current.position,
direction: current.direction,
};
deliver(entry);
}
}
}
/** Drop every listener, including those of an event under way. */
function clear() {
for (const list of Object.values(listeners)) {
for (const entry of list) entry.live = false;
list.length = 0;
}
}
return { on, emit, stepChanged, clear };
}
+6 -1
View File
@@ -14,10 +14,12 @@
* still missing.
* Until a family is ported, its code reaches the Cesium viewer through
* `cesiumViewerOf`, never through a renderer member, so no engine type
* crosses the contract and each call marks code still to port.
* crosses the contract and each call marks code still to port. Ported code
* that still holds the viewer reaches the renderer through `rendererOf`.
*/
import { createApplicationViewer } from '../../app/viewer.js';
import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js';
import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
@@ -101,6 +103,7 @@ export function createCesiumRendererPlugin({
creditContainer.remove();
throw error;
}
let unbind = () => {};
const renderer = Object.freeze({
id: 'cesium',
contractVersion: CONTRACT_VERSION,
@@ -118,6 +121,7 @@ export function createCesiumRendererPlugin({
},
destroy() {
try {
unbind();
input.dispose();
ports.dispose();
if (!viewer.isDestroyed()) viewer.destroy();
@@ -127,6 +131,7 @@ export function createCesiumRendererPlugin({
},
});
viewers.set(renderer, viewer);
unbind = bindRenderer(viewer, renderer);
return renderer;
},
});
+8 -3
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js';
import { rendererOf } from '../rendererOf.js';
import {
ReadonlySet,
cesiumRenderer,
@@ -49,10 +50,14 @@ function fakeViewer(log, { failDestroy = false } = {}) {
return {
listeners,
scene: {
camera: {},
camera: {
moveStart: fakeEvent(listeners),
moveEnd: fakeEvent(listeners),
},
primitives: { add() {}, remove() {} },
requestRender() {},
preUpdate: fakeEvent(listeners),
postUpdate: fakeEvent(listeners),
preRender: fakeEvent(listeners),
postRender: fakeEvent(listeners),
},
@@ -121,6 +126,7 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
assert.throws(() => renderer.capabilities.clear(), TypeError);
assert.ok(!('viewer' in renderer), 'no engine object is a member');
assert.equal(cesiumViewerOf(renderer).canvas, renderer.canvas);
assert.equal(rendererOf(viewer), renderer, 'the viewer finds its renderer');
assert.ok(viewer.listeners.size > 0, 'the ports follow the frame phases');
assert.equal(typeof renderer.draw.icons, 'function');
@@ -129,6 +135,7 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
renderer.resize();
renderer.destroy();
assert.equal(viewer.listeners.size, 0, 'and stop on destroy');
assert.equal(rendererOf(viewer), null, 'and lets go of the viewer');
assert.deepEqual(log, ['resize', 'destroy']);
assert.deepEqual(doc.children, [], 'credits leave with the renderer');
renderer.destroy();
@@ -340,12 +347,10 @@ const EXPECTED_MISSING = [
'camera.lookAt',
'camera.matrices',
'camera.move',
'camera.on',
'camera.onCommand',
'camera.release',
'camera.rotateAround',
'camera.setFov',
'camera.viewRectangle',
'camera.zoom',
'draw.atlas',
'draw.clampState',
+1
View File
@@ -14,6 +14,7 @@ import { createCesiumSceneRenderer, pointerFeedOf } from './sceneRenderer.js';
/** @type {ReadonlySet<string>} */
export const CESIUM_CHECKS = new Set([
'camera.viewRectangle',
'draw.drillPick',
'draw.ids',
'draw.models',
+39 -1
View File
@@ -13,6 +13,7 @@
*/
import * as Cesium from 'cesium';
import { heightsFor } from '../../queries/heights.js';
import { createCameraEvents } from '../camera/events.js';
import {
atEndOfTick,
billboardLoadError,
@@ -788,7 +789,23 @@ export function createCesiumPorts(widget, { capabilities }) {
models: (spec) => makeSet('models', { ...spec }, buildModels),
};
// Camera events: Cesium's own moveStart and moveEnd (500 ms after the
// last change, never while following), and `changed` measured per
// listener on every tick, where Cesium measures its single threshold.
const cameraEvents = createCameraEvents({
pose: () => cameraPort.pose(),
report,
});
removers.push(
scene.postUpdate.addEventListener(() => {
if (!disposed) cameraEvents.stepChanged();
}),
camera.moveStart.addEventListener(() => cameraEvents.emit('moveStart')),
camera.moveEnd.addEventListener(() => cameraEvents.emit('moveEnd')),
);
const cameraPort = {
on: (event, cb, options) => cameraEvents.on(event, cb, options),
setView(spec) {
const d = spec.destination;
if (d && 'rect' in d)
@@ -804,9 +821,29 @@ export function createCesiumPorts(widget, { capabilities }) {
});
scene.requestRender();
},
viewRectangle() {
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
if (!rect) return null;
const deg = Cesium.Math.toDegrees;
return {
west: deg(rect.west),
south: deg(rect.south),
east: deg(rect.east),
north: deg(rect.north),
};
},
pose() {
const v = (c) => ({ x: c.x, y: c.y, z: c.z });
// Cesium has no cartographic position for an eye at the earth's
// centre; the pose then says so with NaN.
const carto = camera.positionCartographic ?? {
longitude: NaN,
latitude: NaN,
height: NaN,
};
return {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
position: v(camera.positionWC),
direction: v(camera.directionWC),
up: v(camera.upWC),
@@ -814,7 +851,7 @@ export function createCesiumPorts(widget, { capabilities }) {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll,
height: camera.positionCartographic.height,
height: carto.height,
fovy: camera.frustum.fovy,
aspectRatio: camera.frustum.aspectRatio,
near: camera.frustum.near,
@@ -1183,6 +1220,7 @@ export function createCesiumPorts(widget, { capabilities }) {
// A listener that disposes the renderer stops the rest of its event.
for (const list of Object.values(rendererListeners)) list.clear();
for (const list of Object.values(frameListeners)) list.clear();
cameraEvents.clear();
for (const done of [...pendingRenders]) done();
// Late model loads find no host and destroy themselves.
for (const record of sets.values()) record.host = null;
+117 -1
View File
@@ -6,6 +6,7 @@ import {
createCesiumPorts,
listenerList,
} from './ports.js';
import { updateCameraChanged } from './internals.js';
test('capabilities follow what the scene supports', () => {
assert.deepEqual(cesiumCapabilities({}), ['models']);
@@ -85,13 +86,14 @@ function fakeWidget(overrides = {}) {
const calls = [];
const primitives = [];
const scene = {
camera: {},
camera: { moveStart: event(), moveEnd: event() },
primitives: {
add: (p) => primitives.push(p),
remove: (p) => primitives.splice(primitives.indexOf(p), 1),
},
requestRender() {},
preUpdate: event(),
postUpdate: event(),
preRender: event(),
postRender: event(),
sampleHeightSupported: true,
@@ -266,6 +268,7 @@ function tickingWidget() {
scene._renderRequested = true;
},
preUpdate: event('preUpdate'),
postUpdate: event('postUpdate'),
preRender: event('preRender'),
postRender: event('postRender'),
};
@@ -500,3 +503,116 @@ test('the loop starts on demand and never draws for scene time alone', () => {
assert.equal(ports.frame.diagnostics().targetFps, 60, 'the widget’s cap');
ports.dispose();
});
/** A city view over Austin, looking part-way down. */
function cityView(camera) {
camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 2000),
orientation: { heading: 0, pitch: -0.5, roll: 0 },
});
}
/** How often Cesium's own `changed` fires at one threshold, over `steps`. */
function cesiumChangedCount(threshold, steps) {
const { scene } = tickingWidget();
const camera = scene.camera;
cityView(camera);
camera.percentageChanged = threshold;
let count = 0;
camera.changed.addEventListener(() => (count += 1));
updateCameraChanged(camera);
for (const step of steps) {
step(camera);
updateCameraChanged(camera);
}
return count;
}
test('changed fires per listener, at each threshold as Cesium would', () => {
const steps = [
...Array.from({ length: 24 }, () => (c) => c.lookRight(0.05)),
...Array.from({ length: 12 }, () => (c) => c.twistLeft(0.2)),
...Array.from({ length: 10 }, () => (c) => c.moveForward(400)),
];
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const ports = createCesiumPorts(widget, { capabilities: all });
const counts = { 0.5: 0, 0.1: 0 };
for (const t of [0.5, 0.1])
ports.camera.on('changed', () => (counts[t] += 1), { threshold: t });
raise('postUpdate');
for (const step of steps) {
step(scene.camera);
raise('postUpdate');
}
assert.ok(counts[0.1] > counts[0.5], JSON.stringify(counts));
for (const t of [0.5, 0.1])
assert.equal(counts[t], cesiumChangedCount(t, steps), `threshold ${t}`);
ports.dispose();
});
test('camera events: Cesium’s moves relayed, a throw reported, off and dispose stop them', () => {
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const ports = createCesiumPorts(widget, { capabilities: all });
const errors = [];
ports.on('error', (e) => errors.push(e.message));
const seen = [];
ports.camera.on('moveStart', () => {
throw new Error('first');
});
const off = ports.camera.on('moveStart', () => seen.push('start'));
ports.camera.on('moveEnd', () => seen.push('end'));
ports.camera.on('changed', () => seen.push('changed'), { threshold: 0.01 });
scene.camera.moveStart.raiseEvent();
scene.camera.moveEnd.raiseEvent();
assert.deepEqual(seen, ['start', 'end']);
assert.deepEqual(errors, ['first']);
off();
scene.camera.moveStart.raiseEvent();
assert.deepEqual(seen, ['start', 'end']);
assert.throws(() => ports.camera.on('turned', () => {}), /Unknown camera event/);
ports.dispose();
scene.camera.moveEnd.raiseEvent();
scene.camera.lookRight(1);
raise('postUpdate');
assert.deepEqual(seen, ['start', 'end'], 'nothing after dispose');
});
test('pose: degrees, and NaN where Cesium has no cartographic position', () => {
const { widget, scene } = tickingWidget();
cityView(scene.camera);
const ports = createCesiumPorts(widget, { capabilities: all });
const pose = ports.camera.pose();
assert.ok(Math.abs(pose.lon + 97.74) < 1e-9 && Math.abs(pose.lat - 30.27) < 1e-9);
assert.ok(Math.abs(pose.height - 2000) < 1e-6);
scene.camera.position = new Cesium.Cartesian3(0, 0, 0);
const centre = ports.camera.pose();
assert.ok(Number.isNaN(centre.lon) && Number.isNaN(centre.height));
ports.dispose();
});
test('a camera listener that disposes the port stops the rest of its event', () => {
const { widget, scene } = tickingWidget();
const ports = createCesiumPorts(widget, { capabilities: all });
const seen = [];
ports.camera.on('moveStart', () => ports.dispose());
ports.camera.on('moveStart', () => seen.push('second'));
scene.camera.moveStart.raiseEvent();
assert.deepEqual(seen, []);
});
test('viewRectangle is in degrees, around the point below a downward eye', () => {
const { widget, scene } = tickingWidget();
scene.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 5000),
});
const ports = createCesiumPorts(widget, { capabilities: all });
const rect = ports.camera.viewRectangle();
assert.ok(
rect.west < -97.74 && rect.east > -97.74 && rect.east - rect.west < 0.2,
JSON.stringify(rect),
);
assert.ok(rect.south < 30.27 && rect.north > 30.27, JSON.stringify(rect));
ports.dispose();
});
-1
View File
@@ -41,7 +41,6 @@
"src/data/osmOverlays.js",
"src/data/trackedCamera.js",
"src/data/trailRenderer.js",
"src/hud.js",
"src/input/dispatcher.js",
"src/input/sensorPick.js",
"src/layers/airQuality/index.js",
+29
View File
@@ -0,0 +1,29 @@
/**
* @module render/rendererOf
* @description The renderer that draws a scene, found from the scene object
* the code already holds. It bridges the migration: code that still holds
* the scene reaches the renderer's ports through it, and the lookup goes
* once that code is handed the renderer itself.
*/
const renderers = new WeakMap();
/**
* Bind a renderer to its scene object.
* @param {object} host The scene object callers hold.
* @param {object} renderer
* @returns {() => void} Unbinds, if the binding is still this one.
*/
export function bindRenderer(host, renderer) {
if (renderers.has(host)) throw new Error('This scene already has a renderer');
renderers.set(host, renderer);
return () => {
if (renderers.get(host) === renderer) renderers.delete(host);
};
}
/**
* @param {object|null|undefined} host
* @returns {object|null} The renderer bound to `host`, or null.
*/
export const rendererOf = (host) => (host && renderers.get(host)) || null;
+25
View File
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindRenderer, rendererOf } from './rendererOf.js';
test('a scene finds its renderer until it is unbound', () => {
const scene = {};
const renderer = { id: 'r' };
assert.equal(rendererOf(scene), null);
assert.equal(rendererOf(null), null);
const unbind = bindRenderer(scene, renderer);
assert.equal(rendererOf(scene), renderer);
assert.throws(() => bindRenderer(scene, { id: 'other' }), /already has/);
unbind();
assert.equal(rendererOf(scene), null);
});
test('a stale unbind leaves a later binding alone', () => {
const scene = {};
const unbindFirst = bindRenderer(scene, { id: 'first' });
unbindFirst();
const second = { id: 'second' };
bindRenderer(scene, second);
unbindFirst();
assert.equal(rendererOf(scene), second);
});
+3 -91
View File
@@ -11,7 +11,6 @@ import {
IDENTITY,
PI_OVER_TWO,
TWO_PI,
acosClamped,
add,
clone,
cross,
@@ -44,6 +43,7 @@ import {
vec,
zeroToTwoPi,
} from './math.js';
import { createCameraEvents } from '../camera/events.js';
import { geodesicAt } from './geodesic.js';
const DEFAULT_FOV = Math.PI / 3;
@@ -94,13 +94,8 @@ export function createStubCamera({
const near = 1;
const far = 5e8;
const listeners = {
changed: [],
moveStart: [],
moveEnd: [],
followChanged: [],
flightEnd: [],
};
const events = createCameraEvents({ pose, report });
const { emit, on, stepChanged } = events;
const commandHooks = [];
const holds = new Map();
let holdSeq = 0;
@@ -727,89 +722,6 @@ export function createStubCamera({
// --- Events ----------------------------------------------------------------
function emit(event) {
for (const entry of listeners[event].slice()) {
if (!entry.live) continue;
try {
entry.cb();
} catch (error) {
report(error);
}
}
}
function on(event, cb, options = {}) {
const entry = {
cb,
live: true,
threshold: options.threshold ?? 0.5,
ref: null,
};
listeners[event].push(entry);
return () => {
entry.live = false;
const list = listeners[event];
const i = list.indexOf(entry);
if (i >= 0) list.splice(i, 1);
};
}
/** How far the view moved from a listener's reference, as a fraction. */
const angleDelta = (a, b) => {
const d = Math.abs(a - b) % TWO_PI;
return (d > Math.PI ? TWO_PI - d : d) / Math.PI;
};
/**
* Per listener, the reference camera's formula: heading and roll each
* against their own last reported value, then direction and position
* against the last reported view. Each can report in the same frame.
*/
function stepChanged() {
const list = listeners.changed;
if (!list.length) return;
const current = pose();
for (const entry of list.slice()) {
if (!entry.live) continue;
const t = entry.threshold;
entry.heading ??= current.heading;
entry.roll ??= current.roll;
const headingF = angleDelta(entry.heading, current.heading);
const rollF = angleDelta(entry.roll, current.roll);
if (headingF > t) entry.heading = current.heading;
if (rollF > t) entry.roll = current.roll;
if (headingF > t || rollF > t) deliver(entry);
if (!entry.view) {
entry.view = {
position: current.position,
direction: current.direction,
};
continue;
}
const dirF =
acosClamped(dot(current.direction, entry.view.direction)) /
(current.fovy * 0.5);
const heightF =
distance(current.position, entry.view.position) / current.height;
if (dirF > t || heightF > t) {
entry.view = {
position: current.position,
direction: current.direction,
};
deliver(entry);
}
}
}
function deliver(entry) {
if (!entry.live) return;
try {
entry.cb();
} catch (error) {
report(error);
}
}
function sameView(a, b) {
return (
a &&