Merge origin/main into the renderer-contract branch: the procedural fleet models drawn through the renderer's model sets

Aircraft, military, local ADS-B, vessel, transit and rail models come from
the fleet model set, loaded up front and drawn life size through the draw
port's models sets; no layer touches the viewer or Cesium outside
src/render/cesium/. The models capability gains glTF bytes (gltf), a
per-axis stretch (axisScale), a colour for tinted parts (maskColor) and a
cut below the origin (clip: 'belowOrigin'), with conformance checks.

Main's rail layer and Data Library are ported to the ports; the CCTV
footprint probe keeps the globe-terrain clamp through the query port.
This commit is contained in:
Sameh Khamis committed 2026-11-13 14:14:42 -08:00
commit e3865f462f
533 files changed
+55738 -2518

No files matched your search

+356
View File
@@ -0,0 +1,356 @@
/**
* Reads the procedural fleet models' GLBs in Node: their JSON chunk, and their
* triangles in scene space (raw glTF axes, node transforms applied, metres).
*
* The GLBs use EXT_meshopt_compression and KHR_mesh_quantization, so their
* buffers are decoded with the meshoptimizer decoder Cesium itself ships (a
* dependency of `@cesium/engine`, resolved through it rather than named as one
* of this package's own).
*/
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
let decoderPromise = null;
/** The meshoptimizer decoder Cesium decodes these models with. */
async function meshoptDecoder() {
decoderPromise ??= (async () => {
const fromHere = createRequire(import.meta.url);
const fromCesium = createRequire(fromHere.resolve('cesium/package.json'));
const fromEngine = createRequire(
fromCesium.resolve('@cesium/engine/package.json'),
);
const module = await import(
pathToFileURL(fromEngine.resolve('meshoptimizer')).href
);
await module.MeshoptDecoder.ready;
return module.MeshoptDecoder;
})();
return decoderPromise;
}
/**
* A GLB's JSON and binary chunks.
* @param {string} file
* @returns {{json: object, bin: Uint8Array}}
*/
export function readGlb(file) {
const bytes = fs.readFileSync(file);
if (bytes.readUInt32LE(0) !== 0x46546c67)
throw new Error(`${file}: not a GLB`);
const jsonLength = bytes.readUInt32LE(12);
const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8'));
const binStart = 20 + jsonLength;
const bin =
binStart + 8 <= bytes.length
? new Uint8Array(
bytes.buffer,
bytes.byteOffset + binStart + 8,
bytes.readUInt32LE(binStart),
)
: new Uint8Array(0);
return { json, bin };
}
/** Column-major node matrix from a glTF node's TRS (or its matrix). */
function nodeMatrix(node) {
if (node.matrix) return node.matrix;
const t = node.translation || [0, 0, 0];
const [x, y, z, w] = node.rotation || [0, 0, 0, 1];
const s = node.scale || [1, 1, 1];
return [
(1 - 2 * (y * y + z * z)) * s[0],
2 * (x * y + z * w) * s[0],
2 * (x * z - y * w) * s[0],
0,
2 * (x * y - z * w) * s[1],
(1 - 2 * (x * x + z * z)) * s[1],
2 * (y * z + x * w) * s[1],
0,
2 * (x * z + y * w) * s[2],
2 * (y * z - x * w) * s[2],
(1 - 2 * (x * x + y * y)) * s[2],
0,
t[0],
t[1],
t[2],
1,
];
}
function multiply(a, b) {
const out = new Array(16).fill(0);
for (let c = 0; c < 4; c++)
for (let r = 0; r < 4; r++)
for (let k = 0; k < 4; k++) out[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
return out;
}
const COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 };
const READERS = {
5120: ['getInt8', 1, 127],
5121: ['getUint8', 1, 255],
5122: ['getInt16', 2, 32767],
5123: ['getUint16', 2, 65535],
5125: ['getUint32', 4, 4294967295],
5126: ['getFloat32', 4, 1],
};
/**
* Every element of accessor `index`, normalised integers mapped to -1..1 or
* 0..1 the way a renderer reads them.
*/
function readAccessor(gltf, views, index) {
const accessor = gltf.accessors[index];
const view = gltf.bufferViews[accessor.bufferView];
const bytes = views[accessor.bufferView];
const [getter, size, max] = READERS[accessor.componentType];
const components = COMPONENTS[accessor.type];
const stride = view.byteStride || size * components;
const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const out = new Float64Array(accessor.count * components);
for (let i = 0; i < accessor.count; i++)
for (let c = 0; c < components; c++) {
const value = data[getter](
(accessor.byteOffset || 0) + i * stride + c * size,
true,
);
out[i * components + c] = accessor.normalized
? Math.max(value / max, -1)
: value;
}
return out;
}
/** Each buffer view's bytes, meshopt-compressed ones decoded. */
async function bufferViews(gltf, bin) {
const decoder = await meshoptDecoder();
return gltf.bufferViews.map((view) => {
const meshopt = view.extensions?.EXT_meshopt_compression;
if (!meshopt)
return bin.subarray(
view.byteOffset || 0,
(view.byteOffset || 0) + view.byteLength,
);
const source = bin.subarray(
meshopt.byteOffset || 0,
(meshopt.byteOffset || 0) + meshopt.byteLength,
);
const target = new Uint8Array(meshopt.count * meshopt.byteStride);
decoder.decodeGltfBuffer(
target,
meshopt.count,
meshopt.byteStride,
source,
meshopt.mode,
meshopt.filter,
);
return target;
});
}
/**
* A fleet model's triangles in scene space: raw glTF axes (X along the body,
* nose toward -X; Y up; Z across), node transforms applied, metres.
* @param {string} file
* @returns {Promise<{verts: number[][], tris: number[][]}>}
*/
export async function fleetMesh(file) {
const { json: gltf, bin } = readGlb(file);
const views = await bufferViews(gltf, bin);
const verts = [];
const tris = [];
const visit = (index, parent) => {
const node = gltf.nodes[index];
const m = multiply(parent, nodeMatrix(node));
if (node.mesh != null) {
for (const primitive of gltf.meshes[node.mesh].primitives) {
const base = verts.length;
const positions = readAccessor(
gltf,
views,
primitive.attributes.POSITION,
);
for (let i = 0; i < positions.length; i += 3) {
const [x, y, z] = [positions[i], positions[i + 1], positions[i + 2]];
verts.push([
m[0] * x + m[4] * y + m[8] * z + m[12],
m[1] * x + m[5] * y + m[9] * z + m[13],
m[2] * x + m[6] * y + m[10] * z + m[14],
]);
}
const indices = readAccessor(gltf, views, primitive.indices);
for (let i = 0; i + 2 < indices.length; i += 3)
tris.push([
base + indices[i],
base + indices[i + 1],
base + indices[i + 2],
]);
}
}
for (const child of node.children || []) visit(child, m);
};
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
for (const root of gltf.scenes[gltf.scene ?? 0].nodes) visit(root, identity);
return { verts, tris };
}
/** Axis-aligned bounds of a vertex list. */
export function vertexBounds(verts) {
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
for (const v of verts)
for (let a = 0; a < 3; a++) {
if (v[a] < min[a]) min[a] = v[a];
if (v[a] > max[a]) max[a] = v[a];
}
return { min, max };
}
const dist3 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
/** Closest point of triangle abc to p (Ericson, Real-Time Collision Detection). */
function closestOnTriangle(p, a, b, c) {
const sub = (u, v) => [u[0] - v[0], u[1] - v[1], u[2] - v[2]];
const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
const ab = sub(b, a);
const ac = sub(c, a);
const ap = sub(p, a);
const d1 = dot(ab, ap);
const d2 = dot(ac, ap);
if (d1 <= 0 && d2 <= 0) return a;
const bp = sub(p, b);
const d3 = dot(ab, bp);
const d4 = dot(ac, bp);
if (d3 >= 0 && d4 <= d3) return b;
const vc = d1 * d4 - d3 * d2;
if (vc <= 0 && d1 >= 0 && d3 <= 0) {
const v = d1 / (d1 - d3);
return [a[0] + ab[0] * v, a[1] + ab[1] * v, a[2] + ab[2] * v];
}
const cp = sub(p, c);
const d5 = dot(ab, cp);
const d6 = dot(ac, cp);
if (d6 >= 0 && d5 <= d6) return c;
const vb = d5 * d2 - d1 * d6;
if (vb <= 0 && d2 >= 0 && d6 <= 0) {
const w = d2 / (d2 - d6);
return [a[0] + ac[0] * w, a[1] + ac[1] * w, a[2] + ac[2] * w];
}
const va = d3 * d6 - d5 * d4;
if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
const w = (d4 - d3) / (d4 - d3 + (d5 - d6));
return [
b[0] + (c[0] - b[0]) * w,
b[1] + (c[1] - b[1]) * w,
b[2] + (c[2] - b[2]) * w,
];
}
const den = 1 / (va + vb + vc);
const v = vb * den;
const w = vc * den;
return [
a[0] + ab[0] * v + ac[0] * w,
a[1] + ab[1] * v + ac[1] * w,
a[2] + ab[2] * v + ac[2] * w,
];
}
/** How far a point lies from the nearest triangle of the mesh. */
export function distanceToSurface(p, verts, tris) {
let best = Infinity;
for (const [i, j, k] of tris) {
const d = dist3(p, closestOnTriangle(p, verts[i], verts[j], verts[k]));
if (d < best) best = d;
}
return best;
}
/** The segments where the mesh's triangles cross the z = 0 (centreline) plane. */
export function centrelineSegments(verts, tris) {
const segments = [];
for (const [i, j, k] of tris) {
const t = [verts[i], verts[j], verts[k]];
const points = [];
for (let e = 0; e < 3; e++) {
const a = t[e];
const b = t[(e + 1) % 3];
if (a[2] === 0) points.push(a);
if ((a[2] < 0 && b[2] > 0) || (a[2] > 0 && b[2] < 0)) {
const s = a[2] / (a[2] - b[2]);
points.push([a[0] + (b[0] - a[0]) * s, a[1] + (b[1] - a[1]) * s, 0]);
}
}
if (points.length >= 2) segments.push([points[0], points[1]]);
}
return segments;
}
/** Closest point of the centreline segments to `target`, or null. */
export function closestCentrelinePoint(target, segments) {
let best = null;
let bestD = Infinity;
for (const [a, b] of segments) {
const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const den = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];
let q = a;
if (den > 0) {
let s =
((target[0] - a[0]) * ab[0] +
(target[1] - a[1]) * ab[1] +
(target[2] - a[2]) * ab[2]) /
den;
s = Math.max(0, Math.min(1, s));
q = [a[0] + ab[0] * s, a[1] + ab[1] * s, a[2] + ab[2] * s];
}
const d = dist3(target, q);
if (d < bestD) {
bestD = d;
best = q;
}
}
return best;
}
/**
* The trail attachment point a model's construction gives: the point of its
* centreline profile nearest its aft-belly bounding-box corner, in scene
* space (raw glTF axes, metres). Null when the centreline crosses no triangle.
* @param {{verts: number[][], tris: number[][]}} mesh
* @returns {number[]|null}
*/
export function measuredTrailAnchor({ verts, tris }) {
const { min, max } = vertexBounds(verts);
return closestCentrelinePoint(
[max[0], min[1], 0],
centrelineSegments(verts, tris),
);
}
/** The repository's `public/` directory, where the fleet set is served from. */
const PUBLIC_DIR = new URL('../../public/', import.meta.url);
/**
* A `fetch` that serves the repository's `public/` files from disk, for
* loading the fleet model set in Node.
* @param {string} url Site path, e.g. `/models/fleet/catalog.json`.
* @returns {Promise<{ok: boolean, status: number, json: () => Promise<object>,
* arrayBuffer: () => Promise<ArrayBuffer>}>}
*/
export async function fetchPublicFile(url) {
const file = new URL(String(url).replace(/^\//, ''), PUBLIC_DIR);
let body;
try {
body = fs.readFileSync(file);
} catch {
return { ok: false, status: 404 };
}
return {
ok: true,
status: 200,
json: async () => JSON.parse(body.toString('utf8')),
arrayBuffer: async () =>
body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
};
}
+503
View File
@@ -0,0 +1,503 @@
// A Rail layer on a scene host bound to fake renderer ports (draw, camera,
// frame, globe, query, input), a scripted proxy and fake camera services
// that record what the layer asks of the camera. Shared by the Rail layer's
// tests that run a whole layer (camera follow, live-only feeds, ground
// height, layer stats, selected route lines).
import { createRailLayer } from '../layers/rail/index.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from './fakeDrawPort.mjs';
import { CAMERA_DEBOUNCE_MS } from '../layers/rail/policy.js';
import { WORLD_FOCUS_FRAMING } from '../worldFocus.js';
import { publicRailCatalog } from '../data/railFeeds.js';
/** The tests' wall clock at the start: 2026-09-10T00:26:40Z. */
export const RAIL_HARNESS_T0 = 1_789_000_000_000;
export const BOSTON = Object.freeze({ lat: 42.3601, lon: -71.0589 });
/** A train as the rail proxy sends it. */
export function railTrain(id, lat, lon, extra = {}) {
return {
id,
lat,
lon,
bearing: null,
speedMps: null,
timestamp: Math.floor(Date.now() / 1000),
timestampSource: 'vehicle',
routeId: 'R1',
tripId: `trip-${id}`,
label: id,
category: 'regional',
mode: 'rail',
positionSource: 'gps',
...extra,
};
}
/** A canvas good enough for the sprite drawing: every 2D call is a no-op. */
function fakeCanvas() {
const context = new Proxy(
{},
{
get: (target, key) => (key in target ? target[key] : () => {}),
set: (target, key, value) => {
target[key] = value;
return true;
},
},
);
return { width: 0, height: 0, getContext: () => context };
}
const headersOf = (values = {}) => ({
get: (name) => values[String(name).toLowerCase()] ?? null,
});
/**
* The harness. `feeds` scripts each feed's live answer, one call per poll:
* an array of trains (200), `{positions: 'schedule'}` (a 200 answer with
* no live positions, which the layer must not draw), `{status, backoff?, retryInSec?}` (a failure as the proxy
* answers it), or nothing (502). `schedules` holds the schedule packs the
* proxy serves for stop labels (404 otherwise).
* `requested`, `requestedSchedules` and `requestedPaths` list the feed ids
* asked for, in order.
* @param {import('node:test').TestContext} t
* @param {{at?: {lat: number, lon: number}, altitude?: number,
* catalog?: object[]|Promise<object[]>|Function|false,
* ground?: object,
* stops?: object|null, scheduleStops?: boolean,
* paths?: Record<string, object>|null}} [options]
* `ground`: a floor service in place of the always-cold stub; `catalog`:
* the server's feed catalog (it may list fewer feeds than are bundled; a
* promise answers when it settles, a function is called per request and
* answers so); without it, a server with every pack built (all enabled
* feeds); `false` for a source with no catalog at all;
* `stops`: a stops provider (none by default); `scheduleStops`: the
* layer's own provider, its schedule tier, in its place;
* `paths`: feed id → the path pack the proxy serves, or a
* failure status it answers with (404 for any other feed; without it the
* source has no path route at all).
*/
export function railLayerHarness(
t,
{
at = BOSTON,
altitude = 20_000,
catalog = undefined,
ground = null,
stops = null,
scheduleStops = false,
paths = null,
} = {},
) {
const T0 = RAIL_HARNESS_T0;
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: T0,
});
t.mock.method(performance, 'now', () => Date.now() - T0);
for (const name of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
]) {
const prior = globalThis[name];
globalThis[name] = class {};
t.after(() => {
if (prior === undefined) delete globalThis[name];
else globalThis[name] = prior;
});
}
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
globalThis.document = Object.assign(new EventTarget(), {
visibilityState: 'visible',
documentElement: { dataset: {} },
createElement: () => fakeCanvas(),
});
globalThis.window = new EventTarget();
// The layer logs its feeds and catalog.
t.mock.method(console, 'info', () => {});
t.mock.method(console, 'log', () => {});
// `position` (ECEF), when set, is where the eye stands in place of the
// point `altitude` metres over `lat`, `lon`.
const view = { lat: at.lat, lon: at.lon, altitude, heading: 0 };
const listeners = (names) =>
Object.fromEntries(names.map((name) => [name, new Set()]));
const cameraEvents = listeners(['changed', 'followChanged']);
const frameEvents = listeners(['preUpdate', 'preRender', 'postRender']);
const raise = (set, arg) => {
for (const cb of [...set]) cb(arg);
};
let followed = null;
/** Every target the camera was told to follow, in order. */
const follows = [];
const camera = {
flightsCancelled: 0,
pose: () => ({
lon: view.lon,
lat: view.lat,
height: view.altitude,
heading: view.heading,
pitch: -Math.PI / 2,
roll: 0,
position: view.position
? { ...view.position }
: fromDegrees(view.lon, view.lat, view.altitude),
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
near: 1,
far: 5e8,
frameIsIdentity: true,
}),
viewRectangle: () => ({
west: view.lon - 0.1,
south: view.lat - 0.1,
east: view.lon + 0.1,
north: view.lat + 0.1,
}),
on(event, cb) {
const set = cameraEvents[event];
if (!set) return () => {};
set.add(cb);
return () => set.delete(cb);
},
get followed() {
return followed;
},
// The port raises `followChanged` whenever `followed` changes, and only
// then, as the renderer's does.
follow(target) {
if (target === followed) return;
followed = target;
if (target) follows.push(target);
raise(cameraEvents.followChanged);
},
cancelFlight() {
this.flightsCancelled += 1;
},
flying: false,
};
/** The tiles drawn in place of the globe, once a test puts some there. */
const surface = { globeShown: false, tiles: null, mesh: null };
const globe = {
isGlobeVisible: () => surface.globeShown,
surfaceVersion: () => 0,
isSettled: (kind) =>
kind === 'surface' || kind === 'tiles'
? surface.tiles?.tilesLoaded === true
: true,
};
/** What the next pick names (`click`), else nothing. */
let pickAnswer = null;
const query = {
pick: () => pickAnswer,
drillPick: () => [],
pickPosition: () => null,
pickEllipsoid: () => null,
project: () => null,
isOccluded: () => false,
// The tiles' mesh, as a test sets it; terrain is never loaded here.
sampleHeightNow(point, options = {}) {
if (options.against === 'terrain' || !surface.mesh) return null;
surface.mesh.probes.push({ lat: point.lat, lon: point.lon, options });
return surface.mesh.height;
},
};
const frame = {
on(phase, cb) {
const set = frameEvents[phase];
if (!set) return () => {};
set.add(cb);
return () => set.delete(cb);
},
requestRender() {},
time: () => Date.now(),
};
// Pointer input as the renderer reports it: a test clicks through `click`.
const inputEvents = listeners(['down', 'move', 'up', 'click', 'dblclick']);
const stock = () => ({ enabled: true, suppress: () => () => {} });
const input = {
on(type, cb) {
const set = inputEvents[type];
if (!set) return () => {};
set.add(cb);
return () => set.delete(cb);
},
isPointerFree: () => true,
suspendCameraControls: () => () => {},
behaviours: { select: stock(), dblclickFollow: stock() },
};
const viewer = {
isDestroyed: () => false,
canvas: {
clientWidth: 1000,
clientHeight: 1000,
width: 1000,
height: 1000,
addEventListener() {},
removeEventListener() {},
},
};
const draw = fakeDrawPort();
const unbind = bindRenderer(viewer, {
get canvas() {
return viewer.canvas;
},
draw,
camera,
frame,
globe,
query,
input,
});
const feeds = new Map();
const schedules = new Map();
const requested = [];
const requestedSchedules = [];
const requestedPaths = [];
/** When each catalog request was made. */
const catalogRequests = [];
/**
* A pack as the proxy serves it: 200 with its body, a number as that
* failure status, else 404.
*/
const packAnswer = (raw) =>
raw && typeof raw === 'object'
? { ok: true, status: 200, headers: headersOf(), json: async () => raw }
: {
ok: false,
status: typeof raw === 'number' ? raw : 404,
headers: headersOf(),
json: async () => ({}),
};
const source = {
async requestSnapshot(feedId) {
requested.push(feedId);
const answer = feeds.get(feedId)?.() ?? null;
if (Array.isArray(answer))
return {
ok: true,
status: 200,
headers: headersOf(),
json: async () => ({ fetchedAt: Date.now(), trains: answer }),
};
if (answer?.positions === 'schedule')
return {
ok: true,
status: 200,
headers: headersOf({ 'x-gev-cache': 'SCHEDULE' }),
json: async () => ({
fetchedAt: Date.now(),
positions: 'schedule',
trains: [],
}),
};
const status = answer?.status ?? 502;
return {
ok: false,
status,
headers: headersOf(
answer?.backoff ? { 'x-rail-backoff': answer.backoff } : {},
),
json: async () => ({
error: 'Rail feed unavailable',
...(Number.isFinite(answer?.retryInSec)
? { retryInSec: answer.retryInSec }
: {}),
}),
};
},
async requestSchedule(feedId) {
requestedSchedules.push(feedId);
return packAnswer(schedules.get(feedId));
},
...(paths
? {
async requestPaths(feedId) {
requestedPaths.push(feedId);
return packAnswer(paths[feedId]);
},
}
: {}),
...(catalog === false
? {}
: {
async getFeeds() {
catalogRequests.push(Date.now());
if (catalog === undefined) return publicRailCatalog();
return typeof catalog === 'function' ? catalog() : catalog;
},
}),
};
const focusRequests = [];
/** Overlay source id → the entries last published to it. */
const overlayEntries = new Map();
let cockpit = false;
const layer = createRailLayer({
source,
// Left out, the layer reads stops from its own schedule tier.
...(scheduleStops ? {} : { stops }),
services: {
render: {
governorRequestRender() {},
holdContinuousRender() {},
releaseContinuousRender() {},
},
sprites: { spriteDrawOrder: () => -5 },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
overlays: {
setOverlayEntries(sourceId, entries) {
overlayEntries.set(sourceId, entries);
},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
credits: {
registerDynamicCredit() {},
railFeedCredit: (feed) => ({ key: `rail-${feed.id}`, html: feed.id }),
},
ground: ground ?? {
GROUND_FLOOR_LIFT_M: 1.5,
cachedGroundFloor: () => null,
warmGroundFloor() {},
},
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus(detail) {
focusRequests.push(detail);
return true;
},
isCockpitActive: () => cockpit,
},
},
});
layer.init(viewer);
t.after(() => {
try {
layer.destroy(viewer);
} catch {
/* a test may already have destroyed it */
}
unbind();
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
});
const state = () => layer._railStateForTest();
const parts = () => layer._railPartsForTest();
/** Let pending promises (a poll's fetch, JSON and packs) settle. */
const settle = async () => {
for (let i = 0; i < 24; i += 1) await Promise.resolve();
};
return {
layer,
viewer,
state,
parts,
feeds,
schedules,
requested,
requestedSchedules,
requestedPaths,
catalogRequests,
draw,
camera,
follows,
overlayEntries,
focusRequests,
settle,
setCockpit(value) {
cockpit = value;
},
entry: (key) => state()._trains.get(key),
async enable() {
layer.enable(viewer);
await settle();
t.mock.timers.tick(0);
await settle();
},
async poll() {
await layer.update();
await settle();
// The duplicate filter runs off the poll's stack.
t.mock.timers.tick(0);
await settle();
},
/** Wall time with frames along the way, as in the app. */
run(ms, step = 250) {
const until = Date.now() + ms;
while (Date.now() < until) {
t.mock.timers.tick(Math.min(step, until - Date.now()));
raise(frameEvents.preUpdate, { frame: 0 });
raise(frameEvents.preRender, { frame: 0 });
}
},
/** Move the camera without the camera reporting the move. */
moveCameraQuietly(next) {
Object.assign(view, next);
},
/** Move the camera and let the debounced feed check run. */
async moveCamera(next) {
Object.assign(view, next);
raise(cameraEvents.changed);
t.mock.timers.tick(CAMERA_DEBOUNCE_MS);
await settle();
},
/** Let a deferred feed check (after a selection change) run. */
async recheck() {
t.mock.timers.tick(0);
await settle();
},
/** A left click at `position` whose pick names `hit` (null: the map). */
click(hit, position = { x: 10, y: 10 }) {
pickAnswer = hit;
const modifiers = { shift: false, ctrl: false, alt: false, meta: false };
raise(inputEvents.click, {
type: 'click',
position,
button: 0,
modifiers,
timestamp: Date.now(),
pointerType: 'mouse',
});
pickAnswer = null;
},
/** Where the followed target is now, or undefined. */
trackedPosition() {
return followed?.position(Date.now()) ?? undefined;
},
/**
* Draw the photorealistic tiles in place of the globe: whether they have
* loaded what is in view, and the mesh height every probe reads (each
* probe recorded). Returns both, for the test to change.
*/
photoreal({ loaded = true, height = 158 } = {}) {
surface.tiles = { tilesLoaded: loaded };
surface.mesh = { height, probes: [] };
return {
tileset: surface.tiles,
mesh: surface.mesh,
};
},
/** The live draw set of `kind` whose id ends with `suffix`. */
drawn(kind, suffix = '') {
return [...draw.sets.values()].find(
(set) =>
!set.disposed && set.kind === kind && set.spec.id.endsWith(suffix),
);
},
};
}