Merge branch 'main' into fix/shortcuts-modifier-keys

This commit is contained in:
German Khokhlov committed 2026-11-18 18:59:50 +04:00
commit 649d29e409
2262 files changed
+393849 -45495

No files matched your search

+7 -9
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { findCamera } from '../render/rendererOf.js';
import {
feedProvenanceEnvelope,
layerSnapshot,
@@ -104,14 +104,12 @@ export function getWorldPacket(options = {}) {
// A default parameter only covers undefined; null or NaN would age every
// feed against the epoch and report stale data as "just now".
const now = Number.isFinite(requestedNow) ? requestedNow : Date.now();
if (!viewer?.camera?.positionWC)
throw new TypeError('World Packet requires a viewer camera');
const pose = findCamera(viewer)?.pose();
if (!pose) throw new TypeError('World Packet requires a viewer camera');
if (!dataManager || typeof dataManager.getAll !== 'function')
throw new TypeError('World Packet requires a data manager');
const cartographic = Cesium.Cartographic.fromCartesian(
viewer.camera.positionWC,
);
const eye = { lon: pose.lon, lat: pose.lat, height: pose.height };
// Read the roster once. Voice must not rewalk disabled layers: preserving the
// current enabled-only view keeps the model's context budget bounded.
const rows = dataManager.getAll();
@@ -126,9 +124,9 @@ export function getWorldPacket(options = {}) {
ok: true,
action: 'get_current_view_state',
camera: {
latitude: Cesium.Math.toDegrees(cartographic.latitude),
longitude: Cesium.Math.toDegrees(cartographic.longitude),
heightM: cartographic.height,
latitude: eye.lat,
longitude: eye.lon,
heightM: eye.height,
},
style: styleManager?.activeStyle || 'normal',
context: contextState
+13
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { getWorldPacket } from './worldPacket.js';
import { bindRenderer } from '../render/rendererOf.js';
import { createStubRenderer } from '../render/stub/index.js';
import { createGevActionRunner } from '../voice/gevActions.js';
function withoutVoicePresentation(result) {
@@ -18,6 +20,9 @@ function harness() {
const viewer = {
trackedEntity: undefined,
clock: { onTick: { addEventListener: () => () => {} } },
get canvas() {
return this.scene.canvas;
},
scene: {
canvas: {
clientWidth: 1200,
@@ -60,6 +65,14 @@ function harness() {
getCockpitState: () => null,
getControlState: () => ({ hud: { visible: 'auto' } }),
};
// The packet reads the eye from the camera port of the renderer bound to
// the scene object.
const renderer = createStubRenderer();
renderer.camera.setView({
destination: { lon: -97.74, lat: 30.26, height: 500 },
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-45), roll: 0 },
});
bindRenderer(viewer, renderer);
return { viewer, dataManager, styleManager };
}
+4 -2
View File
@@ -4,11 +4,13 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { createAnnotationEngine } from './annotationEngine.js';
import { _resetRenderGovernorForTest } from '../renderGovernor.js';
function viewerAt(lat, lon, height = 20_000) {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -16,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
+88 -63
View File
@@ -1,6 +1,9 @@
import { isUnavailableCapability } from '../sources/capability.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import { cameraOf, findCamera, findQuery } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { distance, toRadians } from '../geo/vector.js';
import { greatCircleMeters } from '../geoDistance.js';
import {
holdContinuousRender,
@@ -20,11 +23,6 @@ import {
} from '../sources/phaseTiming.js';
import { formatDistanceText } from '../data/distanceFormat.js';
// Dev convenience: expose the app's Cesium instance for console/preview probing
// (single shared module instance — avoids dual-Cesium state bugs when testing).
if (typeof window !== 'undefined' && !window.__CESIUM__)
window.__CESIUM__ = Cesium;
/**
* Annotation engine — the voice agent's "whiteboard" over the 3D world.
*
@@ -1717,18 +1715,20 @@ export function createAnnotationEngine({
frameAnnotation(marks[0]);
return;
}
const cart = points.map((p) =>
Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0),
const cart = points.map((p) => fromDegrees(p.lon, p.lat, p.height || 0));
const sphere = sphereFromPoints(cart);
const camera = cameraOf(viewer);
camera.flyToBounds(
{ center: sphere.center, radius: sphere.radius },
{
offset: {
heading: camera.pose().heading,
pitch: toRadians(-35),
range: Math.max(900, sphere.radius * 2.6),
},
durationS: 1.6,
},
);
const sphere = Cesium.BoundingSphere.fromPoints(cart);
viewer.camera.flyToBoundingSphere(sphere, {
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading,
Cesium.Math.toRadians(-35),
Math.max(900, sphere.radius * 2.6),
),
duration: 1.6,
});
} catch {
/* camera assist is best-effort */
}
@@ -1738,23 +1738,35 @@ export function createAnnotationEngine({
* globe. On any API hiccup, report visible — bad data must never move the camera. */
function isPointOnScreen(p) {
try {
const camera = viewer.camera;
const pos = Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0);
const cv = camera.frustum.computeCullingVolume(
camera.position,
camera.direction,
camera.up,
);
if (
cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) ===
Cesium.Intersect.OUTSIDE
)
return false;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.position,
);
return occluder.isPointVisible(pos);
const camera = findCamera(viewer);
const query = findQuery(viewer);
if (!camera || !query) return true;
const pos = fromDegrees(p.lon, p.lat, p.height || 0);
// Inside the view frustum: a 1 m sphere at the point is not wholly
// outside any of its six planes, read off the view-projection (depth
// runs -1..1). An invalid matrix measures no distance and reads as
// visible.
const { view, projection } = camera.matrices();
const m = new Float64Array(16);
for (let col = 0; col < 4; col++)
for (let row = 0; row < 4; row++) {
let sum = 0;
for (let k = 0; k < 4; k++)
sum += projection[k * 4 + row] * view[col * 4 + k];
m[col * 4 + row] = sum;
}
const at = (row, col) => m[col * 4 + row];
for (const [axis, sign] of FRUSTUM_PLANES) {
const a = at(3, 0) + sign * at(axis, 0);
const b = at(3, 1) + sign * at(axis, 1);
const c = at(3, 2) + sign * at(axis, 2);
const d = at(3, 3) + sign * at(axis, 3);
const distanceM =
(a * pos.x + b * pos.y + c * pos.z + d) / Math.hypot(a, b, c);
if (distanceM < -1) return false;
}
// On the near side of the globe.
return !query.isOccluded(pos);
} catch {
return true;
}
@@ -1778,22 +1790,23 @@ export function createAnnotationEngine({
: anno.ring,
)
: viewportRange(anno.viewport) || 600;
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
Cesium.Cartesian3.fromDegrees(
target.lon,
target.lat,
anno.anchor.height || 0,
),
range,
),
const camera = cameraOf(viewer);
camera.flyToBounds(
{
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading,
Cesium.Math.toRadians(-35),
range * 2.4,
),
duration: 1.8,
center: {
lon: target.lon,
lat: target.lat,
height: anno.anchor.height || 0,
},
radius: range,
},
{
offset: {
heading: camera.pose().heading,
pitch: toRadians(-35),
range: range * 2.4,
},
durationS: 1.8,
},
);
} catch {
@@ -2005,15 +2018,17 @@ export function createAnnotationEngine({
}) {
if (destroyed) return;
try {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
orientation: {
heading: Cesium.Math.toRadians(heading),
pitch: Cesium.Math.toRadians(pitch),
roll: 0,
cameraOf(viewer).flyTo(
{ lon, lat, height },
{
orientation: {
heading: toRadians(heading),
pitch: toRadians(pitch),
roll: 0,
},
durationS: duration,
},
duration,
});
);
} catch {
/* camera flight best-effort */
}
@@ -2175,13 +2190,23 @@ function pendingAnimation(anno, now) {
// fly_to_location natural-region heuristic uses (owner field test 2026-07-23).
const VIEWPORT_ASSIST_RANGE_CAP_M = 120000;
/** The view frustum's planes as `row 3 ± row axis` of the view-projection. */
const FRUSTUM_PLANES = [
[0, 1],
[0, -1],
[1, 1],
[1, -1],
[2, 1],
[2, -1],
];
/** flyTo range from a Places viewport box (low/high lat-lng corners), or null. */
function viewportRange(vp) {
if (!vp?.low || !vp?.high) return null;
try {
const span = Cesium.Cartesian3.distance(
Cesium.Cartesian3.fromDegrees(vp.low.longitude, vp.low.latitude),
Cesium.Cartesian3.fromDegrees(vp.high.longitude, vp.high.latitude),
const span = distance(
fromDegrees(vp.low.longitude, vp.low.latitude),
fromDegrees(vp.high.longitude, vp.high.latitude),
);
return Number.isFinite(span) && span > 0
? Math.max(300, Math.min(span * 0.7, VIEWPORT_ASSIST_RANGE_CAP_M))
@@ -2206,9 +2231,9 @@ function ringRange(ring) {
if (lon < minLon) minLon = lon;
if (lon > maxLon) maxLon = lon;
}
const span = Cesium.Cartesian3.distance(
Cesium.Cartesian3.fromDegrees(minLon, minLat),
Cesium.Cartesian3.fromDegrees(maxLon, maxLat),
const span = distance(
fromDegrees(minLon, minLat),
fromDegrees(maxLon, maxLat),
);
return Math.max(300, span * 0.7);
}
+70 -4
View File
@@ -1,3 +1,4 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { createStandalonePlaceSearch } from '../standalone/placeSearch.js';
// Voice-annotation resilience contract tests — pure logic, no network, no browser.
//
@@ -25,6 +26,7 @@ import {
installRenderGovernor,
_resetRenderGovernorForTest,
} from '../renderGovernor.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
// A resolver that replays a scripted sequence of outcomes (undefined = transient,
// null = definitive miss, object = footprint) and counts its invocations.
@@ -1471,7 +1473,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } },
viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }),
renderer,
});
let changes = 0;
@@ -1540,12 +1542,12 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: {
viewer: bindFakeCesiumCamera({
camera: {
heading: 0,
flyToBoundingSphere: (sphere) => flights.push(sphere),
},
},
}),
renderer,
});
let changes = 0;
@@ -1757,7 +1759,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
let renders = 0;
installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } });
installRenderGovernor(framePortFor({ requestRenderMode: true, requestRender: () => (renders += 1) }));
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([
@@ -1898,3 +1900,67 @@ test('plain recaption keeps the old mark addressable when its removal throws', a
);
assert.equal(engine.count(), 0);
});
// The camera assist frames a fresh mark only when none of it is in view:
// off the frustum or behind the globe, as the renderer's camera and query
// ports see it. A camera that cannot answer leaves the view alone.
test('camera assist frames marks out of view and leaves visible ones alone', async (t) => {
installAnimationFrameStubs(t);
const { bindRenderer } = await import('../render/rendererOf.js');
const { horizonFrom } = await import('../geo/horizon.js');
const viewerOver = (lon, lat, height, { broken = false } = {}) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
const direction = Cesium.Cartesian3.negate(
Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
const view = Cesium.Matrix4.computeView(position, direction, up, right, new Cesium.Matrix4());
const frustum = new Cesium.PerspectiveFrustum({
fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, far: 5e7,
});
const flights = [];
const viewer = {};
const horizon = horizonFrom(position);
bindRenderer(viewer, {
camera: {
pose: () => ({ heading: 0 }),
matrices() {
if (broken) throw new Error('no camera');
return {
view: Float64Array.from(Cesium.Matrix4.toArray(view)),
projection: Float64Array.from(Cesium.Matrix4.toArray(frustum.projectionMatrix)),
};
},
flyTo: (...args) => flights.push(['flyTo', ...args]),
flyToBounds: (...args) => flights.push(['flyToBounds', ...args]),
},
query: { isOccluded: (p) => !horizon.isPointVisible(p) },
});
return { viewer, flights };
};
const pinAt = async (viewer, lon, lat) => {
const engine = createAnnotationEngine({ viewer, renderer: fakeRenderer().renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: lat, longitude: lon }], { persist: true, flyTo: false });
};
const inView = viewerOver(-97.74, 30.27, 9000);
await pinAt(inView.viewer, -97.742, 30.268);
assert.equal(inView.flights.length, 0, 'a mark in view is left alone');
const aside = viewerOver(-97.74, 30.27, 9000);
await pinAt(aside.viewer, -97.5, 30.6);
assert.equal(aside.flights.length, 1, 'a mark off the frustum is framed');
const behind = viewerOver(60, 30, 9_000_000);
await pinAt(behind.viewer, -120, -30);
assert.equal(behind.flights.length, 1, 'a mark behind the globe is framed');
const broken = viewerOver(-97.74, 30.27, 9000, { broken: true });
await pinAt(broken.viewer, -97.5, 30.6);
assert.equal(broken.flights.length, 0, 'a camera that cannot answer moves nothing');
});
+6 -4
View File
@@ -13,6 +13,7 @@ import { createPlaceSearch } from '../search/placeSearch.js';
// Run with: npm test (node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import {
resolveAnnotationTarget as resolveTarget,
selectFootprint,
@@ -157,7 +158,8 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => {
});
function closeViewportViewer() {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: 30.2672 * Math.PI / 180,
@@ -165,7 +167,7 @@ function closeViewportViewer() {
height: 1000,
},
},
};
});
}
function geocodePayload({ lat, lon, types, label }) {
@@ -369,11 +371,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township
// Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs.
const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 };
function capitolViewer() {
return { camera: { positionCartographic: {
return bindFakeCesiumCamera({ camera: { positionCartographic: {
latitude: CAPITOL_ANCHOR.lat * Math.PI / 180,
longitude: CAPITOL_ANCHOR.lon * Math.PI / 180,
height: 1000,
} } };
} } });
}
function installCapitolMocks(t, elements, components = [
{ long_name: 'Washington', types: ['locality', 'political'] },
+144 -1
View File
@@ -43,24 +43,167 @@ export function drawMarkFallbackName(mark) {
: shape;
}
/** The kind of shape a row action is offered for: `area` or `line`. */
const ACTION_SHAPES = Object.freeze({ area: 'area', route: 'line' });
const lonLat = (point) =>
Array.isArray(point)
? [Number(point[0]), Number(point[1])]
: [Number(point?.lon), Number(point?.lat)];
const finitePairs = (points) =>
(Array.isArray(points) ? points : [])
.map(lonLat)
.filter(([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat));
/** A longitude in [-180, 180]; an unwrapped outline can carry ±540. */
const wrapLon = (lon) =>
lon >= -180 && lon <= 180 ? lon : ((((lon + 180) % 360) + 360) % 360) - 180;
/** Whether consecutive positions step across the antimeridian once wrapped. */
const crossesAntimeridian = (points) =>
points.some(
(point, index) =>
index > 0 && Math.abs(point[0] - points[index - 1][0]) > 180,
);
/** Positions wrapped into range, or null when the sequence crosses ±180°. */
const inRange = (points) => {
if (points.some(([, lat]) => Math.abs(lat) > 90)) return null;
const wrapped = points.map(([lon, lat]) => [wrapLon(lon), lat]);
return crossesAntimeridian(wrapped) ? null : wrapped;
};
const closed = (ring) => {
if (ring.length < 3) return ring;
const [first, last] = [ring[0], ring[ring.length - 1]];
return first[0] === last[0] && first[1] === last[1] ? ring : [...ring, first];
};
/**
* A drawn shape's geometry as GeoJSON in `[lon, lat]` degrees, longitudes in
* [-180, 180]: an area is a closed `Polygon` (a `MultiPolygon` when an area
* handle has several parts), a line a `LineString`. A pin, a shape too small
* to be one, or one that crosses the antimeridian has none, so it is offered
* no action rather than a shape that wraps the wrong way round the world.
*/
export function drawMarkGeometry(mark) {
if (mark?.type === 'route') {
const path = inRange(finitePairs(mark.path));
return path?.length >= 2 ? { type: 'LineString', coordinates: path } : null;
}
if (mark?.type !== 'area') return null;
const ringOf = (points) => {
const ring = inRange(closed(finitePairs(points)));
return ring?.length >= 4 ? ring : null;
};
if (Array.isArray(mark.polygons) && mark.polygons.length) {
const polygons = [];
for (const rings of mark.polygons) {
const parts = (Array.isArray(rings) ? rings : []).map(ringOf);
// A part that cannot be given whole is no part: never a hole dropped.
if (!parts.length || parts.some((ring) => !ring)) return null;
polygons.push(parts);
}
return polygons.length > 1
? { type: 'MultiPolygon', coordinates: polygons }
: { type: 'Polygon', coordinates: polygons[0] };
}
const ring = ringOf(mark.ring);
return ring ? { type: 'Polygon', coordinates: [ring] } : null;
}
/**
* The actions an application adds to Draw's rows, checked once: each has an
* `id`, a Material Symbols `icon`, a `label(name)` worded by the application,
* the `shapes` it is for (`area`, `line`), an optional `accepts(geometry)` and
* `run({ id, shape, name, title, geometry })` (`name` the person's own, `title`
* as the row shows it). Malformed or repeated ids are dropped.
*/
export function drawMarkActions(actions = []) {
const kept = new Map();
for (const action of Array.isArray(actions) ? actions : []) {
const wellFormed =
typeof action?.id === 'string' &&
/^[a-z][a-z0-9-]{0,39}$/.test(action.id) &&
typeof action.icon === 'string' &&
typeof action.label === 'function' &&
typeof action.run === 'function' &&
Array.isArray(action.shapes);
if (!wellFormed || kept.has(action.id)) continue;
kept.set(
action.id,
Object.freeze({
id: action.id,
icon: action.icon,
label: action.label,
shapes: Object.freeze(
action.shapes.filter((shape) =>
Object.values(ACTION_SHAPES).includes(shape),
),
),
accepts:
typeof action.accepts === 'function' ? action.accepts : () => true,
run: action.run,
}),
);
}
return Object.freeze([...kept.values()]);
}
/** The actions from `drawMarkActions` that `mark` is offered, with its geometry. */
export function drawMarkActionsFor(mark, actions = []) {
const shape = ACTION_SHAPES[mark?.type];
if (!shape || !actions.length) return { shape, geometry: null, actions: [] };
const geometry = drawMarkGeometry(mark);
if (!geometry) return { shape, geometry, actions: [] };
return {
shape,
geometry,
actions: actions.filter((action) => {
if (!action.shapes.includes(shape)) return false;
try {
return action.accepts(geometry, shape) === true;
} catch {
return false;
}
}),
};
}
/** An action's words for a row; an application's label that throws shows its id. */
function actionLabel(action, title) {
try {
const text = action.label(title);
return typeof text === 'string' && text.trim() ? text.trim() : action.id;
} catch {
return action.id;
}
}
/**
* The rows for the hand-drawn marks on the board, in board order. Text is
* worded here, in the current language; the view only lays it out.
* @param {object[]} marks The engine's `list()`.
* @param {ReturnType<typeof drawMarkActions>} [actions] The application's row actions.
* @param {Map<string, {busy: boolean, text: string}>} [notes] What an action said on a shape.
*/
export function presentDrawMarks(marks = []) {
export function presentDrawMarks(marks = [], actions = [], notes = new Map()) {
return marks
.filter((mark) => mark?.manual === true)
.map((mark) => {
const fallback = drawMarkFallbackName(mark);
const title = mark.name || fallback;
const visible = !mark.hidden;
const offered = drawMarkActionsFor(mark, actions).actions;
return {
id: mark.id,
name: mark.name || '',
placeholder: fallback,
color: DRAW_COLORS.includes(mark.color) ? mark.color : 'primary',
hidden: !visible,
busy: notes.get(mark.id)?.busy === true,
note: offered.length ? notes.get(mark.id)?.text || '' : '',
actions: offered.map((action) => ({
id: action.id,
icon: action.icon,
label: actionLabel(action, title),
})),
labels: {
name: t('Name of {name}', { name: title }),
swatch: t('Change the colour of {name}', { name: title }),
+219
View File
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
import {
DRAW_COLORS,
DRAW_COLOR_CSS,
drawMarkActions,
drawMarkActionsFor,
drawMarkFallbackName,
drawMarkGeometry,
presentDrawMarks,
} from './drawMarks.js';
@@ -78,3 +81,219 @@ test('rows list only hand-drawn marks, in board order, with their words', () =>
test('every colour has its swatch', () => {
assert.deepEqual(Object.keys(DRAW_COLOR_CSS), [...DRAW_COLORS]);
});
test("a drawn shape's geometry is GeoJSON in [lon, lat]: a closed area, a line, no pin", () => {
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
}),
{
type: 'Polygon',
coordinates: [
[
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
],
},
);
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
],
}).coordinates[0].at(-1),
[0, 0],
'an open ring is closed',
);
assert.equal(
drawMarkGeometry({
type: 'area',
ring: [
[0, 0],
[1, 0],
],
}),
null,
);
assert.deepEqual(
drawMarkGeometry({
type: 'route',
path: [
{ lon: 1, lat: 2, height: 9 },
{ lon: 3, lat: 4, height: 0 },
],
}),
{
type: 'LineString',
coordinates: [
[1, 2],
[3, 4],
],
},
);
assert.equal(
drawMarkGeometry({ type: 'pin', longitude: 1, latitude: 2 }),
null,
);
const square = (x) => [
[x, 0],
[x + 1, 0],
[x + 1, 1],
[x, 0],
];
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: square(0),
polygons: [[square(0)], [square(5)]],
}),
{ type: 'MultiPolygon', coordinates: [[square(0)], [square(5)]] },
'an area handle with several parts keeps them all',
);
assert.equal(
drawMarkGeometry({
type: 'area',
polygons: [
[
square(0),
[
[0.2, 0.2],
[0.3, 0.2],
],
],
],
}),
null,
'a hole that cannot be given whole is never dropped silently',
);
});
test('longitudes are wrapped into range, and a shape across the antimeridian has no geometry', () => {
assert.deepEqual(
drawMarkGeometry({
type: 'route',
path: [
[370, 1],
[371, 1],
],
}).coordinates,
[
[10, 1],
[11, 1],
],
);
assert.deepEqual(
drawMarkGeometry({
type: 'area',
ring: [
[180, 0],
[179, 0],
[179, 1],
],
}).coordinates[0][0],
[180, 0],
'the antimeridian itself stays put',
);
assert.equal(
drawMarkGeometry({
type: 'area',
ring: [
[179.9, 0],
[-179.9, 0],
[-179.9, 1],
],
}),
null,
);
assert.equal(
drawMarkGeometry({
type: 'route',
path: [
[179.5, 0],
[180.5, 0],
],
}),
null,
);
assert.equal(
drawMarkGeometry({
type: 'route',
path: [
[0, 91],
[1, 0],
],
}),
null,
);
});
test('row actions are checked once: malformed ones and repeated ids are dropped', () => {
const run = () => {};
const label = () => 'x';
const actions = drawMarkActions([
{ id: 'Bad Id', icon: 'a', label, run, shapes: ['area'] },
{ id: 'tag', icon: 'a', label: 'not a function', run, shapes: ['area'] },
{
id: 'tag',
icon: 'sell',
label,
run,
shapes: ['area', 'line', 'pin'],
},
{ id: 'tag', icon: 'other', label, run, shapes: ['area'] },
null,
]);
assert.deepEqual(
actions.map(({ id, icon, shapes }) => ({ id, icon, shapes: [...shapes] })),
[{ id: 'tag', icon: 'sell', shapes: ['area', 'line'] }],
);
assert.deepEqual(drawMarkActions('nope'), []);
const area = {
type: 'area',
ring: [
[0, 0],
[1, 0],
[1, 1],
],
};
const offer = drawMarkActionsFor(area, actions);
assert.equal(offer.shape, 'area');
assert.deepEqual(
offer.actions.map((a) => a.id),
['tag'],
);
const refusing = drawMarkActions([
{
id: 'measure',
icon: 'a',
label,
run,
shapes: ['area'],
accepts: () => {
throw new Error('no');
},
},
]);
assert.deepEqual(
drawMarkActionsFor(area, refusing).actions,
[],
'an accepts that throws offers nothing',
);
assert.deepEqual(
presentDrawMarks([{ id: 'p', type: 'pin', manual: true }], actions)[0]
.actions,
[],
);
});
+239 -179
View File
@@ -1,5 +1,5 @@
/**
* Manual whiteboard drawing: the Cesium + DOM half.
* Manual whiteboard drawing: the scene + DOM half.
*
* UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
* shape (area, line or pin) and a colour, click the vertices on the real world,
@@ -15,12 +15,13 @@
* (`src/data/inputOwnership.js`), and every ambient selection handler yields,
* so a vertex clicked on top of an aircraft or a camera is a vertex and
* nothing else. It is one claim consulted by all of them, not a list of
* exceptions inside each.
* exceptions inside each. Turning Draw on takes the pointer from any tool
* holding it; a newer tool taking it turns Draw off.
* - Cesium's Viewer binds its OWN left click (select the entity under the
* pointer) and double click (track it) on the viewer's handler, outside every
* layer and therefore outside the shared claim. Both are borrowed for the
* layer and therefore outside the shared claim. Both are suppressed for the
* session and given back on the way out, and `destroy()` gives back every
* listener, the Cesium handler, the preview data source and the window
* listener, the pointer subscriptions, the preview draw sets and the window
* handle, so the tool can be turned off or the shell disposed without leaving
* anything behind.
*
@@ -30,14 +31,13 @@
* drapes finished areas and routes onto the surface, so the height is dropped
* at finish, deliberately and in one place — see `finishSpec` in drawMode.js.
*/
import * as Cesium from 'cesium';
import { pickWorldFromScreen } from './annotationResolver.js';
import {
claimPointer,
pointerOwner,
releasePointer,
} from '../data/inputOwnership.js';
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
import { inputFor } from '../input/dispatcher.js';
import {
DRAW_SHAPES,
MAX_VERTICES,
@@ -50,12 +50,46 @@ import {
removeLastVertex,
} from './drawMode.js';
import { DRAW_COLORS, DRAW_COLOR_CSS, presentDrawMarks } from './drawMarks.js';
import {
DRAW_COLORS,
DRAW_COLOR_CSS,
drawMarkActions,
drawMarkActionsFor,
drawMarkFallbackName,
presentDrawMarks,
} from './drawMarks.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { fromDegrees } from '../geo/index.js';
import { cssColor } from '../render/color.js';
import {
canvasOf as sceneCanvasOf,
drawOf,
findFrame,
} from '../render/rendererOf.js';
/** The longest note a row action leaves under its row, in characters. */
const NOTE_MAX = 200;
/** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */
function noteText(text) {
if (typeof text !== 'string') return '';
const trimmed = text.trim();
if (trimmed.length <= NOTE_MAX) return trimmed;
const cut = trimmed.slice(0, NOTE_MAX - 1);
const space = cut.lastIndexOf(' ');
return `${(space > NOTE_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
}
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
/** The id this tool claims the pointer under. */
const DRAW_POINTER_OWNER = 'draw';
const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview';
/** Each tool's preview sets get their own ids. */
let previewSerial = 0;
/**
* Preview sets drawn on each viewer by its live tools, so a tool left
* undestroyed beside its replacement shows up in `diagnostics()`.
*/
const livePreviewSets = new WeakMap();
const countPreviewSets = (viewer, delta) =>
livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta);
const PREVIEW = DRAW_COLOR_CSS;
@@ -67,7 +101,10 @@ const PREVIEW = DRAW_COLOR_CSS;
* through the actions it gives `connect`, which returns their disconnect.
* A row's fly-to is an immediate navigation through `navigation`, like
* Import's, so Cockpit can refuse it and a running orbit or follow lets go.
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* `markActions` are the application's own buttons on an area's or a line's
* row (drawMarks.js `drawMarkActions`); a press runs the action with the
* shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`).
* @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
@@ -76,7 +113,12 @@ export function initDrawTool({
navigation = null,
publish = () => {},
connect = () => () => {},
markActions = [],
}) {
const rowActions = drawMarkActions(markActions);
// What a row action said last on each drawn shape: `{ run, busy, text }`.
const notes = new Map();
let noteRun = 0;
// A page without the Draw controls (the Display controls view omitted) has
// no draw tool.
if (!viewer || !annotations || !document.getElementById('draw-toggle'))
@@ -88,16 +130,13 @@ export function initDrawTool({
let shape = 'area';
let color = 'primary';
let hint = '';
let handler = null;
let unbindScene = null;
let lease = null;
let savedDoubleClick = null;
let savedSingleClick = null;
let cursor = null; // last mouse position on the canvas, for the rubber band
// Bumped by anything that supersedes an in-flight finish: cancelling, clearing
// the board, leaving draw mode, teardown. An `annotate()` that resolves after
// one of those must not write its outcome over the newer state.
let generation = 0;
const previewEntities = [];
// Every DOM listener this tool adds (the session's keydown), so teardown is
// one loop rather than a list that can fall out of step with the bindings.
const domListeners = [];
@@ -106,23 +145,40 @@ export function initDrawTool({
domListeners.push([target, type, listener, options]);
};
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
// remove a source that had not been attached yet and leave the attachment to
// land afterwards — a preview data source nobody owns. Chain the removal onto
// the attachment instead of racing it.
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
() => null,
);
// The preview: one dashed rubber band and a dot per vertex, drawn through
// the renderer's draw port. Both sets live as long as the tool.
const draw = drawOf(viewer);
const previewId = `draw-preview:${++previewSerial}`;
const previewLines = draw.lines({ id: `${previewId}:line` });
const previewPoints = draw.points({ id: `${previewId}:vertices` });
countPreviewSets(viewer, 2);
let previewReleased = false;
const releasePreview = () => {
if (previewReleased) return;
previewReleased = true;
countPreviewSets(viewer, -2);
previewLines.dispose();
previewPoints.dispose();
};
/** The canvas the renderer draws in (the viewer's own when none is bound). */
const canvasOf = () => sceneCanvasOf(viewer);
const requestRender = () => findFrame(viewer)?.requestRender('draw-preview');
// Teardown finishes synchronously; `whenSettled()` keeps its promise.
const attaching = Promise.resolve();
const present = () =>
const present = () => {
const marks = annotations.list?.() || [];
// A note goes with its shape.
for (const id of notes.keys())
if (!marks.some((mark) => mark.id === id)) notes.delete(id);
publish({
active,
shape,
color,
hint,
marks: presentDrawMarks(annotations.list?.() || []),
marks: presentDrawMarks(marks, rowActions, notes),
});
};
// The hint is kept as the call that words it, so a language switch can
// word it again.
let hintText = () => '';
@@ -137,70 +193,71 @@ export function initDrawTool({
// ---- preview ---------------------------------------------------------
const vertexPositions = () =>
session.vertices.map((v) =>
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
);
const previewLine = dataSource.entities.add({
show: false,
polyline: {
positions: new Cesium.CallbackProperty(() => {
if (!session) return [];
const pts = vertexPositions();
if (cursor && session.shape !== 'pin') pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
return pts;
}, false),
width: 3,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
dashLength: 16,
}),
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
dashLength: 16,
}),
clampToGround: false,
},
});
const syncPreview = () => {
session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0));
/** The rubber band, from the vertices to the pointer (and closed for an area). */
const syncPreviewLine = () => {
if (destroyed) return;
previewEntities.forEach((e) => dataSource.entities.remove(e));
previewEntities.length = 0;
if (!session) {
previewLine.show = false;
setHint(() => drawHint(null));
viewer.scene.requestRender();
if (!session || session.shape === 'pin') {
previewLines.clear();
return;
}
const stroke = Cesium.Color.fromCssColorString(
PREVIEW[color] || PREVIEW.primary,
);
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
color: stroke.withAlpha(0.9),
dashLength: 16,
});
previewLine.show = session.shape !== 'pin';
for (const v of session.vertices) {
previewEntities.push(
dataSource.entities.add({
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
point: {
pixelSize: 8,
color: stroke,
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}),
);
const pts = vertexPositions();
if (cursor) pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
if (pts.length < 2) {
previewLines.clear();
return;
}
previewLines.upsert([
{
id: 'band',
positions: pts,
widthPx: 3,
// Along the ellipsoid between vertices, as the entity polyline was.
mode: 'geodesic',
style: {
kind: 'dash',
color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9),
length: 16,
},
// Dashed behind the surface too, as the band in front of it is.
depthFail: {
kind: 'dash',
color: withAlpha(cssColor(PREVIEW.primary), 0.35),
length: 16,
},
},
]);
};
const syncPreview = () => {
if (destroyed) return;
if (!session) {
previewPoints.clear();
previewLines.clear();
setHint(() => drawHint(null));
requestRender();
return;
}
const stroke = cssColor(PREVIEW[color] || PREVIEW.primary);
previewPoints.set(
session.vertices.map((v, index) => ({
id: String(index),
pos: { lon: v.lon, lat: v.lat, height: v.height || 0 },
pixelSize: 8,
color: stroke,
outlineColor: [0, 0, 0, 0.6],
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
})),
);
syncPreviewLine();
setHint(() => drawHint(session));
viewer.scene.requestRender();
requestRender();
};
// ---- vertices from clicks --------------------------------------------
const worldAt = (position) => {
const canvas = viewer.scene.canvas;
const canvas = canvasOf();
const w = canvas.clientWidth || canvas.width || 1;
const h = canvas.clientHeight || canvas.height || 1;
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
@@ -228,11 +285,12 @@ export function initDrawTool({
};
const onMove = (event) => {
if (!session || session.shape === 'pin' || destroyed) return;
const p = worldAt(event.endPosition);
cursor = p
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0)
: null;
viewer.scene.requestRender();
// The click's own position is sensor-corrected; the rubber band must
// follow the same point the click would place.
const p = worldAt(event.pickPosition ?? event.endPosition);
cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null;
syncPreviewLine();
requestRender();
};
// ---- finish / cancel -------------------------------------------------
@@ -312,9 +370,7 @@ export function initDrawTool({
t.closest('button, a, select, [role="button"], [role="radio"]')
)
return false;
return (
t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS'
);
return t === document.body || t === canvasOf() || t.tagName === 'CANVAS';
};
const onKey = (event) => {
if (!active || destroyed || typingElsewhere(event)) return;
@@ -351,18 +407,15 @@ export function initDrawTool({
function setActive(next) {
if (destroyed || next === active) return active;
if (next) {
lease = claimPointer(DRAW_POINTER_OWNER);
if (!lease) {
// Somebody else is using the pointer — possibly an older instance of
// this same tool that has not finished tearing down. Say so instead of
// half-starting.
setHint(() =>
t('{owner} is using the pointer — close it first.', {
owner: translateKnown(pointerOwnerName(pointerOwner())),
}),
);
return active;
}
// The newest claim takes over: a tool holding the pointer is told and
// turns itself off, and a newer one turns Draw off as if the person had.
const claimed = claimPointer(DRAW_POINTER_OWNER, {
onLost: () => {
if (lease === claimed) setActive(false);
},
});
if (!claimed) return active;
lease = claimed;
}
active = next;
present();
@@ -384,50 +437,29 @@ export function initDrawTool({
}
function bindSceneHandler() {
if (handler) return;
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
handler.setInputAction(() => {
void finish();
}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
// single click picks an entity into `viewer.selectedEntity`, the double
// click tracks it. Neither goes through a layer, so neither can be fixed by
// the shared pointer claim — they have to be borrowed outright for the
// session and given back on the way out. Borrowing the single click is what
// stops a vertex placed on a contact from also selecting it.
const stock = viewer.screenSpaceEventHandler;
savedSingleClick =
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
savedDoubleClick =
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
null;
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
if (unbindScene) return;
const input = inputFor(viewer);
const held = { lease: () => lease };
const offs = [
input.onPointer('click', onClick, held),
input.onPointer('move', onMove, held),
input.onPointer('dblclick', () => void finish(), held),
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
// single click picks an entity into `viewer.selectedEntity`, the double
// click tracks it. Neither goes through a layer, so neither yields to the
// shared pointer claim — they are suppressed for the session and given
// back on the way out. Suppressing the single click is what stops a
// vertex placed on a contact from also selecting it.
input.suppressStockClicks(),
];
unbindScene = () => offs.forEach((off) => off());
listen(document, 'keydown', onKey, true);
}
function releaseSceneHandler() {
if (handler) {
handler.destroy();
handler = null;
}
if (savedSingleClick) {
viewer.screenSpaceEventHandler.setInputAction(
savedSingleClick,
Cesium.ScreenSpaceEventType.LEFT_CLICK,
);
savedSingleClick = null;
}
if (savedDoubleClick) {
viewer.screenSpaceEventHandler.setInputAction(
savedDoubleClick,
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
);
savedDoubleClick = null;
}
// Drop the keydown listener bound alongside this handler.
unbindScene?.();
unbindScene = null;
// Drop the keydown listener bound alongside the pointer subscriptions.
for (let i = domListeners.length - 1; i >= 0; i -= 1) {
const [target, type, listener, options] = domListeners[i];
if (listener !== onKey) continue;
@@ -450,6 +482,56 @@ export function initDrawTool({
return annotations.frame?.(id) ?? false;
}
/**
* Run the application's row action `actionId` on drawn shape `id`, if the
* shape is still on the board and still offered it. Returns whether it ran.
* What the action returns, or resolves to, is the row's note (a measurement,
* "saved"): the row is busy until it settles, a newer press or the shape's
* removal makes a late answer moot, and a failure clears the note, so an
* action words its own refusals and resolves with them.
*/
function runMarkAction(id, actionId) {
const mark = (annotations.list?.() || []).find(
(entry) => entry.id === id && entry.manual === true,
);
const offer = drawMarkActionsFor(mark, rowActions);
const action = offer.actions.find((entry) => entry.id === actionId);
if (!action || notes.get(mark.id)?.busy) return false;
const run = ++noteRun;
const settle = (text) => {
if (destroyed || notes.get(mark.id)?.run !== run) return;
notes.set(mark.id, {
run,
busy: false,
text: noteText(text),
});
present();
};
const fail = (error) => {
console.warn(`[draw] ${actionId} failed`, error);
settle('');
};
notes.set(mark.id, { run, busy: true, text: '' });
let answer;
try {
answer = action.run({
id: mark.id,
shape: offer.shape,
name: mark.name || '',
title: mark.name || drawMarkFallbackName(mark),
geometry: offer.geometry,
});
} catch (error) {
fail(error);
return false;
}
if (typeof answer?.then === 'function') {
present();
Promise.resolve(answer).then(settle, fail);
} else settle(answer);
return true;
}
/** Draw `next` from now on; an open shape starts over in it. */
function chooseShape(next) {
shape = normalizeShape(next);
@@ -478,6 +560,7 @@ export function initDrawTool({
},
flyToDrawMark: flyToMark,
removeDrawMark: (id) => annotations.remove?.(id),
runDrawMarkAction: runMarkAction,
});
// The rows follow the board: a shape drawn, renamed, hidden or removed
// here, by voice or by a clear.
@@ -500,13 +583,15 @@ export function initDrawTool({
setActive,
setShape: chooseShape,
/** The hand-drawn marks the list shows, as its rows. */
marks: () => presentDrawMarks(annotations.list?.() || []),
marks: () =>
presentDrawMarks(annotations.list?.() || [], rowActions, notes),
setColor(next) {
color = DRAW_COLORS.includes(next) ? next : 'primary';
present();
syncPreview();
},
flyToMark,
runMarkAction,
/** Test seam: add a vertex from lon/lat as if it had been clicked. */
addVertex(lon, lat, height = 0) {
if (!session) return false;
@@ -523,26 +608,18 @@ export function initDrawTool({
return {
active,
destroyed,
sceneHandler: Boolean(handler),
sceneHandler: Boolean(unbindScene),
domListeners: domListeners.length,
previewDataSources: countPreviewDataSources(viewer),
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
// Every live tool's on this viewer: 2 while one tool lives.
previewSets: livePreviewSets.get(viewer) ?? 0,
previewItems: previewReleased
? 0
: previewLines.size() + previewPoints.size(),
pointerOwner: pointerOwner(),
// The viewer's OWN click actions. While a session is open both are
// borrowed (absent here); after it closes both are back. A harness can
// compare the restored functions by identity with what it captured
// before, which is the only way to prove they were given back rather
// than replaced.
stockSingleClick: Boolean(
viewer.screenSpaceEventHandler?.getInputAction?.(
Cesium.ScreenSpaceEventType.LEFT_CLICK,
),
),
stockDoubleClick: Boolean(
viewer.screenSpaceEventHandler?.getInputAction?.(
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
),
),
// The viewer's own select and follow, which the input port runs: off
// while a session is open, back on after it closes.
stockSingleClick: inputFor(viewer).stockEnabled('select'),
stockDoubleClick: inputFor(viewer).stockEnabled('dblclickFollow'),
};
},
/** Resolves once every deferred teardown step has run. */
@@ -564,18 +641,7 @@ export function initDrawTool({
for (const [target, type, listener, options] of domListeners.splice(0)) {
target.removeEventListener(type, listener, options);
}
previewEntities.length = 0;
dataSource.entities.removeAll();
// Wait for the pending add() before removing: a destroy() in the same
// tick as init would otherwise remove nothing and let the attachment land
// behind it.
attaching = attaching.then(() => {
try {
viewer.dataSources.remove(dataSource, true);
} catch {
/* viewer already disposed — nothing to detach from */
}
});
releasePreview();
document.body.classList.remove('gev-drawing');
hint = '';
present();
@@ -587,13 +653,7 @@ export function initDrawTool({
return api;
}
/** How many draw previews are attached — more than one means a leaked tool. */
function countPreviewDataSources(viewer) {
const sources = viewer?.dataSources;
if (!sources) return 0;
let found = 0;
for (let index = 0; index < sources.length; index += 1) {
if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1;
}
return found;
/** `color` at `alpha`. */
function withAlpha(color, alpha) {
return [color[0], color[1], color[2], alpha];
}
+2 -5
View File
@@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => {
// rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels
// against a keyless server; this stops the constant being narrowed again.
const renderer = read('src/annotations/worldAnnotationRenderer.js');
assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/);
assert.doesNotMatch(
renderer,
/classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/,
);
assert.match(renderer, /const CLAMP_TO = 'both';/);
assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/);
});
test('the draw modules are registered for formatting and boundary checks', () => {
+540 -91
View File
@@ -13,6 +13,8 @@ import {
releasePointer,
resetPointerOwnership,
} from '../data/inputOwnership.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
/* ── DOM doubles ───────────────────────────────────────────────────────── */
@@ -68,9 +70,17 @@ class FakeElement {
}
closest(selector) {
// Only what the tool asks: "am I inside an activatable control?"
const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]'];
const activatable = [
'button',
'a',
'select',
'[role="button"]',
'[role="radio"]',
];
if (!activatable.some((part) => selector.includes(part))) return null;
return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT'
return this.tagName === 'BUTTON' ||
this.tagName === 'A' ||
this.tagName === 'SELECT'
? this
: null;
}
@@ -143,39 +153,22 @@ function fakeViewer() {
setInputAction: (action, type) => actions.set(type, action),
removeInputAction: (type) => actions.delete(type),
};
const attached = [];
const pendingAdds = [];
const dataSources = {
get length() {
return attached.length;
},
get: (index) => attached[index],
add(source) {
// Cesium resolves this on a later tick — the whole point of finding 7.
const promise = Promise.resolve().then(() => {
attached.push(source);
return source;
});
pendingAdds.push(promise);
return promise;
},
remove(source) {
const at = attached.indexOf(source);
if (at >= 0) attached.splice(at, 1);
return at >= 0;
},
};
return {
scene: { canvas, requestRender() {} },
screenSpaceEventHandler: stockHandler,
dataSources,
_attached: attached,
_actions: actions,
};
}
function fakeAnnotations() {
const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] };
const calls = {
annotate: [],
clear: 0,
restyle: [],
setHidden: [],
frame: [],
remove: [],
};
const marks = [];
const listeners = new Set();
const changed = () => listeners.forEach((listener) => listener());
@@ -223,10 +216,21 @@ function fakeAnnotations() {
}
/** Stand up a tool against fresh doubles, with globals restored afterwards. */
function harness({ navigation = null } = {}) {
function harness({
navigation = null,
beforeInput = () => {},
markActions = [],
} = {}) {
resetPointerOwnership();
const { byId, documentDouble } = fakeDom();
const viewer = fakeViewer();
// The viewer's own actions are bound before its input port takes them.
beforeInput(viewer);
const input = fakeInput(viewer);
// The renderer the tool draws its preview with, drawing in the viewer's canvas.
const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, {
canvas: viewer.scene.canvas,
});
const annotations = fakeAnnotations();
const previousDocument = globalThis.document;
const previousWindow = globalThis.window;
@@ -239,6 +243,7 @@ function harness({ navigation = null } = {}) {
viewer,
annotations,
navigation,
markActions,
publish: (view) => (shown.view = view),
connect: (actions) => {
controls.actions = actions;
@@ -249,6 +254,7 @@ function harness({ navigation = null } = {}) {
tool,
shown,
viewer,
draw,
annotations,
byId,
documentDouble,
@@ -256,7 +262,10 @@ function harness({ navigation = null } = {}) {
controls,
/** A control's change, as the view sends it. */
act: (name, ...args) => controls.actions?.[name]?.(...args),
input,
restore() {
input.destroy();
unbindDraw();
resetPointerOwnership();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
@@ -287,23 +296,42 @@ test('turning Draw on takes a lease and turning it off gives it back', async ()
}
});
test('Draw refuses to start when something else holds the pointer', async () => {
test('Draw takes the pointer from another tool, which is told', async () => {
const h = harness();
try {
const other = claimPointer('directions');
let lost = 0;
claimPointer('directions', { onLost: () => (lost += 1) });
h.act('toggleDraw');
assert.equal(h.tool.active, false, 'it must not half-start');
assert.equal(pointerOwner(), 'directions', 'and must not steal the claim');
// Named by its tool, not by the internal owner id.
assert.equal(
h.shown.view.hint,
'Directions is using the pointer — close it first.',
);
assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound');
assert.equal(h.tool.active, true, 'the newest claim takes over');
assert.equal(pointerOwner(), 'draw');
assert.equal(lost, 1, 'the other tool is told once');
} finally {
h.restore();
}
});
test('Draw turns off, as if toggled off, when a newer tool takes the pointer', async () => {
const h = harness({
beforeInput(viewer) {
viewer.screenSpaceEventHandler.setInputAction(() => {}, LEFT_CLICK);
},
});
try {
h.act('toggleDraw');
assert.equal(h.tool.diagnostics().stockSingleClick, false);
assert.ok(h.tool.addVertex(10, 20), 'a shape is under way');
const other = claimPointer('directions');
assert.equal(h.tool.active, false);
assert.equal(h.tool.session, null, 'the half-drawn shape is dropped');
assert.equal(h.shown.view.active, false, 'the Draw control reads off');
const after = h.tool.diagnostics();
assert.equal(after.sceneHandler, false, 'its subscriptions are gone');
assert.equal(after.stockSingleClick, true, 'the stock clicks are back');
assert.equal(after.previewItems, 0, 'the preview is cleared');
assert.equal(pointerOwner(), 'directions', 'the newer tool keeps it');
releasePointer(other);
h.act('toggleDraw');
assert.equal(h.tool.active, true, 'and it starts once the pointer is free');
assert.equal(h.tool.active, true, 'and it turns on again when asked');
} finally {
h.restore();
}
@@ -335,30 +363,36 @@ test('a destroyed instance cannot free the pointer its replacement holds', async
}
});
test('both stock viewer click actions are borrowed for the session and given back', async () => {
const h = harness();
test('both stock viewer click actions are held off for the session and given back', async () => {
const stockClick = () => 'viewer picks and selects';
const stockDouble = () => 'viewer tracks';
const h = harness({
beforeInput(viewer) {
viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
viewer.screenSpaceEventHandler.setInputAction(
stockDouble,
LEFT_DOUBLE_CLICK,
);
},
});
try {
const stockClick = () => 'viewer picks and selects';
const stockDouble = () => 'viewer tracks';
h.viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
h.viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK);
assert.equal(h.input.stockEnabled('select'), true);
h.act('toggleDraw');
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
undefined,
h.input.stockEnabled('select'),
false,
"the viewer's own selecting click must not run while drawing",
);
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
undefined,
);
assert.equal(h.input.stockEnabled('dblclickFollow'), false);
h.act('toggleDraw');
assert.equal(h.input.stockEnabled('select'), true);
assert.equal(h.input.stockEnabled('dblclickFollow'), true);
h.input.destroy();
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
stockClick,
'the exact function is restored, not a replacement',
'the exact function goes back to the viewer, not a replacement',
);
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
@@ -379,20 +413,55 @@ test('Enter finishes from the canvas and the label field, never from a focused b
h.tool.addVertex(-97.74, 30.27);
// Enter while the Clear button has keyboard focus means "press Clear".
h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.element('draw-clear'),
});
await Promise.resolve();
assert.equal(
h.annotations.calls.annotate.length,
0,
'a focused button keeps its own Enter',
);
assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched');
assert.equal(
h.tool.session.vertices.length,
3,
'and the shape is untouched',
);
// Enter from the page body (the canvas has focus in practice) finishes it.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes');
assert.equal(
h.annotations.calls.annotate.length,
1,
'Enter on the map finishes',
);
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
} finally {
h.restore();
}
});
test('Enter on the globe canvas finishes, as after the render failure notice hands focus back', async () => {
const h = harness();
try {
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
// src/ui/views/panels/RenderFailure.vue focuses the canvas when the globe
// draws again and the control that had focus is gone.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.viewer.scene.canvas });
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the canvas finishes');
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
} finally {
h.restore();
@@ -407,21 +476,29 @@ test('the live preview hangs at the height the click landed on', async () => {
h.tool.addVertex(-97.75, 30.26, 187.5);
h.tool.addVertex(-97.74, 30.26, 212.25);
await h.tool.whenSettled();
const source = h.viewer._attached[0] ?? null;
assert.ok(source, 'the preview data source is attached');
const points = source.entities.values.filter((entity) => entity.point);
assert.equal(points.length, 2, 'one preview dot per vertex');
const heights = points.map((entity) => {
const position = entity.position.getValue(Cesium.JulianDate.now());
return Cesium.Cartographic.fromCartesian(position).height;
});
const dots = [...h.draw.sets.values()].find(
(set) => !set.disposed && set.kind === 'points',
);
assert.equal(dots.items.size, 2, 'one preview dot per vertex');
const heights = [...dots.items.values()].map((item) => item.pos.height);
const band = [...h.draw.sets.values()]
.find((set) => !set.disposed && set.kind === 'lines')
.items.get('band');
assert.equal(
band.positions.length,
2,
'the rubber band joins the vertices',
);
assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped');
assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`);
assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`);
// …and the finished shape is still flattened, deliberately: the renderer
// drapes, so a height carried further would be discarded out of sight.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -434,17 +511,60 @@ test('the live preview hangs at the height the click landed on', async () => {
}
});
test('destroy in the same tick as init still removes the preview data source', async () => {
test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => {
const h = harness();
try {
// Nothing has been attached yet — dataSources.add() resolves later.
assert.equal(h.viewer._attached.length, 0, 'the add is still pending');
await h.tool.destroy();
await Promise.resolve();
const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
const band = () =>
sets()
.find((set) => set.kind === 'lines')
.items.get('band');
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
assert.equal(band(), undefined, 'one vertex and no pointer draw no band');
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
assert.equal(
h.viewer._attached.length,
band().positions.length,
4,
'an area of three closes back to its first vertex',
);
assert.deepEqual(band().positions[3], band().positions[0]);
h.tool.setColor('red');
assert.deepEqual(
band().style.color,
[1, 107 / 255, 107 / 255, 0.9],
'the band takes the colour',
);
assert.deepEqual(
band().depthFail,
{ kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 },
'behind the surface it stays the primary colour, dashed, as before',
);
assert.equal(band().style.kind, 'dash');
assert.equal(band().style.length, 16);
assert.equal(band().widthPx, 3);
h.tool.setShape('pin');
assert.equal(band(), undefined, 'a pin has no rubber band');
} finally {
h.restore();
}
});
test('destroy in the same tick as init disposes the preview sets', async () => {
const h = harness();
try {
const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
assert.equal(live().length, 2, 'the rubber band and the vertex dots');
await h.tool.destroy();
assert.equal(live().length, 0, 'nothing is left drawn behind the teardown');
assert.equal(
h.tool.diagnostics().previewSets,
0,
'the preview must not be left attached behind the teardown',
'no live tool draws a preview',
);
} finally {
h.restore();
@@ -468,7 +588,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
assert.equal(isPointerFree(), true, 'the pointer is free');
const after = h.tool.diagnostics();
assert.equal(after.destroyed, true);
assert.equal(after.sceneHandler, false, 'the Cesium handler is gone');
assert.equal(
after.sceneHandler,
false,
'the pointer subscriptions are gone',
);
assert.equal(after.domListeners, 0, 'every DOM listener came off');
assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown');
assert.equal(h.controls.actions, null, 'and the controls are disconnected');
@@ -477,8 +601,12 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
stockClick,
'the viewer got its selecting click back',
);
assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached');
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
assert.equal(after.previewSets, 0, 'the preview sets are disposed');
assert.equal(
h.annotations.listeners.size,
0,
'and it no longer follows the board',
);
// Idempotent: a second destroy is harmless.
await h.tool.destroy();
@@ -497,7 +625,11 @@ test('Clear wipes the board and the shape in progress', async () => {
h.act('clearDraw');
assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed');
assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress');
assert.equal(
h.tool.session.vertices.length,
0,
'and so is the shape in progress',
);
} finally {
h.restore();
}
@@ -511,7 +643,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it
h.act('setDrawColor', 'amber');
assert.deepEqual(
{ ...h.shown.view, hint: undefined },
{ active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] },
{
active: true,
shape: 'line',
color: 'amber',
hint: undefined,
marks: [],
},
'the view shows what the controls chose',
);
h.act('setDrawColor', 'purple');
@@ -523,7 +661,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it
assert.equal(h.tool.session.vertices.length, 0);
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -548,12 +689,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
try {
const board = h.annotations;
board.marks.push(
{ id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false },
{ id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false },
{
id: 'a1',
type: 'route',
manual: true,
name: null,
label: '950 m',
color: 'amber',
hidden: false,
},
{
id: 'a2',
type: 'pin',
manual: false,
label: 'Voice pin',
color: 'primary',
hidden: false,
},
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })),
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({
id,
placeholder,
hidden,
})),
[{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }],
'only hand-drawn marks are listed, an unnamed line by its length',
);
@@ -568,7 +728,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
]);
assert.deepEqual(board.calls.setHidden, [['a1', true]]);
assert.deepEqual(board.calls.frame, ['a1']);
assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy');
assert.deepEqual(
navigations,
['drawing'],
'fly-to goes through the navigation policy',
);
assert.deepEqual(board.calls.remove, ['a1']);
assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark');
} finally {
@@ -576,36 +740,321 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
}
});
test("row actions given to the tool show on the shapes they are for and run with the shape", async () => {
const ran = [];
const h = harness({
markActions: [
{
id: 'tag',
icon: 'sell',
label: (name) => `Tag ${name}`,
shapes: ['area', 'line'],
run: (shape) => ran.push(['tag', shape]),
},
{
id: 'measure',
icon: 'straighten',
label: (name) => `Measure ${name}`,
shapes: ['area'],
accepts: (geometry) => geometry.type === 'Polygon',
run: (shape) => ran.push(['measure', shape]),
},
],
});
try {
const board = h.annotations;
board.marks.push(
{
id: 'r1',
type: 'area',
manual: true,
name: 'Strait',
color: 'primary',
hidden: false,
ring: [
[29, 41],
[29.1, 41],
[29.1, 41.1],
],
},
{
id: 'l1',
type: 'route',
manual: true,
name: null,
label: '9 km',
color: 'amber',
hidden: false,
path: [
{ lon: 29, lat: 41.05, height: 0 },
{ lon: 29.1, lat: 41.05, height: 0 },
],
},
{
id: 'p1',
type: 'pin',
manual: true,
name: 'Camp',
color: 'red',
hidden: false,
},
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, actions }) => [id, actions]),
[
[
'r1',
[
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
],
],
['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]],
['p1', []],
],
);
assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true);
assert.equal(
h.act('runDrawMarkAction', 'l1', 'measure'),
false,
'a line is not offered an area action',
);
assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual(ran, [
[
'tag',
{
id: 'l1',
shape: 'line',
name: '',
title: 'Line · 9 km',
geometry: {
type: 'LineString',
coordinates: [
[29, 41.05],
[29.1, 41.05],
],
},
},
],
[
'measure',
{
id: 'r1',
shape: 'area',
name: 'Strait',
title: 'Strait',
geometry: {
type: 'Polygon',
coordinates: [
[
[29, 41],
[29.1, 41],
[29.1, 41.1],
[29, 41],
],
],
},
},
],
]);
} finally {
h.restore();
}
});
test('an action that throws is reported and leaves the row alone', async () => {
const h = harness({
markActions: [
{
id: 'boom',
icon: 'bolt',
label: () => {
throw new Error('label');
},
shapes: ['area'],
run: () => {
throw new Error('run');
},
},
],
});
const warn = console.warn;
const warned = [];
console.warn = (...args) => warned.push(args[0]);
try {
h.annotations.marks.push({
id: 'r1',
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
h.annotations.changed();
assert.deepEqual(h.shown.view.marks[0].actions, [
{ id: 'boom', icon: 'bolt', label: 'boom' },
]);
assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false);
assert.deepEqual(warned, ['[draw] boom failed']);
} finally {
console.warn = warn;
h.restore();
}
});
test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => {
const pending = [];
const h = harness({
markActions: [
{
id: 'measure',
icon: 'straighten',
label: (name) => `Measure ${name}`,
shapes: ['area'],
run: () =>
new Promise((resolve, reject) => pending.push({ resolve, reject })),
},
{
id: 'now',
icon: 'bolt',
label: () => 'Now',
shapes: ['area'],
run: () => ' 12 km² ',
},
{
id: 'long',
icon: 'notes',
label: () => 'Long',
shapes: ['area'],
run: () => `${'word '.repeat(60)}end`,
},
],
});
const warn = console.warn;
console.warn = () => {};
try {
const board = h.annotations;
const area = (id) => ({
id,
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
board.marks.push(area('r1'), area('r2'));
board.changed();
const row = (id) => h.shown.view.marks.find((entry) => entry.id === id);
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']);
h.act('runDrawMarkAction', 'r1', 'long');
assert.ok(
row('r1').note.length <= 200 && row('r1').note.endsWith('word…'),
'a long note is cut at a word',
);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [true, '']);
assert.equal(
h.act('runDrawMarkAction', 'r1', 'now'),
false,
'a busy row takes no second press',
);
pending[0].resolve('412 km², 38 km of edge');
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, '412 km², 38 km of edge'],
);
h.act('runDrawMarkAction', 'r1', 'measure');
pending[1].reject(new Error('refused'));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, ''],
'a failure clears the note',
);
h.act('runDrawMarkAction', 'r2', 'measure');
board.marks.splice(1, 1);
board.changed();
pending[2].resolve('late');
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(row('r2'), undefined);
board.marks.push(area('r2'));
board.changed();
assert.deepEqual(
[row('r2').busy, row('r2').note],
[false, ''],
'a late answer never reaches a shape that went',
);
} finally {
console.warn = warn;
h.restore();
}
});
test('Backspace on the page removes the last vertex', () => {
const h = harness();
try {
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Backspace',
target: h.documentDouble.body,
});
assert.equal(h.tool.session.vertices.length, 1);
} finally {
h.restore();
}
});
test('keys on the shape list are the list\'s, not the drawing\'s', async () => {
test("keys on the shape list are the list's, not the drawing's", async () => {
const h = harness();
try {
const listButton = new FakeElement('BUTTON');
listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null);
listButton.closest = (selector) =>
selector === '#draw-mark-list' ? {} : null;
const elsewhere = new FakeElement('INPUT', 'location-search');
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Escape', target: listButton });
assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape');
assert.equal(
h.tool.session.vertices.length,
2,
'Escape in the list keeps the shape',
);
assert.equal(h.tool.active, true, 'and keeps Draw on');
h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere });
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter');
h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body });
assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape');
assert.equal(
h.annotations.calls.annotate.length,
0,
'another field keeps its Enter',
);
h.documentDouble.emit('keydown', {
key: 'Escape',
target: h.documentDouble.body,
});
assert.equal(
h.tool.session.vertices.length,
0,
'Escape on the page drops the open shape',
);
} finally {
h.restore();
}
+106 -104
View File
@@ -5,6 +5,9 @@ import { createPinia } from 'pinia';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
/** A hybrid renderer whose screen board is presented to its own store. */
function hybridWithBoard(viewer) {
@@ -89,11 +92,41 @@ function installBrowserGlobals(t) {
});
}
/**
* `viewer` with the fake scene's camera, query, frame and draw ports and the
* fake credits bound over it as one renderer.
*/
function withScenePorts(viewer) {
const { unbind, ...ports } = bindFakeCesiumScene(viewer);
unbind();
bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) });
return ports.draw;
}
/** What the world renderer draws, each item of its live sets (of `kind`). */
function worldItems(draw, kind) {
const items = [];
for (const record of draw.sets.values())
if (
!record.disposed &&
record.spec.id.startsWith('annotations:') &&
(!kind || record.kind === kind)
)
items.push(...record.items.values());
return items;
}
/** Surface heights the scene samples: `height(lon, lat)` in degrees. */
function sampleHeights(scene, height) {
scene.sampleHeightSupported = true;
scene.sampleHeight = (carto) =>
height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude));
}
/** A viewer whose scene/camera is just enough for both sub-renderers. */
function fakeViewer(lon, lat) {
const credits = new Set();
const camera = cameraLookingAt(lon, lat);
const dataSources = [];
const frames = controlledFrames();
const scene = {
camera,
@@ -107,31 +140,19 @@ function fakeViewer(lon, lat) {
scene.renderRequests += 1;
},
};
return {
dataSources,
frames,
viewer: {
credits,
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
removeStaticCredit: (credit) => credits.delete(credit),
},
scene,
camera,
trackedEntity: null,
dataSources: {
add(dataSource) {
dataSources.push(dataSource);
return dataSource;
},
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
const viewer = {
credits,
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
removeStaticCredit: (credit) => credits.delete(credit),
},
scene,
camera,
canvas: scene.canvas,
trackedEntity: null,
};
const draw = withScenePorts(viewer);
return { draw, frames, viewer };
}
function controlledFrames() {
@@ -192,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
});
const camera = cameraLookingAt(-99, 31);
const dataSources = [];
const frames = controlledFrames();
const scene = {
camera,
@@ -206,19 +226,12 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
const viewer = {
scene,
camera,
canvas: scene.canvas,
trackedEntity: null,
dataSources: {
add(dataSource) {
dataSources.push(dataSource);
return dataSource;
},
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
// The screen board projects through the renderer's camera and query; the
// world renderer draws through its draw port.
const { draw } = bindFakeCesiumScene(viewer);
const { store, renderer } = hybridWithBoard(viewer);
const anno = {
id: 'anno-hybrid-fb3',
@@ -235,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
renderer.add(anno);
const [before] = annotationGroups(store);
assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2);
assert.equal(dataSources.length, 1);
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
const ring = [
[-106, 25],
@@ -268,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1));
assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1));
assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned');
assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline');
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1);
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1);
assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy');
assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline');
assert.equal(worldItems(draw, 'shapes').length, 1);
assert.equal(worldItems(draw, 'lines').length, 1);
assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy');
const outer = [
[-99, 31],
[-98.999, 31],
@@ -298,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
buildingHeight: 20,
};
const completion = renderer.add(building);
assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes');
assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes');
for (let frame = 0; frame < 8; frame += 1) frames.emit();
assert.equal((await completion).status, 'installed');
const added = dataSources[0].entities.values.slice(2);
const fills = added.filter(
(entity) => entity.polygon && entity.polygon.fill?.getValue() !== false,
);
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
assert.equal(
fills.length,
2,
'every building part gets a classification volume',
'every building part gets a volume',
);
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1);
assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0);
assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole');
assert.equal(fills[1].geometry.rings.length, 1);
assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour');
assert.equal(
fills[0].polygon.material,
fills[1].polygon.material,
'parts share the fill material',
);
assert.equal(
added.filter((entity) => entity.polyline).length,
worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length,
3,
'all outer and hole outlines are retained',
);
renderer.remove(building);
assert.equal(
dataSources[0].entities.values.length,
worldItems(draw).length,
2,
'multipart removal leaves only the earlier area',
);
@@ -341,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -369,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove',
};
assert.throws(() => renderer.add(anno), /screen insert failed/);
assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live');
assert.equal(worldItems(draw).length, 2, 'the world drape is already live');
assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself');
// The engine's rollback path — it must reach the partial state by id.
renderer.remove(anno);
assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released');
assert.equal(worldItems(draw).length, 0, 'partial world state must be released');
// …and the id is free again: a retry draws ONE mark, not a second one over
// an orphan nothing owns.
renderer.add(anno);
assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape');
assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape');
assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption');
renderer.remove(anno);
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
renderer.destroy();
});
test('a release that throws keeps the mark addressable for a retry cleanup', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -404,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
};
renderer.add(anno);
assert.equal(dataSources[0].entities.values.length, 2);
assert.equal(worldItems(draw).length, 2);
assert.equal(annotationGroups(store).length, 1);
// The world route releases fine, then the screen release fails part-way
@@ -412,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
const workingSetTimeout = globalThis.window.setTimeout;
globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); };
assert.throws(() => renderer.remove(anno), /teardown scheduling failed/);
assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release');
assert.equal(worldItems(draw).length, 0, 'the world route did release');
assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan');
// Dropping the routing entry here would make that orphan permanently
@@ -420,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
globalThis.window.setTimeout = workingSetTimeout;
renderer.remove(anno);
assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan');
assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route');
assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route');
// Fully released now — a third call is inert.
renderer.remove(anno);
@@ -430,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
test('a world add that fails mid-way leaves its landed entities removable', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -446,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t)
};
// The draped fill lands; the outline throws (bad geometry / lost context).
const entities = dataSources[0].entities;
const realAdd = entities.add.bind(entities);
let addsLeft = 1;
entities.add = (options) => {
if (addsLeft <= 0) throw new Error('entity add failed');
addsLeft -= 1;
return realAdd(options);
const realLines = draw.lines;
draw.lines = (spec) => {
const set = realLines(spec);
set.set = () => { throw new Error('draw failed'); };
return set;
};
assert.throws(() => renderer.add(anno), /entity add failed/);
assert.equal(entities.values.length, 1, 'one entity landed before the failure');
assert.throws(() => renderer.add(anno), /draw failed/);
assert.equal(worldItems(draw).length, 1, 'one item landed before the failure');
entities.add = realAdd;
draw.lines = realLines;
renderer.remove(anno);
assert.equal(entities.values.length, 0,
'the rollback must see the entities that landed before the throw');
assert.equal(worldItems(draw).length, 0,
'the rollback must see the items that landed before the throw');
renderer.add(anno);
assert.equal(entities.values.length, 2, 'the retry draws a complete mark');
assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark');
assert.equal(annotationGroups(store).length, 1);
renderer.destroy();
});
@@ -475,7 +478,7 @@ function workTrace() {
test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => {
installBrowserGlobals(t);
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
t.after(() => renderer.destroy());
const first = buildingAnnotation('sampled-building');
@@ -485,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
showOsmCredit(viewer, otherOwner);
const probes = [];
const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90];
viewer.scene.clampToHeight = (position) => {
const cartographic = Cesium.Cartographic.fromCartesian(position);
const lon = Cesium.Math.toDegrees(cartographic.longitude);
const lat = Cesium.Math.toDegrees(cartographic.latitude);
sampleHeights(viewer.scene, (lon, lat) => {
probes.push([lon, lat]);
const outcome = outcomes[probes.length - 1];
if (outcome instanceof Error) throw outcome;
return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome);
};
return outcome == null ? undefined : outcome;
});
// Suppress screen points: these counts concern the eight outside-building
// probes, not the screen renderer's separate anchor-height sampling.
const firstTrace = workTrace();
@@ -510,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace });
const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace });
assert.equal(probes.length, 0, 'enqueue must not probe synchronously');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1,
'pending outlines add no tile credit to the other owner');
for (let frame = 0; frame < 16; frame += 1) {
const before = probes.length;
frames.emit();
assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget');
if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts');
if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts');
}
const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]);
assert.equal(installed.status, 'installed');
@@ -540,8 +540,9 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
const detail = parent.detail;
assert.equal(detail.index, index);
assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing');
// The fourth probe finds nothing and the fifth throws: both are misses.
assert.equal(detail.clampResult,
trace === firstTrace && index === 4 ? 'threw' : 'returned');
trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed');
assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd));
assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end);
if (index === 7) {
@@ -571,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10);
}
assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8);
const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon);
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
assert.equal(fills.length, 2);
assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
const afterCompletion = probes.length;
frames.emit();
assert.equal(probes.length, afterCompletion, 'completion releases the sampler');
@@ -597,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as
t.mock.method(globalThis.performance, 'now', () => now);
const { viewer, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
viewer.scene.clampToHeight = (position) => position;
sampleHeights(viewer.scene, () => 0);
const traces = [workTrace(), workTrace(), workTrace()];
const completions = [0, 0.01, 0.02].map((offset, index) =>
renderer.add(buildingAnnotation(`queued-${index}`, offset), {
@@ -626,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
installBrowserGlobals(t);
t.mock.timers.enable({ apis: ['setTimeout'] });
t.after(() => t.mock.timers.reset());
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
let probeCount = 0;
viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; };
sampleHeights(viewer.scene, () => { probeCount += 1; return 0; });
const cancelled = buildingAnnotation('cancelled-building');
const cancelledTrace = workTrace();
const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace });
@@ -671,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
assert.equal(viewer.credits.size, 0);
for (const listener of savedTimeout) listener();
assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
const pending = buildingAnnotation('destroyed-building');
const destruction = renderer.add(pending, { pendingVisible: false });
@@ -681,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
for (const listener of savedDestroy) listener();
t.mock.timers.tick(2000);
assert.equal(probeCount, 1);
assert.equal(dataSources.length, 0, 'destroy removes the owned data source');
assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go');
assert.equal(frames.size, 0, 'destroy removes frame listeners');
assert.equal(viewer.credits.size, 0);
});
@@ -690,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
installBrowserGlobals(t);
t.mock.timers.enable({ apis: ['setTimeout'] });
t.after(() => t.mock.timers.reset());
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' };
renderer.add(anno);
@@ -703,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
assert.equal(after.key, before.key);
assert.equal(others.length, 0);
assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
frames.emit();
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
renderer.destroy();
});
test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => {
installBrowserGlobals(t);
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' };
renderer.add(anno);
@@ -724,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
// Frame projection is still ordinary pending-point work. Arm the failure
// only after sampling completes, before its promise converts the caption.
for (let frame = 0; frame < 8; frame += 1) frames.emit();
assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion');
assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion');
assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy');
// The caption conversion fails when it presents the converted mark.
const publish = store.publish;
@@ -747,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8);
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1);
assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back');
assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back');
assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy');
assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable');
globalThis.window.setTimeout = workingSetTimeout;
@@ -781,6 +782,7 @@ test('a deadline passed during caption conversion leaves a drawn pending point',
const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out'));
assert.equal(live.length, 1);
assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws');
assert.notEqual(live[0].display, 'none', 'and is on screen');
renderer.remove(anno);
renderer.destroy();
});
+11 -8
View File
@@ -18,6 +18,7 @@ import {
outlineQueryText,
} from './outlineRungs.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { decodeOpenFreeMapOutlineTile } from '../sources/openFreeMapOutlines.js';
import { createNominatimOutlineClient } from '../sources/nominatimOutlines.js';
import { createApplicationRequestServices } from '../services/requests.js';
@@ -924,15 +925,17 @@ const PLACES = {
},
};
const viewerAt = (lat, lon, height = 4000) => ({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
// The resolver reads the camera through the renderer's camera port.
const viewerAt = (lat, lon, height = 4000) =>
bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
},
},
},
});
});
test('default settings: outline, street and building asks send nothing to Overpass', async (t) => {
const prior = process.env.OVERPASS_UPSTREAMS;
+7 -4
View File
@@ -5,11 +5,14 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { polygonsContain } from '../data/adminBoundaries.js';
import { streetFootprint } from './outlineRungs.js';
import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
function viewerAt(lat, lon, height = 20_000) {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -17,7 +20,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
@@ -180,10 +183,10 @@ test('a geocoded city or neighborhood upgrades to the bundled outline', async ()
const credits = [];
const cancelled = await city.resolve(
'Austin',
{
bindFakeCesiumCredits({
...viewerAt(39, -100, 5_000_000),
creditDisplay: { addStaticCredit: (credit) => credits.push(credit) },
},
}),
{ signal: controller.signal },
);
const pending = cancelled.resolveOutline();
+43 -71
View File
@@ -14,7 +14,6 @@ import {
nearestPointOnLines,
} from '../sources/featureGeometry.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js';
import {
lookupNaturalRegionOutline,
@@ -45,6 +44,9 @@ import {
import { createOutlineRungs } from './outlineRungs.js';
import { unavailablePlaceSearch } from '../search/placeSearch.js';
import { isPickedWorldPosition } from '../data/scenePick.js';
import { heightsOf } from '../queries/heights.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js';
/** Prepare only local dateline outlines for planar admission and centering. */
function localOutlineFrame(fp) {
@@ -178,7 +180,7 @@ export function createAnnotationResolver({
* Resolve a single annotation target to a normalized world anchor.
*
* @param {object} opts
* @param {Cesium.Viewer} opts.viewer
* @param {object} opts.viewer The viewer the renderer is bound to.
* @param {string} [opts.target] Place name to geocode.
* @param {number} [opts.latitude] Explicit latitude (wins over target).
* @param {number} [opts.longitude] Explicit longitude.
@@ -2216,11 +2218,10 @@ export function createAnnotationResolver({
*/
function viewportProximity(viewer) {
try {
const carto = viewer?.camera?.positionCartographic;
if (!carto) return null;
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const radiusKm = Math.max((carto.height / 1000) * 3, 5);
const pose = viewer ? findCamera(viewer)?.pose() : null;
if (!pose) return null;
const { lat, lon } = pose;
const radiusKm = Math.max((pose.height / 1000) * 3, 5);
if (![lat, lon, radiusKm].every(Number.isFinite)) return null;
return { lat, lon, radiusKm };
} catch {
@@ -2231,12 +2232,12 @@ export function createAnnotationResolver({
/** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */
function viewportBias(viewer) {
try {
const rect = viewer?.camera?.computeViewRectangle?.();
const rect = viewer ? findCamera(viewer)?.viewRectangle() : null;
if (!rect) return null;
const swLat = Cesium.Math.toDegrees(rect.south).toFixed(4);
const swLng = Cesium.Math.toDegrees(rect.west).toFixed(4);
const neLat = Cesium.Math.toDegrees(rect.north).toFixed(4);
const neLng = Cesium.Math.toDegrees(rect.east).toFixed(4);
const swLat = rect.south.toFixed(4);
const swLng = rect.west.toFixed(4);
const neLat = rect.north.toFixed(4);
const neLng = rect.east.toFixed(4);
if ([swLat, swLng, neLat, neLng].some((v) => v === 'NaN')) return null;
return `${swLat},${swLng}|${neLat},${neLng}`;
} catch {
@@ -2289,58 +2290,39 @@ export function createAnnotationResolver({
* name the place, and we anchor the mark to the actual world point under it.
*/
function pickWorldFromScreen(viewer, nx, ny) {
const scene = viewer?.scene;
if (!scene) return null;
const canvas = scene.canvas;
const query = viewer ? findQuery(viewer) : null;
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvas = canvasOf(viewer);
if (!query || !canvas) return null;
const w = canvas.clientWidth || canvas.width || 0;
const h = canvas.clientHeight || canvas.height || 0;
if (!w || !h) return null;
const px = Math.max(0, Math.min(1, nx)) * w;
const py = Math.max(0, Math.min(1, ny)) * h;
const pos = new Cesium.Cartesian2(px, py);
// Each stage is validated before it is accepted: a depth pick over empty sky
// can return a NaN or centre-of-the-earth Cartesian, and converting one of
// those throws inside Cesium. A degenerate pick IS a missed pick, so it falls
// through to the next stage and ultimately to the caller's null.
let cart = null;
if (
scene.pickPositionSupported &&
typeof scene.pickPosition === 'function'
) {
// can return a NaN or centre-of-the-earth position, and converting one of
// those throws inside the renderer. A degenerate pick IS a missed pick, so it
// falls through to the next stage and ultimately to the caller's null.
const attempt = (pick) => {
try {
cart = scene.pickPosition(pos);
return pick();
} catch {
cart = null;
return null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.pickEllipsoid === 'function'
) {
try {
cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84);
} catch {
cart = null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.getPickRay === 'function'
) {
try {
const ray = viewer.camera.getPickRay(pos);
cart = ray ? scene.globe?.pick(ray, scene) || null : null;
} catch {
cart = null;
}
}
};
// The depth pick answers null where the renderer has no depth support.
let cart = attempt(() => query.pickPosition(px, py));
if (!isPickedWorldPosition(cart))
cart = attempt(() => query.pickEllipsoid(px, py));
if (!isPickedWorldPosition(cart))
cart = attempt(() => query.pickGlobe(query.pickRay(px, py)));
if (!isPickedWorldPosition(cart)) return null;
const carto = Cesium.Cartographic.fromCartesian(cart);
const carto = toLonLatH(cart);
if (!carto) return null;
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
lat: carto.lat,
lon: carto.lon,
// The height the pick actually landed on — a roof, a hillside, or 0 on
// the ellipsoid. Callers that only want a coordinate ignore it; the draw
// tool's live preview needs it, or the rubber band sinks to sea level
@@ -2355,28 +2337,18 @@ export function createAnnotationResolver({
* the tiles for that spot aren't loaded we fall back to the ellipsoid (0).
*/
function sampleGroundHeight(viewer, lon, lat) {
const scene = viewer?.scene;
if (!scene) return 0;
try {
if (
scene.clampToHeightSupported &&
typeof scene.clampToHeight === 'function'
) {
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
const surface = Cesium.Cartographic.toCartesian(carto);
const clamped = scene.clampToHeight(surface);
if (clamped) {
const h = Cesium.Cartographic.fromCartesian(clamped).height;
if (Number.isFinite(h)) return h;
}
if (!viewer) return 0;
const heights = heightsOf(viewer);
// A miss is tiles not ready: fall through to the terrain, then 0.
if (heights.supported().clamp) {
const clamped = heights.clampNow(fromDegrees(lon, lat, 0));
if (clamped) {
const h = toLonLatH(clamped)?.height;
if (Number.isFinite(h)) return h;
}
} catch {
/* tiles not ready — fall through */
}
const globeHeight = scene.globe?.getHeight?.(
Cesium.Cartographic.fromDegrees(lon, lat),
);
return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0;
const globeHeight = heights.now({ lon, lat }, { against: 'terrain' });
return globeHeight !== null && globeHeight > 0 ? globeHeight : 0;
}
function shortLabel(formattedAddress) {
+78 -65
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { followedOf } from '../data/followed.js';
import { getOverlayPaintRect } from '../overlays/worldOverlay.js';
import {
getActiveTrackedReadoutId,
@@ -8,6 +8,15 @@ import { t } from '../i18n/index.js';
import { nextTick } from 'vue';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsOf } from '../queries/heights.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import {
canvasOf as sceneCanvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
/** A label whose detailed outline could not be resolved. */
function outlineUnavailableLabel(label) {
@@ -78,11 +87,13 @@ export function createScreenAnnotationRenderer(
const arrowMarkers = new Map();
let viewBox = null;
const scene = viewer.scene;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
scene.camera.positionWC,
);
// The eye this frame is projected from (the camera port's pose), and the
// query port and canvas it is projected through, read once per pass.
let pose = null;
let passQuery = null;
let passCanvas = null;
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvasOf = () => sceneCanvasOf(viewer);
const records = new Map(); // anno.id -> { key, anno, group, parts }
const leaving = new Map(); // key -> a removed mark's record while it fades out
const byKey = new Map(); // key -> record, live or fading
@@ -91,8 +102,6 @@ export function createScreenAnnotationRenderer(
let published = '';
// Only the renderer whose board the store shows may change or remove it.
const shown = () => store.board?.owner === owner;
const scratch = new Cesium.Cartesian2();
const scratchDir = new Cesium.Cartesian3();
// Per-point ground height cache. Marks must sit on the real surface, not at
// sea level — otherwise in elevated cities (Austin ~150 m) they project
// underground and parallax sinks them at oblique angles. Sampled once the
@@ -121,7 +130,7 @@ export function createScreenAnnotationRenderer(
// Re-project every annotation each rendered frame so marks stay glued to the
// world. postRender runs after the camera/tiles update, so positions are exact.
const onPostRender = () => projectAll();
scene.postRender.addEventListener(onPostRender);
const removePostRender = findFrame(viewer)?.on('postRender', onPostRender);
function color(anno) {
return PALETTE[anno.color] || PALETTE.primary;
@@ -141,15 +150,12 @@ export function createScreenAnnotationRenderer(
return cached.h;
}
try {
if (
scene.clampToHeightSupported &&
typeof scene.clampToHeight === 'function'
) {
const c = scene.clampToHeight(
Cesium.Cartesian3.fromDegrees(lon, lat, 0),
);
const heights = heightsOf(viewer);
if (heights.supported().clamp) {
// A miss is tiles not ready.
const c = heights.clampNow(fromDegrees(lon, lat, 0));
if (c) {
const h = Cesium.Cartographic.fromCartesian(c).height;
const h = toLonLatH(c)?.height;
if (Number.isFinite(h) && h > -430 && h < 9000) {
heightCache.set(key, { h, settled: true, gen: projGen });
trimHeightCache();
@@ -278,7 +284,7 @@ export function createScreenAnnotationRenderer(
}
// Record the mark BEFORE it reaches the board, then unwind on any throw
// from here down (projectAll reaches into Cesium and can fail on a lost
// from here down (projectAll reaches into the renderer and can fail on a lost
// context). Previously a throw past the insert left an ORPHANED mark: the
// engine's rollback only deletes its own map entry, so the next annotate
// of the same geometry stacked a fresh mark on top of the corpse.
@@ -363,26 +369,27 @@ export function createScreenAnnotationRenderer(
// Anchor at the real surface height (cached + validated), so marks sit on
// the ground/building instead of at sea level. The settle-once cache keeps
// it stable (no per-frame jitter that earlier broke nearby projections).
const world = Cesium.Cartesian3.fromDegrees(
lon,
lat,
groundHeight(lon, lat),
);
const world = fromDegrees(lon, lat, groundHeight(lon, lat));
if (!pose) return null;
// Reject points behind the camera (they produce wrapped/extreme coords).
Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir);
if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0)
const eye = pose.position;
const look = pose.direction;
if (
(world.x - eye.x) * look.x +
(world.y - eye.y) * look.y +
(world.z - eye.z) * look.z <=
0
)
return null;
// Reject points beyond the globe horizon.
if (!occluder.isPointVisible(world)) return null;
const win = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
world,
scratch,
);
const query = passQuery;
if (!query || query.isOccluded(world)) return null;
const win = query.project(world);
if (!win || !Number.isFinite(win.x) || !Number.isFinite(win.y)) return null;
// Reject absurd off-screen projections (anchor not in view).
const w = scene.canvas.clientWidth || scene.canvas.width;
const h = scene.canvas.clientHeight || scene.canvas.height;
const canvas = passCanvas;
const w = canvas.clientWidth || canvas.width;
const h = canvas.clientHeight || canvas.height;
if (
!allowOffscreen &&
(win.x < -w || win.x > 2 * w || win.y < -h || win.y > 2 * h)
@@ -399,9 +406,13 @@ export function createScreenAnnotationRenderer(
// from the host's ACTUAL painted rectangle after final layout; the billboard extent
// is unioned for aircraft/satellites that also own a native tracked graphic.
const TRACKED_BBOX_MARGIN = 8; // px buffer added around the footprint
const TRACKED_FADE_EASE = 0.22; // per-frame ease toward hidden(0) / visible(1)
// Ease toward hidden(0) / visible(1): this share of the gap closes in one
// 60 Hz frame (about 200 ms to settle), scaled by elapsed time so the fade
// takes as long at any refresh rate.
const TRACKED_FADE_EASE = 0.22;
const TRACKED_FADE_FRAME_MS = 1000 / 60;
let trackedFadeAtMs = -Infinity;
const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop
const _scratchTrackedWin = new Cesium.Cartesian2();
// Evaluate a NearFarScalar (billboard scaleByDistance) at a camera distance.
function nearFarValue(nfs, dist) {
@@ -422,32 +433,23 @@ export function createScreenAnnotationRenderer(
let top = painted?.y;
let bottom = painted ? painted.y + painted.h : undefined;
const ent = viewer.trackedEntity;
const now = Cesium.JulianDate.now();
const followed = followedOf(viewer);
const displayPosition = followed?.displayPosition;
const world =
typeof ent?.gevDisplayPosition === 'function'
? ent.gevDisplayPosition()
: null;
const win = world
? Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
world,
_scratchTrackedWin,
)
: null;
typeof displayPosition === 'function' ? displayPosition() : null;
const win = world ? (passQuery?.project(world) ?? null) : null;
// Billboard box — centered on the anchor, magnified by scaleByDistance.
const bb = ent?.billboard;
if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
const baseW = bb.width?.getValue?.(now) ?? 28;
const baseH = bb.height?.getValue?.(now) ?? 28;
// Billboard box — centered on the anchor, magnified by scaleByDistance, from
// the size the tracking layer recorded for its sprite.
const sprite = followed?.sprite;
if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
const baseW = sprite.width ?? 28;
const baseH = sprite.height ?? 28;
let scale = 1;
const sbd = bb.scaleByDistance?.getValue?.(now);
if (sbd)
scale = nearFarValue(
sbd,
Cesium.Cartesian3.distance(scene.camera.positionWC, world),
);
const sbd = sprite.scaleByDistance;
// No eye to measure from: the sprite's own size.
if (sbd && pose)
scale = nearFarValue(sbd, distance(pose.position, world));
const hw = (baseW * scale) / 2;
const hh = (baseH * scale) / 2;
const bbLeft = win.x - hw;
@@ -476,14 +478,17 @@ export function createScreenAnnotationRenderer(
return;
}
projGen += 1; // new frame: entries touched below are "hot" and survive trimming
pose = findCamera(viewer)?.pose() ?? null;
passQuery = findQuery(viewer);
passCanvas = canvasOf();
const trackedRect = trackedEntityRect();
occluder.cameraPosition = scene.camera.positionWC;
const h = scene.canvas.clientHeight || scene.canvas.height;
const w = scene.canvas.clientWidth || scene.canvas.width;
const canvas = passCanvas;
const h = canvas.clientHeight || canvas.height;
const w = canvas.clientWidth || canvas.width;
viewBox = `0 0 ${w} ${h}`;
// Shrink point-marker geometry as the camera pulls back (declutter the blob).
const mScale = markScale(
viewer.camera.positionCartographic?.height ?? 1000,
Number.isFinite(pose?.height) ? pose.height : 1000,
);
for (const rec of records.values()) {
@@ -677,6 +682,14 @@ export function createScreenAnnotationRenderer(
// safe and not jarring.
function fadeTracked(trackedRect) {
if (!shown()) return;
const nowMs = performance.now();
// A gap longer than a slow frame means the fade was not running (nothing
// followed): it starts again as from one 60 Hz frame.
const gapMs = nowMs - trackedFadeAtMs;
const stepMs = gapMs >= 0 && gapMs <= 100 ? gapMs : TRACKED_FADE_FRAME_MS;
trackedFadeAtMs = nowMs;
const ease =
1 - Math.pow(1 - TRACKED_FADE_EASE, stepMs / TRACKED_FADE_FRAME_MS);
let changed = false;
for (const rec of records.values()) {
const { anno, group } = rec;
@@ -705,10 +718,10 @@ export function createScreenAnnotationRenderer(
}
}
const target = overlapping ? 0 : 1;
const next = cur + (target - cur) * TRACKED_FADE_EASE;
const next = cur + (target - cur) * ease;
rec._trackedFade = Math.abs(next - target) < 0.02 ? target : next;
// The base alpha applies unless faded. (The CSS `transition: opacity` was
// removed from .gev-anno so this per-frame JS ease is the ONLY easing —
// removed from .gev-anno so this JS ease is the ONLY easing —
// previously the two fought and produced an opacity oscillation.)
const opacity = String(
(anno.alpha ?? 1) * (rec._trackedFade !== 1 ? rec._trackedFade : 1),
@@ -821,7 +834,7 @@ export function createScreenAnnotationRenderer(
function destroy() {
try {
scene.postRender.removeEventListener(onPostRender);
removePostRender?.();
} catch {
/* torn down */
}
@@ -6,7 +6,19 @@ import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import ScreenAnnotations from '../ui/views/panels/ScreenAnnotations.vue';
import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js';
import { createScreenAnnotationRenderer as createRenderer } from './screenAnnotationRenderer.js';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
import { rendererOf } from '../render/rendererOf.js';
/**
* The renderer over a viewer double with the camera, query and frame ports
* bound over it (once per double), and the scene's canvas as the viewer's.
*/
function createScreenAnnotationRenderer(viewer, options) {
if (!rendererOf(viewer)) bindFakeCesiumScene(viewer);
viewer.canvas ??= viewer.scene?.canvas;
return createRenderer(viewer, options);
}
// happy-dom does not lay out SVG; every element measures as a 40 x 16 box.
for (const type of [globalThis.SVGElement, globalThis.SVGGraphicsElement]) {
@@ -53,7 +65,7 @@ function sceneFor(camera, extra = {}) {
return {
camera,
canvas: { clientWidth: 800, clientHeight: 600, width: 800, height: 600 },
clampToHeightSupported: false,
sampleHeightSupported: false,
postRender: { addEventListener() {}, removeEventListener() {} },
...extra,
};
@@ -173,14 +185,13 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
const sampledAnchors = [];
const scene = sceneFor(camera, {
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
clampToHeightSupported: true,
clampToHeight(world) {
const cartographic = Cesium.Cartographic.fromCartesian(world);
sampleHeightSupported: true,
sampleHeight(cartographic) {
sampledAnchors.push([
Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)),
Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)),
]);
return world;
return 0;
},
});
const renderer = createScreenAnnotationRenderer(
@@ -216,7 +227,7 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
assert.ok(after === before, 'the rendered group is mutated, not replaced');
assert.deepEqual(sampledAnchors.at(-1), [-97.5, 31.2], 'the existing group projects from the re-seated anchor');
assert.equal(groups().length, 1);
assert.equal(after.querySelector('.gev-anno-ring'), null, 'reticle rings are removed in place');
assert.equal(after.querySelector('.gev-anno-ring') === null, true, 'reticle rings are removed in place');
assert.ok(after.querySelector('.gev-anno-callout') === callout, 'the original callout remains in the group');
assert.ok(after.querySelector('.gev-anno-dot') === dot, 'the anchor dot remains in the group');
assert.ok(svg());
@@ -330,7 +341,7 @@ test('a removed mark fades out, then leaves the board', async (t) => {
assert.equal(group.isConnected, false);
renderer.destroy();
await settle();
assert.equal(document.querySelector('.gev-screen-whiteboard'), null);
assert.equal(document.querySelector('.gev-screen-whiteboard') === null, true);
});
// ── Partial-add unwind (review round 2) ───────────────────────────────────────
File diff suppressed because it is too large. Load diff
+423 -45
View File
@@ -1,70 +1,448 @@
// A mark hidden from Draw's list leaves the globe whole: every entity it put
// there is taken out on sync and comes back when shown, and the line's
// flowing stroke, which keeps its own colour, follows the mark's alpha.
// The world renderer draws each mark through the draw port, in sets of its
// own: a hidden mark has its sets hidden on sync and shown again; a fading
// mark takes its new colours in place; every kind draws what it drew as
// entities, draped and clamped to terrain and tiles alike.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import {
FlowMaterialProperty,
createWorldAnnotationRenderer,
} from './worldAnnotationRenderer.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js';
const noop = () => {};
function viewer(t) {
for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) {
const original = globalThis[name];
globalThis[name] = class {};
t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; });
}
const before = globalThis.document;
globalThis.document = { addEventListener: noop, removeEventListener: noop };
t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; });
/**
* A viewer with a fake draw port, frame, camera and query bound. The camera
* stands at `camera.height`; `preRender()` runs the frame's preRender
* listeners, `emit()` its postRender ones.
*/
function viewer(t, { heights = () => null } = {}) {
const draw = fakeDrawPort();
const frames = new Set();
const before = new Set();
const v = { requests: 0 };
const frame = {
on(phase, cb) {
const listeners =
phase === 'postRender' ? frames : phase === 'preRender' ? before : null;
if (!listeners) return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
requestRender() {
v.requests += 1;
},
};
const camera = { height: 2000, pose: () => ({ height: camera.height }) };
const query = { sampleHeightNow: (point) => heights(point) };
const unbind = bindRenderer(v, { draw, frame, query, camera });
t.after(unbind);
return {
creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop },
entities: new C.EntityCollection(),
dataSources: new C.DataSourceCollection(),
camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } },
scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(),
primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } },
v,
draw,
frames,
before,
camera,
emit: () => [...frames].forEach((cb) => cb()),
preRender: () => [...before].forEach((cb) => cb()),
};
}
const marks = () => [
{ id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] },
{ id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] },
{ id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } },
{
id: 'route',
type: 'route',
color: 'amber',
alpha: 1,
anchor: { lat: 0, lon: 0 },
path: [
{ lat: 0, lon: 0 },
{ lat: 0.01, lon: 0.01 },
],
},
{
id: 'area',
type: 'area',
color: 'green',
alpha: 1,
anchor: { lat: 0.005, lon: 0.005 },
ring: [
[0, 0],
[0.01, 0],
[0.01, 0.01],
[0, 0],
],
},
{
id: 'pin',
type: 'pin',
color: 'primary',
alpha: 1,
anchor: { lat: 0.02, lon: 0.02 },
},
];
test('a hidden mark has every entity taken off on sync, and back when shown', (t) => {
const renderer = createWorldAnnotationRenderer(viewer(t));
/** The live sets a mark draws into. */
const setsOf = (draw, anno) =>
[...draw.sets.values()].filter(
(record) =>
!record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`),
);
test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
for (const anno of [route, area, pin]) renderer.add(anno);
const shown = (anno) => anno._entities.map((entity) => entity.show);
for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id);
for (const anno of [route, area, pin])
assert.ok(setsOf(draw, anno).length > 0, anno.id);
const shown = (anno) => setsOf(draw, anno).map((record) => record.show);
route.hidden = true;
area.hidden = true;
renderer.sync();
assert.ok(shown(route).every((show) => show === false), 'the line is off');
assert.ok(shown(area).every((show) => show === false), 'the area is off');
assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays');
assert.ok(
shown(route).every((show) => show === false),
'the line is off',
);
assert.ok(
shown(area).every((show) => show === false),
'the area is off',
);
assert.ok(
shown(pin).every((show) => show === true),
'a visible mark stays',
);
route.hidden = false;
renderer.sync();
assert.ok(shown(route).every((show) => show === true), 'the line is back');
assert.ok(
shown(route).every((show) => show === true),
'the line is back',
);
const areaSets = setsOf(draw, area);
renderer.remove(area);
assert.ok(
areaSets.every((record) => record.disposed),
'a removed mark lets its sets go',
);
renderer.sync();
assert.equal(area._entities, null, 'a removed mark is no longer synced');
renderer.destroy();
assert.equal(
[...draw.sets.values()].filter((record) => !record.disposed).length,
0,
);
});
test('a fading mark takes its new colours in place, its pulses with them', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area] = marks();
renderer.add(route);
renderer.add(area);
const line = () => [...setsOf(draw, route)[0].items.values()][0];
const fill = () =>
setsOf(draw, area)
.find((r) => r.kind === 'shapes')
.items.get('fill:0');
assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9);
assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9);
route.alpha = 0.5;
area.alpha = 0.5;
renderer.sync();
assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading');
assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9);
assert.deepEqual(
[fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)),
[60, 100],
'its pulse swings between 60% and all of its alpha',
);
route.alpha = 0;
renderer.sync();
assert.equal(line().style.color[3], 0, 'faded out: nothing painted');
renderer.destroy();
});
test('the line\'s flowing stroke follows its mark\'s alpha', () => {
let alpha = 1;
const material = new FlowMaterialProperty('#ffb547', () => alpha);
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9);
alpha = 0;
assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted');
alpha = 0.5;
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading');
assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before');
test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
const synth = { ...area, id: 'synth', synthesized: true };
const arrow = {
id: 'arrow',
type: 'arrow',
color: 'red',
alpha: 1,
anchor: { lon: 0, lat: 0 },
to: { lon: 0.01, lat: 0 },
};
const label = {
id: 'label',
type: 'label',
color: 'amber',
alpha: 1,
anchor: { lon: 0.03, lat: 0 },
};
for (const anno of [route, area, pin, synth, arrow, label])
renderer.add(anno);
const items = (anno, kind) => [
...(setsOf(draw, anno)
.find((r) => r.kind === kind)
?.items.values() ?? []),
];
for (const record of [...draw.sets.values()])
assert.equal(record.spec.clampTo, 'both');
const [flow] = items(route, 'lines');
assert.equal(flow.mode, 'draped');
assert.equal(flow.widthPx, 9);
assert.deepEqual(
{ ...flow.style, color: undefined },
{ kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 },
);
const [areaFill] = items(area, 'shapes');
assert.equal(areaFill.height, 'clampGround');
assert.equal(areaFill.animate.property, 'alpha');
assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9);
const [areaLine] = items(area, 'lines');
assert.deepEqual(
[areaLine.widthPx, areaLine.style.kind, areaLine.style.power],
[6, 'glow', 0.35],
);
const [synthLine] = items(synth, 'lines');
assert.deepEqual(
[synthLine.style.kind, synthLine.style.length],
['dash', 24],
);
assert.ok(
Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9,
'an approximate area is fainter',
);
const [arrowLine] = items(arrow, 'lines');
assert.deepEqual(
[arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind],
['draped', 16, 'arrow'],
);
const [ring] = items(pin, 'shapes');
assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height');
assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor);
const [marker] = items(pin, 'points');
assert.deepEqual(
[
marker.pixelSize,
marker.height,
marker.outlineWidth,
marker.disableDepthTest,
],
[14, 'clampGround', 3, Infinity],
);
assert.equal(items(label, 'shapes').length, 0, 'a label has no ring');
assert.equal(items(label, 'points')[0].pixelSize, 8);
renderer.destroy();
});
test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => {
const { v, draw, camera, preRender, before } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [, , pin] = marks();
const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } };
renderer.add(pin);
renderer.add(other);
const ringOf = (anno) =>
setsOf(draw, anno)
.find((r) => r.kind === 'shapes')
.items.get('ring');
// Writes to the rings' sets since they were drawn.
const shapeSets = [pin, other].map((anno) =>
setsOf(draw, anno).find((r) => r.kind === 'shapes'),
);
const upserts = {
get length() {
return shapeSets.reduce((n, record) => n + record.writes - 1, 0);
},
};
assert.equal(ringOf(pin).geometry.semiMajor, 60);
assert.equal(before.size, 1, 'one listener for every ring');
// The camera has not moved: nothing is sent.
preRender();
assert.equal(upserts.length, 0);
// It climbs: both rings are sent at the new radius, once.
camera.height = 4000;
preRender();
preRender();
assert.equal(upserts.length, 2);
assert.equal(ringOf(pin).geometry.semiMajor, 120);
assert.equal(ringOf(pin).geometry.semiMinor, 120);
assert.equal(ringOf(other).geometry.semiMajor, 120);
// A change under 0.1% sends nothing.
camera.height = 4002;
preRender();
assert.equal(upserts.length, 2);
// Held within 14 m and 170 m.
camera.height = 1e6;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 170);
camera.height = 10;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 14);
// A hidden mark waits, and catches up when shown.
other.hidden = true;
renderer.sync();
camera.height = 3000;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 90);
assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent');
other.hidden = false;
renderer.sync();
assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up');
// The last ring gone, the listener goes with it.
renderer.remove(pin);
renderer.remove(other);
assert.equal(before.size, 0);
renderer.destroy();
});
test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => {
const { v, draw, emit, frames } = viewer(t, { heights: () => 150 });
const renderer = createWorldAnnotationRenderer(v);
const ring = [
[0, 0],
[0.001, 0],
[0.001, 0.001],
[0, 0.001],
[0, 0],
];
const anno = {
id: 'b',
type: 'area',
color: 'amber',
alpha: 1,
footprintKind: 'building',
buildingHeight: 40,
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
ring,
};
const done = renderer.add(anno);
assert.equal(frames.size, 1, 'probing on the frames');
assert.equal(
setsOf(draw, anno).length,
0,
'nothing until its ground is known',
);
for (let i = 0; i < 8; i++) emit();
assert.equal((await done).status, 'installed');
assert.equal(frames.size, 0, 'done probing');
const shapes = [
...setsOf(draw, anno)
.find((r) => r.kind === 'shapes')
.items.values(),
];
const volume = shapes.find((s) => s.id === 'volume:0');
assert.equal(volume.extrudeHeight, 150 + 40 + 24);
assert.equal(volume.geometry.rings[0][0].height, 147);
assert.equal(volume.height, 'absolute');
const cage = shapes.find((s) => s.id === 'cage:0');
assert.equal(cage.outlineOnly, true);
assert.ok(cage.geometry.rings[0].length <= 14);
const [base] = setsOf(draw, anno)
.find((r) => r.kind === 'lines')
.items.values();
assert.deepEqual(
[base.mode, base.widthPx, base.style.kind, base.style.power],
['draped', 3, 'glow', 0.25],
);
renderer.destroy();
});
test('each kind paints the alphas it painted as entities, at full alpha', (t) => {
const { v, draw } = viewer(t, { heights: () => 150 });
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
const synth = { ...area, id: 'synth', synthesized: true };
const arrow = {
id: 'arrow',
type: 'arrow',
color: 'red',
alpha: 1,
anchor: { lon: 0, lat: 0 },
to: { lon: 0.01, lat: 0 },
};
const ring = Array.from({ length: 40 }, (_, i) => [
0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI),
0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI),
]);
const building = {
id: 'b',
type: 'area',
color: 'amber',
alpha: 1,
footprintKind: 'building',
buildingHeight: 40,
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
ring,
};
for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno);
renderer.add(building, { sampledGroundHeight: 150 });
const items = (anno, kind) => [
...(setsOf(draw, anno)
.find((r) => r.kind === kind)
?.items.values() ?? []),
];
const alpha = (c) => Math.round(c[3] * 1000) / 1000;
assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(area, 'lines')[0].style.color), 1);
assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38);
const marker = items(pin, 'points')[0];
assert.deepEqual(
[alpha(marker.color), alpha(marker.outlineColor)],
[1, 0.95],
);
assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]);
const [volume, cage] = items(building, 'shapes');
assert.equal(alpha(volume.fill), 0.45);
assert.equal(alpha(cage.outline), 0.32);
assert.equal(
Math.round(cage.animate.from * 1000) / 1000,
0.192,
'the cage pulses too',
);
assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14');
assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7);
renderer.destroy();
});
test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => {
const { v, draw } = viewer(t);
const first = createWorldAnnotationRenderer(v);
const second = createWorldAnnotationRenderer(v);
const [route, area] = marks();
first.add(route);
const prefix = route._draw.prefix;
first.remove(route);
assert.doesNotThrow(() => first.add(route));
assert.notEqual(route._draw.prefix, prefix, 'fresh sets');
assert.doesNotThrow(() => second.add(area));
assert.ok(
!area._draw.prefix.startsWith(
route._draw.prefix.split(':').slice(0, 2).join(':') + ':',
),
);
// Added again as another kind, its old sets go.
const kinds = () =>
setsOf(draw, route)
.map((r) => r.kind)
.sort();
assert.deepEqual(kinds(), ['lines']);
Object.assign(route, { type: 'pin', path: undefined });
first.add(route);
assert.deepEqual(kinds(), ['points', 'shapes']);
assert.doesNotThrow(() => first.remove(null));
first.destroy();
second.destroy();
assert.equal(route._draw, null);
first.add(route);
assert.equal(route._draw, null, 'a destroyed renderer draws nothing more');
assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0);
});
+109 -38
View File
@@ -2,20 +2,74 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { createApplication } from './application.js';
import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js';
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
import * as Cesium from 'cesium';
import {
installFreeLookHeightLimit,
installGlobeInViewRecovery,
installTrackpadPinchZoom,
} from './viewer.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeFrameShare,
globeOutOfFrame,
lookAngleWithinFrame,
lookStepLosesGlobe,
} from '../globeInView.js';
import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js';
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js';
import * as globeInView from '../globeInView.js';
import { createCesiumCamera } from '../render/cesium/camera.js';
import { bindRenderer } from '../render/rendererOf.js';
import { entityFollowTarget } from '../data/followed.js';
/** The camera port bound over each real Cesium camera a test makes. */
const cameraPorts = new WeakMap();
/**
* Bind `viewer` the Cesium renderer's own camera port over its real camera,
* with the camera's own `moveStart` and `moveEnd` so a test raises them, and
* a frame port that counts render requests on the scene.
*/
function bindCameraPorts(viewer) {
const { camera, scene } = viewer;
const noEvent = { addEventListener: () => () => {} };
const real = createCesiumCamera({
scene: {
postUpdate: noEvent,
preUpdate: noEvent,
get screenSpaceCameraController() {
return scene.screenSpaceCameraController;
},
requestRender: () => scene.requestRender?.(),
},
camera,
report: (error) => {
throw error;
},
}).port;
const port = Object.create(real, {
on: { value: (event, cb) => camera[event].addEventListener(cb) },
});
cameraPorts.set(camera, port);
bindRenderer(viewer, {
camera: port,
get canvas() {
return scene.canvas;
},
frame: {
on: () => () => {},
requestRender: () => scene.requestRender?.(),
},
});
}
// The frame measures take a camera pose; these take the test's camera.
const poseOf = (camera) => cameraPorts.get(camera).pose();
const LOOKS = {
lookUp: 'up',
lookDown: 'down',
lookLeft: 'left',
lookRight: 'right',
};
const globeFrameShare = (camera, options) =>
globeInView.globeFrameShare(poseOf(camera), options);
const globeOutOfFrame = (camera, options) =>
globeInView.globeOutOfFrame(poseOf(camera), options);
const lookAngleWithinFrame = (camera, look, angle, options) =>
globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options);
const lookStepLosesGlobe = (camera, look, angle, options) =>
globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options);
const phases = ['Scene', 'Controls', 'Data', 'Tools'];
function fixture(overrides = {}) {
@@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer',
});
test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => {
const { applicationViewerOptions } = await import('./viewer.js');
const { StarrySky } = await import('../sky/starrySky.js');
const { applicationViewerOptions } =
await import('../render/cesium/applicationViewer.js');
const { StarrySky } = await import('../render/cesium/starrySky.js');
const creditContainer = {};
const options = applicationViewerOptions(creditContainer);
// CesiumWidget skips scene.sun and scene.moon when skyBox is false.
@@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) {
return { viewer, controller, container, handlers, relayed, createEvent };
}
test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => {
test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => {
const original = [1, 2, 3];
const f = pinchFixture({ zoomEventTypes: original });
const dispose = installTrackpadPinchZoom(f.viewer, {
const dispose = installTrackpadPinchRelay(f.viewer, {
createWheelEvent: (_type, init) => f.createEvent(init),
});
assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original);
assert.equal(f.controller.zoomEventTypes.length, 4);
assert.equal(f.controller.zoomEventTypes, original);
const plain = f.createEvent({ deltaY: 2 });
f.container.emit(plain);
@@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs
test('trackpad pinch relays pixel deltas once with bounded amplification', () => {
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
installTrackpadPinchZoom(f.viewer, {
installTrackpadPinchRelay(f.viewer, {
createWheelEvent: (_type, init) => f.createEvent(init),
});
@@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () =>
test('trackpad pinch falls back to the original event when relay construction fails', () => {
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
installTrackpadPinchZoom(f.viewer, {
installTrackpadPinchRelay(f.viewer, {
createWheelEvent() {
throw new Error('unsupported');
},
@@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) {
test('free look follows camera height and is restored on dispose', () => {
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(f.controller.enableLook, true);
f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1);
@@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => {
test('drags that start on the stars orbit above the free-look height', () => {
// Below Cesium's trackball height such a drag turns the camera in place.
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(
f.controller.minimumTrackBallHeight,
FREE_LOOK_MAX_HEIGHT_METERS,
@@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
const lower = freeLookFixture({ height: 500 });
lower.controller.minimumTrackBallHeight = 500_000;
const disposeLower = installFreeLookHeightLimit(lower.viewer);
const disposeLower = installFreeLookHeightLimit(
lower.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(
lower.controller.minimumTrackBallHeight,
500_000,
@@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
assert.equal(lower.controller.minimumTrackBallHeight, 500_000);
const later = freeLookFixture({ height: 500 });
const disposeLater = installFreeLookHeightLimit(later.viewer);
const disposeLater = installFreeLookHeightLimit(
later.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
later.controller.minimumTrackBallHeight = 2_000_000;
disposeLater();
assert.equal(
@@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
test('free look keeps a setting other code makes after it is installed', () => {
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
f.controller.enableLook = false;
f.frame(10);
assert.equal(f.controller.enableLook, false, 'turned off stays off');
@@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => {
test('free look stays off when the viewer had it disabled', () => {
const f = freeLookFixture({ enableLook: false, height: 500 });
installFreeLookHeightLimit(f.viewer);
installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS);
f.frame(10);
assert.equal(f.controller.enableLook, false);
});
@@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) {
};
const camera = new Cesium.Camera(scene);
camera.frustum.aspectRatio = width / height;
return { camera, scene, viewer: { camera, scene } };
const viewer = { camera, scene };
bindCameraPorts(viewer);
return { camera, scene, viewer };
}
function aim(
@@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => {
Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3),
);
assert.equal(globeOutOfFrame(camera), false);
assert.equal(scene.renders, 1);
// One render for the new view, one the recovery asks for itself.
assert.equal(scene.renders, 2, 'the turned view is drawn');
// Looking up near the ground, then zoomed out past the limit.
aim(camera, { alt: 3_834_000, pitch: 10 });
@@ -602,7 +674,7 @@ function moveEndKeepsView(camera) {
return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9);
}
test('globe recovery leaves partial, low, locked and 2D views alone', () => {
test('globe recovery leaves partial, low, locked and following views alone', () => {
for (const view of partialGlobeViews) {
const { camera, viewer } = realCamera();
installGlobeInViewRecovery(viewer);
@@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => {
assert.equal(globeOutOfFrame(locked.camera), true);
assert.ok(moveEndKeepsView(locked.camera), 'locked camera');
// Tracking an entity that has no position yet keeps an identity transform.
// Following an entity that has no position yet keeps an identity transform.
const tracked = realCamera();
tracked.viewer.trackedEntity = { id: 'pending-fix' };
const pending = entityFollowTarget(
{ id: 'pending-fix' },
{ position: () => null },
);
Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', {
get: () => pending,
});
installGlobeInViewRecovery(tracked.viewer);
aim(tracked.camera, reportedStuckView);
assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera');
const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW });
installGlobeInViewRecovery(flat.viewer);
flat.scene.mode = Cesium.SceneMode.SCENE3D;
aim(flat.camera, reportedStuckView);
flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
assert.ok(moveEndKeepsView(flat.camera), 'Columbus view');
});
test('the look limit from orbit tolerates grid noise and never reaches zero', () => {
+41 -4
View File
@@ -1,9 +1,12 @@
import { resolveCatalogSources } from './sourceComposition.js';
import { createWeatherClock } from '../layers/weather/clock.js';
import { worldClock } from '../time/worldClock.js';
import { NEWS_LAYER_ID } from '../layers/news/model.js';
import { createWeatherLayer } from '../layers/weather/index.js';
import { createCyclonesLayer } from '../layers/cyclones/index.js';
import { createApplicationCyclones } from './layers/cyclones.js';
import { createWindLayer } from '../layers/wind/index.js';
import { createLayerCatalog } from './catalog.js';
import { layerPlacement } from '../data/placementProvider.js';
import { LAYER_STATE_REGISTRY } from '../data/layerState.js';
import { createMilitaryRegistry } from '../layers/aircraft/classification.js';
import { createApplicationFlights } from './layers/flights.js';
@@ -17,6 +20,7 @@ import { createApplicationDirections } from './layers/directions.js';
import { createApplicationRecentImagery } from './layers/recentImagery.js';
import { createApplicationOsmPlaces } from './layers/osmPlaces.js';
import { createApplicationTransit } from './layers/transit.js';
import { createApplicationRail } from './layers/rail.js';
import { createApplicationInstallations } from './layers/militaryInstallations.js';
import { createApplicationSatellites } from './layers/satellites.js';
import { createApplicationLaunches } from './layers/rocketLaunches.js';
@@ -29,7 +33,9 @@ import { createApplicationAirQuality } from './layers/airQuality.js';
import { createApplicationFirePerimeters } from './layers/perimeters.js';
import { createApplicationGnssIntegrity } from './layers/gnss.js';
import { createApplicationGhostMaps } from './layers/ghostMaps.js';
import { createApplicationShipwrecks } from './layers/shipwrecks.js';
import { createApplicationDroneAirspace } from './layers/droneAirspace.js';
import { createApplicationNews } from './layers/news.js';
import { createApplicationWildlifeSightings } from './layers/wildlifeSightings.js';
import { createApplicationCables } from './layers/submarineCables.js';
import { createOsmOverlayLayers } from '../data/osmOverlays.js';
@@ -58,6 +64,9 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
/** Construct the current catalog without choosing any source provider.
* Scene engines remain page-owned; layers and classification have this app's lifetime.
* The manager owns layer destruction, while abort releases classification even if startup fails.
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
* places live aircraft, vessels, transit and trains; without one each layer
* uses its own motion.
*/
export function createApplicationCatalog({
surface,
@@ -65,9 +74,11 @@ export function createApplicationCatalog({
signal,
metadata = APPLICATION_LAYER_METADATA,
vesselOptions,
newsOptions,
resolveAsset,
nepalBoundaryResolver,
streetLevelProviders,
placement = null,
}) {
if (!signal?.addEventListener)
throw new TypeError('An application lifetime signal is required');
@@ -78,7 +89,7 @@ export function createApplicationCatalog({
const sourceComposition = resolveCatalogSources(sources);
sources = sourceComposition.sources;
const militaryRegistry = createMilitaryRegistry();
const weatherClock = createWeatherClock();
const weatherClock = createWeatherClock({ world: worldClock });
const dispose = () => {
signal.removeEventListener('abort', dispose);
militaryRegistry.dispose();
@@ -91,18 +102,23 @@ export function createApplicationCatalog({
const flights = createApplicationFlights({
surface,
source: sources.flights,
placement: layerPlacement(placement, 'aircraft'),
militaryRegistry,
resolveAsset,
});
const military = createApplicationMilitary({
surface,
source: sources.military,
placement: layerPlacement(placement, 'military'),
militaryRegistry,
resolveAsset,
});
const vessels = createApplicationVessels({
source: sources.vessels,
placement: layerPlacement(placement, 'vessels'),
options: vesselOptions,
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
});
const installations = createApplicationInstallations({
surface,
@@ -135,9 +151,17 @@ export function createApplicationCatalog({
windowMs: sources['gnss-integrity'].windowMs,
}),
createApplicationGhostMaps({ source: sources['s2-ghostmaps'] }),
createApplicationShipwrecks({ source: sources.shipwrecks }),
createApplicationDroneAirspace({
source: sources['drone-airspace'],
}),
// Ages, the window and the counts read the world clock: a host that
// follows it for the layer shows the news at the time on the timeline.
createApplicationNews({
now: worldClock.timeFor(NEWS_LAYER_ID),
...newsOptions,
source: sources.news,
}),
createApplicationWildlifeSightings({
source: sources['wildlife-sightings'],
groundFloor: surface.groundFloor,
@@ -153,7 +177,13 @@ export function createApplicationCatalog({
createApplicationTraffic({ source: sources.traffic, surface }),
createApplicationCctv({ surface, source: sources.cctv }),
createApplicationRadio({ surface, source: sources.radio }),
createApplicationTransit({ surface, source: sources.transit }),
createApplicationTransit({
surface,
source: sources.transit,
placement: layerPlacement(placement, 'transit'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
createApplicationBikeshare({ source: sources.bikeshare }),
createApplicationDirections({ source: sources.directions }),
createApplicationRecentImagery({ source: sources['recent-imagery'] }),
@@ -182,10 +212,17 @@ export function createApplicationCatalog({
id: 'weather-lightning',
clock: weatherClock,
}),
createCyclonesLayer({ feed: sources.cyclones }),
createApplicationCyclones({ feed: sources.cyclones }),
...createOsmOverlayLayers(),
...createInfrastructureLayers(localGeoJsonServices),
createApplicationCables({ source: sources.cables }),
createApplicationRail({
surface,
source: sources.rail,
placement: layerPlacement(placement, 'rail'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
createApplicationFirms({
surface,
id: 'local-firms',
+23 -7
View File
@@ -6,6 +6,11 @@ import { createStandaloneLayerSources } from '../standalone/layerSources.js';
import { catalogControlServices } from './catalog.js';
import { LayerLifecycle } from '../data/lifecycle.js';
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
import { worldClock } from '../time/worldClock.js';
const flush = async () => {
for (let i = 0; i < 20; i++) await Promise.resolve();
};
function fixtureSources(ids, calls) {
const sources = createStandaloneLayerSources();
@@ -27,6 +32,7 @@ test('catalogs construct distinct layers and classification from their supplied
t.after(() => {
a.abort();
b.abort();
worldClock.goLive();
});
const callsA = [];
const callsB = [];
@@ -40,7 +46,7 @@ test('catalogs construct distinct layers and classification from their supplied
signal: b.signal,
surface: fixtureSurface(b.signal),
});
assert.equal(first.layers.length, 38);
assert.equal(first.layers.length, 41);
assert.ok(first.get('local-adsb'), 'Local ADS-B is registered');
assert.deepEqual(
first.metadata.find(({ id }) => id === 'osm-places'),
@@ -53,7 +59,10 @@ test('catalogs construct distinct layers and classification from their supplied
'the hardware-local layer is never serialized into links',
);
assert.notEqual(first.weatherClock, second.weatherClock);
await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z');
// Time moves on the world clock, which the catalog's weather clock follows.
assert.equal(first.weatherClock.world, worldClock);
worldClock.seek(Date.parse('2026-09-21T12:00:00.000Z'));
await flush();
assert.match(
first.get('wind').getRowControls().info,
/Forecast · does not follow history/,
@@ -68,6 +77,7 @@ test('catalogs construct distinct layers and classification from their supplied
assert.ok(first.get('gnss-integrity'));
assert.ok(first.get('s2-ghostmaps'));
assert.ok(first.get('drone-airspace'));
assert.ok(first.get('news'));
assert.ok(first.get('transit'));
const order = first.layers.map(({ id }) => id);
assert.deepEqual(
@@ -110,9 +120,16 @@ test('catalogs construct distinct layers and classification from their supplied
assert.equal(first.militaryRegistry.isMilitaryIcao('def456'), false);
assert.equal(second.militaryRegistry.isMilitaryIcao('def456'), true);
a.abort();
worldClock.seek(Date.parse('2026-09-21T13:00:00.000Z'));
await flush();
assert.equal(
await first.weatherClock.setTarget('2026-09-21T13:00:00.000Z'),
false,
first.weatherClock.getState().target,
'2026-09-21T12:00:00.000Z',
'an aborted catalog no longer follows the world clock',
);
assert.equal(
second.weatherClock.getState().target,
'2026-09-21T13:00:00.000Z',
);
assert.equal(callsA[0].aborted, true);
assert.equal(first.militaryRegistry.isMilitaryIcao('abc123'), false);
@@ -161,7 +178,7 @@ test('Mapillary can be omitted or replaced without changing catalog membership',
surface: fixtureSurface(lifetime.signal),
};
const catalog = createApplicationCatalog(options);
assert.equal(catalog.layers.length, 38);
assert.equal(catalog.layers.length, 41);
assert.deepEqual(catalog.get('street-level').providerIds, []);
assert.equal(
catalogControlServices(catalog).streetLevelLayer,
@@ -217,9 +234,8 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
};
const shows = (layer, minutes) => {
assert.equal(layer.provenance.window.minutes, minutes);
const { info, legend } = layer.getRowControls();
const { info } = layer.getRowControls();
assert.match(info, new RegExp(`visited views over ${minutes} min`));
assert.match(legend[0].blurb, new RegExp(`over ${minutes} minutes`));
};
shows(gnssLayer({ windowMs: 65 * 60_000 }), 65);
shows(gnssLayer({}), 30);
+40 -20
View File
@@ -1,18 +1,31 @@
import { catalogControlServices } from './catalog.js';
import { StyleManager } from '../ui/composition.js';
import { flyToAustin } from '../camera.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
import { createViewSky } from '../viewSky.js';
import { findGlobe } from '../render/rendererOf.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { t } from '../i18n/index.js';
/** Where the camera starts unless a host gives a `startView`. */
export { START_VIEW };
/**
* Construct the existing controls and camera presentation. `initialShareCode`
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
* whose address does not carry one. `localePicker: false` removes the language
* picker, for a host that does not initialize Core's locale.
* picker, for a host that offers its own language choice (`switchLocale` from
* the `./i18n` entry). `startView` is where the camera starts (the whole
* planet by default; a host may pass a city); a shared view flies from there.
* `homeView` is where the title's logo goes back to (with the clock live): the
* start view unless given, for a host whose `startView` only carries a view
* across a rebuild.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
export function createApplicationControls({
scene: { viewer, mapStackController, operations },
scene: { viewer, mapStackController, operations, viewerDrawsEntity },
loaderStatus,
Controls = StyleManager,
services,
@@ -21,16 +34,23 @@ export function createApplicationControls({
defer,
initialShareCode = null,
localePicker = true,
startView = START_VIEW,
homeView = startView,
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
// Initialize the style manager (post-processing, HUD, locations, share links)
const styleManager = new Controls(viewer, {
services: {
...services,
...operations.surface.controlServices,
searchAndFlyTo: operations.searchAndFlyTo,
pickWorldFromScreen: operations.annotationResolver?.pickWorldFromScreen,
fetchRegionalBrief: (...args) =>
operations.requests.regional.getBrief(...args),
...catalogControlServices(catalog),
// Whether an entity is one of the viewer's own; the scene answers it.
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
},
requestServices: operations.requests,
mapStackController,
@@ -38,32 +58,32 @@ export function createApplicationControls({
// A share code to open at start-up instead of the page's address.
initialShareCode,
localePicker,
homeView,
});
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
defer(() => styleManager.dispose());
defer(
installZoomOutGuard(viewer, {
subscribeCameraHandoff: (listener) =>
styleManager.subscribeCameraHandoff?.(listener),
}),
);
// The previous multi-canvas weather compositor remains disabled. Cockpit
// clouds use a separate, capped low-resolution GPU pass that never attaches
// Cesium fog or post-process stages and is fully stopped in map mode.
const weatherEffects = null;
const cockpitCloudEffects = initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
// Where the renderer draws weather, it draws the cockpit's clouds too.
const cockpitCloudEffects = findGlobe(viewer)?.weather
? null
: initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
defer(() => cockpitCloudEffects?.destroy());
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
// chooses in the Display panel.
const viewSky = createViewSky(viewer, {
store: useDisplayStore(applicationPinia()),
});
defer(() => viewSky.destroy());
// If no share link state, do default fly-to Austin
if (!styleManager.hasShareState) {
loaderStatus.textContent = t('Flying to Austin, TX...');
defer(flyToAustin(viewer));
} else {
loaderStatus.textContent = t('Restoring shared view...');
}
loaderStatus.textContent = styleManager.hasShareState
? t('Restoring shared view...')
: t('Loading');
return { styleManager, weatherEffects, cockpitCloudEffects };
}
+6 -32
View File
@@ -1,9 +1,8 @@
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import '../testSupport/stubMgrs.mjs';
import { installVueDom } from '../testSupport/vueDom.mjs';
import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
const { createApplicationControls } = await import('./controls.js');
@@ -13,35 +12,20 @@ before(() => {
});
after(() => uninstallDom());
test('application controls install the zoom-out guard and remove it on teardown', () => {
const canvas = document.createElement('canvas');
const controller = { maximumZoomDistance: Infinity };
const scene = {
mode: Cesium.SceneMode.SCENE3D,
screenSpaceCameraController: controller,
preRender: new Cesium.Event(),
postUpdate: new Cesium.Event(),
};
const camera = {
position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000),
positionCartographic: { height: 1_000_000 },
};
const viewer = { scene, camera, canvas };
const handoffs = new Set();
test('the application controls start and stop', () => {
class Controls {
hasShareState = true;
orbitController = { stop() {} };
hud = { destroy() {} };
dispose() {}
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
}
}
const cleanups = [];
createApplicationControls({
scene: {
viewer,
viewer: bindFakeCesiumCamera({
isDestroyed: () => false,
camera: { setView() {} },
}),
mapStackController: {},
operations: {
surface: { controlServices: {} },
@@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown'
catalog: { get: (id) => ({ id }) },
defer: (cleanup) => cleanups.push(cleanup),
});
assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
assert.equal(scene.preRender.numberOfListeners, 1);
assert.equal(scene.postUpdate.numberOfListeners, 1);
assert.equal(handoffs.size, 1);
for (const cleanup of cleanups.reverse()) cleanup();
assert.equal(controller.maximumZoomDistance, Infinity);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(handoffs.size, 0);
});
+1 -1
View File
@@ -15,7 +15,7 @@ export function createApplicationData({
const dataManager = new LayerLifecycle(viewer, {
allowQaRegistration,
// A panel's host may report it hidden while it is on screen; its layers
// keep polling (see keepPanelRendering in embed.js).
// keep polling (see keepPanelRendering in app/panelRendering.js).
visibilityTarget: panelAwareVisibility(document),
getSourceAvailability: catalog?.getSourceAvailability,
});
+296 -106
View File
@@ -11,14 +11,27 @@
* embedded or not.
*/
import * as Cesium from 'cesium';
import { announceNavigationAuthority } from '../navigationPolicy.js';
import { annotationsFromParams, createView } from '../view/index.js';
import {
announceNavigationAuthority,
watchCameraOwner,
} from '../navigationPolicy.js';
import { toRadians } from '../geo/index.js';
import { t, translateKnown } from '../i18n/index.js';
import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js';
import { cameraOf } from '../render/rendererOf.js';
import {
annotationsFromParams,
createView,
followFromParams,
groundedLookAt,
streetLevelFromParams,
} from '../view/index.js';
const EMBED_VIEW_MESSAGE = 'gev:view';
const EMBED_APPLIED_MESSAGE = 'gev:view-applied';
const EMBED_READY_MESSAGE = 'gev:ready';
const STREET_LEVEL_LAYER = 'street-level';
const FOLLOW_LAYERS = {
aircraft: 'flights',
military_aircraft: 'military',
@@ -27,6 +40,8 @@ const FOLLOW_LAYERS = {
const FOLLOW_ATTEMPTS = 20;
const FOLLOW_RETRY_MS = 1000;
const FLIGHT_SECONDS = 2;
/** How long a posted view waits for the terrain under its camera. */
const TERRAIN_WAIT_MS = 2000;
/**
* Whether this page shows the app embedded: `?embed=1` when another page
@@ -45,9 +60,18 @@ export function isEmbeddedInline() {
return globalThis.GEV_EMBED_INLINE === true;
}
/**
* Whether the panel page started the app for a tool result issued just now,
* not one its host handed back on mounting the panel again.
*/
function isFreshPanelResult() {
return isEmbeddedInline() && globalThis.GEV_EMBED_FRESH === true;
}
/**
* `doc`'s visibility for work that pauses in a hidden page. A panel's host
* may report it hidden while it is on screen (see keepPanelRendering), so an
* may report it hidden while it is on screen (see keepPanelRendering in
* render/cesium/panelRendering.js), so an
* inline panel always reads as visible.
*/
export function panelAwareVisibility(doc = globalThis.document) {
@@ -67,69 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) {
};
}
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep the globe drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* Cesium's render loop; while frames stop arriving, draw from a timer.
* Returns a function that stops it.
*/
export function keepPanelRendering(
viewer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
// Cesium stops drawing after a render error, and so does the timer.
// Report the error in full: workers report plain objects, which Cesium
// prints as [object Object].
let failed = false;
const removeErrorListener = viewer.scene?.renderError?.addEventListener(
(_scene, error) => {
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
},
);
const timer = windowRef.setInterval(() => {
if (
failed ||
now() - lastFrame < MISSED_FRAMES_MS ||
viewer.isDestroyed?.()
)
return;
viewer.resize();
viewer.render();
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
removeErrorListener?.();
};
}
const delay = (ms, signal) =>
new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
@@ -147,24 +108,56 @@ const delay = (ms, signal) =>
function flyTo(viewer, camera) {
announceNavigationAuthority('embed-view');
return new Promise((resolve) => {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
camera.lon,
camera.lat,
camera.altitude_m,
),
orientation: {
heading: Cesium.Math.toRadians(camera.heading_deg),
pitch: Cesium.Math.toRadians(camera.pitch_deg),
roll: 0,
cameraOf(viewer).flyTo(
{ lon: camera.lon, lat: camera.lat, height: camera.altitude_m },
{
orientation: {
heading: toRadians(camera.heading_deg),
pitch: toRadians(camera.pitch_deg),
roll: 0,
},
durationS: FLIGHT_SECONDS,
onComplete: () => resolve(true),
onCancel: () => resolve(false),
},
duration: FLIGHT_SECONDS,
complete: () => resolve(true),
cancel: () => resolve(false),
});
);
});
}
/**
* The `show_street_level` arguments for a view's street-level photos. A plain
* link (`autoOpen: false`) only arms a source that bills every load; a view
* posted into the embedded app is the client's own request and opens.
*/
function streetLevelArgs(streetLevel, { autoOpen = true } = {}) {
return {
latitude: streetLevel.lat,
longitude: streetLevel.lon,
...(streetLevel.provider ? { provider: streetLevel.provider } : {}),
fly: true,
...(autoOpen ? {} : { autoOpen: false }),
};
}
const STREET_LEVEL_PANEL_ID = 'street-level-panel';
/** Dispatched on the window when a link opened after start-up has restored. */
const SHARE_NAVIGATION_RESTORED_EVENT = 'gev:share-navigation-restore-settled';
/** The armed link's toast, naming the OPEN button as the panel shows it. */
function armedToast() {
return t('Street View is ready: press {open} to load it', {
open: t('OPEN {labels}', { labels: translateKnown(GOOGLE_LABEL) }),
});
}
/** Why a link's photo stays shut: its source has no working key here. */
function keyToast(result) {
return t(
"{source} cannot open this link's street-level photo without a working key",
{ source: translateKnown(result.providerName || 'Street Level') },
);
}
/**
* Make the app show a view: style and map, exactly the view's layers,
* annotations, the camera, and the followed entity. Each step runs through the
@@ -173,13 +166,20 @@ function flyTo(viewer, camera) {
*/
export async function applyView(
view,
{ viewer, dataManager, run, signal, retryMs = FOLLOW_RETRY_MS },
{
viewer,
dataManager,
run,
signal,
autoOpen = true,
retryMs = FOLLOW_RETRY_MS,
},
) {
const steps = [];
const act = async (name, args) => {
const act = async (name, args, options) => {
let result = null;
try {
result = await run(name, args);
result = await run(name, args, options);
} catch (error) {
result = { ok: false, error: error?.message || String(error) };
}
@@ -198,6 +198,8 @@ export async function applyView(
await act('set_layer_visibility', { layerId: layer.id, enabled: false });
}
for (const layerId of view.layers) {
// The street-level action lights its source first, then the layer.
if (view.street_level && layerId === STREET_LEVEL_LAYER) continue;
if (!dataManager.isEnabled(layerId))
await act('set_layer_visibility', { layerId, enabled: true });
}
@@ -207,6 +209,29 @@ export async function applyView(
await act('clear_annotations', {});
if (view.annotations.length)
await act('annotate_map', { annotations: [...view.annotations] });
if (view.street_level) {
// The photos frame the camera; when the action fails before flying, the
// view's own camera still applies.
// A posted view replays someone else's view, as a link does: the source
// it lights is not saved as the visitor's own choice.
const result = await act(
'show_street_level',
streetLevelArgs(view.street_level, { autoOpen }),
{ origin: 'programmatic' },
);
if (result?.ok !== true) {
// Overtaken (a click on the map, a newer request): hands off.
if (result?.cancelled || result?.superseded) return steps;
// An earlier view's photo must not stay over a place this view left.
// From the imagery stage on the action has settled the panel itself
// (a photo it could not load keeps its error).
if (result?.stage !== 'imagery')
dataManager.layers?.get?.(STREET_LEVEL_LAYER)?.module?.closeViewer?.();
if (!result?.location)
steps.push({ step: 'camera', ok: await flyTo(viewer, view.camera) });
}
return steps;
}
if (!view.follow) {
steps.push({ step: 'camera', ok: await flyTo(viewer, view.camera) });
return steps;
@@ -243,6 +268,9 @@ export async function applyView(
/**
* Install embed mode when the page asks for it, and draw any annotations the
* opening link carries. Returns a function that removes the message handler.
* `keepRendering({windowRef})` keeps the globe drawing in an inline panel
* whose host stops animation frames, and returns a function that stops it;
* the application scene gives it (`keepPanelRendering`).
*/
export function installViews({
shell,
@@ -250,24 +278,123 @@ export function installViews({
dataManager,
run,
signal,
keepRendering = null,
terrain = null,
location = globalThis.location,
windowRef = globalThis.window,
}) {
const ready = Promise.resolve(shell.initialRestorePromise).catch(() => {});
const linked = annotationsFromParams(
new URLSearchParams(String(location?.hash || '').replace(/^#/, '')),
const hashParams = new URLSearchParams(
String(location?.hash || '').replace(/^#/, ''),
);
if (linked.length)
void ready.then(() => {
if (!signal?.aborted) void run('annotate_map', { annotations: linked });
// The link's own steps run first, one at a time, and posted views queue
// behind them; one failing step does not take the next with it. A passive
// link never flies over someone who took the camera: its steps are skipped
// when a newer link superseded it, when its flight never landed (the
// recipient dragged or searched), or after any navigation since the
// generation its restore flight owned.
const cameraLanded = (outcome) => outcome?.share?.camera === 'applied';
const restoreGeneration = (outcome) =>
Number.isInteger(outcome?.navigationToken)
? outcome.navigationToken
: shell._navigationGeneration;
let generationAtRestore = null;
let startSuperseded = false;
let queue = ready.then((outcome) => {
generationAtRestore = restoreGeneration(outcome);
startSuperseded =
outcome?.status === 'superseded' ||
(Boolean(outcome?.share) && !cameraLanded(outcome));
});
const navigatedSince = (generation) =>
Number.isFinite(generation) && shell._navigationGeneration !== generation;
const linkStep = (work) =>
queue.then(async () => {
if (signal?.aborted) return;
try {
await work();
} catch {
/* reported by the action itself */
}
});
if (!isEmbedded(location)) return () => {};
const linked = annotationsFromParams(hashParams);
if (linked.length)
queue = linkStep(() => run('annotate_map', { annotations: linked }));
// A link's street-level photos open once it has restored. A billed source
// only arms, except for the panel page's own link to a result issued just
// now. A link that follows an entity keeps the camera on it.
const linkedStreetLevel = (params) =>
followFromParams(params) ? null : streetLevelFromParams(params);
const openLinkedStreetLevel = async (
streetLevel,
{ generation, autoOpen = false },
) => {
if (navigatedSince(generation)) return;
// The link replays the sender's view: nothing it switches becomes the
// recipient's own preference.
const result = await run(
'show_street_level',
streetLevelArgs(streetLevel, { autoOpen }),
{ origin: 'programmatic' },
);
// A source without a working key changes nothing: say why, or the link
// looks broken. In a frame the host reads the result instead.
if (result?.stage === 'key' && !isEmbedded(location)) {
shell._showToast?.(keyToast(result));
return;
}
// OPEN must be in view, but embed mode hides the rail that holds it: in
// a frame a posted view is the way to open a photo.
if (result?.armed === true && !isEmbedded(location)) {
// Opened for this link only: the recipient's saved layout stays theirs.
shell.setPanelCollapsed?.(STREET_LEVEL_PANEL_ID, false, {
explicit: true,
persist: false,
});
// On a phone the panel sits in a tab sheet: open it so OPEN shows.
shell.revealPanel?.(STREET_LEVEL_PANEL_ID);
shell._showToast?.(armedToast());
}
};
const startStreetLevel = linkedStreetLevel(hashParams);
if (startStreetLevel)
queue = linkStep(() =>
startSuperseded
? undefined
: openLinkedStreetLevel(startStreetLevel, {
generation: generationAtRestore,
autoOpen: isFreshPanelResult(),
}),
);
// A link pasted into the open tab: its photos follow once its restore
// settles, under the same rules.
const onNavigatedRestore = (event) => {
if (event?.detail?.status !== 'settled' || !cameraLanded(event.detail))
return;
const streetLevel = linkedStreetLevel(
new URLSearchParams(String(location?.hash || '').replace(/^#/, '')),
);
if (!streetLevel) return;
const generation = restoreGeneration(event.detail);
queue = linkStep(() => openLinkedStreetLevel(streetLevel, { generation }));
};
windowRef?.addEventListener?.(
SHARE_NAVIGATION_RESTORED_EVENT,
onNavigatedRestore,
);
const stopNavigatedRestores = () =>
windowRef?.removeEventListener?.(
SHARE_NAVIGATION_RESTORED_EVENT,
onNavigatedRestore,
);
if (!isEmbedded(location)) return stopNavigatedRestores;
windowRef.document.body.classList.add('ui-embed');
shell.setCleanView?.(true);
const stopRendering = isEmbeddedInline()
? keepPanelRendering(viewer, { windowRef })
: () => {};
const stopRendering =
isEmbeddedInline() && keepRendering
? keepRendering({ windowRef })
: () => {};
// A framing page talks to the app across frames; an inline panel shares
// the page with it and talks through the page's own window.
const peer = isEmbeddedInline() ? windowRef : windowRef.parent;
@@ -278,7 +405,6 @@ export function installViews({
peer.postMessage(message, origin);
};
// Views apply one at a time, in the order they arrive.
let queue = ready;
const onMessage = (event) => {
if (event.source !== peer || event.data?.type !== EMBED_VIEW_MESSAGE)
return;
@@ -302,19 +428,82 @@ export function installViews({
);
return;
}
queue = queue.then(async () => {
if (signal?.aborted) return;
const steps = await applyView(view, { viewer, dataManager, run, signal });
post(
{
type: EMBED_APPLIED_MESSAGE,
id,
ok: steps.every((step) => step.ok),
steps,
},
replyOrigin,
// A panel's host can hand back old results on a remount: only one issued
// just now may open a billed photo. A framing page's view is its own.
const autoOpen = !isEmbeddedInline() || event.data.fresh === true;
// Photos asked for without a point open where the camera looks, measured
// from the ground under it, as show_in_gods_eye_view places them.
const asked = event.data.view?.street_level;
const unplaced =
asked &&
typeof asked === 'object' &&
asked.lat == null &&
asked.lon == null;
queue = queue
.then(async () => {
if (signal?.aborted) return;
if (unplaced && view.street_level) {
// A terrain service that does not answer soon leaves the view's
// own estimate.
const wait = AbortSignal.timeout(TERRAIN_WAIT_MS);
const owner = watchCameraOwner(viewer, shell);
const point = await groundedLookAt(
view.camera,
terrain,
signal ? AbortSignal.any([signal, wait]) : wait,
)
.catch(() => null)
.finally(() => owner.stop());
if (signal?.aborted) return;
// Whoever takes the camera while the terrain answers (a drag, a
// search, the assistant) keeps it: the view stands down.
if (owner.taken()) {
post(
{
type: EMBED_APPLIED_MESSAGE,
id,
ok: false,
steps: [{ step: 'street_level', ok: false, superseded: true }],
},
replyOrigin,
);
return;
}
if (point)
view = createView({
...event.data.view,
street_level: { ...asked, ...point },
});
}
const steps = await applyView(view, {
viewer,
dataManager,
run,
signal,
autoOpen,
});
post(
{
type: EMBED_APPLIED_MESSAGE,
id,
ok: steps.every((step) => step.ok),
steps,
},
replyOrigin,
);
})
// A view that fails is answered, and the views behind it still apply.
.catch((error) =>
post(
{
type: EMBED_APPLIED_MESSAGE,
id,
ok: false,
error: error?.message || String(error),
},
replyOrigin,
),
);
});
};
windowRef.addEventListener('message', onMessage);
void ready.then(() => {
@@ -322,6 +511,7 @@ export function installViews({
});
return () => {
stopRendering();
stopNavigatedRestores();
windowRef.removeEventListener('message', onMessage);
};
}
+912 -73
View File
File diff suppressed because it is too large. Load diff
+118
View File
@@ -0,0 +1,118 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { installViews } from './embed.js';
import { createGevActionRunner } from '../voice/gevActions.js';
import { createAnnotationEngine } from '../annotations/annotationEngine.js';
import { fakeCesiumViewer } from '../testSupport/streetLevelFakes.mjs';
// A camera taken while a posted view waits on terrain stays with whoever took
// it: the stale view stands down whole, so it neither stops a newer follow nor
// frames its own marks. Offline: real installViews, action runner and
// annotation engine; the viewer, renderer, flights data and terrain are fixtures.
globalThis.fetch = async () => { throw new Error('Unexpected network request in offline reproduction'); };
globalThis.requestAnimationFrame = () => 1;
globalThis.cancelAnimationFrame = () => {};
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
function deferred() {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
}
async function scenario(t, effect) {
document.body.className = '';
const entered = deferred();
const terrain = deferred();
const viewer = fakeCesiumViewer();
viewer.clock = { onTick: new Cesium.Event() };
viewer.canvas = viewer.scene.canvas;
// A real perspective frustum looking down at 0,0; the old view's mark
// at 48N,2E is outside it. No override of the engine's visibility logic.
Object.assign(viewer.camera, {
position: Cesium.Cartesian3.fromDegrees(0, 0, 1000),
direction: new Cesium.Cartesian3(-1, 0, 0),
up: new Cesium.Cartesian3(0, 0, 1),
heading: 0,
frustum: new Cesium.PerspectiveFrustum({ fov: Math.PI / 3, aspectRatio: 1, near: 1, far: 20000000 }),
});
const entity = { id: 'fixture-aircraft' };
const aircraft = { icao24: 'fixture', callsign: 'Fixture', latitude: 0, longitude: 0 };
let stopCalls = 0;
const flights = {
findByQuery: () => aircraft,
trackById: () => { viewer.trackedEntity = entity; return true; },
getTrackedInfo: () => viewer.trackedEntity ? aircraft : null,
stopTracking: () => { stopCalls++; viewer.trackedEntity = undefined; return true; },
};
const dataManager = {
layers: new Map([['flights', { module: flights }]]),
getAll: () => [{ id: 'flights', enabled: true }],
isEnabled: id => id === 'flights',
setLayerParams: () => true,
};
const shell = {
_navigationGeneration: 1,
initialRestorePromise: Promise.resolve(),
setCleanView() {},
runImmediateNavigation(_noun, navigate) { this._navigationGeneration++; return navigate(); },
};
const annotations = createAnnotationEngine({ viewer,
renderer: { add() {}, update() {}, remove() {}, sync() {}, destroy() {} },
});
const runner = createGevActionRunner({ viewer, dataManager, styleManager: shell, annotations });
const calls = [];
const run = async (name, args, options) => {
calls.push(name);
return runner(name, args, options);
};
const replies = [];
const peer = { postMessage: message => replies.push(message) };
const windowRef = new EventTarget();
windowRef.parent = peer;
windowRef.document = document;
const remove = installViews({ shell, viewer, dataManager, run, windowRef,
location: { search: '?embed=1', hash: '' },
terrain: { getHeights: () => { entered.resolve(); return terrain.promise; } },
});
t.after(() => { remove(); runner.dispose(); annotations.destroy(); document.body.className = ''; });
await tick();
const event = new Event('message');
Object.assign(event, { source: peer, origin: 'https://host.example', data: {
type: 'gev:view', id: 1, view: {
camera: { lat: 48, lon: 2, altitude_m: 1000, pitch_deg: -45 },
layers: ['flights'],
street_level: { provider: 'mapillary' },
annotations: effect === 'annotations'
? [{ type: 'pin', latitude: 48, longitude: 2, label: 'Old view' }] : [],
},
} });
windowRef.dispatchEvent(event);
await entered.promise;
if (effect === 'follow') {
const follow = await runner('track_entity', { query: 'Fixture', layerId: 'flights' });
assert.equal(follow.ok, true, 'new follow starts through the real runner');
assert.equal(viewer.trackedEntity, entity);
} else {
viewer.canvas.dispatchEvent(new Event('pointerdown'));
}
terrain.resolve([{ ellipsoid: 200 }]);
for (let n = 0; n < 50 && !replies.some(reply => reply.id === 1); n++) await tick();
const reply = replies.find(reply => reply.id === 1);
t.diagnostic(JSON.stringify({ effect, calls, stopCalls, followed: viewer.trackedEntity === entity,
annotationCount: annotations.count(), annotationFlights: viewer.flights.started, reply }));
assert.ok(reply, 'host receives completion');
assert.equal(reply.ok, false, 'superseded view is acknowledged as not applied');
assert.ok(!calls.includes('show_street_level'), 'superseded request never reaches photo handler');
if (effect === 'follow') {
assert.equal(stopCalls, 0, 'stale view must not stop the newer follow');
assert.equal(viewer.trackedEntity, entity, 'the new tracked entity stays selected');
} else {
assert.equal(viewer.flights.started, 0, 'stale annotations must not fly the camera');
}
}
for (const effect of ['follow', 'annotations']) {
test(`a camera taken during the terrain wait keeps the user's ${effect}`, { timeout: 5000 }, t => scenario(t, effect));
}
+181
View File
@@ -0,0 +1,181 @@
/**
* @module app/globeInViewRecovery
* @description Turns the camera back to the planet when a move ends looking
* away from it, through the renderer's camera and frame ports.
*/
import { PI_OVER_TWO } from '../geo/vector.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeOutOfFrame,
isFreeGlobeCamera,
} from '../globeInView.js';
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
/** Whether two vectors agree to `tolerance` in every component. */
const within = (a, b, tolerance) =>
Math.abs(a.x - b.x) <= tolerance &&
Math.abs(a.y - b.y) <= tolerance &&
Math.abs(a.z - b.z) <= tolerance;
// How often a moving camera is sampled to see whether it has come to rest, how
// far a pose may drift between samples and still count as at rest, and how
// long after the camera last moved the check gives up if the camera never
// raises moveEnd.
const SETTLE_SAMPLE_MS = 250;
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
const SETTLE_GIVE_UP_MS = 5 * 60_000;
/**
* Turn the camera back to the planet when a move ends above `minHeight` with
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
* one sample cell thick can count as none), and return the disposer. Views with
* more surface, such as an oblique orbital shot, are left as they are. This
* catches a saved or shared view that looked away, or any other move that ends
* looking away from the planet.
* Heading and position are kept. Following cameras, locked ones (a target's
* frame), a camera flight in progress, a pointer held down on the canvas
* (a drag held still), and any time `paused`
* returns true (an authored scene playing) are left alone; a check they defer
* runs once they end, however long they last.
* `keyholeRadius`
* returns the radius of the visible circle when a scope mask hides the rest of
* the frame (see `globeFrameShare`), or 0; it is read at every check.
*
* The camera's `moveEnd` alone is not enough: the default renderer compares
* the camera with the last frame's to the last rounding error, and at some of
* these poses the camera drifts by a rounding error every frame, so it never
* sees it stop.
* So each `moveStart` also starts a check of its own that samples the pose
* every 250 ms, with a tolerance for that drift, and once the pose has held
* for half a second after moving runs the same recovery. It keeps watching
* until the camera raises `moveEnd`, since under that drift it raises no new
* `moveStart` for a later move, and gives up five minutes after the camera
* last moved.
* `setTimeout` and `clearTimeout` can be injected for tests.
*/
export function installGlobeInViewRecovery(
viewer,
{
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
keyholeRadius = () => 0,
paused = () => false,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
} = {},
) {
const camera = findCamera(viewer);
if (!camera) throw new TypeError('A viewer with a camera is required');
// A pointer held on the globe is a gesture in progress, even when it holds
// still for half a second: the check waits until every pointer pressed on
// it (each finger of a pinch) is released. A release the page never sees,
// outside the window, is taken as given when the window loses focus, the
// page is hidden, the canvas loses the pointer's capture, or the pointer
// moves with no button down.
const canvas = canvasOf(viewer);
const releaseTarget = canvas?.ownerDocument ?? canvas;
const releaseWindow = canvas?.ownerDocument?.defaultView;
const heldPointers = new Set();
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
const onPointerMove = (event) => {
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
};
const releaseAll = () => heldPointers.clear();
const onVisibilityChange = () => {
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
};
const listeners = [
[canvas, 'pointerdown', onPointerDown],
[canvas, 'lostpointercapture', onPointerUp],
[releaseTarget, 'pointerup', onPointerUp],
[releaseTarget, 'pointercancel', onPointerUp],
[releaseTarget, 'pointermove', onPointerMove],
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
[releaseWindow, 'blur', releaseAll],
];
for (const [target, type, listener] of listeners)
target?.addEventListener?.(type, listener);
// Returns false while a flight, a paused scene or a held pointer defers the
// check, so the caller can try again once it ends.
const recover = () => {
if (!isFreeGlobeCamera(viewer)) return true;
if (camera.flying || paused() || heldPointers.size > 0) return false;
const pose = camera.pose();
if (
!(pose.height > minHeight) ||
!globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() })
)
return true;
camera.setView({
orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 },
});
findFrame(viewer)?.requestRender?.('globe-in-view');
return true;
};
let lastPosition = null;
let lastDirection = null;
const remember = () => {
({ position: lastPosition, direction: lastDirection } = camera.pose());
};
let settleTimer = null;
let settleElapsed = 0;
let restingSamples = 0;
let movedSinceCheck = false;
const stopSettling = () => {
if (settleTimer !== null) unschedule(settleTimer);
settleTimer = null;
};
const sample = () => {
settleTimer = null;
settleElapsed += SETTLE_SAMPLE_MS;
const now = camera.pose();
const atRest =
within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) &&
within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE);
restingSamples = atRest ? restingSamples + 1 : 0;
if (!atRest) {
movedSinceCheck = true;
settleElapsed = 0;
}
// Two quiet samples in a row after a move: at rest for half a second, as
// for moveEnd.
if (restingSamples >= 2 && movedSinceCheck) {
if (recover()) movedSinceCheck = false;
// A flight or a playing scene bounds its own deferral.
else settleElapsed = 0;
}
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
remember();
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const startSettling = () => {
stopSettling();
settleElapsed = 0;
restingSamples = 0;
movedSinceCheck = true;
remember();
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const removeMoveEnd = camera.on('moveEnd', () => {
if (recover()) stopSettling();
// Deferred: keep sampling so the check runs once the flight or scene ends.
else if (settleTimer === null) startSettling();
});
const removeMoveStart = camera.on('moveStart', startSettling);
let active = true;
return () => {
if (!active) return;
active = false;
stopSettling();
removeMoveEnd();
removeMoveStart();
for (const [target, type, listener] of listeners)
target?.removeEventListener?.(type, listener);
heldPointers.clear();
};
}
+23 -7
View File
@@ -462,8 +462,11 @@ export function panelRuntime(config) {
* Load God's Eye View into this page from the app's panel build, in
* inline embed mode, starting at the first view as its link would.
*/
async function startApp(url, view) {
async function startApp(url, view, fresh = false) {
window.GEV_EMBED_INLINE = true;
// Whether this result was just issued, not handed back by a host that
// mounted the panel again: only then may its link open a billed photo.
window.GEV_EMBED_FRESH = fresh;
window.GEV_APP_BASE_URL = config.appBaseUrl;
try {
history.replaceState(
@@ -551,13 +554,21 @@ export function panelRuntime(config) {
);
}
// Tool results: the first view starts the app, later ones move it.
// Tool results: the first view starts the app, later ones move it. A
// result issued longer ago than this was handed back on a remount.
const FRESH_RESULT_MS = 5 * 60 * 1000;
let started = false;
let ready = false;
let queued = null;
let queuedFresh = false;
let currentUrl = null;
const postView = (view) =>
window.postMessage({ type: 'gev:view', id: nextId++, view }, '*');
// Every view carries whether its result was issued just now: only those may
// open a billed photo, whichever result on this mount they came in.
const postView = (view, fresh) =>
window.postMessage(
{ type: 'gev:view', id: nextId++, view, fresh: fresh === true },
'*',
);
function show(result) {
const data = result?.structuredContent;
const view = data?.view;
@@ -565,13 +576,18 @@ export function panelRuntime(config) {
if (!view || !url) return;
currentUrl = url;
open.hidden = false;
if (ready) return postView(view);
const issuedAt = Number(data.issued_at);
const fresh =
Number.isFinite(issuedAt) &&
Math.abs(Date.now() - issuedAt) <= FRESH_RESULT_MS;
if (ready) return postView(view, fresh);
queued = view;
queuedFresh = fresh;
if (started) return;
started = true;
// i18n-ignore: host-panel script, no app catalogs
say("Loading God's Eye View…");
startApp(url, view).catch((error) =>
startApp(url, view, fresh).catch((error) =>
// i18n-ignore: host-panel script, no app catalogs
say(`God's Eye View could not load here: ${error?.message || error}.`),
);
@@ -592,7 +608,7 @@ export function panelRuntime(config) {
if (message?.type === 'gev:ready') {
ready = true;
status.remove();
if (queued) postView(queued);
if (queued) postView(queued, queuedFresh);
queued = null;
}
return;
+71
View File
@@ -0,0 +1,71 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { panelRuntime } from './globePanelRuntime.js';
const element = () => ({
isConnected: true,
hidden: true,
textContent: '',
addEventListener() {},
remove() {
this.isConnected = false;
},
});
test('every view the panel posts says whether its result was issued just now', async () => {
const savedWindow = globalThis.window;
const savedDocument = globalThis.document;
const views = [];
const parent = { postMessage() {} };
const windowRef = new EventTarget();
Object.assign(windowRef, {
parent,
postMessage: (message) => {
if (message?.type === 'gev:view') views.push(message);
},
});
const elements = { status: element(), open: element(), expand: element() };
globalThis.window = windowRef;
globalThis.document = {
getElementById: (id) => elements[id] ?? null,
addEventListener() {},
baseURI: 'https://host.example/panel',
body: { clientWidth: 600 },
};
const deliver = (source, data) => {
const event = new Event('message');
Object.assign(event, { source, data });
windowRef.dispatchEvent(event);
};
const result = (issuedAt) => ({
jsonrpc: '2.0',
method: 'ui/notifications/tool-result',
params: {
structuredContent: {
url: 'http://localhost:4173/#sl=google,48.85840,2.29450',
issued_at: issuedAt,
view: { camera: { lat: 48.8584, lon: 2.2945 } },
},
},
});
try {
panelRuntime({
appBaseUrl: 'http://localhost:4173/',
panelBase: '/panel/',
protocolVersion: '2025-06-18',
panelHeight: 480,
});
deliver(windowRef, { type: 'gev:ready' });
deliver(parent, result(Date.now()));
// A host replaying an old result on the same mount.
deliver(parent, result(Date.now() - 60 * 60 * 1000));
deliver(parent, result(undefined));
} finally {
globalThis.window = savedWindow;
globalThis.document = savedDocument;
}
assert.deepEqual(
views.map((message) => message.fresh),
[true, false, false],
);
});
+1
View File
@@ -18,6 +18,7 @@ export class LayerPresentation {
this.pendingVisible = false;
this._unsubscribe = manager.subscribeActivity((change) => {
if (change.type === 'status') this.refresh();
else if (change.type === 'registrations') this._panel?.rerender();
else if (change.type === 'destroy-all') this.destroy();
else {
const reason =
+19 -2
View File
@@ -10,9 +10,21 @@ import * as focus from '../../data/focusDeemphasis.js';
import * as worldFocus from '../../worldFocus.js';
import * as render from '../../renderGovernor.js';
import * as readouts from '../../hudReadouts.js';
import { fleetModelServices } from './fleetModels.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationVessels({ source, options = {} }) {
/**
* Construct one layer using the application scene owners and a supplied
* source. `displayParams` reads the Flights layer's DISPLAY-rail 3D
* preference, under which nearby vessels are drawn as fleet models.
* `placement`: a host-supplied placement for its live vessels, or null.
*/
export function createApplicationVessels({
source,
placement = null,
options = {},
displayParams = null,
resolveAsset,
}) {
return createVesselLayer({
source,
options,
@@ -28,6 +40,11 @@ export function createApplicationVessels({ source, options = {} }) {
worldFocus,
render,
readouts,
placement,
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
+10
View File
@@ -0,0 +1,10 @@
import { createCyclonesLayer } from '../../layers/cyclones/index.js';
import * as context from '../../data/contextStore.js';
/** Wire cyclone selection to the application shared context. */
export function createApplicationCyclones(options) {
return createCyclonesLayer({
context: typeof window !== 'undefined' ? context : null,
...options,
});
}
-5
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire FAA special-use airspace into the application catalog. */
export function createApplicationDroneAirspace(options) {
@@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
-4
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js';
import * as render from '../../renderGovernor.js';
import * as sprites from '../../data/spriteOrder.js';
@@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory:
options.screenSpaceEventHandlerFactory ??
((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)),
});
}
+19
View File
@@ -0,0 +1,19 @@
import { FLEET_MODEL_POLICY } from '../../layers/flights/policy.js';
/**
* The fleet-model service the Vessels, Transit and Rail layers draw their 3D
* models with: the Flights layer's DISPLAY-rail 3D preference
* (`{ models3d, models3dMode }`), the aircraft layers' icon-to-model rules,
* and the resolver the fleet set's files are fetched through.
* @param {{display?: (() => object|null)|null,
* resolveAsset?: (url: string) => string}} [options]
* @returns {object|null} Null without a display preference (no models).
*/
export function fleetModelServices({
display = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
} = {}) {
if (!display) return null;
return Object.freeze({ display, policy: FLEET_MODEL_POLICY, resolveAsset });
}
+4 -1
View File
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
import * as render from '../../renderGovernor.js';
import * as recession from '../../data/aircraftRecession.js';
/** Construct one layer using the application scene owners and a supplied source. */
/** Construct one layer using the application scene owners and a supplied source.
* `placement`: a host-supplied placement for its live aircraft, or null. */
export function createApplicationFlights({
surface,
source,
militaryRegistry,
placement = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
@@ -41,6 +43,7 @@ export function createApplicationFlights({
render,
groundSnap,
recession,
placement,
},
});
}
-5
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire the S2 Underground GhostMaps layer into the application catalog. */
export function createApplicationGhostMaps(options) {
@@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) {
hitTest: overlays.hitTestWorldOverlay,
},
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
+5 -1
View File
@@ -1,6 +1,10 @@
import { createGnssIntegrityLayer } from '../../layers/gnss/index.js';
import { worldTimeFor } from '../../time/worldClock.js';
/** Wire the adsb.lol GNSS navigation-integrity layer into the application catalog. */
export function createApplicationGnssIntegrity(options) {
return createGnssIntegrityLayer(options);
return createGnssIntegrityLayer({
worldNow: worldTimeFor('gnss-integrity'),
...options,
});
}
+4 -1
View File
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
import * as render from '../../renderGovernor.js';
import * as recession from '../../data/aircraftRecession.js';
/** Construct one layer using the application scene owners and a supplied source. */
/** Construct one layer using the application scene owners and a supplied source.
* `placement`: a host-supplied placement for its live aircraft, or null. */
export function createApplicationMilitary({
surface,
source,
militaryRegistry,
placement = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
@@ -41,6 +43,7 @@ export function createApplicationMilitary({
render,
groundSnap,
recession,
placement,
},
});
}
+6
View File
@@ -0,0 +1,6 @@
import { createNewsLayer } from '../../layers/news/index.js';
import { overlayHost } from './overlayHost.js';
/** Wire the news layer to the application overlay host. */
export function createApplicationNews(options) {
return createNewsLayer({ overlayHost, ...options });
}
-5
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
createFirePerimetersLayer,
createInciwebIndexSource,
@@ -6,7 +5,6 @@ import {
} from '../../layers/perimeters/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire WFIGS fire perimeters into the application catalog. */
export function createApplicationFirePerimeters(options) {
@@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) {
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
+64
View File
@@ -0,0 +1,64 @@
import { createRailLayer } from '../../layers/rail/index.js';
import * as render from '../../renderGovernor.js';
import { fleetModelServices } from './fleetModels.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js';
import {
railFeedCredit,
registerDynamicCredit,
} from '../../data/dataCredits.js';
/**
* Construct the Rail layer on the application's scene owners and its shared
* ground floor, the same floor Transit and the aircraft stand on.
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby trains are drawn as fleet models.
* `placement` is a host-supplied placement for its live trains, or null.
* @param {{surface: object, source?: object, placement?: object|null,
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
* @returns {object}
*/
export function createApplicationRail({
surface,
source,
placement = null,
displayParams = null,
resolveAsset,
}) {
if (!surface?.groundFloor)
throw new TypeError('Rail needs the application surface services');
const { groundFloor } = surface;
return createRailLayer({
source,
services: {
render,
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, railFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
cachedGroundFloor: groundFloor.cachedGroundFloor,
warmGroundFloor: groundFloor.warmGroundFloor,
neighborFloorM: groundFloor.neighborFloorM,
coarseFloorCoord: groundFloor.coarseFloorCoord,
},
// A selected train is followed as a tracked aircraft is, or flown to
// once as a vessel is (src/layers/rail/follow.js).
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus,
isCockpitActive: () =>
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
true,
},
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
+4
View File
@@ -2,6 +2,9 @@ import { createRecentImageryLayer } from '../../layers/recentImagery/index.js';
import { createRecentImageryRenderer } from '../../layers/recentImagery/rendering.js';
import { createThumbnailLoader } from '../../layers/recentImagery/thumbnails.js';
import { governorRequestRender } from '../../renderGovernor.js';
import { worldTimeFor } from '../../time/worldClock.js';
const imageryTime = worldTimeFor('recent-imagery');
/** Construct imagery presentation over one explicitly supplied acquisition source. */
export function createApplicationRecentImagery({ source }) {
@@ -15,5 +18,6 @@ export function createApplicationRecentImagery({ source }) {
thumbnails: createThumbnailLoader({
requestThumbnail: (...args) => source.getThumbnail(...args),
}),
now: () => new Date(imageryTime()),
});
}
+20
View File
@@ -0,0 +1,20 @@
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire the EMODnet + Wikidata shipwrecks layer into the application catalog. */
export function createApplicationShipwrecks(options) {
return createShipwrecksLayer({
overlayHost: {
setEntries: overlays.setOverlayEntries,
setVisible: overlays.setOverlaySourceVisible,
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
picking,
pointer: { isPointerFree },
...options,
});
}
+1 -3
View File
@@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as input from '../../data/inputOwnership.js';
import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
@@ -37,6 +35,6 @@ export function createApplicationStreetLevel({
}) {
return createStreetLevelLayer({
providers,
services: { sprites, picking, input, scenePick, render },
services: { picking, scenePick, render },
});
}
-3
View File
@@ -1,12 +1,9 @@
import * as Cesium from 'cesium';
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
screenSpaceEventHandlerFactory: (canvas) =>
new Cesium.ScreenSpaceEventHandler(canvas),
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
+19 -2
View File
@@ -1,5 +1,6 @@
import { createTransitLayer } from '../../layers/transit/index.js';
import * as render from '../../renderGovernor.js';
import { fleetModelServices } from './fleetModels.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -19,10 +20,21 @@ import {
* own mesh floors. An earlier cut imported the legacy module-level singleton
* instead and could not see either.
*
* @param {{surface: object}} options
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby vehicles are drawn as fleet models.
*
* `placement` is a host-supplied placement for its live vehicles, or null.
* @param {{surface: object, source?: object, placement?: object|null,
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
* @returns {object}
*/
export function createApplicationTransit({ surface, source }) {
export function createApplicationTransit({
surface,
source,
placement = null,
displayParams = null,
resolveAsset,
}) {
if (!surface?.groundFloor || !surface?.meshFloor)
throw new TypeError('Transit needs the application surface services');
const { groundFloor, meshFloor } = surface;
@@ -33,6 +45,7 @@ export function createApplicationTransit({ surface, source }) {
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, transitFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
@@ -44,6 +57,10 @@ export function createApplicationTransit({ surface, source }) {
allocateCorridorCells: groundFloor.allocateCorridorCells,
},
mesh: { sampleMeshFloorCells: meshFloor.sampleMeshFloorCells },
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
-3
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
sprites,
+2
View File
@@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { governorRequestRender } from '../renderGovernor.js';
import {
clearSelectedEntityContextForLayer,
getSelectedEntityContext,
registerEntityContext,
removeEntityContextsForLayer,
selectEntityContext,
@@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({
setVisible: setOverlaySourceVisible,
}),
clearSelectedEntityContextForLayer,
getSelectedEntityContext,
registerEntityContext,
removeEntityContextsForLayer,
selectEntityContext,
+5 -3
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MapStackController } from '../mapStackController.js';
import '../render/cesium/mapEngine.js';
import {
installRenderGovernor,
uninstallRenderGovernor,
@@ -8,6 +9,7 @@ import {
governorRequestRender,
getRenderGovernorDiagnostics,
} from '../renderGovernor.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => {
let resolveProvider;
@@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests
},
},
};
installRenderGovernor(viewer);
installRenderGovernor(framePortFor(viewer.scene));
holdContinuousRender('fixture');
uninstallRenderGovernor({});
uninstallRenderGovernor(framePortFor({}));
assert.equal(getRenderGovernorDiagnostics().installed, true);
uninstallRenderGovernor(viewer);
uninstallRenderGovernor(framePortFor(viewer.scene));
const before = renders;
governorRequestRender('late');
assert.equal(renders, before);
+74
View File
@@ -0,0 +1,74 @@
/**
* @module app/panelRendering
* @description Keeping the globe drawing in an inline panel whose host stops
* animation frames (`src/app/embed.js`, embed mode), through the ports alone: the
* application scene hands it to the embed views (`src/app/scene.js`).
*/
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep `renderer` drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* the renderer's own loop; while frames stop arriving, draw from a timer
* (`resize`, then a frame of the loop, `frame.renderNow({ifDue: true})`: the
* camera moves, input and the clock run, and it draws when due). While the
* renderer's loop is stopped after a failed frame (`stopped` in its frame
* diagnostics) the timer waits, and goes on once a retry starts the loop
* again; the render failure notice reports the error
* (src/render/cesium/renderFailure.js). Where the renderer never says so, a frame
* that fails stops the timer, its error reported in full. Returns a
* function that stops it.
* @param {import('../render/contract/renderer').Renderer} renderer
* @param {{windowRef?: Window, now?: () => number}} [options]
* @returns {() => void}
*/
export function keepPanelRendering(
renderer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
let failed = false;
const stopped = () => renderer.frame.diagnostics?.().stopped;
const timer = windowRef.setInterval(() => {
if (failed || now() - lastFrame < MISSED_FRAMES_MS || stopped()) return;
try {
renderer.resize();
renderer.frame.renderNow({ ifDue: true });
} catch (error) {
// Stopped by now: the render failure notice has the error.
if (stopped() !== undefined) return;
// Report the error in full: workers report plain objects, which
// would print as [object Object].
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
}
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
};
}
+125
View File
@@ -0,0 +1,125 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { keepPanelRendering } from './panelRendering.js';
const windowWith = () => {
const handles = { tick: null, frame: null };
handles.windowRef = {
requestAnimationFrame: (fn) => ((handles.frame = fn), 1),
cancelAnimationFrame: () => (handles.frame = null),
setInterval: (fn) => ((handles.tick = fn), 1),
clearInterval: () => (handles.tick = null),
};
return handles;
};
test('a panel keeps drawing from a timer while animation frames stop', () => {
let clock = 0;
const handles = windowWith();
const drawn = [];
const renderer = {
resize: () => drawn.push('resize'),
frame: {
renderNow: (options) =>
drawn.push(options?.ifDue ? 'loop frame' : 'forced frame'),
},
};
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
// Frames arrive: the render loop draws, so the timer does nothing.
clock = 100;
handles.frame();
handles.tick();
assert.deepEqual(drawn, []);
// Frames stop, as in a panel its host reports hidden: the timer draws.
clock = 400;
handles.tick();
// A frame of the loop, as the loop's own: the camera moves, input and
// the clock run, and it draws when due.
assert.deepEqual(drawn, ['resize', 'loop frame']);
stop();
assert.equal(handles.tick, null);
assert.equal(handles.frame, null);
});
test('a panel reports a failed frame in full and stops drawing', () => {
const handles = windowWith();
let renders = 0;
const renderer = {
resize() {},
frame: {
renderNow() {
renders += 1;
// Workers report plain objects.
throw { name: 'RuntimeError', message: 'worker failed' };
},
},
};
const logged = [];
const original = console.error;
console.error = (...args) => logged.push(args.join(' '));
try {
let clock = 0;
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
clock = 1000;
handles.tick();
assert.match(logged[0], /render error: .*"message":"worker failed"/);
handles.tick();
assert.equal(renders, 1, 'no frame after the one that failed');
stop();
} finally {
console.error = original;
}
});
test('a panel waits while its renderer’s loop is stopped after a failed frame, and draws again once it restarts', () => {
let clock = 0;
const handles = windowWith();
let stopped = false;
let fail = false;
let renders = 0;
const renderer = {
resize() {},
frame: {
diagnostics: () => ({ stopped }),
renderNow() {
renders += 1;
if (fail) {
// The renderer stops its loop as the frame fails.
stopped = true;
throw new Error('frame failed');
}
},
},
};
const errors = [];
const error = console.error;
console.error = (...args) => errors.push(args);
try {
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
clock = 1000;
fail = true;
handles.tick();
assert.equal(renders, 1);
// Stopped: the timer waits, and leaves the error to the notice.
handles.tick();
assert.equal(renders, 1);
assert.deepEqual(errors, []);
// A retry starts the loop again: the timer draws again.
stopped = false;
fail = false;
handles.tick();
assert.equal(renders, 2);
stop();
} finally {
console.error = error;
}
});
+132
View File
@@ -0,0 +1,132 @@
// Retry in an inline panel whose host stops animation frames, so the panel
// draws from keepPanelRendering's timer. Drives Cesium's real startRenderLoop
// and useDefaultRenderLoop setter (CesiumWidget.prototype), through the
// Cesium frame port.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { keepPanelRendering } from './panelRendering.js';
import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs';
import { createSceneFrame } from '../render/cesium/frame.js';
function setup() {
let tick = null;
let clock = 0;
// The host reports the panel hidden: its own animation frames never arrive.
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const previousError = console.error;
console.error = () => {};
const state = { failure: null, drawn: 0 };
const scene = {
renderError: new Cesium.Event(),
preUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
requestRender() {},
initializeFrame() {},
// Scene.render: a failing primitive update raises renderError
// (tryAndCatchError) and returns; a failing listener throws.
render() {
state.drawn += 1;
this.preUpdate.raiseEvent(this);
if (state.failure === 'caught')
this.renderError.raiseEvent(this, new Error('boom'));
if (state.failure === 'thrown') throw new Error('boom');
this.postRender.raiseEvent(this);
},
};
const { frames, widget, viewer, store, runFrames, restore } =
renderLoopFixture(scene, {
viewer: {
isDestroyed: () => false,
render: () => widget.render(),
resize: () => widget.resize(),
},
notice: { allowReload: false },
});
const frame = createSceneFrame(viewer);
const renderer = { resize: () => viewer.resize(), frame: frame.port };
const stopPanel = keepPanelRendering(renderer, {
windowRef,
now: () => clock,
});
const stop = () => {
stopPanel();
frame.dispose();
};
viewer.useDefaultRenderLoop = true;
const timerFrame = () => {
clock += 400;
tick();
};
return {
frames,
state,
store,
timerFrame,
animationFrames: runFrames,
restore: () => {
stop();
restore();
console.error = previousError;
},
};
}
for (const failure of ['caught', 'thrown']) {
test(`an error ${failure} in a frame the timer draws: Retry draws again with one render loop`, () => {
const { frames, state, store, timerFrame, animationFrames, restore } =
setup();
try {
// The host stops animation frames with the loop's next one queued.
assert.equal(frames.length, 1);
state.failure = failure;
timerFrame(); // an error thrown here does not reach the host page
assert.equal(store.renderFailure?.reason, 'render-error');
assert.equal(typeof store.renderFailure.retry, 'function');
state.failure = null;
store.renderFailure.retry();
const before = state.drawn;
timerFrame();
assert.ok(state.drawn > before, 'the panel draws again after Retry');
assert.equal(
store.renderFailure,
null,
'a clean frame clears the notice',
);
assert.equal(frames.length, 1, 'Retry starts no second loop');
// The host resumes frames: the globe draws once a frame.
state.drawn = 0;
animationFrames(3);
assert.equal(state.drawn, 3);
} finally {
restore();
}
});
}
test('an error Scene caught in an animation frame right before the host stopped frames: Retry keeps one render loop', () => {
const { frames, state, store, timerFrame, animationFrames, restore } =
setup();
try {
state.failure = 'caught';
animationFrames(1);
assert.equal(store.renderFailure?.reason, 'render-error');
assert.equal(frames.length, 1);
state.failure = null;
store.renderFailure.retry();
timerFrame();
assert.equal(store.renderFailure, null);
assert.equal(frames.length, 1, 'Retry starts no second loop');
state.drawn = 0;
animationFrames(3);
assert.equal(state.drawn, 3);
} finally {
restore();
}
});
+164 -33
View File
@@ -1,24 +1,66 @@
import { createApplicationOperations } from './operations.js';
import * as Cesium from 'cesium';
import {
createApplicationViewer,
installFreeLookHeightLimit,
installTrackpadPinchZoom,
} from '../app/viewer.js';
import { registerDataCredits } from '../data/dataCredits.js';
import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
import { mountCreditsView } from '../ui/creditsView.js';
import { MapStackController } from '../mapStackController.js';
import { loadPhotorealisticTileset } from '../mapStartup.js';
import { mapEngineFor } from '../maps/engine.js';
import { initLogoGaze } from '../logoGaze.js';
import { inputFor } from '../input/dispatcher.js';
import {
holdContinuousRender,
installRenderGovernor,
uninstallRenderGovernor,
governorRequestRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { describeError } from './errors.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { isEmbeddedInline } from './embed.js';
import { worldClock, worldTimeFor } from '../time/worldClock.js';
import { followWorldTime } from '../time/viewerClock.js';
import { t } from '../i18n/index.js';
import {
applicationHooksOf,
provideApplicationHooks,
} from '../render/applicationHooks.js';
import { keepPanelRendering } from './panelRendering.js';
import { useStatusStore } from '../ui/stores/status.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { createSceneHost } from '../render/rendererOf.js';
/** Construct the application globe using the caller's local configuration. */
let defaultLoad = null;
/**
* The application's composition root picks the renderer: the one given, else
* the default (Cesium), loaded only then, so a page on the stub never
* loads it. This is the only part of an adapter the application imports. A
* page that starts on the default calls this as it starts, so the renderer
* loads beside the rest of the page rather than after it.
* @returns {Promise<object>} The default `RendererPlugin`.
*/
export function loadDefaultRenderer() {
if (defaultLoad) return defaultLoad;
const load = (async () => {
const { cesiumRenderer } = await import('../render/cesium/application.js');
return cesiumRenderer;
})();
defaultLoad = load;
// A load that failed is tried again by the next call.
load.catch(() => {
if (defaultLoad === load) defaultLoad = null;
});
return load;
}
/**
* Construct the application globe using the caller's local configuration.
* `renderer` is the `RendererPlugin` that draws it, or a promise of one
* (default: Cesium, `loadDefaultRenderer`). The
* application runs on a renderer with only the contract's required members:
* what a renderer's plugin hands it beside the contract
* (`src/render/applicationHooks.js`) it uses where given, and does without
* where not.
*/
export async function createApplicationScene({
renderer: givenPlugin,
requestServices,
googleApiKey,
googleTokens = null,
@@ -45,46 +87,117 @@ export async function createApplicationScene({
});
}
loaderStatus.textContent = t('Configuring viewer...');
// Provider attribution stays visible, including clean-view and recording.
const creditContainer = document.createElement('div');
creditContainer.id = 'cesium-credits';
document.body.appendChild(creditContainer);
defer(() => creditContainer.remove());
const viewer = createApplicationViewer({
container: 'cesiumContainer',
creditContainer,
const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer());
signal.throwIfAborted();
const container = document.getElementById('cesiumContainer');
const renderer = await rendererPlugin.create({
container,
googleApiKey: googleApiKey || undefined,
googleTokens: googleTokens
? (options) => googleTokens.token(options)
: undefined,
worldDataToken: cesiumToken || undefined,
signal,
});
// The scene object every layer and tool is handed: the application's own,
// bound to the renderer.
const scene = createSceneHost(renderer, { container });
const viewer = scene.host;
// The governor keeps its holds on the renderer's frame port. The loop
// draws every frame until the application's tools are up (they release
// 'boot'), as it did before anything could hold it. A camera move holds
// it drawing every frame too.
installRenderGovernor(renderer.frame, { camera: renderer.camera });
holdContinuousRender('boot');
defer(() => {
uninstallRenderGovernor(viewer);
if (!viewer.isDestroyed()) viewer.destroy();
try {
uninstallRenderGovernor(renderer.frame);
} finally {
try {
renderer.destroy();
} finally {
scene.release();
}
}
});
defer(installTrackpadPinchZoom(viewer));
defer(installFreeLookHeightLimit(viewer));
// What the plugin hands the application beside the contract, each hook
// optional (render/applicationHooks.js).
if (typeof rendererPlugin.applicationHooks === 'function')
provideApplicationHooks(
renderer,
rendererPlugin.applicationHooks(renderer),
);
const hooks = applicationHooksOf(renderer);
// The renderer follows its container's size (`Renderer.resize`).
if (typeof ResizeObserver === 'function' && container) {
const resizes = new ResizeObserver(() => renderer.resize());
resizes.observe(container);
defer(() => resizes.disconnect());
}
// Before any layer binds a click: every layer and tool shares this one.
// Deferred after the renderer, so it is released before the renderer goes.
const input = inputFor(viewer);
defer(() => input.destroy());
// Ctrl+wheel and trackpad pinches zoom the globe, not the page.
const { controls } = renderer.camera;
if (!controls.zoomInputs.includes('ctrlWheel'))
controls.zoomInputs = [...controls.zoomInputs, 'ctrlWheel'];
// The user's outward zooms stop at a whole-Earth view, which stays framed.
if (renderer.capabilities.has('keepEarthFramed')) {
controls.keepEarthFramed = true;
defer(() => {
controls.keepEarthFramed = false;
});
}
// The renderer's own notice when the globe stops drawing, in place of a
// dead-end panel; an inline panel must not reload or navigate its host's
// page.
const offRenderFailure = hooks.renderFailureNotice?.({
allowReload: !isEmbeddedInline(),
store: useStatusStore(applicationPinia()),
});
if (offRenderFailure) defer(offRenderFailure);
defer(
followWorldTime(viewer, worldTimeFor('sky'), {
subscribe: worldClock.subscribe,
requestRender: () => governorRequestRender('world-time'),
// A playing world time moves something every frame: draw at the
// display's rate meanwhile, not the parked scene's cap.
onPlaying: (playing) =>
playing
? holdContinuousRender('world-time')
: releaseContinuousRender('world-time'),
}),
);
registerDataCredits(viewer, credits);
configureCreditKeyboardAccess(document);
defer(onLocaleChange(() => configureCreditKeyboardAccess(document)));
// The credits, in the application's own line, unless the renderer shows
// them in a display of its own.
if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer));
loaderStatus.textContent =
googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...')
: t('Loading the keyless globe...');
const photoreal = await loadPhotorealisticTileset(Cesium, {
// The map stacks, and the photoreal base among them, switch through the
// scene's map engine: the renderer's own, or its globe port.
const engine = mapOptions.engine ?? mapEngineFor(viewer);
const photoreal = (await engine.loadPhotoreal?.(viewer, {
googleApiKey,
googleTokens,
cesiumToken,
});
})) ?? { tileset: null, route: 'none', errors: [] };
const tileset = photoreal.tileset;
// A provider can finish after cancellation; retain ownership of its result.
defer(() => {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
if (!tileset || engine.isDestroyed(tileset)) return;
engine.removeTileset(viewer, tileset);
engine.release(tileset);
});
signal.throwIfAborted();
if (tileset) {
viewer.scene.primitives.add(tileset);
engine.addTileset(viewer, tileset);
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
// Google Photorealistic 3D Tiles provide their own terrain/elevation.
viewer.scene.globe.show = false;
renderer.globe.setGlobeVisible(false);
console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`);
} else {
if (photoreal.errors.length) {
@@ -101,7 +214,7 @@ export async function createApplicationScene({
},
);
}
viewer.scene.globe.show = true;
renderer.globe.setGlobeVisible(true);
}
loaderStatus.textContent = t('Initializing systems...');
@@ -109,6 +222,7 @@ export async function createApplicationScene({
const mapStackController = new MapController(viewer, {
requestRender: governorRequestRender,
...mapOptions,
engine,
googleTileset: tileset,
cesiumToken,
initialStack: tileset ? 'photoreal' : 'esri-imagery',
@@ -130,5 +244,22 @@ export async function createApplicationScene({
});
signal.throwIfAborted();
return { viewer, tileset, mapStackController, operations };
return {
renderer,
viewer,
tileset,
mapStackController,
operations,
input,
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js); returns its disposer.
keepPanelRendering: (options) => keepPanelRendering(renderer, options),
// What the renderer's plugin hands the application beside the contract,
// each optional: trims stale draw commands, says whether an entity is
// the renderer's own, and what QA scripts read
// (render/applicationHooks.js).
trimStaleCommands: hooks.trimStaleCommands,
viewerDrawsEntity: hooks.viewerDrawsEntity,
qaHandles: hooks.qaHandles,
};
}
+152
View File
@@ -0,0 +1,152 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApplicationScene } from './scene.js';
import { createApplicationRequestServices } from '../services/requests.js';
import { createStubRendererPlugin } from '../render/stub/index.js';
import { rendererOf } from '../render/rendererOf.js';
/** Start the scene on a stub renderer with `capabilities`. */
async function startOnStub(t, { capabilities = [], ...rest } = {}) {
document.body.innerHTML = '<div id="cesiumContainer"></div>';
const made = [];
const deferred = [];
t.after(async () => {
for (const fn of deferred.reverse()) await fn();
});
const scene = await createApplicationScene({
renderer: createStubRendererPlugin({ capabilities }, (renderer) =>
made.push(renderer),
),
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
...rest,
});
return { scene, renderer: made[0], deferred };
}
test('the scene runs on a renderer with only the required members', async (t) => {
const { scene, renderer, deferred } = await startOnStub(t);
assert.equal(scene.renderer, renderer);
assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound');
assert.equal(
scene.viewer.container,
document.getElementById('cesiumContainer'),
);
assert.equal(scene.viewer.isDestroyed(), false);
assert.ok(
scene.viewer.container.contains(renderer.canvas),
'the renderer fills the container',
);
// Nothing of the engine on the scene object.
assert.deepEqual(Object.keys(scene.viewer).sort(), [
'container',
'isDestroyed',
]);
// No hooks: each is left out, not faked.
for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles'])
assert.equal(scene[name], undefined, name);
// What the renderer does through its ports.
assert.equal(typeof scene.keepPanelRendering, 'function');
assert.equal(
renderer.camera.controls.keepEarthFramed,
undefined,
'no framing on a renderer without it',
);
// Keyless, the map stack shows Esri on the globe through the globe port.
assert.equal(scene.tileset, null);
assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery');
const layers = renderer.globe.imagery.list();
assert.equal(layers.length, 1, 'one base imagery layer');
assert.ok(
renderer.testing.calls.some(
(call) =>
call.port === 'globe' &&
call.member === 'imagery.add' &&
call.args[0]?.url?.includes('World_Imagery'),
),
'Esri imagery through the port',
);
assert.equal(scene.mapStackController.getDrapeSurface(), 'globe');
// The credits show in the application's own line: the Esri base's on it,
// the data credits in the list it opens.
const line = document.getElementById('gev-credits');
assert.ok(line, 'a credits line');
assert.match(line.textContent, /Esri/);
assert.ok(
document.querySelectorAll('#gev-credits-panel li').length > 10,
'the data credits',
);
// Switching stacks goes through the port too.
await scene.mapStackController.setStack('osm');
assert.equal(scene.mapStackController.getActiveId(), 'osm');
assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way');
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(scene.viewer.isDestroyed(), true);
assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer');
assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released');
assert.equal(document.getElementById('gev-credits'), null, 'credits gone');
});
test('the scene keeps the Earth framed where the renderer can', async (t) => {
const { renderer, deferred } = await startOnStub(t, {
capabilities: ['keepEarthFramed'],
});
assert.equal(renderer.camera.controls.keepEarthFramed, true);
const controls = renderer.camera.controls;
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown');
});
test("the scene takes a plugin's application hooks", async (t) => {
const stub = createStubRendererPlugin({ capabilities: [] });
const given = [];
const handles = Object.freeze({ probe: 'qa' });
const { scene } = await startOnStub(t, {
renderer: {
id: 'stub-with-hooks',
create: (options) => stub.create(options),
applicationHooks(made) {
given.push(made);
return { qaHandles: handles, ownCreditDisplay: true };
},
},
});
assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer');
assert.equal(scene.qaHandles, handles, 'QA scripts read its handles');
assert.equal(
document.getElementById('gev-credits'),
null,
'its own display shows the credits',
);
});
test('with credentials, the photoreal base loads through the globe port', async (t) => {
const { scene, renderer } = await startOnStub(t, {
capabilities: ['photoreal', 'globeVisibility'],
googleApiKey: 'stub-key',
});
assert.ok(scene.tileset, 'a photoreal base');
assert.equal(scene.mapStackController.getActiveId(), 'photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden');
const photoreal = renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === 'setPhotoreal',
);
assert.equal(photoreal[0]?.args[0]?.key, 'stub-key');
// A globe stack hides photoreal through the port, and shows the globe.
await scene.mapStackController.setStack('esri-imagery');
assert.equal(renderer.globe.isGlobeVisible(), true);
assert.equal(
renderer.testing.calls
.filter((call) => call.port === 'globe' && call.member === 'setPhotoreal')
.at(-1).args[0],
null,
);
await scene.mapStackController.setStack('photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false);
});
+3
View File
@@ -49,10 +49,13 @@ export const CATALOG_SOURCE_CONTRACTS = Object.freeze({
'air-quality': contract(['air-quality'], ['getSnapshot']),
'gnss-integrity': contract(['gnss-integrity'], ['getSnapshot']),
's2-ghostmaps': contract(['s2-ghostmaps'], ['getCatalog', 'getFile']),
shipwrecks: contract(['shipwrecks'], ['getSnapshot']),
'drone-airspace': contract(['drone-airspace'], ['getSnapshot']),
news: contract(['news'], ['getHotspots', 'getFeed', 'getOutline']),
'wildlife-sightings': contract(['wildlife-sightings'], ['getSnapshot']),
cables: contract(['telegeography-submarine-cables'], ['fetch']),
transit: contract(['transit'], ['requestSnapshot', 'getHistory']),
rail: contract(['rail'], ['requestSnapshot', 'getFeeds']),
});
/** An omitted provider is unavailable, never an authoritative empty dataset. */
+47 -1
View File
@@ -1,3 +1,5 @@
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
import '../render/cesium/input.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import {
@@ -37,7 +39,7 @@ test('every acquisition source can be omitted without losing catalog membership'
test('all acquisition sources may be absent, and enable fails before initializing or fetching', async (t) => {
const actual = catalog({}, t);
assert.equal(actual.layers.length, 38);
assert.equal(actual.layers.length, 41);
const manager = new LayerLifecycle(
{},
{ getSourceAvailability: actual.getSourceAvailability },
@@ -150,6 +152,35 @@ test('GhostMaps obeys source omission, replacement and explicit removal', async
assert.equal(fetches, 0);
});
test('News is unavailable without a source and the standalone default reads only same-origin /api/news', async (t) => {
const missing = catalog({}, t);
assert.equal(missing.getSourceAvailability('news')?.available, false);
const manager = new LayerLifecycle(
{},
{ getSourceAvailability: missing.getSourceAvailability },
);
manager.register(missing.get('news'));
assert.equal(await manager.setEnabled('news', true), false);
assert.equal(manager.layers.get('news').initialized, false);
assert.equal(createStandaloneLayerSources({ news: null }).news, null);
const urls = [];
t.mock.method(globalThis, 'fetch', async (url) => {
urls.push(url);
return new Response(
JSON.stringify({
error: 'news_not_configured',
unavailable: true,
retryable: false,
}),
{ status: 503 },
);
});
const standalone = createStandaloneLayerSources().news;
await assert.rejects(standalone.getHotspots(), { unavailable: true });
assert.deepEqual(urls, ['/api/news/hotspots']);
});
test('empty Street Level uses the shared unavailable lifecycle without initialization', async (t) => {
const actual = catalog({}, t);
const manager = new LayerLifecycle(
@@ -218,3 +249,18 @@ test('absent military acquisition does not poll, suppress flights, or erase supp
assert.equal(registry.isMilitaryLayerActive(), false);
assert.equal(fetches, 0);
});
test('a rail source must carry the feed catalog that keeps unbuilt packs out', () => {
// Without getFeeds the layer could never learn which schedule packs are
// built, so the live feeds that read their routes from one would never run.
assert.throws(
() =>
resolveCatalogSources({ rail: { requestSnapshot: async () => null } }),
/Invalid catalog source: rail/,
);
const source = {
requestSnapshot: async () => null,
getFeeds: async () => [],
};
assert.equal(resolveCatalogSources({ rail: source }).sources.rail, source);
});
+31 -15
View File
@@ -1,25 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { flyToAustin } from '../camera.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
test('teardown before the initial camera delay prevents a late flight', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let flights = 0;
let cancelled = 0;
const stop = flyToAustin({
function viewerRecording(views) {
return bindFakeCesiumCamera({
isDestroyed: () => false,
camera: {
setView() {},
flyTo() {
flights++;
setView(view) {
views.push(view);
},
cancelFlight() {
cancelled++;
flyTo() {
assert.fail('a start view is set, not flown to');
},
},
});
stop();
t.mock.timers.tick(1000);
assert.equal(flights, 0);
assert.equal(cancelled, 1);
}
test('the camera starts over the whole planet, looking straight down', () => {
const views = [];
applyStartView(viewerRecording(views));
assert.equal(views.length, 1);
assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view');
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9);
assert.equal(views[0].orientation.heading, 0);
});
test('a host can start the camera at a city instead', () => {
const views = [];
applyStartView(viewerRecording(views), {
lon: 2.35,
lat: 48.86,
height: 5000,
heading: 90,
pitch: -30,
});
assert.equal(views.length, 1);
assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9);
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9);
});
+176 -43
View File
@@ -1,12 +1,31 @@
import { onFollowChanged } from '../data/followed.js';
import {
bootStories,
stopVoiceForStories,
storiesOpener,
} from '../stories/boot.js';
import { t } from '../i18n/index.js';
import { useStoriesStore } from '../ui/stores/stories.js';
import { SceneDirector } from '../scenes/director.js';
import { initAnnotations } from '../annotations/index.js';
import { initDrawTool } from '../annotations/drawTool.js';
import {
claimPointer,
isPointerFree,
releasePointer,
} from '../data/inputOwnership.js';
import { initGeoFileImport } from '../ui/geoFileImport.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
import { createRecentImageryPanel } from '../ui/recentImagery.js';
import { createDataLibrary } from '../library/controller.js';
import { flyToLibraryExtent } from '../library/camera.js';
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
import { localGeoJsonServices } from './localGeojsonServices.js';
import { initGevVoiceCommands } from '../voice/gevRealtime.js';
import { isStoriesOpen } from '../voice/realtimeInputPolicy.js';
import { installViews, isEmbeddedInline } from './embed.js';
import {
installScopeMask,
@@ -14,17 +33,26 @@ import {
isScopeMaskEnabled,
} from '../scopeMask.js';
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
import { installGlobeInViewRecovery } from './viewer.js';
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
import {
installRenderGovernor,
getRenderGovernorDiagnostics,
governorRequestRender,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { entityRecord, readEntityRecord } from '../data/entityRecords.js';
import { overlayHost } from './layers/overlayHost.js';
/** Attach scene tools, rendering listeners and the application debug handle. */
/**
* Attach scene tools, rendering listeners and the application debug handle.
* `scene` is what `createApplicationScene` returns; its `trimStaleCommands`
* runs after each layer disable (a scene without one keeps that memory).
* `library.fetchTile` and `library.fetchData` fetch the Data Library's tiles
* and proxied datasets in place of the defaults (`createLibrarySource`).
* `library.requireCatalog` offers only what the server's library catalog
* names, and nothing while it does not answer.
*/
export function createApplicationTools({
scene,
controls,
@@ -35,14 +63,16 @@ export function createApplicationTools({
startChrome,
onSceneDirector,
sceneDataPacks,
drawMarkActions = [],
library = {},
signal,
defer,
}) {
const { viewer, tileset, mapStackController, operations } = scene;
const { viewer, renderer, tileset, mapStackController, operations } = scene;
const { styleManager, weatherEffects, cockpitCloudEffects } = controls;
const { dataManager } = data;
const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, {
dataPacks: sceneDataPacks,
dataPacks: { overlayHost, ...sceneDataPacks },
isMapStackAvailable: (id) =>
mapStackController?.isStackAvailable(id) === true,
});
@@ -59,6 +89,26 @@ export function createApplicationTools({
}),
);
onSceneDirector?.(sceneDirector);
// Stories: GEV scenes on this globe, from a Stories button. Its screens,
// styles, story data and controller load on first use.
const storiesStore = useStoriesStore(applicationPinia());
let voiceCommands;
const stories = bootStories({
// Inline in a host page, the URL and history are the host's.
available: !isEmbeddedInline(),
viewer,
director: sceneDirector,
store: storiesStore,
onEnter: () => {
if (stopVoiceForStories(voiceCommands?.session))
storiesStore.flashToast(t('Voice is disabled in Stories.'), 4000);
},
onLoadFailed: () =>
styleManager._showToast?.(
t('Stories could not load. Check the connection and try again.'),
),
});
defer(() => stories.destroy());
const annotations = initAnnotations({
viewer,
tileset,
@@ -80,12 +130,15 @@ export function createApplicationTools({
// while a session is open, so its teardown belongs to the application
// lifetime rather than to whoever last pressed the button. A row's fly-to
// goes through the shell's navigation policy, as Import's does.
// `drawMarkActions` are an application's own buttons on a drawn area's or
// line's row (annotations/drawMarks.js); the standalone shell adds none.
const drawTool = initDrawTool({
viewer,
annotations,
navigation: styleManager,
publish: (view) => displayStore.publishDraw(view),
connect: connectDisplay,
markActions: drawMarkActions,
});
defer(() => drawTool?.destroy());
// UTILITIES ▸ Import: the person's own GeoJSON/KML/KMZ/GPX files, each its
@@ -100,6 +153,56 @@ export function createApplicationTools({
connect: connectDisplay,
});
defer(() => geoFileImport?.destroy());
// DATA ▸ Library: entries register their layers only when a viewer adds
// them, after the core catalog is sealed. The browser dialog and the
// controller share the application lifetime.
const dataLibrary = createDataLibrary({
dataManager,
services: localGeoJsonServices,
getTileset: () => tileset,
mapStackController,
shareLink: styleManager.shareLinkManager,
requestRender: governorRequestRender,
// An application's own tile and dataset fetches, when it keeps them in
// its own cache.
fetchTile: library.fetchTile ?? null,
fetchData: library.fetchData ?? null,
requireCatalog: library.requireCatalog === true,
// Zoom to layer: an immediate navigation, so Cockpit can refuse it and
// the current follow owner is released first (as for imported files).
zoomTo: (extent) =>
styleManager.runImmediateNavigation('layer', () =>
flyToLibraryExtent(viewer, extent),
) !== false,
});
defer(() => dataLibrary.destroy());
// Browse: the owner presents the dialog through the store; LayerPanelsView
// draws the Browse button and the dialog from it.
const libraryStore = useDataLibraryStore(applicationPinia());
const libraryBrowser = createLibraryBrowser({
library: dataLibrary,
publish: (view) => libraryStore.publish(view),
});
libraryStore.connect(libraryBrowser.controls);
defer(() => {
libraryBrowser.destroy();
libraryStore.connect(null);
});
dataLibrary.start({ signal }).catch((error) => {
if (!signal?.aborted) console.warn('[Library] start failed:', error);
});
// The live gate's handle (scripts/qa-data-library.mjs).
const libraryHandle = {
library: dataLibrary,
browser: libraryBrowser,
// What Copy Link would copy.
buildShareLink: () => styleManager.shareLinkManager?.buildLink?.() ?? null,
};
window.__gevDataLibrary = libraryHandle;
defer(() => {
if (window.__gevDataLibrary === libraryHandle)
delete window.__gevDataLibrary;
});
// DATA ▸ Recent Imagery: the box tool claims the pointer like Draw and the
// panel lives on the right rail, so both belong to the application
// lifetime. The tileset lets the layer drape while the globe is hidden.
@@ -139,19 +242,21 @@ export function createApplicationTools({
}
if (startChrome)
defer(startChrome({ loadingScreen, styleManager, dataManager, signal }));
// Idle render governor: flips the scene into requestRenderMode whenever
// nothing animates per frame. Installed AFTER every module above has had
// its chance to register pre-install holds. (perf wave 2)
installRenderGovernor(viewer);
// Cesium keeps a turned-off layer's draw commands (and so all its entities)
// alive in reused per-pass arrays; trim them after each disable.
defer(
installLayerReleaseTrim({
scene: viewer.scene,
dataManager,
requestRender: governorRequestRender,
}),
);
// Idle render governor: the loop draws on demand whenever nothing animates
// per frame. It goes idle only now, after every module above has had its
// chance to hold. (perf wave 2)
releaseContinuousRender('boot');
// The renderer may keep a turned-off layer's draw commands (and so all its
// entities) alive; trim them after each disable.
if (scene.trimStaleCommands)
defer(
installLayerReleaseTrim({
frame: renderer.frame,
dataManager,
requestRender: governorRequestRender,
trim: scene.trimStaleCommands,
}),
);
// Install the explicit scope mask used by the DISPLAY controls.
installScopeMask(viewer);
@@ -159,12 +264,10 @@ export function createApplicationTools({
// The follow camera recomputes the tracked target's dead-reckon position
// every frame — tracking anything is a per-frame animation. (perf wave 2)
const removeTrackingListener = viewer.trackedEntityChanged.addEventListener(
() => {
if (viewer.trackedEntity) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
},
);
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
if (followed) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
});
// Hidden-state suspension (perf wave 2): when the window/tab is hidden,
// stop the default render loop outright — a hidden canvas repaints for
@@ -173,9 +276,9 @@ export function createApplicationTools({
// the loop, refresh the one DOM surface we gated, render a frame.
const syncVisibilitySuspension = () => {
// A panel's host may report it hidden while it is on screen; the panel
// keeps drawing itself (see keepPanelRendering in embed.js).
// keeps drawing itself (see keepPanelRendering in app/panelRendering.js).
const hidden = document.hidden && !isEmbeddedInline();
viewer.useDefaultRenderLoop = !hidden;
renderer.frame.suspend(hidden);
cockpitCloudEffects?.setSuspended?.(hidden);
if (!hidden) {
data.presentation.flushVisible();
@@ -195,26 +298,40 @@ export function createApplicationTools({
// loop burning behind a hidden tab. (perf wave 2 fix)
syncVisibilitySuspension();
window.__godsEyeView = {
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
};
window.__godsEyeView = Object.defineProperties(
{
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
},
// What the renderer's plugin lets QA scripts read (the Cesium viewer and
// its photoreal tileset, for the default renderer), in place of the
// scene's objects above; read as they are when asked.
Object.getOwnPropertyDescriptors(scene.qaHandles ?? {}),
);
const debug = window.__godsEyeView;
defer(() => {
if (window.__godsEyeView === debug) delete window.__godsEyeView;
});
const voiceCommands = initGevVoiceCommands({
voiceCommands = initGevVoiceCommands({
...voice,
canStartVoice: () => !isStoriesOpen(),
// An app may supply what open_stories does; the Stories page by default.
openStories: storiesOpener({
openStories: voice?.openStories,
store: storiesStore,
stories,
}),
floorServices: operations.surface.groundFloor,
annotationResolver: operations.annotationResolver,
searchNavigation: operations.searchAndFlyTo,
@@ -237,9 +354,25 @@ export function createApplicationTools({
shell: styleManager,
viewer,
dataManager,
run: (name, args) => voiceCommands.runner(name, args, { signal }),
run: (name, args, options = {}) =>
voiceCommands.runner(name, args, { ...options, signal }),
signal,
keepRendering: scene.keepPanelRendering,
terrain: operations.requests.terrain,
}),
);
return { sceneDirector, annotations, voiceCommands };
// Any other tool takes the pointer as Draw does (the newest
// claim takes over; `claim(owner, {onLost})` tells the tool it replaces),
// and its own click handlers yield while a tool holds it, as the layers' do
// (data/inputOwnership.js).
return {
sceneDirector,
annotations,
voiceCommands,
pointer: {
claim: claimPointer,
release: releasePointer,
isFree: isPointerFree,
},
};
}
-389
View File
@@ -1,389 +0,0 @@
import * as Cesium from 'cesium';
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js';
import { StarrySky } from '../sky/starrySky.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeOutOfFrame,
isFreeGlobeCamera,
} from '../globeInView.js';
const PINCH_ZOOM_MULTIPLIER = 8;
const MAX_PINCH_PIXEL_DELTA = 120;
function boundedPinchDelta(delta) {
if (!Number.isFinite(delta) || delta === 0) return delta;
return (
Math.sign(delta) *
Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA)
);
}
/**
* Add browser trackpad pinch to Cesium's zoom inputs and return its disposer.
* Browsers expose this gesture as a small pixel-mode Ctrl+wheel event.
*/
export function installTrackpadPinchZoom(
viewer,
{ createWheelEvent = (type, init) => new WheelEvent(type, init) } = {},
) {
const controller = viewer?.scene?.screenSpaceCameraController;
const container = viewer?.container;
const canvas = viewer?.canvas;
if (!controller || !container || !canvas)
throw new TypeError('A complete Cesium viewer is required');
const originalZoomEventTypes = controller.zoomEventTypes;
const zoomEventTypes = Array.isArray(originalZoomEventTypes)
? originalZoomEventTypes
: originalZoomEventTypes === undefined
? []
: [originalZoomEventTypes];
const alreadyHandlesControlWheel = zoomEventTypes.some(
(binding) =>
binding?.eventType === Cesium.CameraEventType.WHEEL &&
binding?.modifier === Cesium.KeyboardEventModifier.CTRL,
);
const configuredZoomEventTypes = alreadyHandlesControlWheel
? originalZoomEventTypes
: [
...zoomEventTypes,
{
eventType: Cesium.CameraEventType.WHEEL,
modifier: Cesium.KeyboardEventModifier.CTRL,
},
];
if (!alreadyHandlesControlWheel)
controller.zoomEventTypes = configuredZoomEventTypes;
const relayedEvents = new WeakSet();
const relayPinch = (event) => {
if (
!event.ctrlKey ||
relayedEvents.has(event) ||
event.deltaMode !== 0 ||
!Number.isFinite(event.deltaY) ||
event.deltaY === 0
)
return;
let relayed;
try {
relayed = createWheelEvent('wheel', {
deltaX: event.deltaX,
deltaY: boundedPinchDelta(event.deltaY),
deltaZ: event.deltaZ,
deltaMode: event.deltaMode,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: true,
bubbles: true,
cancelable: true,
view: globalThis.window,
});
} catch {
// The registered Ctrl+wheel binding can still consume the original.
return;
}
relayedEvents.add(relayed);
event.preventDefault();
event.stopPropagation();
canvas.dispatchEvent(relayed);
};
container.addEventListener('wheel', relayPinch, {
capture: true,
passive: false,
});
let active = true;
return () => {
if (!active) return;
active = false;
container.removeEventListener('wheel', relayPinch, true);
if (
!alreadyHandlesControlWheel &&
controller.zoomEventTypes === configuredZoomEventTypes
)
controller.zoomEventTypes = originalZoomEventTypes;
};
}
/**
* Allow Cesium's free look only below `maxHeight` and return its disposer.
* Orbit, tilt and zoom stay available at every height. A value other code
* sets later is kept as the one to allow below that height, and restored on
* dispose; a `false` written while the camera is above `maxHeight` cannot be
* told apart from this limit's own write, so dispose restores the earlier
* value then. `enableLook` gates the Shift+drag binding only: below its trackball
* height Cesium also turns the camera in place for a drag that starts on the
* stars. That height is lowered to `maxHeight` too, so above it such a drag
* orbits the globe, as it does above Cesium's own 7,500 km.
*/
export function installFreeLookHeightLimit(
viewer,
maxHeight = FREE_LOOK_MAX_HEIGHT_METERS,
) {
const scene = viewer?.scene;
const controller = scene?.screenSpaceCameraController;
const camera = viewer?.camera;
if (!controller || !camera || !scene?.preUpdate)
throw new TypeError('A complete Cesium viewer is required');
const originalTrackBallHeight = controller.minimumTrackBallHeight;
const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight);
controller.minimumTrackBallHeight = trackBallHeight;
let wanted = controller.enableLook;
let written;
const sync = () => {
if (written !== undefined && controller.enableLook !== written)
wanted = controller.enableLook;
const height = camera.positionCartographic?.height;
written = wanted && !(Number.isFinite(height) && height > maxHeight);
controller.enableLook = written;
};
sync();
const removeListener = scene.preUpdate.addEventListener(sync);
let active = true;
return () => {
if (!active) return;
active = false;
removeListener();
if (controller.enableLook === written) controller.enableLook = wanted;
if (controller.minimumTrackBallHeight === trackBallHeight)
controller.minimumTrackBallHeight = originalTrackBallHeight;
};
}
// How often a moving camera is sampled to see whether it has come to rest, how
// far a pose may drift between samples and still count as at rest, and how
// long after the camera last moved the check gives up if Cesium never raises
// moveEnd.
const SETTLE_SAMPLE_MS = 250;
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
const SETTLE_GIVE_UP_MS = 5 * 60_000;
/**
* Turn the camera back to the planet when a move ends above `minHeight` with
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
* one sample cell thick can count as none), and return the disposer. Views with
* more surface, such as an oblique orbital shot, are left as they are. This
* catches a saved or shared view that looked away, or any other move that ends
* looking away from the planet.
* Heading and position are kept. Tracked cameras, locked ones (non-identity
* transform), a camera flight in progress, a pointer held down on the canvas
* (a drag held still), the 2D and Columbus modes, and any time `paused`
* returns true (an authored scene playing) are left alone; a check they defer
* runs once they end, however long they last.
* `keyholeRadius`
* returns the radius of the visible circle when a scope mask hides the rest of
* the frame (see `globeFrameShare`), or 0; it is read at every check.
*
* Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the
* last frame's to the last rounding error, and at some of these poses the
* camera drifts by a rounding error every frame, so Cesium never sees it stop.
* So each `moveStart` also starts a check of its own that samples the pose
* every 250 ms, with a tolerance for that drift, and once the pose has held
* for half a second after moving runs the same recovery. It keeps watching
* until Cesium raises `moveEnd`, since under that drift Cesium raises no new
* `moveStart` for a later move, and gives up five minutes after the camera
* last moved.
* `setTimeout` and `clearTimeout` can be injected for tests.
*/
export function installGlobeInViewRecovery(
viewer,
{
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
keyholeRadius = () => 0,
paused = () => false,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
} = {},
) {
const scene = viewer?.scene;
const camera = viewer?.camera;
if (!scene || !camera?.moveEnd || !camera?.moveStart)
throw new TypeError('A complete Cesium viewer is required');
// A pointer held on the globe is a gesture in progress, even when it holds
// still for half a second: the check waits until every pointer pressed on
// it (each finger of a pinch) is released. A release the page never sees,
// outside the window, is taken as given when the window loses focus, the
// page is hidden, the canvas loses the pointer's capture, or the pointer
// moves with no button down.
const canvas = scene.canvas;
const releaseTarget = canvas?.ownerDocument ?? canvas;
const releaseWindow = canvas?.ownerDocument?.defaultView;
const heldPointers = new Set();
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
const onPointerMove = (event) => {
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
};
const releaseAll = () => heldPointers.clear();
const onVisibilityChange = () => {
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
};
const listeners = [
[canvas, 'pointerdown', onPointerDown],
[canvas, 'lostpointercapture', onPointerUp],
[releaseTarget, 'pointerup', onPointerUp],
[releaseTarget, 'pointercancel', onPointerUp],
[releaseTarget, 'pointermove', onPointerMove],
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
[releaseWindow, 'blur', releaseAll],
];
for (const [target, type, listener] of listeners)
target?.addEventListener?.(type, listener);
// Returns false while a flight, a paused scene or a held pointer defers the
// check, so the caller can try again once it ends.
const recover = () => {
if (!isFreeGlobeCamera(viewer)) return true;
// Cesium has no public running-flight flag.
if (camera._currentFlight || paused() || heldPointers.size > 0)
return false;
const height = camera.positionCartographic?.height;
if (
!(height > minHeight) ||
!globeOutOfFrame(camera, { keyholeRadius: keyholeRadius() })
)
return true;
camera.setView({
orientation: {
heading: camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
},
});
scene.requestRender?.();
return true;
};
const lastPosition = new Cesium.Cartesian3();
const lastDirection = new Cesium.Cartesian3();
let settleTimer = null;
let settleElapsed = 0;
let restingSamples = 0;
let movedSinceCheck = false;
const stopSettling = () => {
if (settleTimer !== null) unschedule(settleTimer);
settleTimer = null;
};
const sample = () => {
settleTimer = null;
settleElapsed += SETTLE_SAMPLE_MS;
const atRest =
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
lastPosition,
0,
SETTLE_POSITION_TOLERANCE_M,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastDirection,
0,
SETTLE_DIRECTION_TOLERANCE,
);
restingSamples = atRest ? restingSamples + 1 : 0;
if (!atRest) {
movedSinceCheck = true;
settleElapsed = 0;
}
// Two quiet samples in a row after a move: at rest for half a second, as
// for moveEnd.
if (restingSamples >= 2 && movedSinceCheck) {
if (recover()) movedSinceCheck = false;
// A flight or a playing scene bounds its own deferral.
else settleElapsed = 0;
}
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const startSettling = () => {
stopSettling();
settleElapsed = 0;
restingSamples = 0;
movedSinceCheck = true;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const removeMoveEnd = camera.moveEnd.addEventListener(() => {
if (recover()) stopSettling();
// Deferred: keep sampling so the check runs once the flight or scene ends.
else if (settleTimer === null) startSettling();
});
const removeMoveStart = camera.moveStart.addEventListener(startSettling);
let active = true;
return () => {
if (!active) return;
active = false;
stopSettling();
removeMoveEnd();
removeMoveStart();
for (const [target, type, listener] of listeners)
target?.removeEventListener?.(type, listener);
heldPointers.clear();
};
}
/** Cesium.Viewer options of the standard globe viewer. */
export function applicationViewerOptions(creditContainer) {
return {
timeline: false,
animation: false,
baseLayerPicker: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
navigationHelpButton: false,
fullscreenButton: false,
vrButton: false,
selectionIndicator: false,
infoBox: false,
baseLayer: false,
// Replaces the blocky Tycho-2 default. An option, not `skyBox: false`,
// which would also stop CesiumWidget from creating the Sun and Moon.
skyBox: new StarrySky(),
creditContainer,
msaaSamples: 4,
contextOptions: { webgl: { preserveDrawingBuffer: true } },
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
export function createApplicationViewer({ container, creditContainer }) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer),
);
try {
viewer.targetFrameRate = 60;
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
// Keep Cesium's distance-aware zoom and collision limits, with less travel
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
// Before any tile builds a draw command: Cesium's per-vertex model
// atmosphere fails to LINK on Apple's Metal backend and kills the
// render loop. See app/atmosphereCompat.js.
applyModelAtmosphereWorkaround(viewer.scene);
viewer.scene.globe.show = false;
viewer.scene.skyAtmosphere.show = true;
viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18;
viewer.scene.skyAtmosphere.saturationShift = -0.12;
viewer.scene.skyAtmosphere.brightnessShift = -0.08;
return viewer;
} catch (error) {
viewer.destroy();
throw error;
}
}
+7 -10
View File
@@ -6,11 +6,12 @@
* awareness policy of its own: the publisher passes radius, pulse timing and
* echo styling in, so the overlay never imports awareness internals.
*/
import * as Cesium from 'cesium';
import { scaleToGeodeticSurface } from './geo/ellipsoid.js';
import { distance } from './geo/vector.js';
/**
* @typedef {object} AwarenessEchoField
* @property {Cesium.Cartesian3} center Subject's ground point. The publisher
* @property {{x: number, y: number, z: number}} center Subject's ground point. The publisher
* may move it in place; it is read on every query.
* @property {number} radiusM Range the pulses grow to.
* @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse
@@ -22,7 +23,6 @@ import * as Cesium from 'cesium';
/** @type {AwarenessEchoField|null} */
let field = null;
let layerIds = new Set();
const groundScratch = new Cesium.Cartesian3();
/**
* Start (or replace) the echo field.
@@ -104,7 +104,7 @@ export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) {
* field is set or the layer does not echo. Distance is measured between
* ground points, so an aircraft's altitude does not shift its echo.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
@@ -112,16 +112,13 @@ export function awarenessEchoAt(layerId, position, nowMs) {
if (!field || !position || !layerIds.has(layerId)) return 0;
const level = field.level?.(nowMs) ?? 1;
if (!(level > 0)) return 0;
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(
position,
groundScratch,
);
const ground = scaleToGeodeticSurface(position);
if (!ground) return 0;
return (
level *
awarenessEchoStrength(
nowMs,
Cesium.Cartesian3.distance(field.center, ground),
distance(field.center, ground),
field.radiusM,
field.pulse,
field.echo,
@@ -138,7 +135,7 @@ export function awarenessEchoAt(layerId, position, nowMs) {
* outside the contact's bracket, 0 as the front arrives, growing to the
* field's `spreadPx` as it fades.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1.
* @param {number} steps Alpha bands the overlay batches by.
+22 -29
View File
@@ -1,36 +1,29 @@
import * as Cesium from 'cesium';
import { toRadians } from './geo/index.js';
import { cameraOf } from './render/rendererOf.js';
/**
* Set camera to Austin on load with a cinematic fly-in.
* @returns {Function} Cancels the pending or active startup flight.
* The view the renderer starts from: the whole planet, looking straight
* down, centred where Cesium's default view rectangle is.
*/
export function flyToAustin(viewer) {
// Start from a high altitude, then fly down
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 25000),
export const START_VIEW = Object.freeze({
lon: -82.5,
lat: 35,
height: 23000000,
});
/**
* Put the camera at a start view without a flight. A host may pass a city
* (`{ lon, lat, height, heading?, pitch? }`, angles in degrees) instead of
* the planet.
*/
export function applyStartView(viewer, view = START_VIEW) {
const { lon, lat, height, heading = 0, pitch = -90 } = view;
cameraOf(viewer).setView({
destination: { lon, lat, height },
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-90),
roll: 0.0,
heading: toRadians(heading),
pitch: toRadians(pitch),
roll: 0,
},
});
// Cinematic fly-in after a brief pause
const timer = setTimeout(() => {
if (viewer.isDestroyed()) return;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600),
orientation: {
heading: Cesium.Math.toRadians(15),
pitch: Cesium.Math.toRadians(-30),
roll: 0.0,
},
duration: 4.0,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
}, 500);
return () => {
clearTimeout(timer);
if (!viewer.isDestroyed()) viewer.camera.cancelFlight();
};
}
+103 -161
View File
@@ -1,3 +1,14 @@
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { followedOf } from './data/followed.js';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
import { GLOBE_VIEW } from './locations.js';
import { projectEarthDiscToViewport } from './celestialRing.js';
import assert from 'node:assert/strict';
@@ -13,11 +24,24 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { getRenderGovernorDiagnostics } from './renderGovernor.js';
import {
MIN_GLOBE_FRAME_SHARE,
globeFrameShare,
globeOutOfFrame,
} from './globeInView.js';
import { MIN_GLOBE_FRAME_SHARE } from './globeInView.js';
import * as globeInView from './globeInView.js';
// The frame measures take a camera pose; these read it off the real camera.
const framePose = (camera) => ({
position: camera.positionWC,
direction: camera.directionWC,
up: camera.upWC,
right: camera.rightWC,
fovy: camera.frustum.fovy,
aspectRatio: camera.frustum.aspectRatio,
height: camera.positionCartographic.height,
pitch: camera.pitch,
});
const globeFrameShare = (camera, options) =>
globeInView.globeFrameShare(framePose(camera), options);
const globeOutOfFrame = (camera, options) =>
globeInView.globeOutOfFrame(framePose(camera), options);
import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js';
import { setScopeMaskEnabled } from './scopeMask.js';
@@ -136,7 +160,7 @@ function harness(
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -154,13 +178,37 @@ function harness(
roll: radians(roll),
},
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
clock: { onTick: new Cesium.Event() },
entities: {},
};
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// Count who listens for the port's follow changes.
const renderer = rendererOf(viewer);
const port = renderer.camera;
let followListeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
followListeners += 1;
let live = true;
return () => {
if (live) followListeners -= 1;
live = false;
off();
};
},
},
});
const target = Cesium.Cartesian3.fromDegrees(
longitudeDeg,
latitude,
@@ -174,73 +222,21 @@ function harness(
});
const tick = (seconds = 0.1) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finishOnce = () => {
for (let i = 0; i < 20 && getActiveCameraMotion(); i += 1) tick();
assert.equal(getActiveCameraMotion(), null, 'once motion must finish');
};
return { viewer, camera, canvas, target, tick, finishOnce };
}
for (const [name, sceneMode] of [
['2D', Cesium.SceneMode.SCENE2D],
['Columbus', Cesium.SceneMode.COLUMBUS_VIEW],
['morphing', Cesium.SceneMode.MORPHING],
]) {
test(`globe rotation refuses ${name} before changing the prior owner`, (t) => {
const { viewer, camera } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate', direction: 'right', mode: 'continuous' })
.ok,
true,
);
const priorId = activeCameraMotionId();
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
viewer.scene.mode = sceneMode;
let handoffs = 0;
let cancellations = 0;
camera.cancelFlight = () => {
cancellations += 1;
};
for (const mode of ['once', 'continuous']) {
const result = moveCamera(
{ motion: 'rotate_globe', direction: 'left', mode },
() => {
handoffs += 1;
return { ok: true };
},
);
assert.equal(result.ok, false);
assert.match(result.error, /3D/);
}
assert.equal(handoffs, 0);
assert.equal(cancellations, 0);
assert.equal(activeCameraMotionId(), priorId);
assert.equal(hasRenderHold(), true);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform));
samePose(camera, before);
});
test(`active globe rotation yields to ${name} without changing the camera`, (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
viewer.scene.mode = sceneMode;
const before = pose(camera);
let rotations = 0;
camera.rotate = () => {
rotations += 1;
};
tick();
assert.equal(rotations, 0);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
return {
viewer,
camera,
canvas,
target,
tick,
finishOnce,
followListeners: () => followListeners,
};
}
test('globe rotation yields to tracking acquired and cleared before the next tick', (t) => {
@@ -251,15 +247,13 @@ test('globe rotation yields to tracking acquired and cleared before the next tic
);
const before = pose(camera);
const entity = { id: 'cockpit-aircraft', position: {} };
viewer.trackedEntity = entity;
viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(viewer, entity);
assert.equal(
getActiveCameraMotion(),
null,
'tracking acquisition must synchronously yield',
);
viewer.trackedEntity = undefined;
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
tick();
samePose(camera, before);
assert.equal(hasRenderHold(), false);
@@ -272,33 +266,34 @@ test('tracking event keeps legacy yaw and an untracked globe rotation active', (
true,
);
const yawId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent({ id: 'aircraft' });
followEntity(viewer, { id: 'aircraft' });
assert.equal(activeCameraMotionId(), yawId);
followEntity(viewer, null);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const globeId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
assert.equal(activeCameraMotionId(), globeId);
});
test('replaced viewer releases the old tracking listener without duplicate subscriptions', (t) => {
const first = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
initCameraVerbs(first.viewer);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
const next = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 0);
assert.equal(next.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 0);
assert.equal(next.followListeners(), 1);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const id = activeCameraMotionId();
first.viewer.trackedEntityChanged.raiseEvent({ id: 'stale-aircraft' });
followEntity(first.viewer, { id: 'stale-aircraft' });
assert.equal(activeCameraMotionId(), id);
next.viewer.trackedEntityChanged.raiseEvent({ id: 'new-aircraft' });
followEntity(next.viewer, { id: 'new-aircraft' });
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
});
@@ -534,7 +529,7 @@ test('replacement motion rejects a stale globe owner cancellation', (t) => {
assert.equal(hasRenderHold(), false);
});
test('replacing the viewer retires globe motion and its old clock listener', (t) => {
test('replacing the viewer retires globe motion and its old frame listener', (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
@@ -542,15 +537,16 @@ test('replacing the viewer retires globe motion and its old clock listener', (t)
);
tick();
const before = pose(camera);
const nextViewer = {
...viewer,
clock: { onTick: new Cesium.Event() },
};
const nextScene = { ...viewer.scene, preUpdate: new Cesium.Event() };
const nextViewer = bindFakeCesiumCamera(
{ ...viewer, scene: nextScene },
{ frame: fakeSceneFrame({ scene: nextScene }) },
);
initCameraVerbs(nextViewer);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
tick();
nextViewer.clock.onTick.raiseEvent(nextViewer.clock);
nextScene.preUpdate.raiseEvent(nextScene);
samePose(camera, before);
});
@@ -580,7 +576,7 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(hasRenderHold(), true);
const tracked = { id: 'new-tracked-aircraft' };
if (acquisition === 'tracking') viewer.trackedEntity = tracked;
if (acquisition === 'tracking') followEntity(viewer, tracked);
else
camera.lookAt(
target,
@@ -591,10 +587,9 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
assert.equal(
viewer.trackedEntity,
acquisition === 'tracking' ? tracked : undefined,
);
if (acquisition === 'tracking')
assert.equal(followedEntity(viewer), tracked);
else assert.equal(followedOf(viewer), null);
assert.equal(Cesium.Matrix4.equals(camera.transform, transform), true);
samePose(camera, before);
tick();
@@ -605,7 +600,7 @@ for (const mode of ['once', 'continuous']) {
test('direct globe rotation refuses a tracked camera without disturbing its reference frame', (t) => {
const { viewer, camera, target } = harness(t);
viewer.trackedEntity = { id: 'tracked-aircraft' };
followEntity(viewer, { id: 'tracked-aircraft', name: 'tracked-aircraft' });
camera.lookAt(target, new Cesium.HeadingPitchRange(0, radians(-40), 1_000));
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
@@ -676,18 +671,19 @@ test('close-up refusal preserves an inherited target frame', (t) => {
});
test('navigation callback never releases tracking for globe rotation', (t) => {
const { viewer, camera } = harness(t);
const tracked = (viewer.trackedEntity = { id: 'tracked-aircraft' });
const tracked = { id: 'tracked-aircraft' };
followEntity(viewer, tracked);
const before = pose(camera);
let calls = 0;
assert.equal(
moveCamera({ motion: 'rotate_globe' }, () => {
calls++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
}).ok,
false,
);
assert.equal(calls, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
});
test('direct globe request refuses Cockpit before navigation mutation', (t) => {
@@ -878,8 +874,8 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
height: owner === 'close-up' ? 5000 : GLOBE_VIEW.heightM,
});
const before = pose(camera);
if (owner === 'tracking') viewer.trackedEntity = { id: 'tracked-aircraft' };
const tracked = viewer.trackedEntity;
if (owner === 'tracking') followEntity(viewer, { id: 'tracked-aircraft' });
const tracked = followedEntity(viewer);
let releases = 0,
stamps = 0;
const styleManager = {
@@ -893,7 +889,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
},
release() {
releases++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
},
navigate,
});
@@ -915,7 +911,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
assert.equal(result.ok, false);
assert.equal(releases, 0);
assert.equal(stamps, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
if (owner === 'close-up') {
assert.equal(result.reason, 'globe-view-required');
@@ -926,29 +922,6 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
}
});
for (const [label, ellipsoid] of [
['nonfinite radii', { minimumRadius: 1, maximumRadius: Infinity }],
['nonpositive radii', { minimumRadius: 0, maximumRadius: 1 }],
['non-WGS84 radii', new Cesium.Ellipsoid(30_000_000, 30_000_000, 1_000_000)],
])
test(`globe rotation refuses ${label} before handoff`, (t) => {
const { viewer, camera } = harness(t, { height: 100_000_000 });
const before = pose(camera);
viewer.scene.globe.ellipsoid = ellipsoid;
let handedOff = false;
const result = moveCamera({ motion: 'rotate_globe' }, () => {
handedOff = true;
});
assert.equal(result.ok, false);
assert.equal(
result.reason,
label === 'non-WGS84 radii' ? 'unsupported-view' : 'unsafe-ellipsoid',
);
assert.equal(handedOff, false);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
test('an external radius change retires globe rotation without another write', (t) => {
const { camera, tick } = harness(t);
moveCamera({ motion: 'rotate_globe', mode: 'continuous' });
@@ -960,16 +933,6 @@ test('an external radius change retires globe rotation without another write', (
samePose(camera, changed);
});
test('a non-WGS84 ellipsoid fails closed rather than borrowing the WGS84 silhouette', (t) => {
const ellipsoid = new Cesium.Ellipsoid(10_000_000, 10_000_000, 8_000_000);
const { camera } = harness(t, { ellipsoid, latitude: 60 });
const before = pose(camera);
const result = moveCamera({ motion: 'rotate_globe' });
assert.equal(result.ok, false);
assert.equal(result.reason, 'unsupported-view');
samePose(camera, before);
});
test('untouched polar framing permits repeated direction and speed changes below preset altitude', (t) => {
const { camera, finishOnce, tick } = harness(t, { latitude: 90 });
const radius = Cesium.Cartesian3.magnitude(camera.positionWC);
@@ -1874,7 +1837,7 @@ test('a voice turn reported as done turns at least the half degree its check pro
/** Track an entity below `camera`, locking it into that entity's frame. */
function trackFrom(viewer, camera) {
viewer.trackedEntity = { id: 'high-satellite' };
followEntity(viewer, { id: 'high-satellite' });
const below = Cesium.Cartesian3.fromDegrees(10, 20, 400_000);
camera.lookAtTransform(Cesium.Transforms.eastNorthUpToFixedFrame(below));
}
@@ -1900,7 +1863,7 @@ test('a voice turn that releases a tracked camera is checked as released', (t) =
});
trackFrom(viewer, camera);
const releaseThenRun = (start) => {
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
};
@@ -1941,14 +1904,14 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
for (let j = 0; j < 600 && getActiveCameraMotion(); j += 1) tick(1 / 60);
}
trackFrom(viewer, camera);
const tracked = viewer.trackedEntity;
const tracked = followedEntity(viewer);
const transform = Cesium.Matrix4.clone(camera.transform);
let released = false;
const result = moveCamera(
{ motion: 'tilt', direction: 'up', mode: 'once' },
(start) => {
released = true;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
},
@@ -1957,7 +1920,7 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
assert.equal(result.ok, false, label);
assert.match(result.error, /globe out of view/, label);
assert.equal(released, false, label);
assert.equal(viewer.trackedEntity, tracked, label);
assert.equal(followedEntity(viewer), tracked, label);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform), label);
}
});
@@ -1988,27 +1951,6 @@ test('a turn proven at one position is checked again after a release moves the c
assert.match(result.error, /globe out of view/);
});
test('the voice frame limit leaves Columbus view alone', (t) => {
// At its limit in 3D a further tilt up is refused; the same tilt in Columbus
// view is not limited by the frame.
withScope(t, false);
const { viewer, finishOnce } = harness(t, {
pitch: -80,
viewportWidth: 1600,
viewportHeight: 900,
});
assert.equal(
moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }).ok,
true,
);
finishOnce();
const refused = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.match(refused.error || '', /globe out of view/);
viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.doesNotMatch(result.error || '', /globe out of view/);
});
test('voice tilt below the free-look height is not limited by the frame', (t) => {
const { camera, finishOnce } = harness(t, { height: 500_000, pitch: -60 });
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
+96 -75
View File
@@ -14,8 +14,11 @@
* lifts the eye if it sits below a usable clearance. Heading and pitch are
* held, so the correction reads as the shot settling.
*/
import * as Cesium from 'cesium';
import { onFollowChanged } from './data/followed.js';
import { ownCameraArrival } from './data/cameraArrival.js';
import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js';
import { heightsOf } from './queries/heights.js';
import { canvasOf, findCamera } from './render/rendererOf.js';
/** Minimum eye height above the rendered surface for a usable view. */
export const MIN_EYE_CLEARANCE_M = 120;
@@ -24,35 +27,79 @@ const GUARD_ATTEMPTS = 8;
const GUARD_INTERVAL_MS = 600;
/** Ignore sub-metre noise rather than nudging the camera forever. */
const GUARD_EPSILON_M = 2;
const probeScratch = new Cesium.Cartographic();
/** Eye travel (m) and turn (cosine) that mean another owner moved the camera. */
const MOVED_M = 0.01;
const TURNED_COS = 1 - 1e-9;
/**
* Highest rendered surface across a few cells, with how many cells answered.
* A cell whose tiles are not streamed yet contributes nothing.
* @param {Cesium.Scene} scene Live scene.
* @param {import('./queries/heights.js').HeightService|null} heights The
* scene's height service.
* @param {Array<{lat: number, lon: number}>} cells Cells to probe.
* @returns {{heightM: number, sampled: number}} Reading.
*/
function sampleSurfaceM(scene, cells) {
function sampleSurfaceM(heights, cells) {
let heightM = Number.NaN;
let sampled = 0;
if (typeof scene?.sampleHeight !== 'function') return { heightM, sampled };
if (!heights) return { heightM, sampled };
for (const cell of cells) {
try {
const height = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch),
);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
} catch {
/* tiles not ready for this cell */
}
// A miss is a cell whose tiles are not ready.
const height = heights.now(cell);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
}
return { heightM, sampled };
}
/**
* The eye as the camera port poses it: where it is (from its position) and
* which way it looks; null when the pose cannot be read.
*/
function eyeOf(camera) {
try {
const pose = camera?.pose();
const at = pose?.position && toLonLatH(pose.position);
if (!at || !pose.direction || !pose.up) return null;
return { ...pose, lon: at.lon, lat: at.lat, height: at.height };
} catch {
return null;
}
}
/** The eye's ground point (height 0), its height, and which way it looks. */
function poseOf(eye) {
if (!eye) return null;
return {
ground: fromDegrees(eye.lon, eye.lat),
height: eye.height,
direction: { ...eye.direction },
up: { ...eye.up },
};
}
/**
* Whether another owner has moved the camera off `pose`: across the ground,
* down, or around. A pure rise is not one: the renderer's terrain collision
* lifts a buried eye straight up as tiles load, which is the case the guard
* exists for, so `pose` follows the highest eye seen and the guard keeps
* measuring.
*/
function moved(now, pose) {
if (!now) return true;
const ground = fromDegrees(now.lon, now.lat);
if (
distance(ground, pose.ground) > MOVED_M ||
now.height < pose.height - MOVED_M ||
dot(now.direction, pose.direction) < TURNED_COS ||
dot(now.up, pose.up) < TURNED_COS
)
return true;
pose.height = Math.max(pose.height, now.height);
return false;
}
/**
* How far the camera must rise to clear the ground, given a measured surface.
* Pure so the policy is testable without a scene.
@@ -76,9 +123,11 @@ export function groundClearanceDeficitM(
* Watch an arrival and lift the camera once the real surface can be measured.
*
* Stops quietly on a clear view, exhausted attempts, the user taking the
* controls (pointer or wheel on the canvas), or `isStale()` reporting that a
* newer arrival owns the camera.
* @param {Cesium.Viewer} viewer Live viewer.
* controls (pointer or wheel on the canvas), `isStale()` reporting that a
* newer arrival owns the camera, or any other caller moving the camera or
* starting a flight in the meantime: the guard only ever corrects the pose it
* was started on.
* @param {object} viewer Live viewer.
* @param {{lat: number, lon: number}} at Destination being framed.
* @param {{clearanceM?: number, attempts?: number, intervalMs?: number,
* isStale?: () => boolean, onLift?: (liftM: number) => void}} [options]
@@ -92,12 +141,16 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
isStale = () => false,
onLift = null,
} = options;
if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return () => {};
// Without a readable pose the guard could not tell a later owner's move.
const arrival = poseOf(eyeOf(findCamera(viewer)));
if (!arrival) return () => {};
let timer = null;
let done = false;
const canvas = viewer.scene.canvas;
const canvas = canvasOf(viewer);
const documentRef = canvas?.ownerDocument;
const removers = [];
let release = () => {};
@@ -112,32 +165,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
release();
};
release = ownCameraArrival(viewer, stop);
// Direct camera API callers (including duration-zero flights) must yield
// before moving the eye. Restore the exact method ownership on completion.
for (const name of [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
]) {
const camera = viewer.camera;
const original = camera[name];
if (typeof original !== 'function') continue;
const descriptor = Object.getOwnPropertyDescriptor(camera, name);
const wrapped = function (...args) {
stop();
return original.apply(this, args);
};
camera[name] = wrapped;
removers.push(() => {
if (camera[name] !== wrapped) return;
if (descriptor) Object.defineProperty(camera, name, descriptor);
else delete camera[name];
});
}
const removeTracking = viewer.trackedEntityChanged?.addEventListener(stop);
if (removeTracking) removers.push(removeTracking);
removers.push(onFollowChanged(viewer, stop));
documentRef?.addEventListener?.('keydown', stop, true);
// A manual gesture ends the guard, as it interrupts camera motion elsewhere.
for (const type of ['pointerdown', 'wheel'])
@@ -147,40 +175,33 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
const attempt = () => {
if (done) return;
if (isStale() || viewer.isDestroyed?.()) return stop();
const camera = findCamera(viewer);
const now = eyeOf(camera);
// Another caller owns the camera now; lifting would undo its move.
if (!camera || camera.flying || moved(now, arrival)) return stop();
remaining -= 1;
const camera = viewer.camera;
const carto = camera.positionCartographic;
// The eye must clear both the framed target and the ground beneath it.
const below = {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
const { heightM, sampled } = sampleSurfaceM(viewer.scene, [
{ lat: at.lat, lon: at.lon },
below,
]);
const below = { lat: now.lat, lon: now.lon };
const { heightM, sampled } = sampleSurfaceM(
viewer ? heightsOf(viewer) : null,
[{ lat: at.lat, lon: at.lon }, below],
);
if (sampled > 0 && Number.isFinite(heightM)) {
const deficit = groundClearanceDeficitM(
carto.height,
heightM,
clearanceM,
);
const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM);
if (deficit > 0) {
stop();
camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
carto.longitude,
carto.latitude,
carto.height + deficit,
),
orientation: {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll,
camera.flyTo(
{ lon: now.lon, lat: now.lat, height: now.height + deficit },
{
orientation: {
heading: now.heading,
pitch: now.pitch,
roll: now.roll,
},
durationS: 0.9,
easing: 'cubicInOut',
},
duration: 0.9,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
);
try {
onLift?.(deficit);
} catch {
+195 -27
View File
@@ -3,6 +3,12 @@
// 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 {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
@@ -47,24 +53,71 @@ test('the clearance frames a subject without turning into an overflight', () =>
assert.ok(MIN_EYE_CLEARANCE_M <= 250);
});
function fakeViewer({ cameraHeightM, surfaceM }) {
/**
* Count the listeners for `viewer`'s camera port follow changes, from now on.
* @returns {() => number}
*/
function countFollowListeners(viewer) {
const renderer = rendererOf(viewer);
const port = renderer.camera;
let listeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
listeners += 1;
let live = true;
return () => {
if (live) listeners -= 1;
live = false;
off();
};
},
},
});
return () => listeners;
}
function fakeViewer({ cameraHeightM, surfaceM, tracks = false }) {
const flights = [];
const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM);
return {
const position = Cesium.Cartographic.fromDegrees(
-97.7603,
30.3141,
cameraHeightM,
);
const viewer = {
flights,
scene: {
canvas: null,
sampleHeightSupported: true,
sampleHeight: (carto) =>
typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM,
},
camera: {
positionCartographic: position,
positionWC: Cesium.Cartographic.toCartesian(position),
directionWC: new Cesium.Cartesian3(0, 0, -1),
upWC: new Cesium.Cartesian3(0, 1, 0),
heading: 0.5,
pitch: -0.55,
roll: 0,
flyTo: (options) => flights.push(options),
// As Cesium does: a flight is under way until it completes.
_currentFlight: undefined,
flyTo(options) {
flights.push(options);
this._currentFlight = {};
},
},
};
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
if (tracks)
Object.assign(viewer, {
trackedEntityChanged: new Cesium.Event(),
entities: {},
});
return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
}
test('the guard lifts a buried arrival once the surface answers', async () => {
@@ -104,7 +157,11 @@ test('the guard waits for streaming tiles and yields to a newer arrival', async
test('the guard leaves a clear view untouched', async () => {
const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 });
guardCameraAboveGround(viewer, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 1 },
);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0);
});
@@ -116,39 +173,85 @@ import { LayerLifecycle } from './data/lifecycle.js';
function handoffFixture(t) {
t.mock.timers.enable({ apis: ['setTimeout'] });
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
const viewer = fakeViewer({
cameraHeightM: 172,
surfaceM: 171,
tracks: true,
});
const followListeners = countFollowListeners(viewer);
viewer.scene.canvas = new EventTarget();
viewer.scene.canvas.ownerDocument = new EventTarget();
viewer.trackedEntityChanged = new Cesium.Event();
viewer.camera.cancelFlight = () => {};
viewer.camera.lookAtTransform = () => {};
viewer.camera.flyToBoundingSphere = () => {};
viewer.camera.setView = () => {};
viewer.camera.flyToBoundingSphere = function () {
this._currentFlight = {};
};
viewer.camera.setView = function () {
this.positionWC = Cesium.Cartesian3.add(
this.positionWC,
new Cesium.Cartesian3(0, 0, 50),
new Cesium.Cartesian3(),
);
};
const originalFly = viewer.camera.flyTo;
const navigation = new NavigationController({
viewer,
tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer',
'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer',
'rocketLaunchesLayer'].map((key) => [key, {}])),
cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {},
getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {},
isCockpitActive: () => false, showToast() {},
tracking: Object.fromEntries(
[
'flightsLayer',
'militaryFlightsLayer',
'satellitesLayer',
'aisLiveVesselsLayer',
'militaryAwarenessLayer',
'rocketLaunchesLayer',
].map((key) => [key, {}]),
),
cancelOrientation() {},
clearLocation() {},
cancelShareSelection() {},
getDataManager() {},
interruptCameraMotion() {},
stopOrbit() {},
isCockpitActive: () => false,
showToast() {},
});
guardCameraAboveGround(viewer, { lat: 30.3, lon: -97.7 });
return { viewer, navigation, originalFly };
return { viewer, navigation, originalFly, followListeners };
}
for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) {
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);
const { viewer, navigation, originalFly, followListeners } =
handoffFixture(t);
const methods = [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
].map((name) => viewer.camera[name]);
if (handoff === 'Director') {
SceneDirector.prototype._claimCameraOwnership.call({
viewer, styleManager: { runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn) },
viewer,
styleManager: {
runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn),
},
});
} else if (handoff === 'tracking') {
viewer.trackedEntityChanged.raiseEvent({ id: 'contact' });
followEntity(viewer, { id: 'contact' });
} else if (handoff === 'follow' || handoff === 'UI') {
navigation._stampNavigation({ cancelPendingSelection: false });
} else if (handoff === 'keyboard') {
@@ -156,16 +259,81 @@ for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
} else if (handoff === 'app-stop') navigation.stop();
else if (handoff.startsWith('layer-')) {
const lifecycle = new LayerLifecycle(viewer);
lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} });
lifecycle.register({
id: 'test',
init() {},
enable() {},
disable() {},
destroy() {},
});
await lifecycle.setEnabled('test', true);
if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false);
if (handoff === 'layer-disable')
await lifecycle.setEnabled('test', false);
else await lifecycle.destroyLayer('test');
} else viewer.camera[handoff]({});
// A direct flyTo is itself one recorded flight; the guard adds none.
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);
assert.equal(
viewer.flights.length,
priorFlights,
'the old probe cannot fly',
);
assert.equal(viewer.camera.flyTo, originalFly);
assert.deepEqual(
['flyTo', 'flyToBoundingSphere', 'setView', 'lookAt', 'cancelFlight'].map(
(name) => viewer.camera[name],
),
methods,
'the guard never replaces camera methods',
);
assert.equal(followListeners(), 0);
navigation.destroy();
});
}
test('the guard yields to a camera moved without any camera method', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// A cockpit or follow frame writes the pose directly.
viewer.camera.directionWC = new Cesium.Cartesian3(1, 0, 0);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0, 'the moved view is not corrected');
});
test('Cesium lifting a buried eye straight up is not another owner', async () => {
const viewer = fakeViewer({ cameraHeightM: 104, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// Terrain collision raises the eye to just above the loaded ground.
const raised = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 172);
viewer.camera.positionCartographic = raised;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(raised);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 1, 'the guard still lifts the eye');
const lifted = Cesium.Cartographic.fromCartesian(
viewer.flights[0].destination,
);
assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5);
});
test('another owner lowering the eye is not corrected', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
const lowered = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 150);
viewer.camera.positionCartographic = lowered;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(lowered);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 0);
});
+14 -13
View File
@@ -42,10 +42,10 @@ function ordered(source, needles, label) {
test('Cockpit takeover invalidates deferred work before camera cancellation', () => {
const enter = cockpitEnter.toString();
ordered(enter, [
'if (!info || !entity?.position) return false;',
'if (!info || (!vessel && !satellite && !entity?.position)) return false;',
'this.onCameraTakeover?.();',
'this.viewer.camera.cancelFlight();',
'this.viewer.trackedEntity = undefined;',
'cameraOf(this.viewer).cancelFlight();',
'stopFollowing(this.viewer);',
], 'Cockpit takeover');
assert.match(
ui,
@@ -97,7 +97,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// The transaction has exactly two camera-owner mutations, and each one
// stamps:
// 1. selectedLayer.trackById(id) -> viewer.trackedEntity
// -> viewer.trackedEntityChanged -> _stampNavigation()
// -> onFollowChanged(viewer) -> _stampNavigation()
// 2. cockpitView.enter() -> onCameraTakeover() -> _stampNavigation()
const transaction = body(
cockpitTracking,
@@ -106,7 +106,8 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
);
ordered(transaction, [
/if \(\s*!selectedLayer\.trackById\?\.\(selectedTarget\.id, \{\s*origin: selectionOrigin,?\s*\}\)\s*\) \{/,
'if (!entryError) entered = Boolean(cockpitView.enter());',
// Aircraft-only: a selected vessel must not stand in for a voice target.
"if (!entryError) entered = Boolean(cockpitView.enter({ kind: 'aircraft' }));",
], 'Cockpit entry transaction');
// No direct camera control: every mutation goes through a layer tracker or
// the cockpit controller, both of which stamp.
@@ -117,7 +118,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// Seam 1: any tracker handoff stamps, so the adoption step is covered.
assert.match(
ui,
/viewer\.trackedEntityChanged\.addEventListener\(\s*\(entity\) => \{\s*if \(entity && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
/onFollowChanged\(\s*this\.viewer,\s*\(followed\) => \{\s*if \(followed && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
'tracker handoff must stamp',
);
// Seam 2 is pinned by "Cockpit takeover invalidates deferred work" above.
@@ -190,10 +191,10 @@ test('accepted navigation releases through PR15-aware ownership before flight',
'origin: trackingOrigin',
'satellitesLayer.stopTracking?.({ origin: trackingOrigin })',
'rocketLaunchesLayer.releaseCameraOwnership?.()',
'this.viewer.trackedEntity = undefined;',
'stopFollowing(this.viewer);',
"interruptCameraMotion('explicit-navigation')",
'this.viewer.camera.cancelFlight();',
'this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);',
'camera?.cancelFlight();',
'camera?.release();',
], 'follow release');
assert.match(release, /flightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
assert.match(release, /militaryFlightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
@@ -281,11 +282,11 @@ test('a direct globe gesture retires delayed camera and selection restore only',
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
@@ -398,7 +399,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
}
const vesselClick = body(
vessels,
/handler\.setInputAction\(\s*\(click\) => \{([\s\S]*?)\n\s*\},\s*Cesium\.ScreenSpaceEventType\.LEFT_CLICK,?\s*\);/,
/inputFor\(viewer\)\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'vessel click',
);
ordered(vesselClick, [
@@ -414,7 +415,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
assert.match(vesselFocus, /requestWorldFocus\(\{/);
const fireClick = body(
firms,
/_clickHandler\.setInputAction\(\(click\) => \{([\s\S]*?)\n \}, Cesium\.ScreenSpaceEventType\.LEFT_CLICK\);/,
/input\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'fire click',
);
ordered(fireClick, [
+23 -8
View File
@@ -9,6 +9,14 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { createGevActionRunner } from './voice/gevActions.js';
import {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
const radians = Cesium.Math.toRadians;
const degrees = Cesium.Math.toDegrees;
@@ -39,6 +47,7 @@ function harness(
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -47,13 +56,21 @@ function harness(
destination: Cesium.Cartesian3.fromDegrees(-0.1276, 51.5072, height),
orientation: { heading: radians(heading), pitch: radians(pitch), roll: 0 },
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
clock: { onTick: new Cesium.Event() },
};
// The Cesium renderer's own camera port over the real camera; frames from
// the scene's preUpdate.
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// The app's view target: the ground point under the screen centre.
const viewTarget = () => {
const ray = new Cesium.Ray(camera.positionWC, camera.directionWC);
@@ -68,7 +85,7 @@ function harness(
});
const tick = (seconds = 1 / 30) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finish = () => {
for (let i = 0; i < 600 && getActiveCameraMotion(); i += 1) tick();
@@ -239,9 +256,7 @@ test('a pivoting tilt yields when tracking takes the camera', (t) => {
const h = harness(t);
assert.equal(moveCamera({ motion: 'tilt', pitchDeg: -45 }).ok, true);
h.tick();
const entity = { id: 'tracked' };
h.viewer.trackedEntity = entity;
h.viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(h.viewer, { id: 'tracked' });
assert.equal(getActiveCameraMotion(), null);
});
@@ -548,10 +563,10 @@ test('a regional tilt-up nudge goes to the camera horizon limit', (t) => {
test('a voice tilt from a tracked view judges its limit from the camera pitch', (t) => {
const h = harness(t, { height: 20000, pitch: -5.2 });
h.viewer.trackedEntity = { id: 'tracked' };
followEntity(h.viewer, { id: 'tracked' });
// Voice releases the follow camera before the motion starts.
const release = (start) => {
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
return start();
};
const result = moveCamera({ motion: 'tilt', direction: 'up' }, release);
+437 -514
View File
File diff suppressed because it is too large. Load diff
+9 -8
View File
@@ -1,22 +1,23 @@
/**
* Activates the nearest CCTV record on layer enable and flies only when no
* aircraft tracker or cockpit camera owns the view.
* followed target or cockpit camera owns the view.
* @param {Object} options Layer-enable focus inputs.
* @param {*} options.trackedEntity Current Cesium tracked entity, if any.
* @param {*} options.followed What the camera follows, if anything
* (`followedOf`).
* @param {boolean} options.cockpitActive Whether cockpit mode owns the camera.
* @param {() => (string|null)} options.activate Nearest-camera activation.
* @param {(cameraId: string) => *} options.fly Optional camera flight.
* @returns {*} Activated camera ID for a held view, or the flight result.
*/
export function runCctvLayerEnableFocus({
trackedEntity = null,
followed = null,
cockpitActive = false,
activate,
fly,
} = {}) {
const cameraId = activate?.();
if (!cameraId) return false;
if (trackedEntity || cockpitActive) return cameraId;
if (followed || cockpitActive) return cameraId;
return fly?.(cameraId);
}
@@ -25,11 +26,11 @@ export function runCctvLayerEnableFocus({
* chain. Either observation suppresses the optional CCTV focus flight.
* @param {Object} [before={}] Ownership immediately before the await.
* @param {Object} [after={}] Ownership immediately after the await.
* @returns {{ trackedEntity: *, cockpitActive: boolean }} Conservative ownership.
* @returns {{ followed: *, cockpitActive: boolean }} Conservative ownership.
*/
function mergeCctvEnableOwnership(before = {}, after = {}) {
return {
trackedEntity: before.trackedEntity || after.trackedEntity || null,
followed: before.followed || after.followed || null,
cockpitActive: !!(before.cockpitActive || after.cockpitActive),
};
}
@@ -60,7 +61,7 @@ export async function runCctvLayerEnableTransition({
const ownershipBefore = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership before setEnabled await', {
trackedId: ownershipBefore.trackedEntity?.id ?? null,
trackedId: ownershipBefore.followed?.key ?? null,
cockpitActive: !!ownershipBefore.cockpitActive,
});
}
@@ -68,7 +69,7 @@ export async function runCctvLayerEnableTransition({
const ownershipAfter = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership after setEnabled await', {
trackedId: ownershipAfter.trackedEntity?.id ?? null,
trackedId: ownershipAfter.followed?.key ?? null,
cockpitActive: !!ownershipAfter.cockpitActive,
});
}
+6 -6
View File
@@ -8,8 +8,8 @@ import {
test('CCTV layer enable activates nearest without stealing a tracked or cockpit view', () => {
for (const ownership of [
{ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false },
{ trackedEntity: null, cockpitActive: true },
{ followed: { key: 'tracked-plane' }, cockpitActive: false },
{ followed: null, cockpitActive: true },
]) {
const calls = [];
const result = runCctvLayerEnableFocus({
@@ -48,15 +48,15 @@ test('CCTV layer enable activates nearest without stealing a tracked or cockpit
});
test('CCTV enable retains a pre-await tracking snapshot when tracking clears during enable', async () => {
let trackedEntity = { id: 'tracked-plane' };
let followed = { key: 'tracked-plane' };
let flyCalls = 0;
const diagnostics = [];
const result = await runCctvLayerEnableTransition({
target: true,
readOwnership: () => ({ trackedEntity, cockpitActive: false }),
readOwnership: () => ({ followed, cockpitActive: false }),
setEnabled: async () => {
await Promise.resolve();
trackedEntity = null;
followed = null;
},
shouldFocus: () => true,
activate: () => 'cam-near',
@@ -83,7 +83,7 @@ test('CCTV disable transition does not emit enable-ownership diagnostics', async
const result = await runCctvLayerEnableTransition({
target: false,
readOwnership: () => ({ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }),
readOwnership: () => ({ followed: { key: 'tracked-plane' }, cockpitActive: false }),
setEnabled: async (target) => transitions.push(target),
shouldFocus: () => true,
activate: () => 'cam-near',
+142 -101
View File
@@ -1,5 +1,29 @@
import * as Cesium from 'cesium';
import { governorRequestRender } from './renderGovernor.js';
import {
cameraOf,
canvasOf,
findCamera,
findFrame,
findQuery,
} from './render/rendererOf.js';
import {
moonPositionInertial,
sunPositionInertial,
temeToPseudoFixed,
} from './geo/celestial.js';
import { WGS84 } from './geo/ellipsoid.js';
import { frameVector } from './geo/frames.js';
import {
dot,
magnitude,
normalize,
PI_OVER_TWO,
toRadians,
} from './geo/vector.js';
import { worldClock, worldTimeFor } from './time/worldClock.js';
// The ring shows the sun and moon at the time the sky is drawn.
const skyTime = worldTimeFor('sky');
/** Outer edge of the existing NVG/FLIR keyhole in normalized shader space. */
export const KEYHOLE_OUTER_RADIUS = 1.05;
@@ -28,10 +52,19 @@ export const KEYHOLE_LABEL_FEATHER_MAX_RATIO = 0.4;
*/
export const KEYHOLE_OUTSIDE_OPACITY_DEFAULT = 0.01;
// How far the world time moves before the sun and moon move with it: a
// minute moves the sun a quarter of a degree.
const EPHEMERIS_WORLD_STEP_MS = 60_000;
const RING_INSET_PX = 11;
const MARKER_INSET_PX = 36;
const COLLIDING_MARKER_EXTRA_INSET_PX = 32;
const MARKER_COLLISION_ANGLE = Cesium.Math.toRadians(6);
const MARKER_COLLISION_ANGLE = toRadians(6);
/** The ellipsoid's largest radius, metres. */
const EARTH_MAX_RADIUS_M = Math.max(
WGS84.radii.x,
WGS84.radii.y,
WGS84.radii.z,
);
const FULL_GLOBE_RADIUS_RATIO = 0.61;
const TAU = Math.PI * 2;
// This overlay is a secondary HUD treatment. Keep it smooth while reserving
@@ -211,7 +244,7 @@ export function isFullGlobeInsideKeyhole(geometry, wasVisible = false) {
/** Return the Earth-disc radius in CSS pixels for a perspective camera. */
export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
const earthRadiusM = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadiusM = EARTH_MAX_RADIUS_M;
if (
!Number.isFinite(cameraDistance) ||
cameraDistance <= earthRadiusM ||
@@ -227,15 +260,19 @@ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
return Number.isFinite(radius) && radius > 0 ? radius : null;
}
const EARTH_CENTRE = Object.freeze({ x: 0, y: 0, z: 0 });
/**
* Project the visible Earth disc into viewport coordinates.
* Project the visible Earth disc into viewport coordinates, through the
* renderer's camera pose and its query port's projection.
* Shared by full-globe UI treatments that must agree on visual containment.
*
* @param {object} viewer - Cesium Viewer-like object.
* @param {object} viewer - The scene object the renderer is found from.
* @param {number} width - Viewport width in CSS pixels.
* @param {number} height - Viewport height in CSS pixels.
* @param {object} [scratchCenter] - Reusable Cesium Cartesian2 result.
* @param {object} [scratchToCenter] - Reusable Cesium Cartesian3 result.
* @param {{x:number,y:number}} [scratchCenter] - Takes the projected centre.
* @param {{x:number,y:number,z:number}} [scratchToCenter] - Takes the
* vector from the eye to the Earth's centre.
* @returns {object|null}
*/
export function projectEarthDiscToViewport(
@@ -245,36 +282,32 @@ export function projectEarthDiscToViewport(
scratchCenter = undefined,
scratchToCenter = undefined,
) {
const camera = viewer?.camera;
const scene = viewer?.scene;
if (!camera || !scene || !(width > 0) || !(height > 0)) return null;
const camera = findCamera(viewer);
if (!camera || !(width > 0) || !(height > 0)) return null;
const pose = camera.pose();
const eye = pose.position;
const distance = Cesium.Cartesian3.magnitude(camera.positionWC);
const distance = magnitude(eye);
if (!Number.isFinite(distance) || distance <= EARTH_MAX_RADIUS_M) return null;
const toCenter = scratchToCenter || { x: 0, y: 0, z: 0 };
toCenter.x = -eye.x;
toCenter.y = -eye.y;
toCenter.z = -eye.z;
if (dot(pose.direction, toCenter) <= 0) return null;
const projected = findQuery(viewer)?.project(EARTH_CENTRE);
if (
!Number.isFinite(distance) ||
distance <= Cesium.Ellipsoid.WGS84.maximumRadius
!projected ||
!Number.isFinite(projected.x) ||
!Number.isFinite(projected.y)
)
return null;
const center = scratchCenter || { x: 0, y: 0 };
center.x = projected.x;
center.y = projected.y;
const toCenter = Cesium.Cartesian3.negate(
camera.positionWC,
scratchToCenter || new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(camera.directionWC, toCenter) <= 0) return null;
const center = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
Cesium.Cartesian3.ZERO,
scratchCenter,
);
if (!center || !Number.isFinite(center.x) || !Number.isFinite(center.y))
return null;
const earthRadius = earthDiscScreenRadius(
distance,
height,
camera.frustum?.fovy,
);
const earthRadius = earthDiscScreenRadius(distance, height, pose.fovy);
if (!earthRadius) return null;
const keyhole = getKeyholeGeometry(width, height);
@@ -389,14 +422,23 @@ let rings = 0;
*/
export class CelestialRing {
/**
* @param {Cesium.Viewer} viewer
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object}} options
* @param {object} viewer - The scene object the renderer is found from;
* the ring reads its canvas and container (DOM) and reaches the rest
* through the renderer's camera, frame and query ports.
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object,preciseFrameAt?:Function}} options
* `store` is the celestial ring store (src/ui/stores/celestialRing.js);
* the keyhole helpers here stay free of Vue for the packages that use
* them.
* them. `preciseFrameAt(ms)` gives the ICRF-to-fixed rotation as axes,
* or null while its tables have not loaded; without it, or while it has
* no answer, the ring uses the pseudo-fixed frame.
*/
constructor(viewer, { enabled = true, onAutoDisable = null, store }) {
constructor(
viewer,
{ enabled = true, onAutoDisable = null, store, preciseFrameAt = null },
) {
this.viewer = viewer;
this._preciseFrameAt =
typeof preciseFrameAt === 'function' ? preciseFrameAt : null;
this.enabled = !!enabled;
this.visible = false;
this._onAutoDisable =
@@ -419,18 +461,14 @@ export class CelestialRing {
this._moonCanvas = null;
this._moonCtx = null;
this._sunInertial = new Cesium.Cartesian3();
this._moonInertial = new Cesium.Cartesian3();
this._sunFixed = new Cesium.Cartesian3();
this._moonFixed = new Cesium.Cartesian3();
this._toCenter = new Cesium.Cartesian3();
this._screenCenter = new Cesium.Cartesian2();
this._fixedMatrix = new Cesium.Matrix3();
this._sunFixed = { x: 0, y: 0, z: 0 };
this._moonFixed = { x: 0, y: 0, z: 0 };
this._toCenter = { x: 0, y: 0, z: 0 };
this._screenCenter = { x: 0, y: 0 };
this._initView(store);
this._removePostRender = viewer.scene.postRender.addEventListener(() =>
this._draw(),
);
this._removePostRender =
findFrame(viewer)?.on('postRender', () => this._draw()) ?? null;
// Pre-existing staleness fix (perf wave 2 review): the ephemeris was
// sampled once per visible-enable from the FROZEN app clock, so the
// sun/moon markers aged with the app. Resample real wall time each
@@ -445,6 +483,18 @@ export class CelestialRing {
if (typeof document !== 'undefined' && document.hidden) return;
governorRequestRender('celestial-ephemeris');
}, 60_000);
// A jump in the world time moves the sun and moon at once.
// Played through, the sky moves on each minute of world time it passes.
this._ephemerisWorldMs = null;
this._unsubscribeWorldTime = worldClock.subscribe(({ timeMs }) => {
if (
this._ephemerisWorldMs !== null &&
Math.abs(timeMs - this._ephemerisWorldMs) < EPHEMERIS_WORLD_STEP_MS
)
return;
this._ephemerisWorldMs = timeMs;
this._ephemerisDirty = true;
});
this.setEnabled(this.enabled);
}
@@ -533,9 +583,14 @@ export class CelestialRing {
});
}
/** The renderer's canvas; a viewer with no renderer bound, its own. */
_canvas() {
return canvasOf(this.viewer);
}
/** Whether the current camera already frames the complete globe inside the keyhole. */
isGlobeFullyVisible() {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return false;
@@ -550,13 +605,15 @@ export class CelestialRing {
* @returns {boolean} Whether a valid camera flight was started.
*/
focusFullGlobe({ duration = 2.4 } = {}) {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const height = canvas.clientHeight || canvas.height;
const cartographic = this.viewer.camera.positionCartographic;
const fovy = this.viewer.camera.frustum?.fovy;
const camera = cameraOf(this.viewer);
const pose = camera.pose();
const fovy = pose.fovy;
if (
!(height > 0) ||
!cartographic ||
!Number.isFinite(pose.lon) ||
!Number.isFinite(pose.lat) ||
!Number.isFinite(fovy) ||
fovy <= 0 ||
fovy >= Math.PI
@@ -564,7 +621,7 @@ export class CelestialRing {
return false;
}
const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadius = EARTH_MAX_RADIUS_M;
const keyholeRadius = getKeyholeGeometry(
canvas.clientWidth || canvas.width,
height,
@@ -579,27 +636,25 @@ export class CelestialRing {
this._focusInProgress = true;
const finishFocus = () => {
this._focusInProgress = false;
this.viewer.scene.requestRender?.();
findFrame(this.viewer)?.requestRender('celestial-focus');
};
this.viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
altitude,
),
orientation: {
heading: this.viewer.camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
camera.flyTo(
{ lon: pose.lon, lat: pose.lat, height: altitude },
{
orientation: {
heading: pose.heading,
pitch: -PI_OVER_TWO,
roll: 0,
},
durationS: duration,
easing: 'cubicInOut',
onComplete: finishFocus,
onCancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
},
duration,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
complete: finishFocus,
cancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
});
);
return true;
}
@@ -650,31 +705,16 @@ export class CelestialRing {
/**
* Sample Earth-fixed directions once per enable. Camera movement only
* re-projects these cached vectors; it never re-runs the planetary model.
* The precise ICRF frame serves once its tables have loaded, the
* pseudo-fixed one before.
* @param {number} ms Epoch milliseconds.
*/
_updateEphemeris(time) {
_updateEphemeris(ms) {
if (!this._ephemerisDirty) return true;
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
this._sunInertial,
);
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
this._moonInertial,
);
const matrix =
Cesium.Transforms.computeIcrfToFixedMatrix(time, this._fixedMatrix) ||
Cesium.Transforms.computeTemeToPseudoFixedMatrix(time, this._fixedMatrix);
if (!matrix) return false;
Cesium.Matrix3.multiplyByVector(matrix, this._sunInertial, this._sunFixed);
Cesium.Matrix3.multiplyByVector(
matrix,
this._moonInertial,
this._moonFixed,
);
Cesium.Cartesian3.normalize(this._sunFixed, this._sunFixed);
Cesium.Cartesian3.normalize(this._moonFixed, this._moonFixed);
const frame = this._preciseFrameAt?.(ms) ?? temeToPseudoFixed(ms);
this._sunFixed = normalize(frameVector(frame, sunPositionInertial(ms)));
this._moonFixed = normalize(frameVector(frame, moonPositionInertial(ms)));
this._ephemerisDirty = false;
this._ephemerisUpdateCount += 1;
return true;
@@ -771,7 +811,7 @@ export class CelestialRing {
const now = performance.now();
if (now < this._nextDrawAt) return;
this._nextDrawAt = now + 1000 / CELESTIAL_MAX_FRAME_RATE;
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return;
@@ -801,18 +841,17 @@ export class CelestialRing {
return;
}
const time = Cesium.JulianDate.now();
if (!this._updateEphemeris(time)) return;
if (!this._updateEphemeris(skyTime())) return;
this._present({ ephemerisUpdates: String(this._ephemerisUpdateCount) });
const camera = this.viewer.camera;
const pose = cameraOf(this.viewer).pose();
const sunProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._sunFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._sunFixed, camera.upWC),
dot(this._sunFixed, pose.right),
dot(this._sunFixed, pose.up),
this._sunAngle,
);
const moonProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._moonFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._moonFixed, camera.upWC),
dot(this._moonFixed, pose.right),
dot(this._moonFixed, pose.up),
this._moonAngle,
);
if (sunProjection.stable) this._sunAngle = sunProjection.angle;
@@ -890,6 +929,8 @@ export class CelestialRing {
clearInterval(this._ephemerisTimer);
this._ephemerisTimer = null;
}
this._unsubscribeWorldTime?.();
this._unsubscribeWorldTime = null;
if (this._removePostRender) this._removePostRender();
this._removePostRender = null;
if (this._shown()) {
+135 -5
View File
@@ -9,7 +9,14 @@ import { createPinia } from 'pinia';
import { useCelestialRingStore } from './ui/stores/celestialRing.js';
import CelestialRingView from './ui/views/panels/CelestialRing.vue';
import * as Cesium from 'cesium';
import { CelestialRing } from './celestialRing.js';
import {
CelestialRing,
earthDiscScreenRadius,
projectEarthDiscToViewport,
} from './celestialRing.js';
import { bindRenderer } from './render/rendererOf.js';
import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs';
import { fakeSceneFrame } from './testSupport/fakeCesiumScene.mjs';
// happy-dom has no 2D context; a stand-in takes every drawing call.
const context = new Proxy(
@@ -19,18 +26,26 @@ const context = new Proxy(
globalThis.HTMLCanvasElement.prototype.getContext = () => context;
function fakeViewer(container) {
return {
const canvas = {
clientWidth: 400,
clientHeight: 300,
width: 400,
height: 300,
};
const viewer = {
container,
canvas,
camera: {
rightWC: new Cesium.Cartesian3(1, 0, 0),
upWC: new Cesium.Cartesian3(0, 1, 0),
},
scene: {
canvas: { clientWidth: 400, clientHeight: 300, width: 400, height: 300 },
canvas,
postRender: { addEventListener: () => () => {} },
requestRender() {},
},
};
return bindFakeCesiumCamera(viewer, { frame: fakeSceneFrame(viewer) });
}
function fixture(t) {
@@ -157,8 +172,7 @@ const FRAMED = {
/** Run one rendered frame, past the frame-rate throttle. */
function frame(ring, disc) {
ring._projectedEarthDisc = () => disc;
// Fixed sun and moon directions; Cesium's own model would fetch its
// orientation data.
// Fixed sun and moon directions, so markers do not move with the clock.
ring._updateEphemeris = () => {
if (ring._ephemerisDirty) {
Cesium.Cartesian3.clone(new Cesium.Cartesian3(1, 0, 0), ring._sunFixed);
@@ -249,3 +263,119 @@ test('a ring the store no longer shows stops drawing', async (t) => {
assert.equal(earlier.enabled, true);
assert.equal(disabled, 0);
});
test('the sun and moon directions are the planetary model in the pseudo-fixed frame', () => {
const pinia = createPinia();
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
// The precise frame's tables have not loaded.
preciseFrameAt: () => null,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
assert.equal(ring._updateEphemeris(ms), true);
// Cesium's own, before the sky has loaded the precise frame's tables.
const time = Cesium.JulianDate.fromDate(new Date(ms));
const matrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
const expected = (inertial) =>
Cesium.Cartesian3.normalize(
Cesium.Matrix3.multiplyByVector(
matrix,
inertial,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const sun = expected(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
);
const moon = expected(
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
),
);
for (const [got, want] of [
[ring._sunFixed, sun],
[ring._moonFixed, moon],
])
for (const axis of ['x', 'y', 'z'])
assert.ok(Object.is(got[axis], want[axis]), axis);
assert.equal(ring._ephemerisUpdateCount, 1);
ring.destroy();
});
test('the projected disc reads the camera and query ports', () => {
const canvas = { clientWidth: 800, clientHeight: 600 };
const viewer = { canvas };
const distance = 3 * 6378137;
const pose = {
position: { x: distance, y: 0, z: 0 },
direction: { x: -1, y: 0, z: 0 },
fovy: Math.PI / 3,
};
const unbind = bindRenderer(viewer, {
canvas,
camera: { pose: () => pose },
query: { project: () => ({ x: 410, y: 290 }) },
});
const toCenter = { x: 0, y: 0, z: 0 };
const centre = { x: 0, y: 0 };
const disc = projectEarthDiscToViewport(viewer, 800, 600, centre, toCenter);
assert.equal(disc.earthCenterX, 410);
assert.equal(disc.earthCenterY, 290);
assert.deepEqual(centre, { x: 410, y: 290 });
// The scratch takes the eye-to-centre vector, as callers read it after.
assert.deepEqual(toCenter, { x: -distance, y: -0, z: -0 });
assert.ok(
Math.abs(
disc.earthRadius - earthDiscScreenRadius(distance, 600, pose.fovy),
) < 1e-9,
);
// Facing away: null, with the eye-to-centre vector still written, as
// radio navigation reads it after.
pose.direction = { x: 1, y: 0, z: 0 };
const away = { x: 0, y: 0, z: 0 };
assert.equal(projectEarthDiscToViewport(viewer, 800, 600, null, away), null);
assert.deepEqual(away, { x: -distance, y: -0, z: -0 });
// Inside the ellipsoid's largest radius: null, the scratch untouched.
pose.position = { x: 6378137, y: 0, z: 0 };
const inside = { x: 1, y: 2, z: 3 };
assert.equal(
projectEarthDiscToViewport(viewer, 800, 600, null, inside),
null,
);
assert.deepEqual(inside, { x: 1, y: 2, z: 3 });
unbind();
});
test('the precise frame serves once it answers', () => {
const pinia = createPinia();
// A quarter turn about z: x goes to y.
const quarter = {
x: { x: 0, y: 1, z: 0 },
y: { x: -1, y: 0, z: 0 },
z: { x: 0, y: 0, z: 1 },
};
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
preciseFrameAt: () => quarter,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
ring._updateEphemeris(ms);
const time = Cesium.JulianDate.fromDate(new Date(ms));
const sun = Cesium.Cartesian3.normalize(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
new Cesium.Cartesian3(),
);
assert.ok(Math.abs(ring._sunFixed.x + sun.y) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.y - sun.x) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.z - sun.z) < 1e-12);
ring.destroy();
});
+23 -8
View File
@@ -1,5 +1,6 @@
import { applicationServices } from './services/application.js';
import * as Cesium from 'cesium';
import { toRadians } from './geo/vector.js';
import { findCamera } from './render/rendererOf.js';
import { greatCircleMeters } from './geoDistance.js';
import {
deriveWeatherEffectProfile,
@@ -170,6 +171,18 @@ export function cockpitWeatherEnabledFromStoredValue(value) {
return value === '1';
}
/**
* Whether the cloud pass runs for a Cockpit subject's layer. Not in orbit:
* the pass fades out above 24 km (weatherAltitudeFactors), so a satellite
* would pay for it and see nothing. The saved preference is left as it is
* for the next aircraft or bridge; cloud cover from orbit is the Weather
* layer's.
* @param {string|null|undefined} layerId
*/
export function cockpitCloudsShowFor(layerId) {
return layerId !== 'satellites';
}
/**
* Weather-backed volumetric cloud pass that exists only while cockpit mode is
* active. It owns no Cesium fog/post-process stages and cannot affect map mode.
@@ -207,10 +220,12 @@ class CockpitCloudEffectsController {
this.enabled = this.readEnabledPreference();
this.onResize = () => this.resize();
this.orbit = false;
this.onCockpitMode = (event) => {
const active =
event?.detail?.active ??
document.body.classList.contains('cockpit-mode');
this.orbit = active && !cockpitCloudsShowFor(event?.detail?.layerId);
if (active && this.enabled) this.start();
else this.stop();
};
@@ -327,15 +342,14 @@ class CockpitCloudEffectsController {
}
cameraPoint() {
const cartographic = this.viewer?.camera?.positionCartographic;
if (!cartographic) return null;
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const pose = this.viewer ? findCamera(this.viewer)?.pose() : null;
if (!pose) return null;
const { lat: latitude, lon: longitude } = pose;
if (![latitude, longitude].every(Number.isFinite)) return null;
return {
latitude,
longitude,
altitudeM: Math.max(0, Number(cartographic.height) || 0),
altitudeM: Math.max(0, Number(pose.height) || 0),
};
}
@@ -344,7 +358,8 @@ class CockpitCloudEffectsController {
this.destroyed ||
!this.enabled ||
this.frame !== null ||
this.suspended
this.suspended ||
this.orbit
)
return;
if (!this.gl) {
@@ -528,7 +543,7 @@ class CockpitCloudEffectsController {
render(timeSec) {
const gl = this.gl;
if (!gl || !this.program || !this.locations) return;
const windRadians = Cesium.Math.toRadians(this.windDirectionDeg);
const windRadians = toRadians(this.windDirectionDeg);
const windScale = 0.008 + this.windStrength * 0.022;
gl.useProgram(this.program);
gl.uniform2f(
+8
View File
@@ -2,6 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import {
cockpitCloudRenderSize,
cockpitCloudsShowFor,
cockpitWeatherRefreshDue,
cockpitWeatherEnabledFromStoredValue,
} from './cockpitCloudEffects.js';
@@ -23,6 +24,13 @@ test('cockpit weather defaults off and enables only from an explicit saved opt-i
assert.equal(cockpitWeatherEnabledFromStoredValue('1'), true);
});
test('the cloud pass stays off in orbit and runs for aircraft and bridges', () => {
assert.equal(cockpitCloudsShowFor('satellites'), false);
for (const layerId of ['flights', 'military', 'ais-live-vessels', null]) {
assert.equal(cockpitCloudsShowFor(layerId), true, String(layerId));
}
});
test('cockpit weather refreshes after time or meaningful movement', () => {
const anchor = { latitude: 30, longitude: -97 };
assert.equal(cockpitWeatherRefreshDue({
+244
View File
@@ -0,0 +1,244 @@
/**
* Bridge look-around policy: how the arrow keys turn the bridge camera away
* from the bow and back, and how a turned view is described. Yaw is relative
* to the ship's heading; pitch is the view's absolute pitch. Pure: no DOM, no
* Cesium and no translated text; the Cockpit words the readout.
*/
/** One arrow press turns the view this far. */
export const LOOK_STEP_DEG = 5;
/** One Shift+arrow press turns the view this far: two reach either beam. */
export const LOOK_COARSE_STEP_DEG = 45;
/** The view pitches no further than straight up or straight down. */
export const LOOK_PITCH_LIMIT_DEG = 90;
/**
* The eased view's time constant. Three of them (about 180 ms) close 95% of
* a step, so a press glides rather than snaps and a held key turns smoothly.
*/
export const LOOK_EASE_TAU_MS = 60;
/** Closer than this the eased view lands on its target. */
const LOOK_SETTLE_DEG = 0.05;
/** Arrow key → the axis it turns and the direction it turns it. */
const LOOK_ARROWS = Object.freeze({
ArrowLeft: Object.freeze({ axis: 'yaw', sign: -1 }),
ArrowRight: Object.freeze({ axis: 'yaw', sign: 1 }),
ArrowUp: Object.freeze({ axis: 'pitch', sign: 1 }),
ArrowDown: Object.freeze({ axis: 'pitch', sign: -1 }),
});
/**
* Wrap a yaw to (-180, 180]: negative to port, positive to starboard.
* @param {number} deg Yaw in degrees; a non-finite yaw reads as ahead.
* @returns {number}
*/
export function wrapLookYaw(deg) {
if (!Number.isFinite(deg)) return 0;
const wrapped = (((deg % 360) + 360) % 360) - 360;
const yaw = wrapped <= -180 ? wrapped + 360 : wrapped;
return yaw === 0 ? 0 : yaw;
}
/**
* Clamp a view pitch to [-90, 90].
* @param {number} deg Pitch in degrees; a non-finite pitch reads as level.
* @returns {number}
*/
export function clampLookPitch(deg) {
if (!Number.isFinite(deg)) return 0;
const pitch = Math.min(
LOOK_PITCH_LIMIT_DEG,
Math.max(-LOOK_PITCH_LIMIT_DEG, deg),
);
return pitch === 0 ? 0 : pitch;
}
/**
* The step an arrow key asks for, or null for any other key.
* @param {string} key `KeyboardEvent.key`.
* @param {boolean} [coarse] Shift is held: step 45° instead of 5°.
* @returns {{axis: 'yaw'|'pitch', sign: 1|-1, stepDeg: number}|null}
*/
export function lookKeyStep(key, coarse = false) {
const arrow = LOOK_ARROWS[key];
if (!arrow) return null;
return {
...arrow,
stepDeg: coarse ? LOOK_COARSE_STEP_DEG : LOOK_STEP_DEG,
};
}
/**
* Move one value to the next multiple of `stepDeg` in the direction `sign`.
* A value off the grid (the bridge's -2° rest pitch) lands on it first, so
* the readout shows round angles.
*/
function nextOnGrid(value, sign, stepDeg) {
const cells = value / stepDeg;
const next =
sign > 0 ? Math.floor(cells + 1e-9) + 1 : Math.ceil(cells - 1e-9) - 1;
return next * stepDeg;
}
/**
* Apply one key step to a look target.
* @param {{yawDeg: number, pitchDeg: number}} target Current look target.
* @param {{axis: 'yaw'|'pitch', sign: number, stepDeg: number}} step From
* {@link lookKeyStep}.
* @returns {{yawDeg: number, pitchDeg: number}} The new target: yaw wrapped
* to (-180, 180], pitch clamped to [-90, 90].
*/
export function stepLook(target, step) {
const yawDeg = wrapLookYaw(target?.yawDeg ?? 0);
const pitchDeg = clampLookPitch(target?.pitchDeg ?? 0);
if (!step) return { yawDeg, pitchDeg };
if (step.axis === 'yaw')
return {
yawDeg: wrapLookYaw(nextOnGrid(yawDeg, step.sign, step.stepDeg)),
pitchDeg,
};
return {
yawDeg,
pitchDeg: clampLookPitch(nextOnGrid(pitchDeg, step.sign, step.stepDeg)),
};
}
/**
* Advance the eased view toward its target. Yaw takes the shorter way
* round; with `immediate` (reduced motion) the view jumps to the target.
* @param {{yawDeg: number, pitchDeg: number}} current Eased view now.
* @param {{yawDeg: number, pitchDeg: number}} target Look target.
* @param {number} dtMs Milliseconds since the previous step.
* @param {{immediate?: boolean}} [options]
* @returns {{yawDeg: number, pitchDeg: number}}
*/
export function easeLook(current, target, dtMs, { immediate = false } = {}) {
const goalYaw = wrapLookYaw(target?.yawDeg ?? 0);
const goalPitch = clampLookPitch(target?.pitchDeg ?? 0);
if (immediate || !current) return { yawDeg: goalYaw, pitchDeg: goalPitch };
const fraction =
Number.isFinite(dtMs) && dtMs > 0
? 1 - Math.exp(-dtMs / LOOK_EASE_TAU_MS)
: 0;
const fromYaw = wrapLookYaw(current.yawDeg);
const yawError = wrapLookYaw(goalYaw - fromYaw);
const pitchError = goalPitch - clampLookPitch(current.pitchDeg);
const yawDeg =
Math.abs(yawError * (1 - fraction)) < LOOK_SETTLE_DEG
? goalYaw
: wrapLookYaw(fromYaw + yawError * fraction);
const pitchDeg =
Math.abs(pitchError * (1 - fraction)) < LOOK_SETTLE_DEG
? goalPitch
: clampLookPitch(current.pitchDeg + pitchError * fraction);
return { yawDeg, pitchDeg };
}
/**
* Whether a look differs from the rest view (ahead at `restPitchDeg`).
* @param {{yawDeg: number, pitchDeg: number}} look
* @param {number} restPitchDeg The camera profile's pitch.
* @returns {boolean}
*/
export function lookIsOffset(look, restPitchDeg) {
return (
wrapLookYaw(look?.yawDeg ?? 0) !== 0 ||
clampLookPitch(look?.pitchDeg ?? restPitchDeg) !==
clampLookPitch(restPitchDeg)
);
}
/**
* The parts of a look readout, for the Cockpit to word. A part is null when
* that axis rests: yaw ahead, or pitch at the rest pitch.
* @param {{yawDeg: number, pitchDeg: number}} look Look target.
* @param {number} restPitchDeg The camera profile's pitch.
* @returns {{side: 'port'|'starboard'|'astern'|null, bearingDeg: number,
* elevation: 'up'|'down'|'level'|null, angleDeg: number}} `bearingDeg` is
* the angle off the bow (0–180) and `angleDeg` the angle off level (0–90),
* both rounded to whole degrees.
*/
export function lookReadoutParts(look, restPitchDeg) {
const yaw = Math.round(wrapLookYaw(look?.yawDeg ?? 0));
const pitch = Math.round(clampLookPitch(look?.pitchDeg ?? restPitchDeg));
const pitchOffset =
clampLookPitch(look?.pitchDeg ?? restPitchDeg) !==
clampLookPitch(restPitchDeg);
let side = null;
if (Math.abs(yaw) >= 180) side = 'astern';
else if (yaw > 0) side = 'starboard';
else if (yaw < 0) side = 'port';
let elevation = null;
if (pitchOffset) elevation = pitch > 0 ? 'up' : pitch < 0 ? 'down' : 'level';
return {
side,
bearingDeg: Math.abs(yaw),
elevation,
angleDeg: Math.abs(pitch),
};
}
/**
* The orbital view's off-nadir limit on each axis. The orbital look reuses
* the bridge's `{yawDeg, pitchDeg}` shape over a fixed nadir frame: yaw tilts
* the view east (positive) or west, pitch tilts it north (positive) or
* south. Single 5° steps only; the bridge keeps its own limits.
*/
export const ORBITAL_LOOK_LIMIT_DEG = 45;
/** Clamp one orbital look axis to ±ORBITAL_LOOK_LIMIT_DEG; NaN rests. */
function clampOrbitalAxis(deg) {
if (!Number.isFinite(deg)) return 0;
const value = Math.min(
ORBITAL_LOOK_LIMIT_DEG,
Math.max(-ORBITAL_LOOK_LIMIT_DEG, deg),
);
return value === 0 ? 0 : value;
}
/**
* Clamp an orbital look to the off-nadir limit on both axes.
* @param {{yawDeg: number, pitchDeg: number}} look East and north tilt.
* @returns {{yawDeg: number, pitchDeg: number}}
*/
export function clampOrbitalLook(look) {
return {
yawDeg: clampOrbitalAxis(look?.yawDeg),
pitchDeg: clampOrbitalAxis(look?.pitchDeg),
};
}
/**
* Apply one arrow step to an orbital look: the bridge's stepping on the
* same 5° grid, then the off-nadir clamp.
* @param {{yawDeg: number, pitchDeg: number}} target Current look target.
* @param {{axis: 'yaw'|'pitch', sign: number, stepDeg: number}} step From
* {@link lookKeyStep}.
* @returns {{yawDeg: number, pitchDeg: number}}
*/
export function stepOrbitalLook(target, step) {
return clampOrbitalLook(stepLook(clampOrbitalLook(target), step));
}
/**
* The parts of an off-nadir readout, for the Cockpit to word: the north or
* south tilt and the east or west tilt, each null at rest, in whole degrees.
* @param {{yawDeg: number, pitchDeg: number}} look Orbital look target.
* @returns {{northSouth: 'N'|'S'|null, northSouthDeg: number,
* eastWest: 'E'|'W'|null, eastWestDeg: number}}
*/
export function orbitalLookReadoutParts(look) {
const { yawDeg, pitchDeg } = clampOrbitalLook(look);
const north = Math.round(pitchDeg);
const east = Math.round(yawDeg);
return {
northSouth: north > 0 ? 'N' : north < 0 ? 'S' : null,
northSouthDeg: Math.abs(north),
eastWest: east > 0 ? 'E' : east < 0 ? 'W' : null,
eastWestDeg: Math.abs(east),
};
}
+195
View File
@@ -0,0 +1,195 @@
// src/cockpitLook.test.mjs — the bridge look-around policy: arrow steps,
// yaw wrapping, pitch limits, easing and the readout's parts.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LOOK_COARSE_STEP_DEG,
LOOK_STEP_DEG,
ORBITAL_LOOK_LIMIT_DEG,
clampLookPitch,
clampOrbitalLook,
easeLook,
lookIsOffset,
lookKeyStep,
lookReadoutParts,
orbitalLookReadoutParts,
stepLook,
stepOrbitalLook,
wrapLookYaw,
} from './cockpitLook.js';
const REST = { yawDeg: 0, pitchDeg: -2 };
/** Press one key `count` times from `start`. */
function press(start, key, count = 1, coarse = false) {
let look = start;
for (let index = 0; index < count; index += 1)
look = stepLook(look, lookKeyStep(key, coarse));
return look;
}
test('yaw wraps to (-180, 180] and pitch clamps to [-90, 90]', () => {
assert.equal(wrapLookYaw(0), 0);
assert.equal(wrapLookYaw(-0), 0);
assert.equal(wrapLookYaw(180), 180);
assert.equal(wrapLookYaw(-180), 180);
assert.equal(wrapLookYaw(185), -175);
assert.equal(wrapLookYaw(-185), 175);
assert.equal(wrapLookYaw(720 + 45), 45);
assert.equal(wrapLookYaw(NaN), 0);
assert.equal(clampLookPitch(120), 90);
assert.equal(clampLookPitch(-120), -90);
assert.equal(clampLookPitch(-0), 0);
assert.equal(clampLookPitch(Infinity), 0);
});
test('only the arrows step, 5° plain and 45° with Shift', () => {
assert.deepEqual(lookKeyStep('ArrowLeft'), {
axis: 'yaw',
sign: -1,
stepDeg: LOOK_STEP_DEG,
});
assert.deepEqual(lookKeyStep('ArrowUp', true), {
axis: 'pitch',
sign: 1,
stepDeg: LOOK_COARSE_STEP_DEG,
});
assert.equal(lookKeyStep('ArrowDown').sign, -1);
assert.equal(lookKeyStep('ArrowRight').sign, 1);
for (const key of ['Home', '0', 'a', 'Escape', undefined])
assert.equal(lookKeyStep(key), null);
});
test('arrows turn the yaw in 5° steps and Shift reaches either beam in two', () => {
assert.deepEqual(press(REST, 'ArrowRight'), { yawDeg: 5, pitchDeg: -2 });
assert.deepEqual(press(REST, 'ArrowLeft', 3), { yawDeg: -15, pitchDeg: -2 });
assert.equal(press(REST, 'ArrowRight', 2, true).yawDeg, 90);
assert.equal(press(REST, 'ArrowLeft', 2, true).yawDeg, -90);
// A coarse step from off the 45° grid lands on it.
assert.equal(press({ ...REST, yawDeg: 5 }, 'ArrowRight', 1, true).yawDeg, 45);
// Past astern the yaw wraps to the other side.
assert.equal(press(REST, 'ArrowRight', 4, true).yawDeg, 180);
assert.equal(press(REST, 'ArrowRight', 5, true).yawDeg, -135);
assert.equal(press(REST, 'ArrowLeft', 37).yawDeg, 175);
});
test('pitch steps onto the 5° grid from the rest pitch and stops at ±90°', () => {
assert.equal(press(REST, 'ArrowUp').pitchDeg, 0);
assert.equal(press(REST, 'ArrowUp', 3).pitchDeg, 10);
assert.equal(press(REST, 'ArrowDown').pitchDeg, -5);
assert.equal(press(REST, 'ArrowUp', 40).pitchDeg, 90);
assert.equal(press(REST, 'ArrowDown', 40).pitchDeg, -90);
assert.equal(press(REST, 'ArrowUp', 3, true).pitchDeg, 90);
assert.equal(press(REST, 'ArrowDown', 2, true).pitchDeg, -90);
assert.equal(press(REST, 'ArrowUp').yawDeg, 0, 'pitch leaves the yaw');
});
test('the eased view closes most of a step in about 180 ms', () => {
const target = { yawDeg: 90, pitchDeg: -2 };
let view = { ...REST };
view = easeLook(view, target, 180);
assert.ok(view.yawDeg > 85 && view.yawDeg < 90, `yaw ${view.yawDeg}`);
for (let step = 0; step < 20; step += 1) view = easeLook(view, target, 50);
assert.deepEqual(view, target, 'it lands exactly on the target');
assert.deepEqual(easeLook(REST, target, 0), REST, 'no time, no motion');
});
test('the eased yaw takes the short way across astern', () => {
const view = easeLook(
{ yawDeg: 170, pitchDeg: 0 },
{ yawDeg: -170, pitchDeg: 0 },
30,
);
assert.ok(view.yawDeg > 170 || view.yawDeg < -170, `yaw ${view.yawDeg}`);
});
test('reduced motion jumps straight to the target', () => {
const target = { yawDeg: -45, pitchDeg: 30 };
assert.deepEqual(easeLook(REST, target, 1, { immediate: true }), target);
});
test('the readout names the side, the bearing and the elevation', () => {
assert.equal(lookIsOffset(REST, -2), false);
assert.equal(lookIsOffset({ yawDeg: 0, pitchDeg: 0 }, -2), true);
assert.equal(lookIsOffset({ yawDeg: 5, pitchDeg: -2 }, -2), true);
assert.deepEqual(lookReadoutParts({ yawDeg: 45, pitchDeg: 10 }, -2), {
side: 'starboard',
bearingDeg: 45,
elevation: 'up',
angleDeg: 10,
});
assert.deepEqual(lookReadoutParts({ yawDeg: -90, pitchDeg: -2 }, -2), {
side: 'port',
bearingDeg: 90,
elevation: null,
angleDeg: 2,
});
assert.deepEqual(lookReadoutParts({ yawDeg: 0, pitchDeg: -30 }, -2), {
side: null,
bearingDeg: 0,
elevation: 'down',
angleDeg: 30,
});
assert.equal(
lookReadoutParts({ yawDeg: 0, pitchDeg: 0 }, -2).elevation,
'level',
);
assert.equal(
lookReadoutParts({ yawDeg: 180, pitchDeg: -2 }, -2).side,
'astern',
);
});
test('an orbital look steps 5° per arrow and stops at 45° on each axis', () => {
let look = { yawDeg: 0, pitchDeg: 0 };
for (let index = 0; index < 3; index += 1)
look = stepOrbitalLook(look, lookKeyStep('ArrowUp'));
assert.deepEqual(look, { yawDeg: 0, pitchDeg: 15 });
look = stepOrbitalLook(look, lookKeyStep('ArrowRight'));
assert.deepEqual(look, { yawDeg: 5, pitchDeg: 15 });
for (let index = 0; index < 20; index += 1) {
look = stepOrbitalLook(look, lookKeyStep('ArrowDown'));
look = stepOrbitalLook(look, lookKeyStep('ArrowLeft'));
}
assert.deepEqual(look, {
yawDeg: -ORBITAL_LOOK_LIMIT_DEG,
pitchDeg: -ORBITAL_LOOK_LIMIT_DEG,
});
assert.deepEqual(clampOrbitalLook({ yawDeg: 90, pitchDeg: NaN }), {
yawDeg: 45,
pitchDeg: 0,
});
assert.deepEqual(clampOrbitalLook({ yawDeg: 180, pitchDeg: -60 }), {
yawDeg: 45,
pitchDeg: -45,
});
});
test('the orbital readout names north or south and east or west', () => {
assert.deepEqual(orbitalLookReadoutParts({ yawDeg: 15, pitchDeg: 10 }), {
northSouth: 'N',
northSouthDeg: 10,
eastWest: 'E',
eastWestDeg: 15,
});
assert.deepEqual(orbitalLookReadoutParts({ yawDeg: -5, pitchDeg: 0 }), {
northSouth: null,
northSouthDeg: 0,
eastWest: 'W',
eastWestDeg: 5,
});
assert.equal(
orbitalLookReadoutParts({ yawDeg: 0, pitchDeg: -45 }).northSouth,
'S',
);
});
test('the bridge look keeps its own limits beside the orbital clamp', () => {
const look = stepLook({ yawDeg: 45, pitchDeg: 45 }, lookKeyStep('ArrowUp'));
assert.deepEqual(look, { yawDeg: 45, pitchDeg: 50 });
assert.equal(
stepLook({ yawDeg: 45, pitchDeg: 0 }, lookKeyStep('ArrowRight', true))
.yawDeg,
90,
);
});
+54 -34
View File
@@ -26,10 +26,7 @@ import {
setSignalCollapsed,
} from './ui/cockpitLayout.js';
import { createBriefState } from './ui/cockpitBriefPages.js';
import {
publishBriefView,
setBriefAutoRotate,
} from './ui/cockpitBriefing.js';
import { publishBriefView, setBriefAutoRotate } from './ui/cockpitBriefing.js';
import { CockpitDisplayPortal } from './ui/cockpitDisplayPortal.js';
import { _handleContextLayerChange } from './ui/contextLayerChanges.js';
import { clearSelectedLayers } from './ui/contextActions.js';
@@ -79,7 +76,7 @@ test('Cockpit has one reset action beside its bottom exit path', () => {
assert.doesNotMatch(html, /id="cockpit-exit"/);
assert.match(
html,
/id="map-view-switch"[^>]*aria-label="Exit cockpit view"[^>]*aria-keyshortcuts="Escape C"[\s\S]*?close_fullscreen[\s\S]*?EXIT COCKPIT/,
/id="map-view-switch"[^>]*aria-label="Exit cockpit view"[^>]*aria-keyshortcuts="Escape"[\s\S]*?close_fullscreen[\s\S]*?EXIT COCKPIT/,
);
const topCenterActions = html.match(
/<nav id="top-center-actions"[\s\S]*?<\/nav>/,
@@ -163,7 +160,8 @@ test('Cockpit vision cycle exposes every map preset exactly once', () => {
assert.match(html, /id="cockpit-vision-current-label"[^>]*>NORMAL<\/strong>/);
assert.match(
cockpitEnter.toString(),
/this\.setVisionMode\(this\.getInitialVisionMode\(\)\)/,
// Orbit alone opens optical (src/ui/cockpitOrbitalView.test.mjs).
/this\.setVisionMode\(\s*satellite \? 'optical' : this\.getInitialVisionMode\(\)\s*,?\s*\)/,
'Cockpit must enter on the mode matching the active map preset',
);
assert.match(
@@ -227,19 +225,17 @@ test('Cockpit Escape handling precedes form-control shortcut suppression and foc
assert.doesNotMatch(exit, /applyTrackedCameraFrame/);
assert.match(
ui,
/restoreTrackingFrame: \(entity\) => \{[\s\S]*?gevTrackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/,
/restoreTrackingFrame: \(entity\) => \{[\s\S]*?readEntityRecord\(entity\)\?\.trackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/,
'Cockpit exit must return camera-frame ownership through the source layer so Contact Focus cannot accumulate a second owner',
);
});
test('Cockpit shortcut failures do not leak and open utilities own the first Escape', () => {
test('open utilities own the first Escape and Cockpit leaves C alone', () => {
const keydown = cockpitKeyDown.toString();
assert.ok(keydown, 'Cockpit keyboard handler is missing');
assert.match(keydown, /if \(this\.isUtilityDisclosureOpen\?\.\(\)\) return;/);
assert.match(
keydown,
/const cockpitAttempt = !!\(\s*this\.readAircraftInfo\(\) && this\.viewer\.trackedEntity\?\.position\s*\);[\s\S]*?event\.preventDefault\(\);[\s\S]*?event\.stopImmediatePropagation\(\);[\s\S]*?!this\.isEntryAllowed\(\)/,
);
// C is the app-wide CCTV shortcut; Cockpit never claims it.
assert.doesNotMatch(keydown, /=== 'c'/);
});
test('the Contact panel never hides itself out from under its own NEXT button', () => {
@@ -295,14 +291,14 @@ test('the Contact panel never hides itself out from under its own NEXT button',
);
});
test('the cockpit reads its aircraft from the layer that owns Cesium tracking', () => {
test('the cockpit reads its aircraft from the layer the camera follows', () => {
const read = readAircraftInfo.toString();
assert.ok(read, 'readAircraftInfo is missing');
assert.match(read, /resolveTrackedAircraftInfo\(\{/);
assert.match(read, /gevTrackedId/);
// In cockpit mode the controller moves the entity off viewer.trackedEntity,
// so its own handle is the tracked identity there.
assert.match(read, /this\.viewer\?\.trackedEntity \|\| this\.trackedEntity/);
assert.match(read, /trackedId: followed\?\.key/);
// In cockpit mode the controller stops the camera following, so its own
// handle is the tracked identity there.
assert.match(read, /followedOf\(this\.viewer\) \|\| this\.trackedFollow/);
});
test('programmatic Context layer changes cannot bypass explicit expansion policy', () => {
@@ -439,13 +435,10 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
/data-cockpit-launcher="radio"[\s\S]*?id="cockpit-radio-toggle-btn"/,
);
const cockpitRadio = html.match(
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<\/aside>/,
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<div class="cockpit-utility-rail/,
);
assert.ok(cockpitRadio, 'Cockpit compact Radio controls are missing');
assert.doesNotMatch(
cockpitRadio[0],
/radio-filter|radio-tuner/,
);
assert.doesNotMatch(cockpitRadio[0], /radio-filter|radio-tuner/);
assert.match(
css,
/\.cockpit-utility-controls[\s\S]*?top:\s*var\(\s*--cockpit-utility-top/,
@@ -531,12 +524,12 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
);
});
test('Display orders 3D above Celestial, Clean UI below it, and Parameters below Detection', () => {
test('Visual orders Parameters below Detection, 3D below them, and Clean UI above the Effects', () => {
const display = html.match(/id="pp-toggles"[\s\S]*?id="clean-view-exit"/);
assert.ok(display, 'Display markup is missing');
assert.match(
display[0],
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="celestial-toggle"[\s\S]*?id="clean-view-toggle"/,
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="scope-toggle"[\s\S]*?id="clean-view-toggle"[\s\S]*?class="pp-section-heading">Effects<[\s\S]*?id="celestial-toggle"/,
);
assert.equal(
(html.match(/id="param-slider-panel"/g) || []).length,
@@ -812,18 +805,27 @@ test('Reset releases Contact camera ownership through its selection-preserving r
);
assert.match(ui, /onReset: \(\) => this\.resetToGlobeView\(\)/);
assert.match(ui, /this\._connectGlobeReset\?\.\(this\._locationControls\)/);
assert.match(controls, /reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/);
assert.match(
controls,
/reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/,
);
// Both reset buttons ask the one reset owner.
const globeActions = fs.readFileSync(
path.join(ROOT, 'src', 'ui', 'views', 'panels', 'GlobeActions.vue'),
'utf8',
);
assert.match(globeActions, /id="reset-globe-view"[^>]*@click="act\('reset'\)"/);
assert.match(
globeActions,
/id="reset-globe-view"[^>]*@click="act\('reset'\)"/,
);
const cockpitView = readRadioSource(
new URL('./ui/views/CockpitView.vue', import.meta.url),
'utf8',
);
assert.match(cockpitView, /id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/);
assert.match(
cockpitView,
/id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/,
);
assert.match(
cockpitEnter.toString(),
/Object\.assign\(this\.presence, \{\s*active: true,/,
@@ -1171,7 +1173,7 @@ test('cockpit route direction uses self-contained vector artwork, not a font lig
test('cockpit aircraft handoff invalidates the prior world-position anchor', () => {
const match = _adoptTrackedEntity.toString();
assert.ok(match, 'cockpit tracked-entity handoff block is missing');
assert.match(match, /this\.viewer\.trackedEntity = undefined;/);
assert.match(match, /stopFollowing\(this\.viewer\);/);
assert.match(match, /this\.cockpitAnchorValid = false;/);
assert.match(
match,
@@ -1194,7 +1196,10 @@ test('cockpit summary presents the focused item as Contact', () => {
const match = html.match(/<aside id="cockpit-context"[\s\S]*?<\/aside>/);
assert.ok(match, 'cockpit Contact summary is missing');
assert.match(match[0], /aria-label="Contact cockpit summary"/);
assert.match(match[0], /class="cockpit-card-kicker cockpit-context-kicker">CONTACT</);
assert.match(
match[0],
/class="cockpit-card-kicker cockpit-context-kicker">CONTACT</,
);
assert.match(match[0], /aria-label="Contact navigation"/);
assert.match(
match[0],
@@ -1409,15 +1414,30 @@ test('Contact folded for one Cockpit left panel comes back only once neither is
const previous = globalThis.document;
const panels = {};
globalThis.document = { getElementById: (id) => panels[id] ?? null };
const panel = (...classes) => ({ classList: { contains: (name) => classes.includes(name) } });
const panel = (...classes) => ({
classList: { contains: (name) => classes.includes(name) },
});
try {
const otherOpen = (id) => PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
const otherOpen = (id) =>
PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
panels['data-panel'] = panel('collapsed');
assert.equal(otherOpen('utilities-panel'), false, 'Data Layers closed: restore');
assert.equal(
otherOpen('utilities-panel'),
false,
'Data Layers closed: restore',
);
panels['data-panel'] = panel('collapsed', 'layout-auto-collapsed');
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers comes back: keep Contact folded');
assert.equal(
otherOpen('utilities-panel'),
true,
'Data Layers comes back: keep Contact folded',
);
panels['data-panel'] = panel();
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers open: keep it folded');
assert.equal(
otherOpen('utilities-panel'),
true,
'Data Layers open: keep it folded',
);
} finally {
globalThis.document = previous;
}
+109 -3
View File
@@ -32,8 +32,15 @@ export function slewHeading(current, target, maxStepDeg) {
* then uses this amount to converge on the layer's delayed display position.
* Capping correction below forward speed prevents a late feed fix from
* becoming a first-person surge or reversal while still removing drift.
* @param {number} [maxDtSec] The longest step corrected for: 0.1 s, or an
* application subject's own (cockpitSubjectStepSec).
*/
export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
export function cockpitAnchorCorrectionStep(
distanceM,
speedMps,
dtSec,
maxDtSec = 0.1,
) {
if (
!Number.isFinite(distanceM) ||
distanceM <= 0 ||
@@ -41,13 +48,36 @@ export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
dtSec <= 0
)
return 0;
const dt = Math.min(0.1, dtSec);
const dt = Math.min(
Number.isFinite(maxDtSec) && maxDtSec > 0 ? maxDtSec : 0.1,
dtSec,
);
const speed = Number.isFinite(speedMps) ? Math.max(0, speedMps) : 0;
const eased = distanceM * (1 - Math.exp(-1.25 * dt));
const correctionRateMps = Math.max(0.75, speed * 0.22);
return Math.min(distanceM, eased, correctionRateMps * dt);
}
/**
* The seconds an application subject's camera update advances its heading
* slew, ground lift and anchor by: the time since the last update, at most
* its update interval plus 0.1 s. A subject updated every 500 ms then turns
* and eases at its configured rates, while a long stall (a hidden tab) still
* moves it no further than one late update would.
* @param {number} elapsedMs Time since the last camera update.
* @param {number} intervalMs The subject's update interval (0: every frame).
* @returns {number}
*/
export function cockpitSubjectStepSec(elapsedMs, intervalMs) {
const elapsedSec = Number.isFinite(elapsedMs)
? Math.max(0, elapsedMs) / 1000
: 0;
const intervalSec = Number.isFinite(intervalMs)
? Math.max(0, intervalMs) / 1000
: 0;
return Math.min(intervalSec + 0.1, elapsedSec);
}
/** Return whether a throttled cockpit presentation update is due. */
export function cockpitUiUpdateDue(nowMs, lastUpdateMs, intervalMs) {
if (!Number.isFinite(nowMs) || !Number.isFinite(intervalMs) || intervalMs < 0)
@@ -68,6 +98,42 @@ export function cockpitSurfaceWaitExpired(nowMs, startedMs, timeoutMs = 5000) {
return nowMs - startedMs >= timeoutMs;
}
/**
* How fast the clearance a ground clamp adds under an application subject's
* eye comes and goes (m/s).
*/
export const COCKPIT_SUBJECT_LIFT_MPS = 1.5;
/**
* The lift the ground clamp gives an application subject's eye this update.
* The floor is read from coarse cells that refine as tiles load, so the lift
* it asks for jumps; a ridden eye takes the clearance part of it at
* `rateMps`, while what it needs to stay out of the floor itself (`hardM`)
* applies at once.
* @param {number|null} previousM The lift given last update; null on entry.
* @param {number} targetM The lift the floor and clearance ask for (m).
* @param {number} hardM The lift that keeps the eye out of the floor (m).
* @param {number} dtSec Seconds since the last update.
* @param {number} [rateMps]
* @returns {number} At least 0, at least `hardM`.
*/
export function easeCockpitLift(
previousM,
targetM,
hardM,
dtSec,
rateMps = COCKPIT_SUBJECT_LIFT_MPS,
) {
const target = Number.isFinite(targetM) ? Math.max(0, targetM) : 0;
const hard = Number.isFinite(hardM) ? Math.max(0, hardM) : 0;
if (!Number.isFinite(previousM)) return Math.max(target, hard);
const step =
Math.max(0, Number.isFinite(rateMps) ? rateMps : 0) *
Math.max(0, Number.isFinite(dtSec) ? dtSec : 0);
const eased = previousM + Math.max(-step, Math.min(step, target - previousM));
return Math.max(0, hard, eased);
}
/**
* Keep the cockpit camera above the shared rendered-surface floor.
* Unknown floors preserve the proposed camera height.
@@ -176,6 +242,46 @@ export function compassDivisions(heading) {
);
}
/**
* A heading tape that scrolls continuously: the 30-degree divisions within
* `reach` divisions of `heading`, each placed by its offset from the exact
* heading in division slots, so the centre caret reads the heading itself
* rather than the nearest division. `nearest` marks the division closest to
* the caret.
* @param {number} heading Degrees true.
* @param {number} [reach] Divisions each side of the caret.
* @returns {Array<{heading: number, slot: number, nearest: boolean}>}
*/
export function scrollingCompassDivisions(heading, reach = 4) {
if (!Number.isFinite(heading)) return [];
const exact = normalizeHeading(heading);
const centre = Math.round(exact / 30) * 30;
const divisions = [];
for (let step = -reach; step <= reach; step += 1) {
const division = normalizeHeading(centre + step * 30);
divisions.push({
heading: division,
slot: Number((relativeBearing(division, exact) / 30).toFixed(4)),
nearest: step === 0,
});
}
return divisions;
}
/**
* Where a heading falls on the `scrollingCompassDivisions(tapeHeading)` tape:
* its offset from the caret (the tape's exact heading) in division slots of
* 30 degrees, or null when it lies more than three divisions out.
* @param {number} heading Degrees true.
* @param {number} tapeHeading The heading under the tape's caret.
* @returns {?number}
*/
export function compassMarkerSlot(heading, tapeHeading) {
if (!Number.isFinite(heading) || !Number.isFinite(tapeHeading)) return null;
const slot = Number((relativeBearing(heading, tapeHeading) / 30).toFixed(4));
return Math.abs(slot) <= 3 ? slot : null;
}
/** Format a compass division as a cardinal/intercardinal label or degrees. */
export function formatCompassDivision(heading) {
const normalized = normalizeHeading(heading);
@@ -306,7 +412,7 @@ export function relativeBearing(bearing, heading) {
* Resolve which flight layer owns the cockpit's tracked aircraft.
*
* Both layers can briefly describe a tracked aircraft during a cross-layer
* handoff, so the viewer's normalized tracked identity (`gevTrackedId`) is the
* handoff, so the viewer's normalized tracked identity (the entity record's `trackedId`) is the
* tie-breaker — the same rule `militaryAwareness.currentTrackedFlightSubject`
* uses. Layer precedence remains the fallback when no normalized identity is
* available, so tracking paths that never stamp one keep working.
+95 -1
View File
@@ -8,9 +8,14 @@ import {
cockpitAnchorCorrectionStep,
cockpitAltitudeDisplayFt,
cockpitGroundSafeHeight,
cockpitSubjectStepSec,
cockpitSurfaceWaitExpired,
cockpitUiUpdateDue,
COCKPIT_SUBJECT_LIFT_MPS,
easeCockpitLift,
compassDivisions,
compassMarkerSlot,
scrollingCompassDivisions,
formatAltitudeRulerTick,
formatCockpitContextScope,
formatCockpitEmergency,
@@ -54,6 +59,28 @@ test('cockpit anchor correction bounds late-fix catch-up and render stalls', ()
assert.equal(cockpitAnchorCorrectionStep(Number.NaN, 250, 0.1), 0);
});
test('an application subject on a slow cadence is corrected for its whole step', () => {
// The built-in views' step stays capped at 0.1 s...
const capped = cockpitAnchorCorrectionStep(100, 0, 0.5);
assert.equal(capped, cockpitAnchorCorrectionStep(100, 0, 0.1));
// ...while a subject updated every 500 ms is corrected for all of it.
const whole = cockpitAnchorCorrectionStep(100, 0, 0.5, 0.5);
assert.ok(Math.abs(whole / capped - 5) < 1e-9);
assert.equal(cockpitAnchorCorrectionStep(100, 0, 0.5, Number.NaN), capped);
});
test('an application subject steps by its interval, never by a long stall', () => {
assert.equal(cockpitSubjectStepSec(16, 0), 0.016);
assert.equal(cockpitSubjectStepSec(500, 500), 0.5);
assert.equal(cockpitSubjectStepSec(520, 500), 0.52);
// A hidden tab's minutes count as one late update.
assert.equal(cockpitSubjectStepSec(60_000, 500), 0.6);
assert.equal(cockpitSubjectStepSec(60_000, 0), 0.1);
assert.equal(cockpitSubjectStepSec(-5, 500), 0);
assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1);
});
test('cockpit camera clearance never falls below the rendered ground floor', () => {
assert.equal(cockpitGroundSafeHeight(47, 57, 12), 69);
assert.equal(cockpitGroundSafeHeight(1200, 57, 12), 1200);
@@ -151,6 +178,46 @@ test('compass divisions remain ordered across north', () => {
assert.deepEqual(compassDivisions(359), [270, 300, 330, 0, 30, 60, 90]);
});
test('compass marks sit in division slots off the caret, or off the tape', () => {
// Measured from the exact heading under the caret, not the nearest division.
assert.equal(compassMarkerSlot(350, 350), 0);
assert.equal(compassMarkerSlot(35, 350), 1.5);
assert.equal(compassMarkerSlot(260, 350), -3);
assert.equal(compassMarkerSlot(80, 350), 3);
assert.equal(compassMarkerSlot(90, 350), null);
assert.equal(compassMarkerSlot(180, 350), null);
assert.equal(compassMarkerSlot(Number.NaN, 0), null);
});
test('a scrolling tape puts the exact heading under the caret', () => {
// At 100° the divisions sit a third of a slot off their snapped places,
// so the bow mark (also 100°) lines up with the caret, not 10° beside it.
const tape = scrollingCompassDivisions(100);
assert.deepEqual(
tape.map(({ heading }) => heading),
[330, 0, 30, 60, 90, 120, 150, 180, 210],
);
const nearest = tape.find((division) => division.nearest);
assert.equal(nearest.heading, 90);
assert.equal(nearest.slot, -0.3333);
assert.equal(tape.find(({ heading }) => heading === 120).slot, 0.6667);
assert.equal(compassMarkerSlot(100, 100), 0);
assert.equal(compassMarkerSlot(90, 100), nearest.slot);
// Across north the slots stay continuous.
assert.deepEqual(
scrollingCompassDivisions(355, 1).map(({ heading, slot }) => [
heading,
slot,
]),
[
[330, -0.8333],
[0, 0.1667],
[30, 1.1667],
],
);
assert.deepEqual(scrollingCompassDivisions(Number.NaN), []);
});
test('compass labels use cardinals where exact and degrees elsewhere', () => {
assert.equal(formatCompassDivision(270), 'W');
assert.equal(formatCompassDivision(30), '030');
@@ -365,7 +432,7 @@ test('tracked-identity resolution falls back to layer precedence', () => {
const civilian = { icao24: 'aaa077' };
const military = { icao24: 'ae01ce' };
// No stamped identity (or one that matches neither layer) keeps the historic
// civilian-first order so tracking paths without gevTrackedId still work.
// civilian-first order so tracking paths without an entity record trackedId still work.
assert.equal(resolveTrackedAircraftInfo({ civilian, military }).layerId, 'flights');
assert.equal(
resolveTrackedAircraftInfo({ civilian, military, trackedId: 'satellites:25544' }).layerId,
@@ -393,3 +460,30 @@ test('cockpit emergency wording states the broadcast code, not a conclusion', ()
assert.equal(formatCockpitEmergency(null), null);
assert.equal(formatCockpitEmergency({ label: '' }), null);
});
test('an application subject’s ground lift eases its clearance, never the floor', () => {
// On entry the lift asked for applies at once.
assert.equal(easeCockpitLift(null, 1.5, 0, 0.016), 1.5);
// A floor cell that rises by a metre is met at the lift rate...
let lift = 0;
const frames = [];
for (let i = 0; i < 60; i += 1) {
lift = easeCockpitLift(lift, 1, 0, 0.016);
frames.push(lift);
}
assert.ok(frames[0] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9);
for (let i = 1; i < frames.length; i += 1)
assert.ok(
frames[i] - frames[i - 1] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9,
);
assert.ok(Math.abs(frames.at(-1) - 1) < 1e-9, 'reached in under a second');
// ...and given back the same way.
assert.ok(Math.abs(easeCockpitLift(1, 0, 0, 0.1) - 0.85) < 1e-9);
// What keeps the eye out of the floor itself is never eased.
assert.equal(easeCockpitLift(0, 201.5, 200, 0.016), 200);
assert.equal(
easeCockpitLift(0.2, -3, -3, 0.016),
0.2 - COCKPIT_SUBJECT_LIFT_MPS * 0.016,
);
assert.equal(easeCockpitLift(0, Number.NaN, Number.NaN, 0.016), 0);
});
+808
View File
@@ -0,0 +1,808 @@
/**
* Camera policy for the orbital (satellite) view: the eye rides the tracked
* satellite and looks straight down at the Earth's centre. Satellites publish
* no attitude, so the picture is turned to the ground track (track-up; see
* nadirOrientation's `headingDeg`), or north-up for a satellite with none
* (geostationary). This module holds the zoom steps,
* the field of view, the nadir orientation, the ground footprint and the zoom
* transition curves. No DOM, Cesium or i18n dependencies: vectors are plain
* `{x, y, z}` objects in Earth-fixed (ECEF) metres, so the policy is
* unit-testable and the Cockpit camera copies them into its own scratch.
*/
/** Mean Earth radius used for footprint and framing geometry, metres. */
export const ORBITAL_EARTH_RADIUS_M = 6371008.8;
/**
* The whole zoom ladder. Steps past ORBITAL_BASE_MAX_ZOOM belong only to
* imaging satellites with a known sensor, each up to the step its sensor's
* swath allows (`orbitalMaxZoom`).
*/
export const ORBITAL_ZOOM_LADDER = Object.freeze([1, 2, 4, 8, 16, 32, 64, 128]);
/** The tightest step for a satellite without sensor data. */
export const ORBITAL_BASE_MAX_ZOOM = 8;
/** The zoom an orbital view opens at. */
export const ORBITAL_DEFAULT_ZOOM = 1;
/**
* Vertical field of view at 1x for low orbits. From the ISS (~420 km) a 60°
* frame spans roughly 490 km of ground top to bottom: a regional picture
* with the curvature just out of frame, which 8x narrows to ~60 km.
*/
export const ORBITAL_BASE_FOV_LEO_RAD = (60 * Math.PI) / 180;
/**
* How much wider than the Earth's disk a high orbit's 1x frame is. A fixed
* 60° frame from GEO (~35,786 km) would show a 17° Earth floating in black;
* above about 8,000 km the base frame instead fits the whole disk with this
* margin, so 1x is "the whole Earth" and the steps zoom into it.
*/
export const ORBITAL_DISK_MARGIN = 1.15;
/** Duration of one zoom step's field-of-view change, ms. */
export const ORBITAL_ZOOM_TRANSITION_MS = 400;
/** How long the reticle shows its lock tick after a step settles, ms. */
export const ORBITAL_LOCK_TICK_MS = 220;
/** Peak focus-pull blur at the middle of a zoom step, CSS pixels. */
export const ORBITAL_MAX_BLUR_PX = 6;
/**
* Longest a zoom step holds its focus pull for the new field of view's
* imagery, ms. The camera moves at orbital speed, so the tiles may never
* all arrive; the hold gives them a start, then the reticle locks anyway.
*/
export const ORBITAL_SETTLE_MAX_MS = 2500;
/** The soft blur held while a step waits for its imagery, CSS pixels. */
export const ORBITAL_SETTLE_BLUR_PX = 2.5;
/** Relative slack so a zoom computed in floating point still meets its step. */
const ZOOM_EPSILON = 1e-6;
/**
* The next tighter ladder step, up to `maxZoom`; at the cap the zoom stays.
* A zoom between steps (the SENSOR step) moves to the step above it.
* @param {number} zoom Current zoom.
* @param {number} [maxZoom] The satellite's tightest step.
* @returns {number}
*/
export function nextOrbitalZoom(zoom, maxZoom = ORBITAL_BASE_MAX_ZOOM) {
const current = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
const next = ORBITAL_ZOOM_LADDER.find(
(step) => step > current * (1 + ZOOM_EPSILON) && step <= maxZoom,
);
return next ?? current;
}
/**
* The next wider ladder step; 1x stays where it is. A zoom between steps
* moves to the step below it.
* @param {number} zoom Current zoom.
* @returns {number}
*/
export function previousOrbitalZoom(zoom) {
const current = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
const wider = ORBITAL_ZOOM_LADDER.filter(
(step) => step < current * (1 - ZOOM_EPSILON),
);
return wider.length ? wider[wider.length - 1] : ORBITAL_DEFAULT_ZOOM;
}
/**
* The ground width the view spans at a zoom: what the SWATH readout shows.
* @param {number} altitudeM Satellite altitude, metres.
* @param {number} zoom Magnification.
* @param {number} aspect Canvas width / height.
* @returns {number|null} Kilometres, or null for an unusable altitude.
*/
export function viewWidthKm(altitudeM, zoom, aspect) {
return footprintWidthKm(
altitudeM,
fovForZoom(orbitalBaseFovRad(altitudeM), zoom),
aspect,
);
}
/**
* A satellite's tightest zoom step at its live altitude: the tightest ladder
* step whose view is still at least as wide as its sensor's narrowest
* standard swath, so the view never shows finer ground than the sensor
* images. Never below ORBITAL_BASE_MAX_ZOOM; no sensor swath, no extra steps.
* @param {number} altitudeM Live altitude, metres.
* @param {number|null|undefined} sensorSwathKm Narrowest standard swath.
* @param {number} aspect Canvas width / height.
* @returns {number} One of ORBITAL_ZOOM_LADDER.
*/
export function orbitalMaxZoom(altitudeM, sensorSwathKm, aspect) {
if (!Number.isFinite(sensorSwathKm) || sensorSwathKm <= 0)
return ORBITAL_BASE_MAX_ZOOM;
let max = ORBITAL_BASE_MAX_ZOOM;
for (const step of ORBITAL_ZOOM_LADDER) {
if (step <= ORBITAL_BASE_MAX_ZOOM) continue;
const width = viewWidthKm(altitudeM, step, aspect);
if (!Number.isFinite(width)) break;
if (width * (1 + ZOOM_EPSILON) < sensorSwathKm) break;
max = step;
}
return max;
}
/**
* The zoom at which the view is exactly as wide as the sensor's swath, for
* the SENSOR step; null when that lies outside 1x..`maxZoom` (a swath wider
* than the 1x view, or narrower than the tightest allowed step).
* @param {number} altitudeM Live altitude, metres.
* @param {number|null|undefined} sensorSwathKm
* @param {number} aspect Canvas width / height.
* @param {number} maxZoom The satellite's tightest step.
* @returns {number|null}
*/
export function sensorSwathZoom(altitudeM, sensorSwathKm, aspect, maxZoom) {
if (!Number.isFinite(sensorSwathKm) || sensorSwathKm <= 0) return null;
const widest = viewWidthKm(altitudeM, 1, aspect);
const tightest = viewWidthKm(altitudeM, maxZoom, aspect);
if (!Number.isFinite(widest) || !Number.isFinite(tightest)) return null;
if (sensorSwathKm > widest * (1 + ZOOM_EPSILON)) return null;
if (sensorSwathKm < tightest * (1 - ZOOM_EPSILON)) return null;
// The width falls monotonically with zoom: bisect in log space.
let low = 0;
let high = Math.log2(maxZoom);
for (let i = 0; i < 48; i += 1) {
const mid = (low + high) / 2;
if (viewWidthKm(altitudeM, 2 ** mid, aspect) > sensorSwathKm) low = mid;
else high = mid;
}
return Math.round(2 ** ((low + high) / 2) * 100) / 100;
}
/**
* How much of the view's width a sensor swath covers, for the strip drawn
* to scale in the reticle: 0..1, 1 when the swath fills the view or more.
* @param {number|null|undefined} sensorSwathKm
* @param {number|null|undefined} viewKm The view's current ground width.
* @returns {number|null} Null without both widths.
*/
export function sensorStripFraction(sensorSwathKm, viewKm) {
if (!Number.isFinite(sensorSwathKm) || sensorSwathKm <= 0) return null;
if (!Number.isFinite(viewKm) || viewKm <= 0) return null;
return Math.min(1, sensorSwathKm / viewKm);
}
/**
* Angular radius of the Earth's disk seen from an altitude, radians.
* @param {number} altitudeM Height above the mean sphere, metres.
* @returns {number} Half-angle from nadir to the limb (π/2 at the surface).
*/
export function earthAngularRadiusRad(altitudeM) {
const h = Math.max(0, Number.isFinite(altitudeM) ? altitudeM : 0);
return Math.asin(ORBITAL_EARTH_RADIUS_M / (ORBITAL_EARTH_RADIUS_M + h));
}
/**
* Vertical field of view at 1x for an altitude, radians.
*
* Low orbits get the fixed 60° regional frame. Higher orbits, where 60° would
* leave the Earth small in a black frame, get the Earth's disk plus
* ORBITAL_DISK_MARGIN. The two meet near 8,100 km, so the base never jumps
* as an eccentric orbit climbs: GPS (~20,200 km) opens at ~32°, GEO at ~20°.
* @param {number} altitudeM Satellite altitude, metres.
* @returns {number} Vertical field of view, radians.
*/
export function orbitalBaseFovRad(altitudeM) {
const diskFov = 2 * earthAngularRadiusRad(altitudeM) * ORBITAL_DISK_MARGIN;
return Math.min(ORBITAL_BASE_FOV_LEO_RAD, diskFov);
}
/**
* Field of view at an optical zoom: magnification divides the tangent of
* the half-angle, as a lens's focal length does.
* @param {number} baseFovRad Field of view at 1x, radians.
* @param {number} zoom Magnification (1 leaves the base unchanged).
* @returns {number} Field of view, radians.
*/
export function fovForZoom(baseFovRad, zoom) {
const magnification = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
return 2 * Math.atan(Math.tan(baseFovRad / 2) / magnification);
}
/**
* Cesium's `PerspectiveFrustum.fov` is horizontal on a landscape canvas and
* vertical on a portrait one; convert a vertical field of view to it.
* @param {number} verticalFovRad Vertical field of view, radians.
* @param {number} aspect Canvas width / height.
* @returns {number} The value to assign to `frustum.fov`, radians.
*/
export function cesiumFrustumFovRad(verticalFovRad, aspect) {
if (!(aspect > 1)) return verticalFovRad;
return 2 * Math.atan(Math.tan(verticalFovRad / 2) * aspect);
}
/**
* Ground width covered across the frame, along a great circle through the
* sub-satellite point, km. A ray past the limb ends at the horizon, so a
* frame wider than the disk reports the visible cap's width.
* @param {number} altitudeM Satellite altitude, metres.
* @param {number} fovRad Vertical field of view, radians.
* @param {number} [aspect=1] Frame width / height; the width is measured
* across the wider horizontal extent.
* @returns {number|null} Width in kilometres, or null without a usable input.
*/
export function footprintWidthKm(altitudeM, fovRad, aspect = 1) {
if (!Number.isFinite(altitudeM) || altitudeM <= 0) return null;
if (!Number.isFinite(fovRad) || fovRad <= 0) return null;
const ratio = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
const halfAngle = Math.atan(Math.tan(fovRad / 2) * ratio);
const R = ORBITAL_EARTH_RADIUS_M;
const sinGround = ((R + altitudeM) / R) * Math.sin(halfAngle);
// Central angle from nadir to where the ray meets the sphere, or the limb.
const central =
sinGround >= 1
? Math.acos(R / (R + altitudeM))
: Math.asin(sinGround) - halfAngle;
return (2 * R * central) / 1000;
}
function length(v) {
return Math.hypot(v.x, v.y, v.z);
}
function scale(v, s) {
return { x: v.x * s, y: v.y * s, z: v.z * s };
}
function dot(a, b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
function cross(a, b) {
return {
x: a.y * b.z - a.z * b.y,
y: a.z * b.x - a.x * b.z,
z: a.x * b.y - a.y * b.x,
};
}
/** `v` with its component along unit `d` removed, or null when degenerate. */
function perpendicularUnit(v, d) {
const along = dot(v, d);
const p = {
x: v.x - along * d.x,
y: v.y - along * d.y,
z: v.z - along * d.z,
};
const n = length(p);
return n > 1e-6 ? scale(p, 1 / n) : null;
}
const NORTH_AXIS = Object.freeze({ x: 0, y: 0, z: 1 });
/**
* Camera orientation looking from an Earth-fixed position at the Earth's
* centre, with north at the top of the frame.
*
* `up` is the Earth's rotation axis projected perpendicular to the view, which
* is local north at the sub-satellite point. Directly over a pole north is
* undefined; the previous frame's `up` is kept when given (so a polar pass
* does not spin the picture), otherwise the limit along the prime meridian
* is used: over the north pole the top of the frame faces 180°E, over the
* south pole 0°E.
*
* With `headingDeg` the frame turns so that bearing (degrees clockwise from
* north) is at the top: the ground track, for a view that scrolls along it.
* @param {{x: number, y: number, z: number}} position ECEF position, metres.
* @param {{previousUp?: {x: number, y: number, z: number}|null,
* headingDeg?: number|null}} [options] `previousUp` is a previous frame's
* `north`, not its turned `up`.
* @returns {{direction: {x: number, y: number, z: number},
* up: {x: number, y: number, z: number},
* right: {x: number, y: number, z: number},
* north: {x: number, y: number, z: number}}|null} Unit vectors (right =
* direction × up, as Cesium's camera keeps them), or null at the centre.
*/
export function nadirOrientation(
position,
{ previousUp = null, headingDeg = null } = {},
) {
if (!position) return null;
const r = length(position);
if (!Number.isFinite(r) || r < 1) return null;
const direction = scale(position, -1 / r);
let up = perpendicularUnit(NORTH_AXIS, direction);
if (!up && previousUp && Number.isFinite(length(previousUp)))
up = perpendicularUnit(previousUp, direction);
if (!up) {
// Looking down -z (north pole): north at longitude 0 points along -x.
up = perpendicularUnit(
{ x: direction.z < 0 ? -1 : 1, y: 0, z: 0 },
direction,
);
}
const north = up;
if (Number.isFinite(headingDeg) && headingDeg % 360 !== 0) {
// Looking down, right = direction × north is east: the bearing turns
// north toward it.
const east = cross(direction, north);
const θ = (headingDeg * Math.PI) / 180;
up = {
x: north.x * Math.cos(θ) + east.x * Math.sin(θ),
y: north.y * Math.cos(θ) + east.y * Math.sin(θ),
z: north.z * Math.cos(θ) + east.z * Math.sin(θ),
};
}
return { direction, up, right: cross(direction, up), north };
}
/**
* Ease-in-out progress of a zoom step (cubic), clamped to 0..1.
* @param {number} elapsedMs Time since the step began.
* @param {{durationMs?: number, reducedMotion?: boolean}} [options]
* Reduced motion cuts straight to the end.
* @returns {number} Eased progress, 0..1.
*/
export function zoomTransitionProgress(
elapsedMs,
{ durationMs = ORBITAL_ZOOM_TRANSITION_MS, reducedMotion = false } = {},
) {
if (reducedMotion || !(durationMs > 0)) return 1;
const linear = Math.min(1, Math.max(0, (elapsedMs || 0) / durationMs));
return linear < 0.5 ? 4 * linear ** 3 : 1 - (-2 * linear + 2) ** 3 / 2;
}
/**
* Focus-pull blur for a zoom step: zero at both ends, peaking mid-step.
* @param {number} progress Step progress, 0..1 (linear or eased).
* @param {{maxBlurPx?: number, reducedMotion?: boolean}} [options]
* Reduced motion never blurs.
* @returns {number} Blur radius, CSS pixels.
*/
export function zoomTransitionBlurPx(
progress,
{ maxBlurPx = ORBITAL_MAX_BLUR_PX, reducedMotion = false } = {},
) {
if (reducedMotion || !Number.isFinite(progress)) return 0;
const p = Math.min(1, Math.max(0, progress));
return Math.max(0, maxBlurPx) * Math.sin(Math.PI * p);
}
/**
* Field of view part-way through a zoom step. Interpolates the tangent of
* the half-angle geometrically, so each moment of the step magnifies by the
* same ratio and 1x→2x feels like 4x→8x.
* @param {number} fromFovRad Field of view the step starts at.
* @param {number} toFovRad Field of view the step ends at.
* @param {number} progress Eased progress, 0..1.
* @returns {number} Field of view, radians.
*/
export function interpolateZoomFov(fromFovRad, toFovRad, progress) {
const p = Math.min(1, Math.max(0, Number.isFinite(progress) ? progress : 1));
const a = Math.log(Math.tan(fromFovRad / 2));
const b = Math.log(Math.tan(toFovRad / 2));
return 2 * Math.atan(Math.exp(a + (b - a) * p));
}
/**
* The HUD's transition state at a moment of a zoom step, in the store shape
* `{ active, blurPx, lockTick }`: blur while the field of view moves, then a
* brief reticle lock tick once it settles. Reduced motion skips the blur and
* the tick (the cut is instant).
* @param {number} elapsedMs Time since the step began.
* @param {{durationMs?: number, lockTickMs?: number, maxBlurPx?: number,
* reducedMotion?: boolean}} [options]
* @returns {{active: boolean, progress: number, blurPx: number,
* lockTick: boolean}}
*/
export function zoomTransitionState(
elapsedMs,
{
durationMs = ORBITAL_ZOOM_TRANSITION_MS,
lockTickMs = ORBITAL_LOCK_TICK_MS,
maxBlurPx = ORBITAL_MAX_BLUR_PX,
reducedMotion = false,
} = {},
) {
const progress = zoomTransitionProgress(elapsedMs, {
durationMs,
reducedMotion,
});
if (reducedMotion)
return { active: false, progress: 1, blurPx: 0, lockTick: false };
const elapsed = Math.max(0, elapsedMs || 0);
const linear = durationMs > 0 ? Math.min(1, elapsed / durationMs) : 1;
return {
active: elapsed < durationMs,
progress,
blurPx: zoomTransitionBlurPx(linear, { maxBlurPx }),
lockTick: elapsed >= durationMs && elapsed < durationMs + lockTickMs,
};
}
/**
* Whether a zoom step whose field of view has landed still holds its focus
* pull: until the imagery has loaded, at most `maxHoldMs`.
* @param {number} sinceLandedMs Time since the field of view stopped moving.
* @param {boolean} tilesLoaded Whether the scene's imagery has loaded.
* @param {{maxHoldMs?: number}} [options]
*/
export function zoomSettleHolding(
sinceLandedMs,
tilesLoaded,
{ maxHoldMs = ORBITAL_SETTLE_MAX_MS } = {},
) {
return !tilesLoaded && Math.max(0, sinceLandedMs || 0) < maxHoldMs;
}
/**
* The total angle between a tilted view and nadir, degrees:
* acos(cos north · cos east), as `offNadirOrientation` tilts.
* @param {{northDeg?: number, eastDeg?: number}} [offset] Tilt in degrees.
* @returns {number}
*/
export function offNadirAngleDeg({ northDeg = 0, eastDeg = 0 } = {}) {
const n = ((Number.isFinite(northDeg) ? northDeg : 0) * Math.PI) / 180;
const e = ((Number.isFinite(eastDeg) ? eastDeg : 0) * Math.PI) / 180;
const cosine = Math.min(1, Math.max(-1, Math.cos(n) * Math.cos(e)));
return (Math.acos(cosine) * 180) / Math.PI;
}
/**
* Whether the view's centre, tilted off nadir, still meets the Earth: its
* angle from nadir (`offNadirAngleDeg`) is within the Earth's angular radius
* from the satellite, asin(R / (R + altitude)).
* @param {number} altitudeM
* @param {{northDeg?: number, eastDeg?: number}} [offset]
* @returns {boolean}
*/
export function offNadirCentreMeetsEarth(altitudeM, offset = {}) {
if (!Number.isFinite(altitudeM) || altitudeM <= 0) return false;
const R = ORBITAL_EARTH_RADIUS_M;
const limbDeg = (Math.asin(R / (R + altitudeM)) * 180) / Math.PI;
return offNadirAngleDeg(offset) < limbDeg;
}
/**
* Roughly how much wider the ground across the frame is at the centre of a
* tilted view than at nadir, on a flat Earth: tilting across the frame (east,
* the frame's right) stretches its width by 1/cos², tilting along it (north,
* the frame's top) by 1/cos. 1 at nadir; an approximation, so the HUD marks
* the width it scales with ≈.
* @param {{northDeg?: number, eastDeg?: number}} [offset] Tilt in degrees.
* @returns {number} At least 1.
*/
export function offNadirSwathScale({ northDeg = 0, eastDeg = 0 } = {}) {
const n = ((Number.isFinite(northDeg) ? northDeg : 0) * Math.PI) / 180;
const e = ((Number.isFinite(eastDeg) ? eastDeg : 0) * Math.PI) / 180;
const along = Math.abs(Math.cos(n));
const across = Math.cos(e) ** 2;
if (!(along > 1e-6) || !(across > 1e-6)) return 1;
return Math.max(1, 1 / (along * across));
}
/**
* Tilt a nadir orientation off nadir: first toward north (a rotation about
* the nadir frame's right axis), then toward east (about the tilted up
* axis). The base frame is always the nadir one, so a tilt never drifts with
* the orbit; the angle from nadir is acos(cos north · cos east).
* @param {{direction: object, up: object, right: object}} nadir From
* {@link nadirOrientation}.
* @param {{northDeg?: number, eastDeg?: number}} [offset] Tilt in degrees;
* negative is south or west.
* @returns {{direction: object, up: object, right: object}} Unit vectors,
* right = direction × up.
*/
export function offNadirOrientation(nadir, { northDeg = 0, eastDeg = 0 } = {}) {
const n = ((Number.isFinite(northDeg) ? northDeg : 0) * Math.PI) / 180;
const e = ((Number.isFinite(eastDeg) ? eastDeg : 0) * Math.PI) / 180;
if (n === 0 && e === 0) return nadir;
const { direction: d, up: u, right: r } = nadir;
const combine = (a, ka, b, kb) => ({
x: a.x * ka + b.x * kb,
y: a.y * ka + b.y * kb,
z: a.z * ka + b.z * kb,
});
// Toward north: the view swings onto the up axis, up swings off it.
const d1 = combine(d, Math.cos(n), u, Math.sin(n));
const u1 = combine(u, Math.cos(n), d, -Math.sin(n));
// Toward east: the view swings onto the right axis.
const direction = combine(d1, Math.cos(e), r, Math.sin(e));
return { direction, up: u1, right: cross(direction, u1) };
}
/** Scroll distance, in pixels, that makes one zoom step. A mouse notch is ~100. */
export const ORBITAL_WHEEL_PIXELS_PER_STEP = 100;
/**
* After a step, the rest of that gesture is absorbed for this long, so one
* physical notch (which some browsers deliver as several events) is one step.
*/
export const ORBITAL_WHEEL_COOLDOWN_MS = 200;
/**
* A pause this long ends a scroll gesture: a partial sum left from an earlier
* gesture never adds to a later one.
*/
export const ORBITAL_WHEEL_GESTURE_GAP_MS = 300;
/** `WheelEvent.deltaMode` line and page units, in pixels. */
const WHEEL_LINE_PX = 16;
const WHEEL_PAGE_PX = 800;
/**
* Turn wheel events into zoom steps. Trackpads send many small pixel deltas,
* so they are summed until they reach a step; a change of direction, or a
* pause of ORBITAL_WHEEL_GESTURE_GAP_MS, starts over. Wheeling away from the
* viewer (negative deltaY) zooms in.
* @param {{sum: number, lastStepMs: number, lastEventMs?: number}|null}
* accumulator Previous state.
* @param {{deltaY: number, deltaMode?: number}} wheel The event's deltas.
* @param {number} nowMs
* @returns {{accumulator: {sum: number, lastStepMs: number,
* lastEventMs: number}, step: -1|0|1}} The new state and the step to take
* (1 = zoom in).
*/
export function wheelZoomStep(accumulator, wheel, nowMs) {
const held = accumulator || { sum: 0, lastStepMs: -Infinity };
const previous =
nowMs - (held.lastEventMs ?? -Infinity) > ORBITAL_WHEEL_GESTURE_GAP_MS
? { ...held, sum: 0 }
: held;
const unit =
wheel?.deltaMode === 1
? WHEEL_LINE_PX
: wheel?.deltaMode === 2
? WHEEL_PAGE_PX
: 1;
const delta = (Number.isFinite(wheel?.deltaY) ? wheel.deltaY : 0) * unit;
if (!delta) return { accumulator: held, step: 0 };
if (nowMs - previous.lastStepMs < ORBITAL_WHEEL_COOLDOWN_MS)
return {
accumulator: { ...previous, sum: 0, lastEventMs: nowMs },
step: 0,
};
const sum =
Math.sign(previous.sum) === -Math.sign(delta)
? delta
: previous.sum + delta;
if (Math.abs(sum) < ORBITAL_WHEEL_PIXELS_PER_STEP)
return { accumulator: { ...previous, sum, lastEventMs: nowMs }, step: 0 };
return {
accumulator: { sum: 0, lastStepMs: nowMs, lastEventMs: nowMs },
step: sum < 0 ? 1 : -1,
};
}
/** From this zoom the view pre-loads imagery ahead along the ground track. */
export const ORBITAL_PREFETCH_MIN_ZOOM = 16;
/** How often the pre-load looks ahead, ms. */
export const ORBITAL_PREFETCH_INTERVAL_MS = 2000;
/** How far ahead it looks, seconds of ground-track travel, nearest first. */
export const ORBITAL_PREFETCH_LEAD_S = Object.freeze([5, 10, 15, 20]);
/**
* Where across the track it looks, as fractions of the view's width: the
* centre line, a third out and the frame's edges each side, so a row of
* tiles a fifth of the view wide or more spans the frame.
*/
export const ORBITAL_PREFETCH_ACROSS = Object.freeze([
0,
-1 / 3,
1 / 3,
-1 / 2,
1 / 2,
]);
/**
* The points ahead, regrouped by their place across the track: every lead's
* centre point first, then each lead's next pair out, so the tile cap trims
* the frame's edges before it trims the far leads.
* @param {Array<{lat: number, lon: number}>} points From `groundTrackAhead`,
* lead by lead.
* @param {number} [across] Points per lead.
* @returns {Array<{lat: number, lon: number}>}
*/
export function centreLinesFirst(
points,
across = ORBITAL_PREFETCH_ACROSS.length,
) {
const out = [];
for (let k = 0; k < across; k += 1)
for (let i = k; i < points.length; i += across) out.push(points[i]);
return out;
}
/** At most this many tile requests per look-ahead. */
export const ORBITAL_PREFETCH_MAX_TILES = 12;
const toRadians = (deg) => (deg * Math.PI) / 180;
const toDegrees = (rad) => (rad * 180) / Math.PI;
/**
* The point `distanceM` from a point along an initial bearing, on a sphere.
* @returns {{lat: number, lon: number}} Degrees, longitude in -180..180.
*/
export function destinationPoint(latDeg, lonDeg, bearingDeg, distanceM) {
const delta = distanceM / ORBITAL_EARTH_RADIUS_M;
const lat1 = toRadians(latDeg);
const theta = toRadians(bearingDeg);
const lat2 = Math.asin(
Math.sin(lat1) * Math.cos(delta) +
Math.cos(lat1) * Math.sin(delta) * Math.cos(theta),
);
const lon2 =
toRadians(lonDeg) +
Math.atan2(
Math.sin(theta) * Math.sin(delta) * Math.cos(lat1),
Math.cos(delta) - Math.sin(lat1) * Math.sin(lat2),
);
const lon = ((((toDegrees(lon2) + 180) % 360) + 360) % 360) - 180;
return { lat: toDegrees(lat2), lon };
}
/**
* Points the view will pass over: for each lead time, the sub-satellite
* point that far along the ground track (orbital speed scaled down to the
* ground), and points across the track at `across` fractions of the view's
* width. Nearest lead first. Empty without a track, speed or width.
* @param {{latitude: number, longitude: number, groundTrackDeg: number,
* velocityMps: number, altitudeM: number}} info Satellite subject.
* @param {number} viewKm The view's ground width, km.
* @returns {Array<{lat: number, lon: number}>}
*/
export function groundTrackAhead(
info,
viewKm,
{ leadS = ORBITAL_PREFETCH_LEAD_S, across = ORBITAL_PREFETCH_ACROSS } = {},
) {
const { latitude, longitude, groundTrackDeg, velocityMps, altitudeM } =
info || {};
if (
![latitude, longitude, groundTrackDeg, velocityMps, altitudeM].every(
Number.isFinite,
) ||
velocityMps <= 0 ||
altitudeM <= 0 ||
!(viewKm > 0)
)
return [];
const R = ORBITAL_EARTH_RADIUS_M;
const groundMps = (velocityMps * R) / (R + altitudeM);
const points = [];
for (const seconds of leadS) {
const centre = destinationPoint(
latitude,
longitude,
groundTrackDeg,
groundMps * seconds,
);
for (const fraction of across) {
points.push(
fraction === 0
? centre
: destinationPoint(
centre.lat,
centre.lon,
groundTrackDeg + (fraction > 0 ? 90 : -90),
Math.abs(fraction) * viewKm * 1000,
),
);
}
}
return points;
}
/** WGS84's equatorial radius: Cesium sizes terrain and imagery tiles on it. */
const WGS84_MAXIMUM_RADIUS_M = 6378137;
/**
* Cesium's geometric error for a heightmap terrain tile at `level`, metres:
* its level-zero estimate (TerrainProvider's
* getEstimatedLevelZeroGeometricErrorForAHeightmap, heightmap quality 0.25)
* for the ellipsoid terrain's 64-sample tiles on two root tiles, halved per
* level.
* @param {number} level
* @returns {number}
*/
export function ellipsoidTerrainLevelErrorM(level) {
return (WGS84_MAXIMUM_RADIUS_M * 2 * Math.PI * 0.25) / (64 * 2) / 2 ** level;
}
/** The deepest terrain level considered. */
const MAX_TERRAIN_LEVEL = 30;
/**
* The imagery level Cesium draws under the view, and so the one to pre-load.
* Cesium refines the terrain tile under the view while its geometric error
* spans more than `maximumScreenSpaceError` pixels (QuadtreePrimitive's
* screenSpaceError: error over the ground a pixel covers), then drapes the
* imagery level whose texel spacing is nearest that error (ImageryLayer's
* getLevelWithMaximumTexelSpacing, rounded): about one to two screen pixels
* per texel, not one. Fog, which below 800 km can only coarsen the choice,
* is left out. Clamped to the provider's levels; null without a usable input.
* @param {{getNumberOfXTilesAtLevel?: (level: number) => number,
* rectangle?: {width: number}}} tilingScheme The imagery tiling scheme.
* @param {{metresPerPixel: number, latitudeDeg: number,
* geographic?: boolean, tileWidthPx?: number, minimumLevel?: number,
* maximumLevel?: number, maximumScreenSpaceError?: number,
* terrainLevelErrorM?: (level: number) => number}} view `metresPerPixel`
* is the ground one CSS pixel covers at the view's centre; `geographic`
* marks a scheme in the geographic projection, whose texels do not narrow
* with latitude as Web Mercator's do; `terrainLevelErrorM` is the terrain
* provider's getLevelMaximumGeometricError.
* @returns {number|null}
*/
export function imageryLevelForView(
tilingScheme,
{
metresPerPixel,
latitudeDeg,
geographic = false,
tileWidthPx = 256,
minimumLevel = 0,
maximumLevel = 30,
maximumScreenSpaceError = 2,
terrainLevelErrorM = ellipsoidTerrainLevelErrorM,
},
) {
if (!(metresPerPixel > 0) || !Number.isFinite(latitudeDeg)) return null;
const sse = maximumScreenSpaceError > 0 ? maximumScreenSpaceError : 2;
let terrainLevel = 0;
while (
terrainLevel < MAX_TERRAIN_LEVEL &&
!(terrainLevelErrorM(terrainLevel) / metresPerPixel <= sse)
)
terrainLevel += 1;
const errorM = terrainLevelErrorM(terrainLevel);
if (!(errorM > 0)) return null;
const rootTiles = tilingScheme?.getNumberOfXTilesAtLevel?.(0) || 1;
const widthRad = tilingScheme?.rectangle?.width || 2 * Math.PI;
const latitudeFactor = geographic
? 1
: Math.cos(toRadians(Math.min(89, Math.abs(latitudeDeg))));
const levelZeroTexelM =
(WGS84_MAXIMUM_RADIUS_M * widthRad * latitudeFactor) /
((tileWidthPx || 256) * rootTiles);
const level = Math.max(0, Math.round(Math.log2(levelZeroTexelM / errorM)));
if (!Number.isFinite(level)) return null;
const top = Number.isFinite(maximumLevel) ? maximumLevel : 30;
const bottom = Number.isFinite(minimumLevel) ? minimumLevel : 0;
return Math.min(top, Math.max(bottom, level));
}
/**
* The tiles at `level` holding `points`, in order, without repeats or tiles
* `skip` reports as already asked for, at most `maxTiles`.
* @param {{positionToTileXY: Function}} tilingScheme Cesium tiling scheme.
* @param {Array<{lat: number, lon: number}>} points Degrees.
* @param {number} level
* @param {{maxTiles?: number, skip?: (key: string) => boolean}} [options]
* @returns {Array<{x: number, y: number, level: number, key: string}>}
*/
export function tilesForPoints(
tilingScheme,
points,
level,
{ maxTiles = ORBITAL_PREFETCH_MAX_TILES, skip = () => false } = {},
) {
const tiles = [];
if (typeof tilingScheme?.positionToTileXY !== 'function') return tiles;
if (!Number.isInteger(level) || level < 0) return tiles;
const seen = new Set();
for (const point of points) {
if (tiles.length >= maxTiles) break;
const xy = tilingScheme.positionToTileXY(
{ longitude: toRadians(point.lon), latitude: toRadians(point.lat) },
level,
);
if (!xy) continue;
const key = `${level}/${xy.x}/${xy.y}`;
if (seen.has(key) || skip(key)) continue;
seen.add(key);
tiles.push({ x: xy.x, y: xy.y, level, key });
}
return tiles;
}
+618
View File
@@ -0,0 +1,618 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
ORBITAL_ZOOM_LADDER,
ORBITAL_BASE_FOV_LEO_RAD,
ORBITAL_EARTH_RADIUS_M,
ORBITAL_SETTLE_MAX_MS,
ORBITAL_WHEEL_COOLDOWN_MS,
cesiumFrustumFovRad,
earthAngularRadiusRad,
footprintWidthKm,
fovForZoom,
interpolateZoomFov,
nadirOrientation,
nextOrbitalZoom,
offNadirAngleDeg,
offNadirCentreMeetsEarth,
centreLinesFirst,
offNadirSwathScale,
orbitalMaxZoom,
sensorStripFraction,
sensorSwathZoom,
viewWidthKm,
wheelZoomStep,
ORBITAL_WHEEL_GESTURE_GAP_MS,
offNadirOrientation,
orbitalBaseFovRad,
previousOrbitalZoom,
zoomSettleHolding,
zoomTransitionBlurPx,
zoomTransitionProgress,
zoomTransitionState,
ORBITAL_PREFETCH_ACROSS,
ORBITAL_PREFETCH_LEAD_S,
ORBITAL_PREFETCH_MAX_TILES,
destinationPoint,
groundTrackAhead,
imageryLevelForView,
tilesForPoints,
} from './cockpitOrbital.js';
import * as Cesium from 'cesium';
import { greatCircleKm } from './geoDistance.js';
const RAD = Math.PI / 180;
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const norm = (v) => Math.hypot(v.x, v.y, v.z);
/** ECEF position on the mean sphere at a latitude, longitude and altitude. */
function ecef(latDeg, lonDeg, altitudeM) {
const r = ORBITAL_EARTH_RADIUS_M + altitudeM;
const lat = latDeg * RAD;
const lon = lonDeg * RAD;
return {
x: r * Math.cos(lat) * Math.cos(lon),
y: r * Math.cos(lat) * Math.sin(lon),
z: r * Math.sin(lat),
};
}
/** Local north unit vector at a latitude and longitude. */
function localNorth(latDeg, lonDeg) {
const lat = latDeg * RAD;
const lon = lonDeg * RAD;
return {
x: -Math.sin(lat) * Math.cos(lon),
y: -Math.sin(lat) * Math.sin(lon),
z: Math.cos(lat),
};
}
function assertOrthonormal(orientation) {
const { direction, up, right } = orientation;
for (const v of [direction, up, right])
assert.ok(Math.abs(norm(v) - 1) < 1e-9);
assert.ok(Math.abs(dot(direction, up)) < 1e-9);
assert.ok(Math.abs(dot(direction, right)) < 1e-9);
assert.ok(Math.abs(dot(up, right)) < 1e-9);
}
test('the nadir view points at the Earth centre with north up', () => {
for (const [lat, lon, alt] of [
[0, 0, 420e3],
[51.6, -97.3, 420e3],
[-33.9, 151.2, 20.2e6],
[0.05, 75, 35.786e6],
]) {
const position = ecef(lat, lon, alt);
const orientation = nadirOrientation(position);
const toCentre = {
x: -position.x / norm(position),
y: -position.y / norm(position),
z: -position.z / norm(position),
};
assert.ok(dot(orientation.direction, toCentre) > 1 - 1e-12);
assert.ok(dot(orientation.up, localNorth(lat, lon)) > 1 - 1e-9);
assertOrthonormal(orientation);
// North up puts east on the right of a picture looking down.
const east = { x: -Math.sin(lon * RAD), y: Math.cos(lon * RAD), z: 0 };
assert.ok(dot(orientation.right, east) > 1 - 1e-9);
}
});
test('over a pole the orientation stays valid and keeps the previous up', () => {
for (const z of [1, -1]) {
const position = { x: 0, y: 0, z: z * (ORBITAL_EARTH_RADIUS_M + 800e3) };
const fallback = nadirOrientation(position);
assertOrthonormal(fallback);
assert.equal(fallback.direction.z, -z);
// The prime-meridian limit of north.
assert.ok(Math.abs(fallback.up.x - -z) < 1e-9);
const kept = nadirOrientation(position, {
previousUp: { x: 0, y: 1, z: 0 },
});
assertOrthonormal(kept);
assert.ok(kept.up.y > 1 - 1e-9);
}
// Just off the pole, north still points over it.
const nearPole = nadirOrientation(ecef(89.9999, 30, 500e3));
assertOrthonormal(nearPole);
assert.ok(dot(nearPole.up, localNorth(89.9999, 30)) > 1 - 1e-6);
});
test('a degenerate position has no orientation', () => {
assert.equal(nadirOrientation(null), null);
assert.equal(nadirOrientation({ x: 0, y: 0, z: 0 }), null);
assert.equal(nadirOrientation({ x: NaN, y: 0, z: 0 }), null);
});
test('each zoom step divides the tangent of the half-angle', () => {
const base = ORBITAL_BASE_FOV_LEO_RAD;
for (const zoom of ORBITAL_ZOOM_LADDER) {
const fov = fovForZoom(base, zoom);
assert.ok(Math.abs(Math.tan(fov / 2) - Math.tan(base / 2) / zoom) < 1e-12);
}
assert.ok(
Math.abs(
Math.tan(fovForZoom(base, 4) / 2) / Math.tan(fovForZoom(base, 2) / 2) -
0.5,
) < 1e-12,
);
assert.equal(fovForZoom(base, 1), base);
assert.equal(fovForZoom(base, 0), base);
});
test('zoom steps clamp at both ends without wrapping', () => {
assert.equal(nextOrbitalZoom(1), 2);
assert.equal(nextOrbitalZoom(4), 8);
assert.equal(nextOrbitalZoom(8), 8);
assert.equal(previousOrbitalZoom(8), 4);
assert.equal(previousOrbitalZoom(2), 1);
assert.equal(previousOrbitalZoom(1), 1);
assert.equal(nextOrbitalZoom(undefined), 2);
});
test('the base frame is regional in low orbit and fits the disk from GEO', () => {
assert.equal(orbitalBaseFovRad(420e3), ORBITAL_BASE_FOV_LEO_RAD);
const geo = orbitalBaseFovRad(35.786e6);
const disk = 2 * earthAngularRadiusRad(35.786e6);
assert.ok(geo > disk && geo < ORBITAL_BASE_FOV_LEO_RAD);
// Continuous across the crossover: no jump as an orbit climbs.
let previous = orbitalBaseFovRad(1e6);
for (let alt = 1e6; alt <= 40e6; alt += 50e3) {
const fov = orbitalBaseFovRad(alt);
assert.ok(fov <= previous + 1e-12);
assert.ok(previous - fov < 0.01);
previous = fov;
}
});
test('the footprint shrinks with zoom and stops at the limb', () => {
const alt = 420e3;
const widths = [1, 2, 4, 8].map((zoom) =>
footprintWidthKm(alt, fovForZoom(orbitalBaseFovRad(alt), zoom)),
);
for (let i = 1; i < widths.length; i++) assert.ok(widths[i] < widths[i - 1]);
assert.ok(widths[0] > 400 && widths[0] < 600, `1x ${widths[0]} km`);
assert.ok(widths[3] > 40 && widths[3] < 80, `8x ${widths[3]} km`);
// A wider frame covers more ground across.
assert.ok(
footprintWidthKm(alt, ORBITAL_BASE_FOV_LEO_RAD, 16 / 9) > widths[0],
);
// From GEO a frame wider than the disk spans the visible cap only.
const cap =
(2 *
ORBITAL_EARTH_RADIUS_M *
Math.acos(ORBITAL_EARTH_RADIUS_M / (ORBITAL_EARTH_RADIUS_M + 35.786e6))) /
1000;
assert.ok(Math.abs(footprintWidthKm(35.786e6, 40 * RAD) - cap) < 1e-6);
assert.equal(footprintWidthKm(0, 1), null);
assert.equal(footprintWidthKm(420e3, NaN), null);
});
test('Cesium frustum fov widens to the horizontal on a landscape canvas', () => {
const vertical = 30 * RAD;
assert.equal(cesiumFrustumFovRad(vertical, 0.75), vertical);
const horizontal = cesiumFrustumFovRad(vertical, 2);
assert.ok(
Math.abs(Math.tan(horizontal / 2) - 2 * Math.tan(vertical / 2)) < 1e-12,
);
});
test('zoom transition curves stay bounded and settle', () => {
assert.equal(zoomTransitionProgress(0), 0);
assert.equal(zoomTransitionProgress(400), 1);
assert.equal(zoomTransitionProgress(9999), 1);
assert.equal(zoomTransitionProgress(-50), 0);
assert.equal(zoomTransitionProgress(0, { reducedMotion: true }), 1);
let previous = 0;
for (let ms = 0; ms <= 500; ms += 10) {
const p = zoomTransitionProgress(ms);
assert.ok(p >= previous && p >= 0 && p <= 1);
previous = p;
const blur = zoomTransitionBlurPx(ms / 400);
assert.ok(blur >= 0 && blur <= 6);
}
assert.equal(zoomTransitionBlurPx(0), 0);
assert.ok(zoomTransitionBlurPx(1) < 1e-9);
assert.ok(Math.abs(zoomTransitionBlurPx(0.5) - 6) < 1e-9);
assert.equal(zoomTransitionBlurPx(0.5, { reducedMotion: true }), 0);
const from = fovForZoom(1, 1);
const to = fovForZoom(1, 2);
assert.equal(interpolateZoomFov(from, to, 0).toFixed(12), from.toFixed(12));
assert.equal(interpolateZoomFov(from, to, 1).toFixed(12), to.toFixed(12));
const mid = interpolateZoomFov(from, to, 0.5);
assert.ok(mid < from && mid > to);
});
test('the transition state blurs, then ticks the lock, then rests', () => {
const moving = zoomTransitionState(200);
assert.equal(moving.active, true);
assert.ok(moving.blurPx > 5);
assert.equal(moving.lockTick, false);
const settled = zoomTransitionState(450);
assert.equal(settled.active, false);
assert.equal(settled.lockTick, true);
assert.equal(settled.progress, 1);
assert.ok(settled.blurPx < 1e-9);
const rest = zoomTransitionState(2000);
assert.equal(rest.lockTick, false);
assert.deepEqual(zoomTransitionState(100, { reducedMotion: true }), {
active: false,
progress: 1,
blurPx: 0,
lockTick: false,
});
});
test('an off-nadir tilt turns the view by its angle from the nadir frame', () => {
const nadir = nadirOrientation(ecef(30, -97, 420_000));
assert.equal(offNadirOrientation(nadir), nadir, 'no tilt is nadir itself');
const angle = (v) => Math.acos(Math.min(1, dot(v, nadir.direction))) / RAD;
const north = offNadirOrientation(nadir, { northDeg: 10 });
assert.ok(Math.abs(angle(north.direction) - 10) < 1e-9);
assert.ok(dot(north.direction, nadir.up) > 0, 'toward north');
assert.ok(Math.abs(dot(north.direction, nadir.right)) < 1e-12);
const west = offNadirOrientation(nadir, { eastDeg: -20 });
assert.ok(Math.abs(angle(west.direction) - 20) < 1e-9);
assert.ok(dot(west.direction, nadir.right) < 0, 'toward west');
const both = offNadirOrientation(nadir, { northDeg: 45, eastDeg: 45 });
const expected = Math.acos(Math.cos(45 * RAD) ** 2) / RAD;
assert.ok(Math.abs(angle(both.direction) - expected) < 1e-9);
for (const view of [north, west, both]) {
assert.ok(Math.abs(norm(view.direction) - 1) < 1e-12);
assert.ok(Math.abs(norm(view.up) - 1) < 1e-12);
assert.ok(Math.abs(dot(view.direction, view.up)) < 1e-12);
}
});
test('a landed zoom step holds for its imagery, but never past the cap', () => {
assert.equal(zoomSettleHolding(0, false), true, 'still loading');
assert.equal(zoomSettleHolding(ORBITAL_SETTLE_MAX_MS - 1, false), true);
assert.equal(zoomSettleHolding(ORBITAL_SETTLE_MAX_MS, false), false, 'cap');
assert.equal(zoomSettleHolding(0, true), false, 'loaded: lock at once');
assert.equal(zoomSettleHolding(Number.NaN, false), true);
});
const WIDE = 16 / 9;
test("the zoom ladder climbs to a satellite's own cap and steps off a SENSOR zoom", () => {
assert.equal(nextOrbitalZoom(8), 8, 'no sensor: 8x is the top');
assert.equal(nextOrbitalZoom(8, 64), 16);
assert.equal(nextOrbitalZoom(32, 64), 64);
assert.equal(nextOrbitalZoom(64, 64), 64, 'the cap holds');
assert.equal(nextOrbitalZoom(5.7, 64), 8, 'between steps: the step above');
assert.equal(previousOrbitalZoom(5.7), 4, 'between steps: the step below');
assert.equal(previousOrbitalZoom(128), 64);
assert.equal(previousOrbitalZoom(1), 1);
});
test('a sensor caps the zoom at its swath for the live altitude', () => {
// WorldView-3 at 617 km, 13.1 km swath: 64x spans ~20 km, 128x ~10 km.
assert.ok(viewWidthKm(617e3, 64, WIDE) >= 13.1);
assert.ok(viewWidthKm(617e3, 128, WIDE) < 13.1);
assert.equal(orbitalMaxZoom(617e3, 13.1, WIDE), 64);
// ICEYE spotlight, 5 km at 570 km.
assert.equal(orbitalMaxZoom(570e3, 5, WIDE), 128);
// PlanetScope SuperDove, 32.5 km: 32x at 525 km but 16x at 470 km.
assert.equal(orbitalMaxZoom(525e3, 32.5, WIDE), 32);
assert.equal(orbitalMaxZoom(470e3, 32.5, WIDE), 16);
// Landsat's 185 km swath fits inside 8x: no extra steps, never fewer.
assert.equal(orbitalMaxZoom(705e3, 185, WIDE), 8);
assert.equal(orbitalMaxZoom(705e3, 2330, WIDE), 8);
// No sensor, or an unusable swath.
assert.equal(orbitalMaxZoom(617e3, null, WIDE), 8);
assert.equal(orbitalMaxZoom(617e3, 0, WIDE), 8);
// A swath exactly as wide as the 16x view allows 16x.
assert.equal(orbitalMaxZoom(617e3, viewWidthKm(617e3, 16, WIDE), WIDE), 16);
});
test('the SENSOR step frames the swath when it lies in range', () => {
const landsat = sensorSwathZoom(705e3, 185, WIDE, 8);
assert.ok(landsat > 4 && landsat < 8, String(landsat));
assert.ok(Math.abs(viewWidthKm(705e3, landsat, WIDE) - 185) < 1);
const worldview = sensorSwathZoom(617e3, 13.1, WIDE, 64);
assert.equal(worldview, null, 'narrower than the 64x cap allows');
assert.equal(sensorSwathZoom(705e3, 2330, WIDE, 8), null, 'wider than 1x');
assert.equal(sensorSwathZoom(705e3, null, WIDE, 8), null);
});
test('the sensor strip spans its share of the view', () => {
assert.equal(sensorStripFraction(13, 130), 0.1);
assert.equal(sensorStripFraction(500, 131), 1, 'clipped to the view');
assert.equal(sensorStripFraction(null, 131), null);
assert.equal(sensorStripFraction(13.1, null), null);
});
test('the wheel steps once per notch and sums a trackpad swipe', () => {
// A mouse notch away from the viewer zooms in.
let r = wheelZoomStep(null, { deltaY: -100, deltaMode: 0 }, 1000);
assert.equal(r.step, 1);
// The rest of that notch, inside the cooldown, is absorbed.
r = wheelZoomStep(r.accumulator, { deltaY: -100, deltaMode: 0 }, 1050);
assert.equal(r.step, 0);
// A notch toward the viewer after the cooldown zooms out.
r = wheelZoomStep(
r.accumulator,
{ deltaY: 120, deltaMode: 0 },
1050 + ORBITAL_WHEEL_COOLDOWN_MS + 1,
);
assert.equal(r.step, -1);
// A trackpad's small deltas add up before they step.
let pad = null;
const steps = [];
for (let i = 0; i < 4; i += 1) {
const out = wheelZoomStep(
pad,
{ deltaY: -30, deltaMode: 0 },
5000 + i * 16,
);
pad = out.accumulator;
steps.push(out.step);
}
assert.deepEqual(steps, [0, 0, 0, 1]);
// Turning back starts the sum over.
const turned = wheelZoomStep(
{ sum: -90, lastStepMs: -Infinity },
{ deltaY: 30, deltaMode: 0 },
9000,
);
assert.equal(turned.step, 0);
assert.equal(turned.accumulator.sum, 30);
// Line-mode wheels (Firefox): three lines make a notch.
assert.equal(wheelZoomStep(null, { deltaY: -3, deltaMode: 1 }, 0).step, 0);
assert.equal(wheelZoomStep(null, { deltaY: -7, deltaMode: 1 }, 0).step, 1);
assert.equal(wheelZoomStep(null, { deltaY: 0 }, 0).step, 0);
});
test('a heading turns the nadir frame, keeping north to fall back on', () => {
// Over the equator at 0°E: north is +z, east is +y.
const position = { x: ORBITAL_EARTH_RADIUS_M + 500_000, y: 0, z: 0 };
const northUp = nadirOrientation(position);
const east = nadirOrientation(position, { headingDeg: 90 });
const close = (a, b) =>
Math.abs(a.x - b.x) < 1e-9 &&
Math.abs(a.y - b.y) < 1e-9 &&
Math.abs(a.z - b.z) < 1e-9;
assert.ok(close(northUp.up, { x: 0, y: 0, z: 1 }));
assert.ok(close(east.up, { x: 0, y: 1, z: 0 }), 'east at the top');
assert.ok(close(east.north, northUp.up), 'north kept for the next frame');
assert.ok(
close(nadirOrientation(position, { headingDeg: 0 }).up, northUp.up),
);
});
test('a partial scroll does not carry over into a later gesture', () => {
// 90 px: short of a step.
let r = wheelZoomStep(null, { deltaY: -90, deltaMode: 0 }, 1000);
assert.equal(r.step, 0);
// Still the same gesture: 10 px more completes the step.
const same = wheelZoomStep(
r.accumulator,
{ deltaY: -10, deltaMode: 0 },
1100,
);
assert.equal(same.step, 1);
// Minutes later a 10 px nudge is a new gesture, not the rest of the old.
r = wheelZoomStep(
r.accumulator,
{ deltaY: -10, deltaMode: 0 },
1000 + ORBITAL_WHEEL_GESTURE_GAP_MS + 60_000,
);
assert.equal(r.step, 0);
});
test('the total off-nadir angle combines both tilts', () => {
assert.equal(offNadirAngleDeg(), 0);
assert.ok(Math.abs(offNadirAngleDeg({ northDeg: 10 }) - 10) < 1e-9);
// FWD 15° and RIGHT 10° read OFF-NADIR 18.0°.
const total = offNadirAngleDeg({ northDeg: 15, eastDeg: 10 });
assert.equal(total.toFixed(1), '18.0');
assert.equal(offNadirAngleDeg({ northDeg: -15, eastDeg: -10 }), total);
});
test("a tilted view's width grows faster across the frame than along it", () => {
assert.equal(offNadirSwathScale(), 1, 'nadir');
const cos = (deg) => Math.cos((deg * Math.PI) / 180);
assert.ok(
Math.abs(offNadirSwathScale({ northDeg: 30 }) - 1 / cos(30)) < 1e-9,
);
assert.ok(
Math.abs(offNadirSwathScale({ eastDeg: 30 }) - 1 / cos(30) ** 2) < 1e-9,
);
let last = 1;
for (const deg of [5, 15, 25, 35, 45]) {
const scale = offNadirSwathScale({ northDeg: deg, eastDeg: deg });
assert.ok(scale > last, `${deg}°`);
last = scale;
}
assert.equal(offNadirSwathScale({ northDeg: Number.NaN }), 1);
});
// ── imagery pre-load ahead of the ground track ─────────────────────────
const PASS = Object.freeze({
latitude: 30,
longitude: -97,
groundTrackDeg: 45,
velocityMps: 7_600,
altitudeM: 500_000,
});
test('destinationPoint walks a great circle along a bearing', () => {
const east = destinationPoint(0, 179.9, 90, 111_195 * 0.2);
assert.ok(Math.abs(east.lat) < 1e-9);
assert.ok(Math.abs(east.lon - -179.9) < 1e-3, 'wraps the antimeridian');
const north = destinationPoint(10, 20, 0, 50_000);
assert.ok(Math.abs(greatCircleKm({ lat: 10, lon: 20 }, north) - 50) < 0.1);
assert.ok(north.lat > 10 && Math.abs(north.lon - 20) < 1e-9);
});
test('the points ahead run along the ground track at ground speed', () => {
const points = groundTrackAhead(PASS, 20);
const across = ORBITAL_PREFETCH_ACROSS.length;
assert.equal(points.length, ORBITAL_PREFETCH_LEAD_S.length * across);
// Ground speed is the orbital speed scaled to the surface: ~7.0 km/s.
const groundKmPerS = (7.6 * 6371) / (6371 + 500);
const start = { lat: PASS.latitude, lon: PASS.longitude };
ORBITAL_PREFETCH_LEAD_S.forEach((seconds, i) => {
const centre = points[i * across];
const km = greatCircleKm(start, centre);
assert.ok(Math.abs(km - groundKmPerS * seconds) < 0.5, `${seconds} s`);
// North-east of the start, on a 45° track.
assert.ok(centre.lat > PASS.latitude && centre.lon > PASS.longitude);
// The side points sit their fraction of the view off the centre line.
points.slice(i * across + 1, (i + 1) * across).forEach((side, k) => {
const offKm = 20 * Math.abs(ORBITAL_PREFETCH_ACROSS[k + 1]);
assert.ok(Math.abs(greatCircleKm(centre, side) - offKm) < 0.05);
});
});
assert.deepEqual(groundTrackAhead({ ...PASS, groundTrackDeg: null }, 20), []);
assert.deepEqual(groundTrackAhead(PASS, null), []);
});
test('the tile level is the one Cesium draws for the view', () => {
const mercator = new Cesium.WebMercatorTilingScheme();
// Worked case: 10 m per CSS pixel at the equator. Cesium refines the
// ellipsoid terrain until a tile's error is at most 2 px, 20 m: level 12,
// 78,271.5 m / 2^12 = 19.11 m. The Web Mercator texel nearest that is
// level 13's (156,543 m / 2^13 = 19.11 m), about 1.9 px each, where a
// one-pixel texel would have asked for level 14.
assert.equal(
imageryLevelForView(mercator, { metresPerPixel: 10, latitudeDeg: 0 }),
13,
);
// 5 m/px: terrain level 13 (9.55 m), imagery level 14.
assert.equal(
imageryLevelForView(mercator, { metresPerPixel: 5, latitudeDeg: 0 }),
14,
);
// 7 m/px still takes terrain level 13 (9.55 m <= 14 m): level 14, so a
// texel spans 1.4 px.
assert.equal(
imageryLevelForView(mercator, { metresPerPixel: 7, latitudeDeg: 0 }),
14,
);
// At 60° a Mercator texel covers half the ground: one level coarser.
assert.equal(
imageryLevelForView(mercator, { metresPerPixel: 10, latitudeDeg: 60 }),
12,
);
// A geographic scheme starts from two root tiles and keeps its texels at
// every latitude.
const geographic = new Cesium.GeographicTilingScheme();
for (const latitudeDeg of [0, 60])
assert.equal(
imageryLevelForView(geographic, {
metresPerPixel: 10,
latitudeDeg,
geographic: true,
}),
12,
`${latitudeDeg}°`,
);
// A terrain provider's own errors (Cesium World Terrain: 65-sample tiles)
// and a looser screen-space error are honoured.
const worldTerrain = (level) =>
(6378137 * 2 * Math.PI * 0.25) / (65 * 2) / 2 ** level;
assert.equal(
imageryLevelForView(mercator, {
metresPerPixel: 10,
latitudeDeg: 0,
terrainLevelErrorM: worldTerrain,
}),
13,
);
assert.equal(
imageryLevelForView(mercator, {
metresPerPixel: 10,
latitudeDeg: 0,
maximumScreenSpaceError: 4,
}),
12,
);
// Clamped to the provider's levels.
assert.equal(
imageryLevelForView(mercator, {
metresPerPixel: 5,
latitudeDeg: 0,
maximumLevel: 12,
}),
12,
);
assert.equal(
imageryLevelForView(mercator, { metresPerPixel: 0, latitudeDeg: 0 }),
null,
);
});
test('the tiles ahead are the ones the points fall in, bounded and new', () => {
const mercator = new Cesium.WebMercatorTilingScheme();
const points = groundTrackAhead(PASS, 20);
const tiles = tilesForPoints(mercator, points, 13);
assert.ok(tiles.length > 0 && tiles.length <= ORBITAL_PREFETCH_MAX_TILES);
assert.equal(new Set(tiles.map((tile) => tile.key)).size, tiles.length);
// Each tile holds its point: the first is the centre line 5 s ahead.
const first = mercator.tileXYToRectangle(tiles[0].x, tiles[0].y, 13);
assert.ok(
Cesium.Rectangle.contains(
first,
Cesium.Cartographic.fromDegrees(points[0].lon, points[0].lat),
),
);
// Ahead along a north-east track: rows north (smaller y), columns east.
const here = mercator.positionToTileXY(
Cesium.Cartographic.fromDegrees(PASS.longitude, PASS.latitude),
13,
);
assert.ok(tiles.every((tile) => tile.x >= here.x && tile.y <= here.y));
// Bounded, and a tile already asked for is skipped.
assert.equal(tilesForPoints(mercator, points, 15, { maxTiles: 3 }).length, 3);
const asked = new Set(
tilesForPoints(mercator, points, 13, { maxTiles: Infinity }).map(
(tile) => tile.key,
),
);
assert.deepEqual(
tilesForPoints(mercator, points, 13, { skip: (key) => asked.has(key) }),
[],
);
assert.deepEqual(tilesForPoints({}, points, 13), []);
});
test('a view tilted past the limb no longer meets the Earth', () => {
// GEO: the Earth spans about 8.7 degrees either side of nadir.
assert.equal(offNadirCentreMeetsEarth(35_786_000, { northDeg: 5 }), true);
assert.equal(offNadirCentreMeetsEarth(35_786_000, { northDeg: 15 }), false);
// LEO: a 30 degree tilt still lands on the ground.
assert.equal(
offNadirCentreMeetsEarth(420_000, { northDeg: 20, eastDeg: 20 }),
true,
);
assert.equal(offNadirCentreMeetsEarth(420_000, { eastDeg: 80 }), false);
assert.equal(offNadirCentreMeetsEarth(NaN, {}), false);
});
test('the centre line of every lead comes before the frame edges', () => {
const points = groundTrackAhead(PASS, 20);
const across = ORBITAL_PREFETCH_ACROSS.length;
const ordered = centreLinesFirst(points);
assert.equal(ordered.length, points.length);
const leads = ORBITAL_PREFETCH_LEAD_S.length;
assert.deepEqual(
ordered.slice(0, leads),
points.filter((_, i) => i % across === 0),
);
// The 12-tile cap at a level of small tiles still reaches the far lead.
const mercator = new Cesium.WebMercatorTilingScheme();
const tiles = tilesForPoints(mercator, ordered, 17);
const far = mercator.positionToTileXY(
Cesium.Cartographic.fromDegrees(
ordered[leads - 1].lon,
ordered[leads - 1].lat,
),
17,
);
assert.ok(tiles.some((tile) => tile.x === far.x && tile.y === far.y));
});
+163
View File
@@ -0,0 +1,163 @@
/**
* Ground focus for the orbital view: the look that keeps a point on the
* ground at the centre of the picture as the satellite moves, whether that
* look is within the off-nadir reach, and which mapped points the view can
* show or be turned to. The look is the orbital view's own
* `{yawDeg, pitchDeg}` over its nadir frame (see `offNadirOrientation` in
* `src/cockpitOrbital.js`), so a focused view is a tilt like any other.
* No DOM, Cesium or i18n dependencies: vectors are plain `{x, y, z}` objects
* in Earth-fixed (ECEF) metres.
*/
import {
LOOK_EASE_TAU_MS,
ORBITAL_LOOK_LIMIT_DEG,
easeLook,
} from './cockpitLook.js';
/**
* How long a focus takes to swing the view onto its target, or back to
* nadir when it ends: the look's own easing curve, on a slower clock. Three
* of them (about 0.75 s) close 95% of the turn.
*/
export const ORBITAL_FOCUS_EASE_TAU_MS = 250;
/** How often the orbital Live Signals rows are rebuilt, ms. */
export const ORBITAL_REACH_REFRESH_MS = 1000;
/** WGS84 semi-axes squared, m²: the surface normal for the horizon test. */
const WGS84_A2 = 6378137 ** 2;
const WGS84_B2 = 6356752.314245179 ** 2;
/** Slack on the reach limit so a target held exactly at 45° stays. */
const REACH_EPSILON_DEG = 1e-6;
const toDegrees = (rad) => (rad * 180) / Math.PI;
function dot(a, b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
function finiteVector(v) {
return (
Boolean(v) &&
Number.isFinite(v.x) &&
Number.isFinite(v.y) &&
Number.isFinite(v.z)
);
}
/**
* The look that centres `target` in the picture, in the nadir frame's tilt
* (north first, then east; see `offNadirOrientation`): east is the angle off
* the frame's top-bottom plane, north the angle along it. Also the single
* angle between nadir and the line of sight, the image's off-nadir angle,
* and whether the target faces the satellite (above its horizon).
* @param {{direction: object, up: object, right: object}} nadir From
* `nadirOrientation`.
* @param {{x: number, y: number, z: number}} satellite ECEF, metres.
* @param {{x: number, y: number, z: number}} target ECEF, metres.
* @returns {{yawDeg: number, pitchDeg: number, offNadirDeg: number,
* visible: boolean}|null} Null without usable positions.
*/
export function focusLook(nadir, satellite, target) {
if (!nadir || !finiteVector(satellite) || !finiteVector(target)) return null;
const line = {
x: target.x - satellite.x,
y: target.y - satellite.y,
z: target.z - satellite.z,
};
const range = Math.hypot(line.x, line.y, line.z);
if (!(range > 1)) return null;
const v = { x: line.x / range, y: line.y / range, z: line.z / range };
const along = dot(v, nadir.direction);
const up = dot(v, nadir.up);
const right = Math.min(1, Math.max(-1, dot(v, nadir.right)));
// The target's own zenith, the WGS84 surface normal there: the satellite
// is above its horizon when the line from the target to it points up.
const normal = {
x: target.x / WGS84_A2,
y: target.y / WGS84_A2,
z: target.z / WGS84_B2,
};
const visible =
Math.hypot(normal.x, normal.y, normal.z) > 0 && -dot(line, normal) > 0;
const yawDeg = toDegrees(Math.asin(right));
const pitchDeg = toDegrees(Math.atan2(up, along));
return {
yawDeg: yawDeg === 0 ? 0 : yawDeg,
pitchDeg: pitchDeg === 0 ? 0 : pitchDeg,
offNadirDeg: toDegrees(Math.acos(Math.min(1, Math.max(-1, along)))),
visible,
};
}
/**
* Whether a focus look is within the off-nadir reach: the target faces the
* satellite and each axis is within the arrows' ±45° clamp.
* @param {{yawDeg: number, pitchDeg: number, visible?: boolean}|null} look
* @returns {boolean}
*/
export function focusInReach(look) {
if (!look || look.visible === false) return false;
const limit = ORBITAL_LOOK_LIMIT_DEG + REACH_EPSILON_DEG;
return (
Number.isFinite(look.yawDeg) &&
Number.isFinite(look.pitchDeg) &&
Math.abs(look.yawDeg) <= limit &&
Math.abs(look.pitchDeg) <= limit
);
}
/**
* Ease what is left of the turn onto a focus target toward nothing: the
* look's easing (`easeLook`) on the focus's slower clock. The view is the
* live target's look plus this remainder, so once it lands the view holds
* the target exactly, without the lag of chasing it. Reduced motion cuts.
* @param {{yawDeg: number, pitchDeg: number}} remainder View minus target.
* @param {number} dtMs Milliseconds since the previous frame.
* @param {{immediate?: boolean}} [options]
* @returns {{yawDeg: number, pitchDeg: number}}
*/
export function easeFocusRemainder(
remainder,
dtMs,
{ immediate = false } = {},
) {
return easeLook(remainder, { yawDeg: 0, pitchDeg: 0 }, focusEaseDtMs(dtMs), {
immediate,
});
}
/**
* A frame's time on the focus's clock, for `easeLook`: its fixed time
* constant scaled to ORBITAL_FOCUS_EASE_TAU_MS.
* @param {number} dtMs
* @returns {number}
*/
export function focusEaseDtMs(dtMs) {
return Number.isFinite(dtMs) && dtMs > 0
? (dtMs * LOOK_EASE_TAU_MS) / ORBITAL_FOCUS_EASE_TAU_MS
: 0;
}
/**
* The mapped points the view can be turned to: those facing the satellite
* and within the off-nadir reach, nearest to nadir first.
* @param {Iterable<{key: string, position: {x: number, y: number,
* z: number}}>} candidates
* @param {{nadir: object, satellite: object}} frame
* @returns {Array<{key: string, offNadirDeg: number, look: object}>}
*/
export function pointsInReach(candidates, { nadir, satellite }) {
const entries = [];
if (!nadir || !finiteVector(satellite)) return entries;
for (const candidate of candidates) {
const look = focusLook(nadir, satellite, candidate?.position);
if (!focusInReach(look)) continue;
entries.push({ key: candidate.key, offNadirDeg: look.offNadirDeg, look });
}
return entries.sort(
(a, b) =>
a.offNadirDeg - b.offNadirDeg || String(a.key).localeCompare(b.key),
);
}
+227
View File
@@ -0,0 +1,227 @@
// src/cockpitOrbitalFocus.test.mjs — the geometry of a ground focus in the
// orbital view: the look that centres a target, its off-nadir angle, the
// reach, the easing onto and off a target, and the reach list.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
ORBITAL_FOCUS_EASE_TAU_MS,
easeFocusRemainder,
focusEaseDtMs,
focusInReach,
focusLook,
pointsInReach,
} from './cockpitOrbitalFocus.js';
import {
ORBITAL_EARTH_RADIUS_M,
nadirOrientation,
offNadirAngleDeg,
offNadirOrientation,
} from './cockpitOrbital.js';
import { LOOK_EASE_TAU_MS } from './cockpitLook.js';
const near = (actual, expected, label, tolerance = 1e-9) =>
assert.ok(
Math.abs(actual - expected) <= tolerance,
`${label}: ${actual} not within ${tolerance} of ${expected}`,
);
const unit = (v) => {
const n = Math.hypot(v.x, v.y, v.z);
return { x: v.x / n, y: v.y / n, z: v.z / n };
};
const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
const angleBetweenDeg = (a, b) => {
const u = unit(a);
const v = unit(b);
const cosine = Math.min(1, Math.max(-1, u.x * v.x + u.y * v.y + u.z * v.z));
return (Math.acos(cosine) * 180) / Math.PI;
};
/** A point on a sphere of radius `radiusM`, ECEF. */
const onSphere = (latDeg, lonDeg, radiusM) => {
const lat = (latDeg * Math.PI) / 180;
const lon = (lonDeg * Math.PI) / 180;
return {
x: radiusM * Math.cos(lat) * Math.cos(lon),
y: radiusM * Math.cos(lat) * Math.sin(lon),
z: radiusM * Math.sin(lat),
};
};
/** A point on the WGS84 ellipsoid, as the globe draws it. */
const geodeticToEcef = (latDeg, lonDeg, heightM = 0) =>
Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, heightM);
const ISS_ALT_M = 420_000;
const satelliteAt = (latDeg, lonDeg, altitudeM = ISS_ALT_M) =>
geodeticToEcef(latDeg, lonDeg, altitudeM);
test('the focus look turns the nadir frame onto the target exactly', () => {
const satellite = satelliteAt(30, -97);
for (const heading of [null, 0, 51.6, 200]) {
const nadir = nadirOrientation(satellite, { headingDeg: heading });
for (const [lat, lon] of [
[31.5, -96],
[28.2, -99.4],
[30, -97],
[32.9, -97.1],
]) {
const target = geodeticToEcef(lat, lon, 300);
const look = focusLook(nadir, satellite, target);
const view = offNadirOrientation(nadir, {
northDeg: look.pitchDeg,
eastDeg: look.yawDeg,
});
near(
angleBetweenDeg(view.direction, sub(target, satellite)),
0,
`centred at ${lat},${lon} heading ${heading}`,
1e-5,
);
// The single angle the readout gives is the tilt's total angle.
near(
look.offNadirDeg,
offNadirAngleDeg({ northDeg: look.pitchDeg, eastDeg: look.yawDeg }),
'one off-nadir angle',
1e-9,
);
assert.equal(look.visible, true);
}
}
});
test('the off-nadir angle is the angle between nadir and the line of sight', () => {
// On a sphere: a target `central` radians from the sub-satellite point is
// seen atan(R sin γ / (R + h − R cos γ)) off nadir.
const R = ORBITAL_EARTH_RADIUS_M;
const satellite = onSphere(10, 20, R + ISS_ALT_M);
const nadir = nadirOrientation(satellite);
for (const centralDeg of [0, 0.5, 2, 5, 12]) {
const target = onSphere(10 + centralDeg, 20, R);
const γ = (centralDeg * Math.PI) / 180;
const expected =
(Math.atan2(R * Math.sin(γ), R + ISS_ALT_M - R * Math.cos(γ)) * 180) /
Math.PI;
const look = focusLook(nadir, satellite, target);
near(look.offNadirDeg, expected, `${centralDeg}° away`, 1e-9);
}
// Straight below reads zero, a real angle and not a missing one.
const below = focusLook(nadir, satellite, onSphere(10, 20, R));
near(below.offNadirDeg, 0, 'straight below', 1e-9);
near(below.yawDeg, 0, 'no east', 1e-9);
near(below.pitchDeg, 0, 'no north', 1e-9);
assert.equal(focusInReach(below), true);
});
test('the reach is the arrows’ ±45° on each axis, facing the satellite', () => {
assert.equal(focusInReach({ yawDeg: 45, pitchDeg: -45, visible: true }), true);
assert.equal(focusInReach({ yawDeg: 45.01, pitchDeg: 0, visible: true }), false);
assert.equal(focusInReach({ yawDeg: 0, pitchDeg: -45.01, visible: true }), false);
assert.equal(focusInReach({ yawDeg: 0, pitchDeg: 0, visible: false }), false);
assert.equal(focusInReach(null), false);
assert.equal(focusInReach({ yawDeg: Number.NaN, pitchDeg: 0 }), false);
// From geostationary height the far side of the Earth lies within a few
// degrees of nadir, but it faces away.
const satellite = satelliteAt(0, 0, 35_786_000);
const nadir = nadirOrientation(satellite);
const farSide = geodeticToEcef(0, 100, 0);
const look = focusLook(nadir, satellite, farSide);
assert.ok(Math.abs(look.yawDeg) < 45 && Math.abs(look.pitchDeg) < 45);
assert.equal(look.visible, false);
assert.equal(focusInReach(look), false);
// A point near the sub-satellite point faces it.
assert.equal(focusInReach(focusLook(nadir, satellite, geodeticToEcef(5, 5))), true);
});
test('a target slides out of reach as the satellite passes it', () => {
const target = geodeticToEcef(0, 10, 0);
const inReach = [];
for (let lon = 10; lon >= -5; lon -= 1) {
const satellite = satelliteAt(0, lon);
inReach.push(focusInReach(focusLook(nadirOrientation(satellite), satellite, target)));
}
assert.equal(inReach[0], true, 'overhead');
assert.equal(inReach.at(-1), false, '15° of longitude behind');
// Once out, it stays out: the reach ends once, not on and off.
const firstOut = inReach.indexOf(false);
assert.ok(firstOut > 0);
assert.ok(inReach.slice(firstOut).every((value) => value === false));
});
test('the turn onto a target eases on the slower focus clock and lands', () => {
assert.equal(
focusEaseDtMs(ORBITAL_FOCUS_EASE_TAU_MS),
LOOK_EASE_TAU_MS,
'one focus time constant is one look time constant',
);
assert.equal(focusEaseDtMs(Number.NaN), 0);
assert.equal(focusEaseDtMs(-5), 0);
let remainder = { yawDeg: -30, pitchDeg: 20 };
let previous = Math.hypot(remainder.yawDeg, remainder.pitchDeg);
let frames = 0;
while ((remainder.yawDeg || remainder.pitchDeg) && frames < 500) {
const before = remainder;
remainder = easeFocusRemainder(remainder, 16);
const size = Math.hypot(remainder.yawDeg, remainder.pitchDeg);
assert.ok(size < previous, 'always closer');
// No axis moves more than a tenth of the way in a frame, but for the
// last few hundredths of a degree it lands on: a turn, not a cut.
for (const axis of ['yawDeg', 'pitchDeg']) {
const step = Math.abs(before[axis] - remainder[axis]);
assert.ok(
step <= Math.max(Math.abs(before[axis]) * 0.1, 0.06),
`frame ${frames} ${axis}`,
);
}
previous = size;
frames += 1;
}
assert.deepEqual(remainder, { yawDeg: 0, pitchDeg: 0 }, 'lands exactly');
// About three time constants close 95%; landing takes a little longer.
assert.ok(frames * 16 > 2 * ORBITAL_FOCUS_EASE_TAU_MS, `${frames} frames`);
assert.ok(frames * 16 < 12 * ORBITAL_FOCUS_EASE_TAU_MS, `${frames} frames`);
assert.deepEqual(
easeFocusRemainder({ yawDeg: 10, pitchDeg: -4 }, 16, { immediate: true }),
{ yawDeg: 0, pitchDeg: 0 },
'reduced motion cuts',
);
});
test('the reach list keeps points in reach or in frame, nearest first, bounded', () => {
const satellite = satelliteAt(0, 0);
const nadir = nadirOrientation(satellite);
const candidates = [];
// A row of points eastward, 0.1° apart: those up to ~3.7° are within the
// 45° tilt, the rest beyond it.
for (let i = 0; i < 80; i += 1)
candidates.push({ key: `east-${i}`, position: geodeticToEcef(0, i * 0.1) });
candidates.push({ key: 'far-side', position: geodeticToEcef(0, 180) });
const entries = pointsInReach(candidates, { nadir, satellite });
assert.ok(entries.every((entry) => entry.key !== 'far-side'));
const angles = entries.map((entry) => entry.offNadirDeg);
assert.deepEqual(angles, [...angles].sort((a, b) => a - b), 'nearest first');
assert.equal(entries[0].key, 'east-0');
assert.equal(entries[0].offNadirDeg, 0);
// Only those within the 45° tilt are listed.
assert.ok(entries.length > 0 && entries.length < 80);
for (const entry of entries) assert.ok(Math.abs(entry.look.yawDeg) <= 45);
const beyond = focusLook(nadir, satellite, candidates[entries.length].position);
assert.ok(Math.abs(beyond.yawDeg) > 45, 'the next one east is past the reach');
assert.deepEqual(pointsInReach([], { nadir, satellite }), []);
});
test('the horizon is the ground’s own: the WGS84 surface normal, not the centre line', () => {
const target = geodeticToEcef(45, 0);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(target);
const satelliteAtElevation = (elevationDeg) => {
const e = Cesium.Math.toRadians(elevationDeg);
const local = new Cesium.Cartesian3(0, -Math.cos(e) * 4e7, Math.sin(e) * 4e7);
return Cesium.Matrix4.multiplyByPoint(enu, local, new Cesium.Cartesian3());
};
const below = satelliteAtElevation(-0.1);
assert.equal(focusLook(nadirOrientation(below), below, target).visible, false);
const above = satelliteAtElevation(0.1);
assert.equal(focusLook(nadirOrientation(above), above, target).visible, true);
});
+74
View File
@@ -0,0 +1,74 @@
/**
* The camera's hop from the satellite the orbital view rides to another.
* No DOM, Cesium or i18n dependencies: vectors are plain `{x, y, z}` objects
* in Earth-fixed (ECEF) metres.
*/
/** The most nearby satellites asked for the orbital rows, nearest first. */
export const ORBITAL_SATELLITES_MAX = 8;
/** How long the camera takes to hop to another satellite, ms. */
export const ORBITAL_HOP_MS = 1200;
function finiteVector(v) {
return (
Boolean(v) &&
Number.isFinite(v.x) &&
Number.isFinite(v.y) &&
Number.isFinite(v.z)
);
}
/**
* Where the camera is part-way through a hop: along the great circle
* between the two positions (never through the Earth), its distance from the
* centre interpolated linearly. The circle is the one through both ends, so
* the path moves smoothly as the destination does, however far round it
* lies; only exactly opposite ends, which no single circle joins, turn about
* a fixed axis square to them.
* @param {{x: number, y: number, z: number}} from
* @param {{x: number, y: number, z: number}} to
* @param {number} progress Eased, 0..1.
* @returns {{x: number, y: number, z: number}|null}
*/
export function hopPosition(from, to, progress) {
if (!finiteVector(from) || !finiteVector(to)) return null;
const p = Math.min(1, Math.max(0, Number.isFinite(progress) ? progress : 1));
const ra = Math.hypot(from.x, from.y, from.z);
const rb = Math.hypot(to.x, to.y, to.z);
if (!(ra > 0) || !(rb > 0)) return null;
const a = { x: from.x / ra, y: from.y / ra, z: from.z / ra };
const b = { x: to.x / rb, y: to.y / rb, z: to.z / rb };
const cosine = a.x * b.x + a.y * b.y + a.z * b.z;
// The direction the circle leaves `a` in: `b` less its part along `a`.
let c = {
x: b.x - cosine * a.x,
y: b.y - cosine * a.y,
z: b.z - cosine * a.z,
};
let rc = Math.hypot(c.x, c.y, c.z);
const r = ra + (rb - ra) * p;
const omega = Math.atan2(rc, cosine);
if (!(rc > 1e-12)) {
if (cosine > 0) return { x: a.x * r, y: a.y * r, z: a.z * r };
// Opposite ends: set off square to `a`, northward (or, near a pole,
// toward the prime meridian).
const pole =
Math.abs(a.z) < 0.9 ? { x: 0, y: 0, z: 1 } : { x: 1, y: 0, z: 0 };
const along = pole.x * a.x + pole.y * a.y + pole.z * a.z;
c = {
x: pole.x - along * a.x,
y: pole.y - along * a.y,
z: pole.z - along * a.z,
};
rc = Math.hypot(c.x, c.y, c.z);
}
const angle = p * omega;
const cos = Math.cos(angle);
const sin = Math.sin(angle) / rc;
return {
x: (a.x * cos + c.x * sin) * r,
y: (a.y * cos + c.y * sin) * r,
z: (a.z * cos + c.z * sin) * r,
};
}
+73
View File
@@ -0,0 +1,73 @@
// src/cockpitOrbitalSatellites.test.mjs — the camera's hop from one ridden
// satellite to another.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { hopPosition } from './cockpitOrbitalSatellites.js';
const at = (lat, lon, alt) => Cesium.Cartesian3.fromDegrees(lon, lat, alt);
test('the hop follows the great circle and lands on the satellite', () => {
const from = at(0, 0, 400_000);
const to = at(0, 90, 800_000);
const start = hopPosition(from, to, 0);
for (const axis of ['x', 'y', 'z'])
assert.ok(Math.abs(start[axis] - from[axis]) < 1e-6, axis);
const end = hopPosition(from, to, 1);
for (const axis of ['x', 'y', 'z'])
assert.ok(Math.abs(end[axis] - to[axis]) < 1e-6, axis);
// Half-way it is above the Earth, between the two heights, not on the
// chord through it.
const mid = hopPosition(from, to, 0.5);
const radius = Math.hypot(mid.x, mid.y, mid.z);
const ra = Cesium.Cartesian3.magnitude(from);
const rb = Cesium.Cartesian3.magnitude(to);
assert.ok(Math.abs(radius - (ra + rb) / 2) < 1e-6);
assert.ok(Math.abs(Math.atan2(mid.y, mid.x) - Math.PI / 4) < 1e-9);
assert.equal(hopPosition(null, to, 0.5), null);
});
test('a hop to the opposite side goes round the Earth, not through it', () => {
const from = at(0, 0, 400_000);
const to = at(0, 180, 400_000);
const radius = Cesium.Cartesian3.magnitude(from);
for (const p of [0.25, 0.5, 0.75]) {
const point = hopPosition(from, to, p);
assert.ok(
Math.abs(Math.hypot(point.x, point.y, point.z) - radius) < 1e-3,
`p=${p}`,
);
}
const end = hopPosition(from, to, 1);
for (const axis of ['x', 'y', 'z'])
assert.ok(Math.abs(end[axis] - to[axis]) < 1e-3, axis);
});
test('a hop to nearly the opposite side moves smoothly as the destination does', () => {
const r = 6_778_137;
const from = { x: r, y: 0, z: 0 };
const near = (delta) => ({
x: -r * Math.cos(delta),
y: r * Math.sin(delta),
z: 0,
});
const mid = (delta) => hopPosition(from, near(delta), 0.5);
const [a, b] = [mid(0.999e-6), mid(1.001e-6)];
assert.ok(
Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z) < 1,
'no jump between neighbours',
);
for (const delta of [1e-3, 1e-6, 1e-9]) {
const to = near(delta);
const end = hopPosition(from, to, 1);
assert.ok(
Math.hypot(end.x - to.x, end.y - to.y, end.z - to.z) < 1e-3,
`lands at ${delta}`,
);
const half = mid(delta);
assert.ok(
Math.abs(Math.hypot(half.x, half.y, half.z) - r) < 1e-3,
`round at ${delta}`,
);
}
});
+182
View File
@@ -0,0 +1,182 @@
/**
* @module cockpitProgress
* @description Lay out a subject's progress line (cockpitSubjectProviders.js)
* at a width in pixels: where each tick, label and the marker go.
*
* Ticks sit at fractions of the line, 0 at the left. Ticks closer than
* `minTickPx` merge, so a long run still reads as a line: a labelled tick
* keeps its place and takes in the bare ticks beside it, and bare ticks merge
* with each other at their mean place. A merged tick takes the strongest tone
* of those it holds. Labels never overlap: where two would, the one of lower
* priority is left out (on a tie, the later one).
*
* Pure: no DOM.
*/
/** Bare ticks closer than this merge (px). */
export const COCKPIT_PROGRESS_MIN_TICK_PX = 6;
/** Room kept between two labels (px). */
export const COCKPIT_PROGRESS_LABEL_GAP_PX = 8;
/** Tones from weakest to strongest, for a merged tick. */
const TONE_RANK = Object.freeze([
'muted',
'normal',
'live',
'estimate',
'warning',
'alert',
]);
const stronger = (a, b) =>
TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a;
/** A label's width estimate (px): its longer line in small capitals. */
export function estimateProgressLabelPx(label) {
const longest = Math.max(
String(label?.text ?? '').length,
String(label?.detail ?? '').length,
);
return longest * 6.4 + 8;
}
/**
* The progress line at `widthPx`, or null when there is nothing to draw.
* @param {{ticks: Array<{at: number, tone: string, label: object|null}>,
* marker: {at: number, dwell: boolean}|null, tag: string}|null} progress
* As cockpitSubjectHudView gives it: ticks sorted by `at`.
* @param {number} widthPx
* @param {{minTickPx?: number, gapPx?: number,
* measure?: (label: object) => number}} [options]
* @returns {{ticks: Array<{x: number, tone: string, count: number,
* labelled: boolean}>, labels: Array<{x: number, left: number,
* width: number, align: string, text: string, detail: string,
* tone: string}>, marker: {x: number, dwell: boolean}|null,
* travelledX: number, tag: string}|null}
*/
export function cockpitProgressLayout(
progress,
widthPx,
{
minTickPx = COCKPIT_PROGRESS_MIN_TICK_PX,
gapPx = COCKPIT_PROGRESS_LABEL_GAP_PX,
measure = estimateProgressLabelPx,
} = {},
) {
const ticks = progress?.ticks;
if (!Array.isArray(ticks) || ticks.length < 2) return null;
if (!Number.isFinite(widthPx) || widthPx <= 0) return null;
const placed = ticks.map((tick, order) => ({
x: tick.at * widthPx,
tone: tick.tone,
label: tick.label,
order,
}));
const labelled = placed.filter((tick) => tick.label);
// Bare ticks beside a labelled one go into it.
const kept = labelled.map((tick) => ({
x: tick.x,
tone: tick.tone,
count: 1,
labelled: true,
label: tick.label,
order: tick.order,
}));
const bare = [];
for (const tick of placed) {
if (tick.label) continue;
const host = kept.find((entry) => Math.abs(entry.x - tick.x) < minTickPx);
if (host) {
host.tone = stronger(host.tone, tick.tone);
host.count += 1;
} else bare.push(tick);
}
// Bare ticks in a chain closer than minTickPx merge at their mean place.
let cluster = null;
const flush = () => {
if (!cluster) return;
kept.push({
x: cluster.sum / cluster.count,
tone: cluster.tone,
count: cluster.count,
labelled: false,
label: null,
order: cluster.order,
});
cluster = null;
};
for (const tick of bare) {
if (cluster && tick.x - cluster.last < minTickPx) {
cluster.sum += tick.x;
cluster.count += 1;
cluster.last = tick.x;
cluster.tone = stronger(cluster.tone, tick.tone);
} else {
flush();
cluster = {
sum: tick.x,
count: 1,
last: tick.x,
tone: tick.tone,
order: tick.order,
};
}
}
flush();
kept.sort((a, b) => a.x - b.x || a.order - b.order);
// Labels by priority; one that would overlap a placed label is left out.
const boxes = [];
const candidates = kept
.filter((tick) => tick.labelled)
.sort((a, b) => b.label.priority - a.label.priority || a.order - b.order);
for (const tick of candidates) {
const width = Math.min(widthPx, Math.max(0, measure(tick.label)));
let left =
tick.label.align === 'start'
? tick.x
: tick.label.align === 'end'
? tick.x - width
: tick.x - width / 2;
left = Math.min(Math.max(0, left), widthPx - width);
const right = left + width;
if (
boxes.some((box) => left < box.right + gapPx && right > box.left - gapPx)
)
continue;
boxes.push({
x: tick.x,
left,
right,
width,
align: tick.label.align,
text: tick.label.text,
detail: tick.label.detail,
tone: tick.tone,
order: tick.order,
});
}
boxes.sort((a, b) => a.left - b.left);
const marker = progress.marker
? { x: progress.marker.at * widthPx, dwell: progress.marker.dwell }
: null;
return {
ticks: kept.map(({ x, tone, count, labelled: isLabelled }) => ({
x,
tone,
count,
labelled: isLabelled,
})),
labels: boxes.map(({ x, left, width, align, text, detail, tone }) => ({
x,
left,
width,
align,
text,
detail,
tone,
})),
marker,
travelledX: marker ? marker.x : 0,
tag: progress.tag || '',
};
}
+144
View File
@@ -0,0 +1,144 @@
// src/cockpitProgress.test.mjs — a subject's progress line laid out at a
// width: close bare ticks merge, labelled ticks keep their place, labels never
// overlap (the lower priority gives way) and the part before the marker is
// the travelled part.
import test from 'node:test';
import assert from 'node:assert/strict';
import { cockpitProgressLayout } from './cockpitProgress.js';
const tick = (at, label = null, tone = 'normal') => ({ at, tone, label });
const label = (text, priority, align = 'center', detail = '') => ({
text,
detail,
priority,
align,
});
/** Every label is 50 px wide. */
const measure = () => 50;
test('nothing is drawn without two ticks or a width', () => {
assert.equal(cockpitProgressLayout(null, 500), null);
assert.equal(cockpitProgressLayout({ ticks: [tick(0)] }, 500), null);
assert.equal(
cockpitProgressLayout({ ticks: [tick(0), tick(1)], marker: null }, 0),
null,
);
});
test('ticks closer than the minimum spacing merge, keeping the strongest tone', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('A', 1, 'start')),
tick(0.1),
tick(0.101, null, 'warning'),
tick(0.102),
tick(0.5),
tick(1, label('Z', 1, 'end')),
],
marker: { at: 0.3, dwell: false },
tag: 'TIMETABLE',
},
1000,
{ measure },
);
assert.deepEqual(
layout.ticks.map(({ x, count, tone, labelled }) => [
Math.round(x),
count,
tone,
labelled,
]),
[
[0, 1, 'normal', true],
[101, 3, 'warning', false],
[500, 1, 'normal', false],
[1000, 1, 'normal', true],
],
);
assert.deepEqual(layout.marker, { x: 300, dwell: false });
assert.equal(layout.travelledX, 300);
assert.equal(layout.tag, 'TIMETABLE');
});
test('a labelled tick keeps its place and takes in the bare ticks beside it', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('A', 1, 'start')),
tick(0.498),
tick(0.5, label('Next', 3), 'alert'),
tick(0.503, null, 'warning'),
tick(1, label('Z', 1, 'end')),
],
marker: null,
},
1000,
{ measure },
);
const next = layout.ticks.find(({ x }) => Math.round(x) === 500);
assert.equal(next.count, 3);
assert.equal(next.labelled, true);
assert.equal(next.tone, 'alert');
assert.equal(layout.ticks.length, 3);
assert.equal(layout.marker, null);
assert.equal(layout.travelledX, 0);
});
test('labels hang from their ticks inside the line, and overlaps give way by priority', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('First', 1, 'start')),
tick(0.04, label('Previous', 2)),
tick(0.5, label('Next', 3)),
tick(0.52, label('Close', 0)),
tick(1, label('Last', 1, 'end')),
],
marker: { at: 0.2, dwell: true },
},
1000,
{ measure },
);
assert.deepEqual(
layout.labels.map(({ text, left }) => [text, Math.round(left)]),
[
['Previous', 15],
['Next', 475],
['Last', 950],
],
);
// The first stop's label would cover the previous stop's: it gives way.
assert.ok(!layout.labels.some(({ text }) => text === 'First'));
assert.ok(!layout.labels.some(({ text }) => text === 'Close'));
assert.deepEqual(layout.marker, { x: 200, dwell: true });
});
test('a centred label at an edge is clamped inside the line', () => {
const layout = cockpitProgressLayout(
{ ticks: [tick(0, label('Edge', 1)), tick(1)], marker: null },
300,
{ measure },
);
assert.equal(layout.labels[0].left, 0);
const right = cockpitProgressLayout(
{ ticks: [tick(0), tick(1, label('Edge', 1))], marker: null },
300,
{ measure },
);
assert.equal(right.labels[0].left, 250);
});
test('a long run of calls still lays out, every one a tick or part of one', () => {
const ticks = Array.from({ length: 60 }, (_, i) => tick(i / 59));
ticks[0].label = label('First', 1, 'start');
ticks[59].label = label('Last', 1, 'end');
const narrow = cockpitProgressLayout({ ticks, marker: null }, 200);
const wide = cockpitProgressLayout({ ticks, marker: null }, 2000);
const count = (layout) =>
layout.ticks.reduce((sum, entry) => sum + entry.count, 0);
assert.equal(count(narrow), 60);
assert.equal(count(wide), 60);
assert.ok(narrow.ticks.length < wide.ticks.length);
assert.equal(wide.ticks.length, 60);
});
+166
View File
@@ -0,0 +1,166 @@
/**
* Bridge radar policy: the range steps, the range rings and the heading-up
* projection of nearby AIS vessels onto the radar's range circle. Pure: no
* DOM, no Cesium and no translated text; the Cockpit words the labels.
*/
import {
bearingBetweenCoordinates,
normalizeHeading,
relativeBearing,
} from './cockpitMath.js';
import { greatCircleMeters } from './geoDistance.js';
/** Metres in one international nautical mile. */
export const METRES_PER_NM = 1852;
/** The radar's range steps in nautical miles, shortest first. */
export const RADAR_RANGES_NM = Object.freeze([3, 6, 12, 24]);
/** The range the radar opens on. */
export const DEFAULT_RADAR_RANGE_NM = 3;
/** At most this many contacts are drawn, nearest first. */
export const RADAR_MAX_CONTACTS = 60;
/** Range rings divide the range into this many equal steps. */
export const RADAR_RING_COUNT = 4;
/**
* Normalize a range to one of the radar's steps.
* @param {number} rangeNm Requested range in nautical miles.
* @returns {number} The range when it is a step, else the default range.
*/
export function radarRangeNm(rangeNm) {
return RADAR_RANGES_NM.includes(rangeNm) ? rangeNm : DEFAULT_RADAR_RANGE_NM;
}
/**
* The range after this one; the longest range wraps to the shortest.
* @param {number} rangeNm Current range in nautical miles.
* @returns {number} The next range step.
*/
export function nextRadarRange(rangeNm) {
const index = RADAR_RANGES_NM.indexOf(radarRangeNm(rangeNm));
return RADAR_RANGES_NM[(index + 1) % RADAR_RANGES_NM.length];
}
/**
* Range ring distances at each quarter of the range, innermost first.
* @param {number} rangeNm Range in nautical miles.
* @returns {number[]} Ring distances in nautical miles; the last is the range.
*/
export function radarRingsNm(rangeNm) {
const range = radarRangeNm(rangeNm);
return Array.from(
{ length: RADAR_RING_COUNT },
(_, index) => (range * (index + 1)) / RADAR_RING_COUNT,
);
}
/**
* The search radius for a range, in metres.
* @param {number} rangeNm Range in nautical miles.
* @returns {number}
*/
export function radarRangeM(rangeNm) {
return radarRangeNm(rangeNm) * METRES_PER_NM;
}
const round4 = (value) => Math.round(value * 1e4) / 1e4;
/**
* Project vessel contacts onto a heading-up radar.
*
* Positions are fractions of the range circle: x to the right (starboard),
* y up (ahead), both in [-1, 1]. Contacts outside the range, or without a
* position, are left out; the rest come nearest first, at most `maxCount`.
* @param {{latitude: number, longitude: number, headingDeg: number}} own
* Own ship position and the heading the radar is drawn up from.
* @param {Array<{id: string, name?: string, latitude: number,
* longitude: number, course?: number|null, color?: string,
* stale?: boolean}>} contacts Nearby vessels.
* @param {{rangeNm?: number, maxCount?: number}} [options]
* @returns {Array<{id: string, name: string, x: number, y: number,
* distanceNm: number, relativeBearingDeg: number,
* relativeCourseDeg: number|null, color: string, stale: boolean}>}
* relativeBearingDeg and relativeCourseDeg are clockwise from the bow in
* [-180, 180).
*/
export function projectRadarContacts(own, contacts, options = {}) {
const rangeNm = radarRangeNm(options.rangeNm ?? DEFAULT_RADAR_RANGE_NM);
const cap =
Number.isFinite(options.maxCount) && options.maxCount > 0
? Math.floor(options.maxCount)
: RADAR_MAX_CONTACTS;
const lat = Number(own?.latitude);
const lon = Number(own?.longitude);
if (
!Number.isFinite(lat) ||
!Number.isFinite(lon) ||
!Array.isArray(contacts)
)
return [];
const heading = normalizeHeading(own.headingDeg ?? 0);
const projected = [];
for (const contact of contacts) {
const toLat = Number(contact?.latitude);
const toLon = Number(contact?.longitude);
const distanceNm =
greatCircleMeters({ lat, lon }, { lat: toLat, lon: toLon }) /
METRES_PER_NM;
if (!Number.isFinite(distanceNm) || distanceNm > rangeNm) continue;
const bearing = bearingBetweenCoordinates(lat, lon, toLat, toLon);
const relativeBearingDeg =
bearing === null ? 0 : relativeBearing(bearing, heading);
const radians = (relativeBearingDeg * Math.PI) / 180;
const fraction = distanceNm / rangeNm;
const course =
contact.course === null || contact.course === undefined
? NaN
: Number(contact.course);
projected.push({
id: String(contact.id),
name: String(contact.name || contact.id),
x: round4(Math.sin(radians) * fraction),
y: round4(Math.cos(radians) * fraction),
distanceNm,
relativeBearingDeg,
relativeCourseDeg: Number.isFinite(course)
? relativeBearing(course, heading)
: null,
color: contact.color || '',
stale: contact.stale === true,
});
}
projected.sort((a, b) => a.distanceNm - b.distanceNm);
return projected.slice(0, cap);
}
/**
* The radar presentation without its worded labels.
* @param {{latitude: number, longitude: number, headingDeg: number,
* courseDeg?: number|null}} own Own ship; `courseDeg` is course over ground.
* @param {Array<object>} contacts See {@link projectRadarContacts}.
* @param {number} rangeNm Range in nautical miles.
* @returns {{rangeNm: number, ringsNm: number[], headingDeg: number,
* ownRelativeCourseDeg: number|null, contacts: Array<object>}}
*/
export function radarPicture(own, contacts, rangeNm) {
const range = radarRangeNm(rangeNm);
const headingDeg = normalizeHeading(own?.headingDeg ?? 0);
const course =
own?.courseDeg === null || own?.courseDeg === undefined
? NaN
: Number(own.courseDeg);
return {
rangeNm: range,
ringsNm: radarRingsNm(range),
headingDeg,
ownRelativeCourseDeg: Number.isFinite(course)
? relativeBearing(course, headingDeg)
: null,
contacts: projectRadarContacts({ ...own, headingDeg }, contacts, {
rangeNm: range,
}),
};
}
+140
View File
@@ -0,0 +1,140 @@
// src/cockpitRadar.test.mjs — the bridge radar's range steps, rings and
// heading-up contact projection.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_RADAR_RANGE_NM,
METRES_PER_NM,
RADAR_MAX_CONTACTS,
RADAR_RANGES_NM,
nextRadarRange,
projectRadarContacts,
radarPicture,
radarRangeM,
radarRingsNm,
} from './cockpitRadar.js';
const OWN = Object.freeze({ latitude: 54.5, longitude: 10.2, headingDeg: 0 });
/** One nautical mile of latitude, in degrees. */
const NM_LAT = 1 / 60;
/** One nautical mile of longitude at 54.5°N, in degrees. */
const NM_LON = 1 / (60 * Math.cos((54.5 * Math.PI) / 180));
function contact(id, northNm, eastNm, extra = {}) {
return {
id,
name: id,
latitude: OWN.latitude + northNm * NM_LAT,
longitude: OWN.longitude + eastNm * NM_LON,
course: null,
color: '#fff',
stale: false,
...extra,
};
}
test('the range steps 3, 6, 12, 24 NM, opens on 3 and wraps', () => {
assert.deepEqual(RADAR_RANGES_NM, [3, 6, 12, 24]);
assert.equal(DEFAULT_RADAR_RANGE_NM, 3);
assert.equal(nextRadarRange(3), 6);
assert.equal(nextRadarRange(6), 12);
assert.equal(nextRadarRange(12), 24);
assert.equal(nextRadarRange(24), 3);
assert.equal(nextRadarRange(7), 6, 'an unknown range steps from the default');
assert.equal(radarRangeM(6), 6 * METRES_PER_NM);
});
test('range rings sit at each quarter of the range', () => {
assert.deepEqual(radarRingsNm(6), [1.5, 3, 4.5, 6]);
assert.deepEqual(radarRingsNm(24), [6, 12, 18, 24]);
});
test('a contact dead ahead is straight up the scope', () => {
const [ahead] = projectRadarContacts(OWN, [contact('A', 3, 0)], {
rangeNm: 6,
});
assert.ok(Math.abs(ahead.x) < 0.01, `x ${ahead.x}`);
assert.ok(Math.abs(ahead.y - 0.5) < 0.01, `y ${ahead.y}`);
assert.ok(Math.abs(ahead.distanceNm - 3) < 0.02);
assert.ok(Math.abs(ahead.relativeBearingDeg) < 0.5);
});
test('heading-up turns the picture with the bow', () => {
// Heading east: a contact to the north is on the port beam, one to the
// south on the starboard beam, one to the east dead ahead.
const own = { ...OWN, headingDeg: 90 };
const byId = Object.fromEntries(
projectRadarContacts(own, [
contact('N', 2, 0),
contact('S', -2, 0),
contact('E', 0, 2),
]).map((entry) => [entry.id, entry]),
);
assert.ok(byId.N.x < -0.3 && Math.abs(byId.N.y) < 0.02, 'north is to port');
assert.ok(
byId.S.x > 0.3 && Math.abs(byId.S.y) < 0.02,
'south is to starboard',
);
assert.ok(Math.abs(byId.E.x) < 0.02 && byId.E.y > 0.3, 'east is ahead');
assert.ok(Math.abs(byId.S.relativeBearingDeg - 90) < 1);
assert.ok(Math.abs(byId.N.relativeBearingDeg + 90) < 1);
});
test('a contact to starboard is right of the centre', () => {
const [starboard] = projectRadarContacts(OWN, [contact('B', 0, 1.5)]);
assert.ok(starboard.x > 0.2, `x ${starboard.x}`);
assert.ok(Math.abs(starboard.y) < 0.01);
});
test('course is drawn relative to the bow and stays null when unknown', () => {
const own = { ...OWN, headingDeg: 90 };
const [crossing, drifting] = projectRadarContacts(own, [
contact('A', 1, 0, { course: 180 }),
contact('B', 2, 0, { course: null }),
]);
assert.equal(crossing.relativeCourseDeg, 90);
assert.equal(drifting.relativeCourseDeg, null);
});
test('contacts beyond the range are left out', () => {
const contacts = projectRadarContacts(
OWN,
[contact('in', 5.9, 0), contact('out', 6.2, 0), contact('far', 0, 30)],
{ rangeNm: 6 },
);
assert.deepEqual(
contacts.map((entry) => entry.id),
['in'],
);
assert.ok(contacts.every((entry) => Math.hypot(entry.x, entry.y) <= 1));
});
test('contacts come nearest first, capped', () => {
const many = Array.from({ length: RADAR_MAX_CONTACTS + 15 }, (_, index) =>
contact(`V${index}`, 0, 5.5 - index * 0.07),
);
const contacts = projectRadarContacts(OWN, many, { rangeNm: 6 });
assert.equal(contacts.length, RADAR_MAX_CONTACTS);
for (let index = 1; index < contacts.length; index += 1)
assert.ok(contacts[index - 1].distanceNm <= contacts[index].distanceNm);
assert.equal(
projectRadarContacts(OWN, many, { rangeNm: 6, maxCount: 3 }).length,
3,
'a smaller cap is honoured',
);
});
test('a picture carries the range, rings, heading and own course over ground', () => {
const picture = radarPicture(
{ ...OWN, headingDeg: 350, courseDeg: 10 },
[contact('A', 1, 0)],
12,
);
assert.equal(picture.rangeNm, 12);
assert.deepEqual(picture.ringsNm, [3, 6, 9, 12]);
assert.equal(picture.headingDeg, 350);
assert.equal(picture.ownRelativeCourseDeg, 20);
assert.equal(picture.contacts.length, 1);
assert.ok(picture.contacts[0].x > 0, 'north is to starboard of 350°');
assert.equal(radarPicture(OWN, [], 6).ownRelativeCourseDeg, null);
});
+2 -2
View File
@@ -209,7 +209,7 @@ test('rows render the signals the controller presents', async (t) => {
);
assert.equal(status.className, 'warning');
assert.equal(status.querySelector('div > strong').textContent, 'UNKNOWN');
assert.equal(status.querySelector('button'), null);
assert.equal(status.querySelector('button') === null, true);
});
test('actual Context refresh retains the focused signal button across unchanged and changed details', async (t) => {
@@ -315,7 +315,7 @@ test('removing the focused identity uses the shown briefing tab once and permits
assert.equal(document.activeElement === f.signalTab(), true);
assert.equal(f.focusCalls(), calls + 1);
assert.equal(f.losses(), 0);
assert.equal(f.signalTab().closest('[hidden]'), null);
assert.equal(f.signalTab().closest('[hidden]') === null, true);
// Traversal carries on forward from the footer tab.
f.tab();
assert.equal(document.activeElement === f.pageTab(1), true);
+644
View File
@@ -0,0 +1,644 @@
/**
* @module cockpitSubjectProviders
* @description Subject providers: kinds of subject an application adds to the
* Cockpit beside its own aircraft, satellite and vessel. A provider names the
* subject entry would take, holds it while the view rides it, hands the camera
* a frame each update and the HUD a view model, and releases it on exit. Core
* knows nothing else about it.
*
* Everything a provider returns is normalized here before the Cockpit uses
* it: a malformed provider is left out, a malformed frame ends the view, and a
* malformed HUD view is read field by field, never thrown on.
*
* Pure: no Cesium, no DOM.
*/
/** The kinds the Cockpit rides itself; no provider may take one. */
export const COCKPIT_BUILT_IN_KINDS = Object.freeze([
'aircraft',
'satellite',
'vessel',
]);
/** The tones a provider's HUD texts may take. */
export const COCKPIT_SUBJECT_TONES = Object.freeze([
'normal',
'muted',
'live',
'estimate',
'warning',
'alert',
]);
/**
* The heights a frame may give (m, ellipsoidal): below the deepest dry
* ground, above anything ridden near it; outside, the frame stands on the
* floor.
*/
export const COCKPIT_SUBJECT_MIN_HEIGHT_M = -1_000;
export const COCKPIT_SUBJECT_MAX_HEIGHT_M = 50_000;
/** The most readouts, sources and signals a HUD view shows. */
export const COCKPIT_SUBJECT_MAX_READOUTS = 4;
export const COCKPIT_SUBJECT_MAX_SOURCES = 4;
export const COCKPIT_SUBJECT_MAX_SIGNALS = 4;
/** The most ticks a progress line takes. */
export const COCKPIT_SUBJECT_MAX_TICKS = 512;
const KIND_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
const LAYER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
const ICON_PATTERN = /^[a-z0-9_]{1,40}$/;
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;
const REQUIRED_METHODS = Object.freeze([
'candidate',
'hold',
'read',
'hud',
'release',
]);
const RESERVED = new Set(COCKPIT_BUILT_IN_KINDS);
const TONES = new Set(COCKPIT_SUBJECT_TONES);
const isObject = (value) =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
/**
* `value` as display text: trimmed, at most `max` characters (the last one
* an ellipsis when cut, the cut never inside a surrogate pair, so an emoji is
* kept whole or left out); '' for anything that is not a string or a number.
*/
export function cockpitSubjectText(value, max) {
if (typeof value !== 'string' && !finite(value)) return '';
const text = String(value).replace(/\s+/g, ' ').trim();
if (text.length <= max) return text;
let end = max - 1;
const last = text.charCodeAt(end - 1);
if (last >= 0xd800 && last <= 0xdbff) end -= 1;
return `${text.slice(0, end)}…`;
}
const tone = (value) => (TONES.has(value) ? value : 'normal');
/** A Material Symbols entry face, or null. */
function faceOf(raw) {
if (!isObject(raw)) return null;
const label = cockpitSubjectText(raw.label, 16);
if (typeof raw.icon !== 'string' || !ICON_PATTERN.test(raw.icon) || !label)
return null;
return Object.freeze({ icon: raw.icon, label });
}
/** The labels a provider gives, normalized, or null without the required. */
function labelsOf(raw) {
if (!isObject(raw)) return null;
const labels = {
view: cockpitSubjectText(raw.view, 48),
exit: cockpitSubjectText(raw.exit, 48),
exitText: cockpitSubjectText(raw.exitText, 24),
kicker: cockpitSubjectText(raw.kicker, 48),
};
return labels.view && labels.exit && labels.exitText
? Object.freeze(labels)
: null;
}
/** A provider's look, normalized, or null without an aheadLabel. */
function lookOf(raw) {
if (!isObject(raw)) return null;
const aheadLabel = cockpitSubjectText(raw.aheadLabel, 64);
if (!aheadLabel) return null;
return Object.freeze({
restPitchDeg: finite(raw.restPitchDeg)
? clamp(raw.restPitchDeg, -90, 90)
: 0,
aheadLabel,
});
}
/**
* A provider's worded member `key` as it reads now, normalized: the value,
* or what the function it is returns when called on `provider` (so it can
* follow the page's language); null when it is malformed or a read throws.
* Reading the member, and reading what it gives, runs provider code too (a
* getter), so both are guarded as the call is.
*/
function wordedNow(provider, key, normalize) {
try {
const value = provider[key];
return (
normalize(typeof value === 'function' ? value.call(provider) : value) ??
null
);
} catch {
return null;
}
}
/** A provider's name in a warning: its kind, cut, or its place in the list. */
function providerName(provider, order) {
try {
if (typeof provider?.kind === 'string') return provider.kind.slice(0, 32);
} catch {
// A kind getter that throws gives no name.
}
return `#${order}`;
}
/** Why `provider` cannot be kept, or null. */
function refusal(provider, kinds) {
if (!isObject(provider)) return 'not an object';
if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind))
return 'malformed kind';
if (RESERVED.has(provider.kind)) return 'reserved kind';
if (kinds.has(provider.kind)) return 'repeated kind';
if (
typeof provider.layerId !== 'string' ||
!LAYER_ID_PATTERN.test(provider.layerId)
)
return 'malformed layer id';
for (const method of REQUIRED_METHODS)
if (typeof provider[method] !== 'function') return `no ${method}()`;
if (
provider.isEntryAllowed !== undefined &&
typeof provider.isEntryAllowed !== 'function'
)
return 'isEntryAllowed is not a function';
if (!wordedNow(provider, 'entryFace', faceOf)) return 'malformed entry face';
if (!wordedNow(provider, 'labels', labelsOf))
return 'labels need view, exit and exitText';
if (provider.look != null && !wordedNow(provider, 'look', lookOf))
return 'look needs an aheadLabel';
return null;
}
/**
* The application's subject providers, checked once and frozen, in the order
* entry asks them: ascending `priority`, ties in list order. Each has
* - `kind`: /^[a-z][a-z0-9-]{1,31}$/, not a built-in kind, unique;
* - `layerId`: the catalog layer the subject belongs to (entry needs it on);
* - `priority`: a finite number (default 0);
* - `entryFace`: `{icon, label}`, a Material Symbols name and a label of at
* most 16 characters, in the page's language;
* - `labels`: `{view, exit, exitText, kicker?}`, the HUD's and the exit
* button's accessible names, the exit button's text and the default kicker,
* in the page's language;
* - `look` (optional): `{restPitchDeg?, aheadLabel}`, arrow-key look-around as
* on a bridge, resting at `restPitchDeg` (default 0, -90..90), its Look
* ahead button named `aheadLabel`;
* `entryFace`, `labels` and `look` may each be a function returning the
* object: it is called on the provider again whenever they are shown and
* when the page's language changes, so its words can follow it
* (`./i18n`). A read that throws or is malformed keeps the last
* good one; `look` is on or off and `restPitchDeg` fixed as first read;
* - `cameraIntervalMs` (optional): 0..1000, null for the Cockpit's default; 0
* updates the camera every rendered frame;
* - `headingSlewDps` (optional): how fast the view turns to a new heading,
* positive or Infinity, null for the Cockpit's default;
* - `candidate()`, `isEntryAllowed(candidate)` (optional), `hold(id)`,
* `read(nowMs, ctx)`, `hud(frame, ctx)` and `release(id, {restore})`, all
* synchronous (createCockpitSubjectCaller) and called on the provider, so
* a class instance's methods keep their `this`. `isEntryAllowed` allows
* entry only by returning `true`. `hold` returns `true` once it holds the
* subject, or `false` to refuse entry; any other answer refuses it too,
* with one warning. A refused hold, and one that throws or returns a
* promise, is followed by `release(id, {restore: false})`, and by another
* once that promise settles; `release` must therefore be harmless for a
* subject it does not hold or already gave back.
*
* A provider that is not so, or whose members throw when read (a getter), is
* left out with one warning naming it; the providers after it are kept.
* @param {unknown} list
* @param {{warn?: (message: string) => void}} [options]
* @returns {ReadonlyArray<object>}
*/
export function cockpitSubjectProviders(
list = [],
{ warn = (message) => console.warn(message) } = {},
) {
const kept = [];
const kinds = new Set();
(Array.isArray(list) ? list : []).forEach((provider, order) => {
let reason;
let copy = null;
try {
reason = refusal(provider, kinds);
if (!reason) copy = keptProvider(provider, order);
} catch {
reason = 'a member threw when read';
}
if (reason) {
warn(
`[Cockpit] subject provider ${providerName(provider, order)} left out: ${reason}`,
);
return;
}
kinds.add(copy.kind);
kept.push(copy);
});
kept.sort((a, b) => a.priority - b.priority || a.order - b.order);
return Object.freeze(kept);
}
/** The frozen copy the Cockpit keeps of a provider `refusal` passed. */
function keptProvider(provider, order) {
// Worded members are read again on each use (see above); the last good
// read stands in for one that is malformed or throws.
let face = wordedNow(provider, 'entryFace', faceOf);
let labels = wordedNow(provider, 'labels', labelsOf);
// On or off, and its rest pitch, as first read.
let look = wordedNow(provider, 'look', lookOf);
const restPitchDeg = look?.restPitchDeg ?? 0;
return Object.freeze({
kind: provider.kind,
layerId: provider.layerId,
priority: finite(provider.priority) ? provider.priority : 0,
order,
get entryFace() {
face = wordedNow(provider, 'entryFace', faceOf) ?? face;
return face;
},
get labels() {
labels = wordedNow(provider, 'labels', labelsOf) ?? labels;
return labels;
},
get look() {
if (!look) return null;
const now = wordedNow(provider, 'look', lookOf);
if (now)
look = Object.freeze({ restPitchDeg, aheadLabel: now.aheadLabel });
return look;
},
cameraIntervalMs:
finite(provider.cameraIntervalMs) &&
provider.cameraIntervalMs >= 0 &&
provider.cameraIntervalMs <= 1000
? provider.cameraIntervalMs
: null,
headingSlewDps:
provider.headingSlewDps === Infinity ||
(finite(provider.headingSlewDps) && provider.headingSlewDps > 0)
? provider.headingSlewDps
: null,
// Bound, so a method that uses `this` (a class instance's, say) still
// reads its own provider when called on this copy.
candidate: provider.candidate.bind(provider),
isEntryAllowed: provider.isEntryAllowed
? provider.isEntryAllowed.bind(provider)
: () => true,
hold: provider.hold.bind(provider),
read: provider.read.bind(provider),
hud: provider.hud.bind(provider),
release: provider.release.bind(provider),
});
}
/**
* A provider's candidate: `{id, name, face, selectedAt}`, or null without a
* usable id. `name` falls back to the id; `face` is null unless well formed;
* `selectedAt` (a number or a short string, else null) is a token the
* provider changes each time its subject is selected, even again: a
* subject selected after the built-in ones takes entry (entryCandidates).
* Null too when reading `raw` throws (a getter runs provider code).
* @param {unknown} raw What `candidate()` returned.
*/
export function cockpitSubjectCandidate(raw) {
try {
return candidateOf(raw);
} catch {
// A getter on what candidate() returned threw: no candidate.
return null;
}
}
function candidateOf(raw) {
if (!isObject(raw) || typeof raw.id !== 'string') return null;
const id = raw.id.trim();
if (!id || id.length > 128) return null;
const selectedAt =
finite(raw.selectedAt) ||
(typeof raw.selectedAt === 'string' && raw.selectedAt.length <= 64)
? raw.selectedAt
: null;
return Object.freeze({
id,
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(id, 64),
face: faceOf(raw.face),
selectedAt,
});
}
/**
* One camera frame from a provider, normalized, or null when it cannot place
* the camera (the view then ends): not an object, an id other than `heldId`,
* a position that is not finite, an eye with no valid `upM` (0..1000), or a
* read of it that throws (a getter runs provider code).
* A `heightM` that is not finite or lies outside
* COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null:
* the eye then stands on the shared floor, or where it last stood while that
* is cold. The anchor is `'inertial'` only when asked for and the frame
* gives a speed; otherwise it is `'exact'`. An id is compared with `heldId`
* trimmed, as `cockpitSubjectCandidate` trims it.
* @param {unknown} raw What `read()` returned.
* @param {string} heldId The subject the view holds.
* @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg,
* courseDeg, speedMps, stale, groundClamp, anchor, eye: {upM, forwardM,
* pitchDeg, minClearanceM}}`.
*/
export function cockpitSubjectFrame(raw, heldId) {
try {
return frameOf(raw, heldId);
} catch {
// A getter on what read() returned threw: as a malformed frame.
return null;
}
}
function frameOf(raw, heldId) {
if (!isObject(raw) || typeof raw.id !== 'string' || raw.id.trim() !== heldId)
return null;
const latitude = raw.latitude;
const longitude = raw.longitude;
if (!finite(latitude) || !finite(longitude) || Math.abs(latitude) > 90)
return null;
const eye = isObject(raw.eye) ? raw.eye : null;
if (!eye || !finite(eye.upM) || eye.upM < 0 || eye.upM > 1000) return null;
const heading = (value) =>
finite(value) ? ((value % 360) + 360) % 360 : null;
const headingDeg = heading(raw.headingDeg);
const speedMps =
finite(raw.speedMps) && raw.speedMps >= 0 ? raw.speedMps : null;
return {
id: heldId,
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64),
latitude,
longitude: ((((longitude + 180) % 360) + 360) % 360) - 180,
heightM:
finite(raw.heightM) &&
raw.heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M &&
raw.heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M
? raw.heightM
: null,
headingDeg,
courseDeg: heading(raw.courseDeg) ?? headingDeg,
speedMps,
stale: raw.stale === true,
groundClamp: raw.groundClamp !== false,
// An inertial anchor runs on at the frame's speed; with none it would
// close on a moving subject at the correction's floor and fall behind.
anchor: raw.anchor === 'exact' || speedMps === null ? 'exact' : 'inertial',
eye: {
upM: eye.upM,
forwardM:
finite(eye.forwardM) && Math.abs(eye.forwardM) <= 500
? eye.forwardM
: 0,
pitchDeg: finite(eye.pitchDeg) ? clamp(eye.pitchDeg, -90, 90) : 0,
minClearanceM:
finite(eye.minClearanceM) && eye.minClearanceM >= 0
? eye.minClearanceM
: 0,
},
};
}
/** A list of `{id, ...}` rows, each read by `row`, at most `max` kept. */
function rowsOf(raw, max, row) {
if (!Array.isArray(raw)) return [];
const rows = [];
const ids = new Set();
for (const entry of raw) {
if (rows.length >= max) break;
if (!isObject(entry)) continue;
const id = typeof entry.id === 'string' ? entry.id : '';
if (!ID_PATTERN.test(id) || ids.has(id)) continue;
const read = row(entry);
if (!read) continue;
ids.add(id);
rows.push({ id, ...read });
}
return rows;
}
/** A progress line, or null without at least two ticks. */
function progressOf(raw) {
if (!isObject(raw) || !Array.isArray(raw.ticks)) return null;
const ticks = [];
for (const tick of raw.ticks) {
if (ticks.length >= COCKPIT_SUBJECT_MAX_TICKS) break;
if (!isObject(tick) || !finite(tick.at) || tick.at < 0 || tick.at > 1)
continue;
let label = null;
if (isObject(tick.label)) {
const text = cockpitSubjectText(tick.label.text, 40);
if (text)
label = {
text,
detail: cockpitSubjectText(tick.label.detail, 64),
priority: finite(tick.label.priority)
? clamp(Math.round(tick.label.priority), 0, 9)
: 0,
align: ['start', 'center', 'end'].includes(tick.label.align)
? tick.label.align
: 'center',
};
}
ticks.push({ at: tick.at, tone: tone(tick.tone), label });
}
if (ticks.length < 2) return null;
ticks.sort((a, b) => a.at - b.at);
const marker =
isObject(raw.marker) && finite(raw.marker.at)
? { at: clamp(raw.marker.at, 0, 1), dwell: raw.marker.dwell === true }
: null;
return {
ticks,
marker,
tag: cockpitSubjectText(raw.tag, 16),
summary: cockpitSubjectText(raw.summary, 160),
};
}
/**
* A provider's HUD view model, normalized; never throws. Texts are coerced
* and cut to their caps, lists to their lengths, tones to
* COCKPIT_SUBJECT_TONES, numbers clamped; a malformed member reads as absent.
* Null when reading `raw` throws (a getter runs provider code), so the caller
* keeps the view it has, as when `hud()` itself throws.
* All text is shown as given: the provider words it in the page's language.
* @param {unknown} raw What `hud()` returned.
* @returns {object|null} `{kicker, title, meta: {text, tone}, speed: {value,
* unit, tag, tone}|null, readouts: [{id, label, value, detail, tone}],
* sources: [{id, label, text, tone}],
* route: {title, from, to, status}|null,
* progress: {ticks: [{at, tone, label: {text, detail, priority,
* align}|null}], marker: {at, dwell}|null, tag, summary}|null,
* banner: {title, detail, tone}|null, veil: {level, streaks}|null,
* lookReadout, signals: [{id, tone, title, detail}]}`.
*/
export function cockpitSubjectHudView(raw) {
try {
return hudViewOf(raw);
} catch {
// A getter on what hud() returned threw: the caller keeps its last view.
return null;
}
}
function hudViewOf(raw) {
const view = isObject(raw) ? raw : {};
const meta = isObject(view.meta) ? view.meta : {};
const speed =
isObject(view.speed) &&
(view.speed.value === null ||
(finite(view.speed.value) && view.speed.value >= 0))
? {
value:
view.speed.value === null
? null
: Math.min(view.speed.value, 99_999),
unit: cockpitSubjectText(view.speed.unit, 12),
tag: cockpitSubjectText(view.speed.tag, 8),
tone: tone(view.speed.tone),
}
: null;
const route = isObject(view.route)
? {
title: cockpitSubjectText(view.route.title, 32),
from: cockpitSubjectText(view.route.from, 48),
to: cockpitSubjectText(view.route.to, 48),
status: cockpitSubjectText(view.route.status, 64),
}
: null;
const bannerTitle = isObject(view.banner)
? cockpitSubjectText(view.banner.title, 48)
: '';
const veil =
isObject(view.veil) && finite(view.veil.level)
? {
level: clamp(view.veil.level, 0, 1),
streaks: view.veil.streaks === true,
}
: null;
return {
kicker: cockpitSubjectText(view.kicker, 48),
title: cockpitSubjectText(view.title, 64),
meta: { text: cockpitSubjectText(meta.text, 96), tone: tone(meta.tone) },
speed,
readouts: rowsOf(view.readouts, COCKPIT_SUBJECT_MAX_READOUTS, (row) => {
const label = cockpitSubjectText(row.label, 24);
const value = cockpitSubjectText(row.value, 48);
return label || value
? {
label,
value,
detail: cockpitSubjectText(row.detail, 80),
tone: tone(row.tone),
}
: null;
}),
sources: rowsOf(view.sources, COCKPIT_SUBJECT_MAX_SOURCES, (row) => {
const text = cockpitSubjectText(row.text, 120);
return text
? {
label: cockpitSubjectText(row.label, 16),
text,
tone: tone(row.tone),
}
: null;
}),
route: route && (route.from || route.to) ? route : null,
progress: progressOf(view.progress),
banner: bannerTitle
? {
title: bannerTitle,
detail: cockpitSubjectText(view.banner.detail, 96),
tone: tone(view.banner.tone),
}
: null,
veil: veil && veil.level > 0 ? veil : null,
lookReadout: cockpitSubjectText(view.lookReadout, 48),
signals: rowsOf(view.signals, COCKPIT_SUBJECT_MAX_SIGNALS, (row) => {
const title = cockpitSubjectText(row.title, 48);
return title
? {
title,
detail: cockpitSubjectText(row.detail, 96),
tone: tone(row.tone),
}
: null;
}),
};
}
/**
* A guarded caller for provider methods: `call(provider, method, args,
* fallback)` returns what the method returns, or `fallback` when it throws,
* warning once per provider and method.
*
* Provider methods are synchronous: the Cockpit calls them on its render
* cadence and uses the answer at once. One that returns a promise (an async
* function, say) breaks that contract: the promise is refused as a throw
* would be (its rejection, if any, is swallowed), with one warning, and
* `onSettled`, when given, runs once the promise has settled, so a caller
* can undo work that lands late.
*
* `call.warnOnce(provider, method, message, error)` warns on the same
* once-per-provider-and-method footing, for an answer the caller finds
* malformed.
* @param {{warn?: (message: string, error: unknown) => void}} [options]
*/
export function createCockpitSubjectCaller({
warn = (message, error) => console.warn(message, error),
} = {}) {
const warned = new Set();
const warnOnce = (provider, method, message, error) => {
const key = `${provider.kind}:${method}`;
if (warned.has(key)) return;
warned.add(key);
warn(
`[Cockpit] subject provider ${provider.kind} ${method}() ${message}`,
error,
);
};
function call(
provider,
method,
args = [],
fallback = null,
onSettled = null,
) {
let result;
let thenable;
try {
result = provider[method](...args);
// Reading `then` runs provider code too (a getter may throw), so it is
// guarded as the call is.
thenable =
result !== null &&
(typeof result === 'object' || typeof result === 'function') &&
typeof result.then === 'function';
} catch (error) {
warnOnce(provider, method, 'failed', error);
return fallback;
}
if (thenable) {
// Its work may still land: `onSettled` runs once it has, either way.
const settled = () => {
if (typeof onSettled === 'function') onSettled();
};
Promise.resolve(result).then(settled, settled);
warnOnce(
provider,
method,
'returned a promise; provider methods are synchronous',
null,
);
return fallback;
}
return result;
}
call.warnOnce = warnOnce;
return call;
}
+698
View File
@@ -0,0 +1,698 @@
// src/cockpitSubjectProviders.test.mjs — an application's subject providers
// are checked once and what they return is normalized before the Cockpit
// uses it: a malformed provider is left out, a malformed frame ends the view,
// and a malformed HUD view is read field by field and never thrown on.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
COCKPIT_BUILT_IN_KINDS,
COCKPIT_SUBJECT_MAX_READOUTS,
COCKPIT_SUBJECT_MAX_TICKS,
cockpitSubjectCandidate,
cockpitSubjectFrame,
cockpitSubjectHudView,
cockpitSubjectProviders,
cockpitSubjectText,
createCockpitSubjectCaller,
} from './cockpitSubjectProviders.js';
const noop = () => null;
/** A well-formed provider, with `overrides`. */
const provider = (overrides = {}) => ({
kind: 'example-kind',
layerId: 'example-layer',
entryFace: { icon: 'commute', label: 'RIDE' },
labels: {
view: 'First-person view',
exit: 'Exit first-person view',
exitText: 'EXIT VIEW',
},
candidate: noop,
hold: () => true,
read: noop,
hud: noop,
release: noop,
...overrides,
});
const keep = (list) => {
const warnings = [];
const kept = cockpitSubjectProviders(list, {
warn: (message) => warnings.push(message),
});
return { kept, warnings };
};
test('well-formed providers are kept, frozen, in priority then list order', () => {
const { kept, warnings } = keep([
provider({ kind: 'late', priority: 5 }),
provider({ kind: 'first-of-two', priority: 1 }),
provider({ kind: 'second-of-two', priority: 1 }),
provider({ kind: 'default-priority' }),
]);
assert.deepEqual(warnings, []);
assert.deepEqual(
kept.map(({ kind }) => kind),
['default-priority', 'first-of-two', 'second-of-two', 'late'],
);
assert.ok(Object.isFrozen(kept));
assert.ok(Object.isFrozen(kept[0]));
const [first] = kept;
assert.equal(first.priority, 0);
assert.equal(first.look, null);
assert.equal(first.cameraIntervalMs, null);
assert.equal(first.headingSlewDps, null);
assert.equal(first.isEntryAllowed(), true, 'no rule of its own allows');
assert.deepEqual(first.labels, {
view: 'First-person view',
exit: 'Exit first-person view',
exitText: 'EXIT VIEW',
kicker: '',
});
});
test('malformed, reserved and repeated providers are left out with one warning each', () => {
const cases = [
[null, /not an object/],
[provider({ kind: 'X' }), /malformed kind/],
[provider({ kind: 'a' }), /malformed kind/],
[provider({ layerId: 'Bad Layer' }), /malformed layer id/],
[provider({ hold: undefined }), /no hold\(\)/],
[provider({ read: 'read' }), /no read\(\)/],
[provider({ isEntryAllowed: true }), /isEntryAllowed/],
[provider({ entryFace: { icon: 'Bad Icon', label: 'X' } }), /entry face/],
[provider({ entryFace: { icon: 'commute', label: '' } }), /entry face/],
[provider({ labels: { view: 'v', exit: 'e' } }), /labels/],
[provider({ look: { restPitchDeg: -3 } }), /aheadLabel/],
];
for (const [entry, reason] of cases) {
const { kept, warnings } = keep([entry]);
assert.equal(kept.length, 0, String(reason));
assert.equal(warnings.length, 1, String(reason));
assert.match(warnings[0], reason);
}
for (const kind of COCKPIT_BUILT_IN_KINDS) {
const { kept, warnings } = keep([provider({ kind })]);
assert.equal(kept.length, 0, kind);
assert.match(warnings[0], /reserved kind/);
}
const { kept, warnings } = keep([provider(), provider()]);
assert.equal(kept.length, 1);
assert.match(warnings[0], /repeated kind/);
assert.deepEqual(keep('not a list').kept, []);
});
test('optional settings are kept when in range and defaulted otherwise', () => {
const [ranged] = keep([
provider({
priority: -2,
look: { restPitchDeg: -120, aheadLabel: 'Look ahead' },
cameraIntervalMs: 0,
headingSlewDps: Infinity,
labels: {
view: 'v',
exit: 'e',
exitText: 'x',
kicker: 'K'.repeat(80),
},
}),
]).kept;
assert.equal(ranged.priority, -2);
assert.deepEqual(ranged.look, {
restPitchDeg: -90,
aheadLabel: 'Look ahead',
});
assert.equal(ranged.cameraIntervalMs, 0);
assert.equal(ranged.headingSlewDps, Infinity);
assert.equal(ranged.labels.kicker.length, 48);
assert.ok(ranged.labels.kicker.endsWith('…'));
const [defaulted] = keep([
provider({
priority: NaN,
cameraIntervalMs: 5000,
headingSlewDps: -1,
}),
]).kept;
assert.equal(defaulted.priority, 0);
assert.equal(defaulted.cameraIntervalMs, null);
assert.equal(defaulted.headingSlewDps, null);
});
test('a candidate needs an id; its name and face are read with care', () => {
assert.equal(cockpitSubjectCandidate(null), null);
assert.equal(cockpitSubjectCandidate({ id: 7 }), null);
assert.equal(cockpitSubjectCandidate({ id: ' ' }), null);
assert.equal(cockpitSubjectCandidate({ id: 'x'.repeat(129) }), null);
assert.deepEqual(cockpitSubjectCandidate({ id: ' a1 ' }), {
id: 'a1',
name: 'a1',
face: null,
selectedAt: null,
});
// A selection token is a number or a short string.
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt: 5 }).selectedAt,
5,
);
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt: 'click-2' }).selectedAt,
'click-2',
);
for (const selectedAt of [Number.NaN, {}, 'x'.repeat(65)])
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt }).selectedAt,
null,
);
const read = cockpitSubjectCandidate({
id: 'a1',
name: ' Example 12 ',
face: { icon: 'tram', label: 'RIDE' },
});
assert.equal(read.name, 'Example 12');
assert.deepEqual(read.face, { icon: 'tram', label: 'RIDE' });
assert.equal(
cockpitSubjectCandidate({ id: 'a1', face: { icon: 'BAD' } }).face,
null,
);
});
test('a frame is the held subject at a finite place with an eye height, else null', () => {
const frame = (overrides = {}) => ({
id: 'a1',
latitude: 47,
longitude: 8,
eye: { upM: 3.5 },
...overrides,
});
const read = cockpitSubjectFrame(frame(), 'a1');
assert.deepEqual(read, {
id: 'a1',
name: 'a1',
latitude: 47,
longitude: 8,
heightM: null,
headingDeg: null,
courseDeg: null,
speedMps: null,
stale: false,
groundClamp: true,
// No speed to run an inertial anchor on: it sits on the subject.
anchor: 'exact',
eye: { upM: 3.5, forwardM: 0, pitchDeg: 0, minClearanceM: 0 },
});
assert.equal(
cockpitSubjectFrame(frame({ speedMps: 30 }), 'a1').anchor,
'inertial',
'with a speed it runs on',
);
// A held id is trimmed (cockpitSubjectCandidate), and so is a frame's.
assert.equal(cockpitSubjectFrame(frame({ id: ' a1 ' }), 'a1')?.id, 'a1');
for (const bad of [
null,
frame({ id: 'other' }),
frame({ latitude: 91 }),
frame({ latitude: NaN }),
frame({ longitude: Infinity }),
frame({ eye: null }),
frame({ eye: { upM: -1 } }),
frame({ eye: { upM: 2000 } }),
frame({ eye: { upM: '3' } }),
])
assert.equal(cockpitSubjectFrame(bad, 'a1'), null, JSON.stringify(bad));
const full = cockpitSubjectFrame(
frame({
name: 'Example',
longitude: 190,
heightM: 412.5,
headingDeg: -10,
courseDeg: 725,
speedMps: 22,
stale: true,
groundClamp: false,
anchor: 'exact',
eye: { upM: 2, forwardM: 600, pitchDeg: -100, minClearanceM: 1.5 },
}),
'a1',
);
assert.equal(full.longitude, -170);
assert.equal(full.heightM, 412.5);
// A height outside any plausible ground reads as none.
for (const heightM of [-6_400_000, 1e9, Infinity])
assert.equal(cockpitSubjectFrame(frame({ heightM }), 'a1').heightM, null);
assert.equal(
cockpitSubjectFrame(frame({ heightM: -400 }), 'a1').heightM,
-400,
);
assert.equal(full.headingDeg, 350);
assert.equal(full.courseDeg, 5);
assert.equal(full.speedMps, 22);
assert.equal(full.stale, true);
assert.equal(full.groundClamp, false);
assert.equal(full.anchor, 'exact');
assert.deepEqual(full.eye, {
upM: 2,
forwardM: 0,
pitchDeg: -90,
minClearanceM: 1.5,
});
// Only exactly false turns the ground clamp off; course falls back to heading.
const loose = cockpitSubjectFrame(
frame({ groundClamp: 0, anchor: 'EXACT', headingDeg: 90, speedMps: -1 }),
'a1',
);
assert.equal(loose.groundClamp, true);
assert.equal(
cockpitSubjectFrame(frame({ anchor: 'EXACT', speedMps: 5 }), 'a1').anchor,
'inertial',
);
assert.equal(loose.courseDeg, 90);
assert.equal(loose.speedMps, null);
});
test('a HUD view is read field by field: caps, tones, clamps, never a throw', () => {
const empty = cockpitSubjectHudView(null);
assert.deepEqual(empty, {
kicker: '',
title: '',
meta: { text: '', tone: 'normal' },
speed: null,
readouts: [],
sources: [],
route: null,
progress: null,
banner: null,
veil: null,
lookReadout: '',
signals: [],
});
for (const odd of [42, 'text', [], { readouts: 'x', progress: { ticks: 3 } }])
assert.doesNotThrow(() => cockpitSubjectHudView(odd));
const view = cockpitSubjectHudView({
kicker: 'LINE · OPERATOR',
title: 'Name → Destination',
meta: { text: 'LIVE', tone: 'bogus' },
speed: { value: 84.4, unit: 'km/h', tag: 'LIVE', tone: 'live' },
readouts: [
...Array.from({ length: 6 }, (_, i) => ({
id: `r${i}`,
label: 'NEXT',
value: `Stop ${i}`,
tone: 'warning',
})),
],
sources: [
{ id: 'track', label: 'TRACK', text: 'operator shape' },
{ id: 'track', label: 'TRACK', text: 'repeated id' },
{ id: 'Bad Id', text: 'refused' },
{ id: 'empty', label: 'X', text: '' },
],
route: { title: 'ROUTE', from: 'A', to: 'B', status: '3 stops' },
banner: { title: 'BANNER', detail: 'detail', tone: 'alert' },
veil: { level: 4, streaks: 1 },
lookReadout: 'LOOK RIGHT',
signals: [{ id: 's1', title: 'T', detail: 'D', tone: 'warning' }],
});
assert.equal(view.meta.tone, 'normal');
assert.deepEqual(view.speed, {
value: 84.4,
unit: 'km/h',
tag: 'LIVE',
tone: 'live',
});
assert.equal(view.readouts.length, COCKPIT_SUBJECT_MAX_READOUTS);
assert.equal(view.readouts[0].tone, 'warning');
assert.deepEqual(
view.sources.map(({ id }) => id),
['track'],
);
assert.deepEqual(view.route, {
title: 'ROUTE',
from: 'A',
to: 'B',
status: '3 stops',
});
assert.equal(view.banner.tone, 'alert');
assert.deepEqual(view.veil, { level: 1, streaks: false });
assert.equal(view.lookReadout, 'LOOK RIGHT');
assert.equal(view.signals[0].tone, 'warning');
// A veil at 0, a speed below 0 and a route with no ends are absent.
const absent = cockpitSubjectHudView({
veil: { level: 0 },
speed: { value: -3 },
route: { from: '', to: '' },
});
assert.equal(absent.veil, null);
assert.equal(absent.speed, null);
assert.equal(absent.route, null);
// A speed of null is a speed not yet known.
assert.equal(
cockpitSubjectHudView({ speed: { value: null } }).speed.value,
null,
);
});
test('a progress line keeps ticks in 0..1, sorted and capped, and needs two', () => {
const read = cockpitSubjectHudView({
progress: {
ticks: [
{ at: 1, label: { text: 'End', align: 'end', priority: 1 } },
{ at: 0.5, tone: 'warning' },
{ at: 2 },
{ at: -0.1 },
{ at: 0, label: { text: 'Start', align: 'start', priority: 12 } },
{ at: 0.25, label: { text: '', detail: 'no text, no label' } },
],
marker: { at: 1.4, dwell: true },
tag: 'TIMETABLE',
summary: 'From Start to End',
},
}).progress;
assert.deepEqual(
read.ticks.map(({ at }) => at),
[0, 0.25, 0.5, 1],
);
assert.equal(read.ticks[0].label.priority, 9);
assert.equal(read.ticks[0].label.align, 'start');
assert.equal(read.ticks[1].label, null);
assert.equal(read.ticks[2].tone, 'warning');
assert.deepEqual(read.marker, { at: 1, dwell: true });
assert.equal(read.tag, 'TIMETABLE');
assert.equal(read.summary, 'From Start to End');
assert.equal(
cockpitSubjectHudView({ progress: { ticks: [{ at: 0.5 }] } }).progress,
null,
);
const many = cockpitSubjectHudView({
progress: {
ticks: Array.from({ length: COCKPIT_SUBJECT_MAX_TICKS + 40 }, (_, i) => ({
at: i / (COCKPIT_SUBJECT_MAX_TICKS + 40),
})),
},
}).progress;
assert.equal(many.ticks.length, COCKPIT_SUBJECT_MAX_TICKS);
});
test('texts are trimmed, collapsed and cut with an ellipsis', () => {
assert.equal(cockpitSubjectText(' a \n b ', 10), 'a b');
assert.equal(cockpitSubjectText('abcdef', 4), 'abc…');
assert.equal(cockpitSubjectText(12.5, 10), '12.5');
assert.equal(cockpitSubjectText({}, 10), '');
assert.equal(cockpitSubjectText(NaN, 10), '');
});
test('a cut never splits a surrogate pair', () => {
// The cut would fall between the emoji's halves: it is left out whole.
assert.equal(cockpitSubjectText('abcd😀efgh', 6), 'abcd…');
// One that fits before the cut is kept whole.
assert.equal(cockpitSubjectText('abc😀efgh', 6), 'abc😀…');
const lone =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
for (let max = 2; max <= 24; max += 1)
assert.equal(
lone.test(cockpitSubjectText('🚆 Example 12 🚉 Central', max)),
false,
`cut at ${max}`,
);
});
test('a provider method that throws returns the fallback and warns once', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const failing = {
kind: 'example-kind',
read() {
throw new Error('boom');
},
hud: (value) => value * 2,
};
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
assert.equal(call(failing, 'hud', [21]), 42);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /example-kind read\(\) failed/);
});
test('a provider method that returns a promise is refused as a throw is, warning once', async () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const asynchronous = {
kind: 'example-kind',
hold: async () => true,
read: () => Promise.reject(new Error('late')),
};
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(call(asynchronous, 'read', [], null), null);
assert.equal(warnings.length, 2, 'once per method');
assert.match(warnings[0], /hold\(\) returned a promise/);
// The rejected promise is not left unhandled.
await new Promise((resolve) => setTimeout(resolve, 0));
});
test('an answer whose `then` throws when read is handled as a throw', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const tricky = {
kind: 'example-kind',
hold: () => ({
get then() {
throw new Error('no then');
},
}),
};
assert.equal(call(tricky, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(warnings.length, 1);
assert.match(warnings[0], /example-kind hold\(\) failed/);
});
test('the caller’s warnOnce shares its once-per-provider-and-method record', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const ride = {
kind: 'example-kind',
hold() {
throw new Error('boom');
},
};
call.warnOnce(ride, 'read', 'is odd');
call.warnOnce(ride, 'read', 'is odd again');
call(ride, 'hold', ['a1']);
call.warnOnce(ride, 'hold', 'is odd');
assert.deepEqual(warnings, [
'[Cockpit] subject provider example-kind read() is odd',
'[Cockpit] subject provider example-kind hold() failed',
]);
});
test('a class-based provider keeps its `this`, in its methods and its worded members', () => {
class Ride {
#word = 'RIDE';
#held = null;
kind = 'example-kind';
layerId = 'example-layer';
speak(word) {
this.#word = word;
}
entryFace() {
return { icon: 'commute', label: this.#word };
}
get labels() {
return {
view: `${this.#word} view`,
exit: 'Exit ride view',
exitText: 'EXIT RIDE',
};
}
look() {
return { aheadLabel: `Look ahead, ${this.#word}` };
}
candidate() {
return { id: 'a1', name: this.#word };
}
isEntryAllowed(candidate) {
return candidate.id === 'a1' && this.#held === null;
}
hold(id) {
this.#held = id;
return true;
}
read() {
return this.#held;
}
hud(frame) {
return { title: `${this.#word} ${frame}` };
}
release() {
this.#held = null;
return 'released';
}
}
const instance = new Ride();
const { kept, warnings } = keep([instance]);
assert.deepEqual(warnings, []);
const [ride] = kept;
assert.equal(ride.entryFace.label, 'RIDE');
assert.equal(ride.labels.view, 'RIDE view');
assert.equal(ride.look.aheadLabel, 'Look ahead, RIDE');
instance.speak('FAHRT');
assert.equal(ride.entryFace.label, 'FAHRT', 'read again, on the instance');
assert.equal(ride.look.aheadLabel, 'Look ahead, FAHRT');
// Called on the kept copy, as the Cockpit calls them.
const failures = [];
const call = createCockpitSubjectCaller({
warn: (message) => failures.push(message),
});
assert.deepEqual(call(ride, 'candidate'), { id: 'a1', name: 'FAHRT' });
assert.equal(ride.isEntryAllowed({ id: 'a1' }), true);
assert.equal(call(ride, 'hold', ['a1']), true);
assert.equal(ride.isEntryAllowed({ id: 'a1' }), false);
assert.equal(call(ride, 'read', [0, {}]), 'a1');
assert.deepEqual(call(ride, 'hud', ['a1', {}]), { title: 'FAHRT a1' });
assert.equal(call(ride, 'release', ['a1', { restore: true }]), 'released');
assert.equal(call(ride, 'read', [0, {}]), null);
assert.deepEqual(failures, []);
});
test('labels, entry face and look given as functions are read again on each use', () => {
let lang = 'en';
const words = {
en: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT RIDE' },
de: { view: 'Fahrtansicht', exit: 'Verlassen', exitText: 'VERLASSEN' },
};
const { kept, warnings } = keep([
provider({
labels: () => words[lang],
entryFace: () => ({
icon: 'commute',
label: { en: 'RIDE', de: 'FAHRT' }[lang],
}),
look: () => ({
restPitchDeg: lang === 'de' ? 40 : -3,
aheadLabel: lang === 'de' ? 'Nach vorn' : 'Look ahead',
}),
}),
]);
assert.deepEqual(warnings, []);
const [ride] = kept;
assert.equal(ride.labels.exitText, 'EXIT RIDE');
assert.equal(ride.entryFace.label, 'RIDE');
assert.equal(ride.look.aheadLabel, 'Look ahead');
lang = 'de';
assert.equal(ride.labels.exitText, 'VERLASSEN');
assert.equal(ride.entryFace.label, 'FAHRT');
assert.equal(ride.look.aheadLabel, 'Nach vorn');
assert.equal(ride.look.restPitchDeg, -3, 'the rest pitch is as first read');
// A read that fails or is malformed keeps the last good one.
lang = 'xx';
assert.equal(ride.labels.exitText, 'VERLASSEN');
assert.equal(ride.entryFace.label, 'FAHRT');
// Functions that are malformed from the start leave the provider out.
const bad = keep([
provider({ kind: 'bad-labels', labels: () => null }),
provider({
kind: 'thrown-face',
entryFace: () => {
throw new Error('no face');
},
}),
]);
assert.deepEqual(bad.kept, []);
assert.equal(bad.warnings.length, 2);
});
/** `target` with a getter for `key` that throws (provider code runs on a read). */
const throwingGetter = (target, key) =>
Object.defineProperty(target, key, {
enumerable: true,
get() {
throw new Error(`${key} unavailable`);
},
});
test('a provider whose getter throws is left out with one warning; the next is kept', () => {
const { kept, warnings } = keep([
throwingGetter(provider({ kind: 'thrown-face' }), 'entryFace'),
throwingGetter(provider({ kind: 'thrown-labels' }), 'labels'),
throwingGetter(provider({ kind: 'thrown-look' }), 'look'),
throwingGetter(provider(), 'kind'),
throwingGetter(provider({ kind: 'thrown-method' }), 'read'),
// Read only once the provider is accepted, so its kind must stay free.
throwingGetter(provider({ kind: 'example-kind' }), 'priority'),
provider({ kind: 'example-kind' }),
]);
assert.deepEqual(
kept.map(({ kind }) => kind),
['example-kind'],
);
assert.deepEqual(warnings, [
'[Cockpit] subject provider thrown-face left out: malformed entry face',
'[Cockpit] subject provider thrown-labels left out: labels need view, exit and exitText',
'[Cockpit] subject provider thrown-look left out: a member threw when read',
'[Cockpit] subject provider #3 left out: a member threw when read',
'[Cockpit] subject provider thrown-method left out: a member threw when read',
'[Cockpit] subject provider example-kind left out: a member threw when read',
]);
});
test('a worded getter that starts throwing keeps the last good words', () => {
let failing = false;
const words = (value) => () => {
if (failing) throw new Error('translations unavailable');
return value;
};
const definition = provider();
for (const [key, value] of Object.entries({
labels: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT' },
entryFace: { icon: 'commute', label: 'RIDE' },
look: { restPitchDeg: 10, aheadLabel: 'Look ahead' },
}))
Object.defineProperty(definition, key, { get: words(value) });
const { kept, warnings } = keep([definition]);
assert.deepEqual(warnings, []);
const [ride] = kept;
failing = true;
assert.equal(ride.labels.view, 'Ride view');
assert.equal(ride.entryFace.label, 'RIDE');
assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' });
// So does a worded object whose own member throws when read.
failing = false;
Object.defineProperty(definition, 'labels', {
get: () => throwingGetter({ view: 'v', exit: 'e', exitText: 'x' }, 'view'),
});
assert.equal(ride.labels.view, 'Ride view');
});
test('a candidate, frame or HUD view whose getter throws reads as null', () => {
assert.equal(
cockpitSubjectCandidate(throwingGetter({ name: 'Example' }, 'id')),
null,
);
const frame = { id: 'a1', latitude: 1, longitude: 2, eye: { upM: 3 } };
assert.ok(cockpitSubjectFrame(frame, 'a1'), 'well formed');
assert.equal(
cockpitSubjectFrame(throwingGetter({ ...frame }, 'latitude'), 'a1'),
null,
);
assert.equal(
cockpitSubjectFrame({ ...frame, eye: throwingGetter({}, 'upM') }, 'a1'),
null,
);
assert.equal(
cockpitSubjectHudView(throwingGetter({ title: 'T' }, 'meta')),
null,
);
assert.equal(
cockpitSubjectHudView({ title: 'T', readouts: [throwingGetter({}, 'id')] }),
null,
);
// Nothing to read is still the empty view, never null.
assert.equal(cockpitSubjectHudView(null).title, '');
});
+170
View File
@@ -0,0 +1,170 @@
/**
* Camera policy for first-person subjects other than aircraft: where a
* vessel's bridge eye sits and how its reported fix advances between feed
* refreshes. No DOM or i18n dependencies, so the policy is unit-testable.
*/
import { projectGroundArcLatLon } from './data/motionModel.js';
/** Bridge cameras look along the horizon; a ship's eye is already high. */
export const VESSEL_BRIDGE_PITCH_DEG = -2;
/** The AIS antenna usually sits on the bridge, so the eye is not moved forward. */
export const VESSEL_BRIDGE_FORWARD_OFFSET_M = 0;
/** Clearance over the shared ground floor for a camera that floats on water. */
export const VESSEL_BRIDGE_MIN_CLEARANCE_M = 2;
/** Eye height used when the vessel layer knows no height for the type. */
export const VESSEL_DEFAULT_EYE_HEIGHT_M = 12;
/**
* A reported fix older than this stops advancing: the vessel holds where the
* last projection left it instead of sailing on through a feed outage.
*/
export const VESSEL_DEAD_RECKON_MAX_S = 180;
/**
* The vessel layer floats every ship on the geoid (mean sea level), but a
* river or lake can sit well above it: the Seine through Paris is ~27 m up,
* which put a bridge eye under the water. The bridge reads the rendered
* surface around its ship instead: probes on a ring this far out, plus one
* at the ship itself.
*/
export const VESSEL_WATERLINE_PROBE_RADIUS_M = 30;
/** Probes on the ring around the ship. */
export const VESSEL_WATERLINE_PROBE_COUNT = 8;
/** How often the bridge reads the water under its ship again, ms. */
export const VESSEL_WATERLINE_REFRESH_MS = 5000;
/** A surface less than this above sea level is the sea itself, metres. */
export const VESSEL_WATERLINE_MIN_RISE_M = 2;
/** Highest navigable water trusted from a sample (Lake Titicaca ~3,810 m). */
export const VESSEL_WATERLINE_MAX_RISE_M = 4000;
/**
* Where to read the surface around a ship: the ship's own position, then a
* ring of probes around it.
* @param {number} latitude
* @param {number} longitude
* @returns {Array<{lat: number, lon: number}>}
*/
export function waterlineProbePoints(
latitude,
longitude,
radiusM = VESSEL_WATERLINE_PROBE_RADIUS_M,
count = VESSEL_WATERLINE_PROBE_COUNT,
) {
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return [];
const points = [{ lat: latitude, lon: longitude }];
const metresPerDegLat = 111_320;
const metresPerDegLon =
metresPerDegLat * Math.max(0.01, Math.cos((latitude * Math.PI) / 180));
for (let i = 0; i < count; i += 1) {
const bearing = (2 * Math.PI * i) / count;
points.push({
lat: latitude + (radiusM * Math.cos(bearing)) / metresPerDegLat,
lon: longitude + (radiusM * Math.sin(bearing)) / metresPerDegLon,
});
}
return points;
}
/**
* The water surface a bridge floats on, ellipsoidal metres. Quays, bridges,
* moored boats and the ship's own model all stand above the water, so the
* lowest probe is the water. A lowest probe barely above sea level is the
* sea; one implausibly high is a bad sample. Either way the geoid stands.
* @param {number} seaSurfaceM The geoid sea surface the layer floats ships on.
* @param {Array<number|null|undefined>} sampleHeightsM Rendered-surface probes.
* @returns {number}
*/
export function vesselWaterlineM(seaSurfaceM, sampleHeightsM) {
const heights = (sampleHeightsM || []).filter(Number.isFinite);
if (!Number.isFinite(seaSurfaceM) || !heights.length) return seaSurfaceM;
const lowest = Math.min(...heights);
const rise = lowest - seaSurfaceM;
return rise >= VESSEL_WATERLINE_MIN_RISE_M &&
rise <= VESSEL_WATERLINE_MAX_RISE_M
? lowest
: seaSurfaceM;
}
/**
* Camera placement for a vessel subject, in the shape the Cockpit camera
* reads for every subject kind.
* @param {{eyeHeightM?: number|null}} info Vessel subject info.
* @returns {{forwardM: number, upM: number, pitchDeg: number, minClearanceM: number}}
*/
export function vesselCameraProfile(info) {
return {
forwardM: VESSEL_BRIDGE_FORWARD_OFFSET_M,
upM: Number.isFinite(info?.eyeHeightM)
? info.eyeHeightM
: VESSEL_DEFAULT_EYE_HEIGHT_M,
pitchDeg: VESSEL_BRIDGE_PITCH_DEG,
minClearanceM: VESSEL_BRIDGE_MIN_CLEARANCE_M,
};
}
/**
* How old a vessel's fix is now, seconds, or null without a fix time.
*
* The fix time is on the AIS feed's clock and `nowMs` on this client's, so
* comparing them directly would turn a client clock running minutes fast
* into minutes of age (every bridge projecting its full limit and reading
* STALE FEED). With the time this client first received the fix (client
* clock) and the newest fix in that refresh (feed clock), the age is the
* time since the fix arrived plus how far it trailed that newest fix; each
* part is read on one clock. A fix the feed keeps re-serving keeps its first
* receipt, so it ages into STALE FEED. The age leaves out the newest fix's
* own delay before the refresh, typically seconds: a feed that was already
* stalled when the bridge first saw it ages from then. Without them it falls
* back to the clock difference, never negative.
* @param {{fixEpochMs: number|null, receivedAtMs?: number|null,
* feedEpochMs?: number|null}} fix
* @param {number} nowMs Wall-clock time, ms.
* @returns {number|null}
*/
export function vesselFixAgeSec(fix, nowMs) {
const { fixEpochMs, receivedAtMs, feedEpochMs } = fix || {};
if (!Number.isFinite(fixEpochMs) || !Number.isFinite(nowMs)) return null;
if (Number.isFinite(receivedAtMs) && Number.isFinite(feedEpochMs))
return (
Math.max(0, (nowMs - receivedAtMs) / 1000) +
Math.max(0, (feedEpochMs - fixEpochMs) / 1000)
);
return Math.max(0, (nowMs - fixEpochMs) / 1000);
}
/**
* Advance a vessel's last reported fix along its course over ground.
*
* The vessel layer redraws a ship only when the feed refreshes, so its icon
* stands still between fixes. A camera converging on that still point would
* sail backwards against its own motion. Projecting the fix forward gives the
* Cockpit anchor a moving target, and the bounded age keeps a silent feed from
* carrying the ship away indefinitely.
* @param {{latitude: number, longitude: number, courseDeg: number|null,
* speedMps: number|null, fixEpochMs: number|null,
* receivedAtMs?: number|null, feedEpochMs?: number|null}} fix Last
* report; its age is `vesselFixAgeSec`.
* @param {number} nowMs Wall-clock time, ms.
* @returns {{latitude: number, longitude: number, ageSec: number|null}}
*/
export function deadReckonVesselFix(fix, nowMs) {
const { latitude, longitude, courseDeg, speedMps } = fix || {};
const ageSec = vesselFixAgeSec(fix, nowMs);
if (ageSec === null) return { latitude, longitude, ageSec: null };
const { lat, lon } = projectGroundArcLatLon(
latitude,
longitude,
courseDeg,
speedMps,
0,
Math.min(ageSec, VESSEL_DEAD_RECKON_MAX_S),
);
return { latitude: lat, longitude: lon, ageSec };
}
+137
View File
@@ -0,0 +1,137 @@
// src/cockpitSubjects.test.mjs — the vessel camera profile and dead
// reckoning of AIS fixes between feed refreshes.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
VESSEL_BRIDGE_MIN_CLEARANCE_M,
VESSEL_BRIDGE_PITCH_DEG,
VESSEL_DEAD_RECKON_MAX_S,
VESSEL_DEFAULT_EYE_HEIGHT_M,
VESSEL_WATERLINE_PROBE_RADIUS_M,
deadReckonVesselFix,
vesselFixAgeSec,
vesselCameraProfile,
vesselWaterlineM,
waterlineProbePoints,
} from './cockpitSubjects.js';
const EARTH_M_PER_DEG_LAT = 111_195;
test('the vessel camera profile puts the eye at the bridge, looking at the horizon', () => {
assert.deepEqual(vesselCameraProfile({ eyeHeightM: 30 }), {
forwardM: 0,
upM: 30,
pitchDeg: VESSEL_BRIDGE_PITCH_DEG,
minClearanceM: VESSEL_BRIDGE_MIN_CLEARANCE_M,
});
});
test('a vessel with no known eye height uses the default', () => {
for (const info of [{}, { eyeHeightM: null }, null]) {
assert.equal(vesselCameraProfile(info).upM, VESSEL_DEFAULT_EYE_HEIGHT_M);
}
});
test('a fix advances along course over ground for its age', () => {
const fixEpochMs = 1_000_000;
const advanced = deadReckonVesselFix(
{
latitude: 0,
longitude: 0,
courseDeg: 0,
speedMps: 10,
fixEpochMs,
},
fixEpochMs + 60_000,
);
assert.equal(advanced.ageSec, 60);
// Sixty seconds north at 10 m/s.
assert.ok(
Math.abs(advanced.latitude * EARTH_M_PER_DEG_LAT - 600) < 2,
`expected ~600 m north, got ${advanced.latitude * EARTH_M_PER_DEG_LAT}`,
);
assert.ok(Math.abs(advanced.longitude) < 1e-9);
});
test('projection stops at the dead-reckoning limit', () => {
const fixEpochMs = 0;
const at = (ageSec) =>
deadReckonVesselFix(
{ latitude: 0, longitude: 0, courseDeg: 90, speedMps: 5, fixEpochMs },
fixEpochMs + ageSec * 1000,
);
const limit = at(VESSEL_DEAD_RECKON_MAX_S);
const later = at(VESSEL_DEAD_RECKON_MAX_S * 4);
assert.equal(later.longitude, limit.longitude);
assert.equal(later.ageSec, VESSEL_DEAD_RECKON_MAX_S * 4);
});
test('a fix without time, course or speed stays where it was reported', () => {
const fix = {
latitude: 54.3,
longitude: 10.1,
courseDeg: null,
speedMps: 6,
fixEpochMs: 0,
};
assert.deepEqual(deadReckonVesselFix(fix, 30_000), {
latitude: 54.3,
longitude: 10.1,
ageSec: 30,
});
assert.deepEqual(
deadReckonVesselFix({ ...fix, courseDeg: 90, fixEpochMs: null }, 30_000),
{ latitude: 54.3, longitude: 10.1, ageSec: null },
);
});
test('waterline probes ring the ship at the probe radius', () => {
const points = waterlineProbePoints(48.859, 2.293);
assert.equal(points.length, 9);
assert.deepEqual(points[0], { lat: 48.859, lon: 2.293 });
for (const point of points.slice(1)) {
const northM = (point.lat - 48.859) * 111_320;
const eastM =
(point.lon - 2.293) * 111_320 * Math.cos((48.859 * Math.PI) / 180);
assert.ok(
Math.abs(Math.hypot(northM, eastM) - VESSEL_WATERLINE_PROBE_RADIUS_M) <
0.01,
);
}
assert.deepEqual(waterlineProbePoints(Number.NaN, 2), []);
});
test('the waterline is the lowest probe when it stands clear of the sea', () => {
// The Seine at the Eiffel Tower: geoid 44.6 m, water about 71 m.
assert.equal(vesselWaterlineM(44.6, [80, 71.2, 75, null, 90]), 71.2);
// Swell and tile noise are the sea itself.
assert.equal(vesselWaterlineM(44.6, [45.5, 46]), 44.6);
// Under the sea surface (a dock, a bad tile) never sinks the ship.
assert.equal(vesselWaterlineM(44.6, [30, 71]), 44.6);
// Nothing sampled, or implausibly high.
assert.equal(vesselWaterlineM(44.6, [undefined, Number.NaN]), 44.6);
assert.equal(vesselWaterlineM(44.6, [9000]), 44.6);
});
test("a fix's age is read on each clock, so a fast client clock adds none", () => {
const fixEpochMs = 1_800_000_000_000;
// The refresh's newest fix is 10 s newer than this one; the client, its
// clock five minutes fast, received the refresh 5 s ago.
const receivedAtMs = fixEpochMs + 12_000 + 300_000;
const fix = {
latitude: 0,
longitude: 0,
courseDeg: 90,
speedMps: 5,
fixEpochMs,
receivedAtMs,
feedEpochMs: fixEpochMs + 10_000,
};
assert.equal(vesselFixAgeSec(fix, receivedAtMs + 5000), 15);
assert.equal(deadReckonVesselFix(fix, receivedAtMs + 5000).ageSec, 15);
// Without receive data the clocks are compared, never below zero.
const bare = { fixEpochMs };
assert.equal(vesselFixAgeSec(bare, fixEpochMs + 60_000), 60);
assert.equal(vesselFixAgeSec(bare, fixEpochMs - 60_000), 0);
assert.equal(vesselFixAgeSec({ fixEpochMs: null }, fixEpochMs), null);
});
+3 -2
View File
@@ -1,7 +1,7 @@
/*
* Cockpit aircraft metadata itself is resolved by `resolveTrackedAircraftInfo`
* in `cockpitMath.js` — the landed owner of that rule. It keeps layer
* precedence as the fallback when no normalized `gevTrackedId` is available,
* precedence as the fallback when the entity record has no normalized `trackedId`,
* so tracking paths that never stamp one keep working; `readAircraftInfo` is
* pinned to it by `cockpitMarkup.test.mjs`. This module owns only the
* multi-step ENTRY TRANSACTION (adopt → enter → roll back).
@@ -65,7 +65,8 @@ export function enterCockpitWithTracking({
);
}
}
if (!entryError) entered = Boolean(cockpitView.enter());
// This transaction selects aircraft; a selected vessel must not stand in.
if (!entryError) entered = Boolean(cockpitView.enter({ kind: 'aircraft' }));
} catch (error) {
entryThrew = true;
entryError = error instanceof Error ? error : new Error(String(error));
+3 -2
View File
@@ -5,6 +5,7 @@ import {
enterCockpitWithTracking,
restoreAircraftTrackingOwner,
} from './cockpitTracking.js';
import { readEntityRecord, withEntityRecord } from './data/entityRecords.js';
/**
* Model the two production stamping seams that sit under this transaction:
@@ -22,7 +23,7 @@ function stampingWorld({ entryAllowed = true } = {}) {
layerId,
trackById(id) {
if (!trackable) return false;
world.trackedEntity = { gevTrackedId: `${layerId}:${id}` };
world.trackedEntity = withEntityRecord({}, { trackedId: `${layerId}:${id}` });
stamp('trackedEntityChanged'); // the ui.js listener
return true;
},
@@ -80,7 +81,7 @@ test('a refused Cockpit entry still stamps for the tracker it already moved', ()
// Adoption stamped, and the rollback re-track stamped again.
assert.deepEqual(world.stamps, ['trackedEntityChanged', 'trackedEntityChanged']);
assert.equal(world.generation, 2);
assert.equal(world.trackedEntity.gevTrackedId, 'military:ae01ce');
assert.equal(readEntityRecord(world.trackedEntity)?.trackedId, 'military:ae01ce');
});
test('a Cockpit entry that mutates nothing takes no camera authority', () => {
+54
View File
@@ -445,6 +445,60 @@ export function cockpitEntryAllowed({
);
}
/**
* Whether the selected vessel's bridge view can be entered. Like aircraft
* Cockpit it needs only its own layer, Live AIS Vessels, with a vessel
* selected. A Context mode change in flight still owns the camera, so entry
* waits it out.
* @param {{vesselsEnabled: boolean, contextModeChanging: boolean}} state
* @returns {boolean}
*/
export function bridgeEntryAllowed({ vesselsEnabled, contextModeChanging }) {
return Boolean(vesselsEnabled) && !contextModeChanging;
}
/**
* Whether the tracked satellite's orbital view can be entered. Like the
* bridge it needs only its own layer, Satellites, with a satellite tracked.
* A Context mode change in flight still owns the camera, so entry waits it
* out. A subject the satellites layer marks as not enterable (debris:
* rocket bodies, fragments, dead satellites; `satelliteClassEnterable` in
* src/layers/satellites/classes.js) can be tracked but is never ridden: it is
* no mission and has no view to offer.
* @param {{satellitesEnabled: boolean, contextModeChanging: boolean,
* subjectEnterable?: boolean}} state
* @returns {boolean}
*/
export function orbitEntryAllowed({
satellitesEnabled,
contextModeChanging,
subjectEnterable = true,
}) {
return (
Boolean(satellitesEnabled) &&
!contextModeChanging &&
subjectEnterable !== false
);
}
/**
* Whether an application subject provider's candidate can be ridden. Like the
* bridge and orbit it needs only its own layer on, and waits out a Context
* change in flight; the provider then has its own say (`isEntryAllowed`).
* @param {{layerEnabled: boolean, contextModeChanging: boolean,
* providerAllows: boolean}} state
* @returns {boolean}
*/
export function subjectEntryAllowed({
layerEnabled,
contextModeChanging,
providerAllows,
}) {
return (
Boolean(layerEnabled) && !contextModeChanging && providerAllows === true
);
}
/**
* Internal context-mode id → the word the voice tools accept for it.
*
+26
View File
@@ -1,6 +1,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
bridgeEntryAllowed,
orbitEntryAllowed,
cockpitEntryAllowed,
contextAllowedLayerIds,
contextLayerEnableBlockReason,
@@ -426,6 +428,30 @@ test("cockpit entry needs only the tracked aircraft's own layer", () => {
subjectLayerEnabled: false,
contextModeChanging: false,
}), false, 'there is no aircraft to ride');
assert.equal(cockpitEntryAllowed({
subjectLayerId: 'ais-live-vessels',
subjectLayerEnabled: true,
contextModeChanging: false,
}), false, "a vessel is the bridge gate's subject, not Cockpit's");
});
test('bridge entry needs only Live AIS Vessels', () => {
assert.equal(bridgeEntryAllowed({ vesselsEnabled: true, contextModeChanging: false }), true);
assert.equal(bridgeEntryAllowed({ vesselsEnabled: false, contextModeChanging: false }), false);
assert.equal(bridgeEntryAllowed({ vesselsEnabled: true, contextModeChanging: true }), false);
});
test('orbital entry needs only Satellites', () => {
assert.equal(orbitEntryAllowed({ satellitesEnabled: true, contextModeChanging: false }), true);
assert.equal(orbitEntryAllowed({ satellitesEnabled: false, contextModeChanging: false }), false);
assert.equal(orbitEntryAllowed({ satellitesEnabled: true, contextModeChanging: true }), false);
});
test('debris can be tracked but never ridden in orbit', () => {
const on = { satellitesEnabled: true, contextModeChanging: false };
assert.equal(orbitEntryAllowed({ ...on, subjectEnterable: false }), false);
assert.equal(orbitEntryAllowed({ ...on, subjectEnterable: true }), true);
assert.equal(orbitEntryAllowed(on), true, 'no subject read yet');
});
test('context teardown guard restores coordination state after success and failure', async () => {
Loaded 100 of 2262 files, more files were not shown because too many files have changed in this diff. Show more