Merge branch 'main' into flights/ground-models-at-once

This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-11-15 17:53:45 -08:00
commit 8dc2371ed8
16 files changed
+1057 -145

No files matched your search

+8
View File
@@ -13,6 +13,8 @@ import { initLogoGaze } from '../logoGaze.js';
import {
uninstallRenderGovernor,
governorRequestRender,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { describeError } from './errors.js';
import { isEmbeddedInline } from './embed.js';
@@ -73,6 +75,12 @@ export async function createApplicationScene({
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'),
}),
);
defer(installFreeLookHeightLimit(viewer));
+65
View File
@@ -0,0 +1,65 @@
import * as Cesium from 'cesium';
/**
* A projector from world positions to window coordinates for one pass over
* many positions under one camera, giving what
* `Cesium.SceneTransforms.worldToWindowCoordinates` gives: in a 3D scene with
* a perspective camera it runs the same arithmetic in the same order once the
* camera's matrices and the canvas size are read, so the results are the same
* numbers; otherwise it asks Cesium for each.
*
* Read the camera again (a new projector) whenever it may have moved.
* @param {Cesium.Scene} scene
* @returns {(position: Cesium.Cartesian3, result: Cesium.Cartesian2) =>
* Cesium.Cartesian2|undefined} The window position in `result`, or
* undefined behind the camera.
*/
export function createWindowProjector(scene) {
const camera = scene?.camera;
const frustum = camera?.frustum;
if (
scene?.frameState?.mode !== Cesium.SceneMode.SCENE3D ||
!camera ||
frustum instanceof Cesium.OrthographicFrustum ||
frustum instanceof Cesium.OrthographicOffCenterFrustum
)
return (position, result) =>
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result);
const v = camera.viewMatrix;
const p = frustum.projectionMatrix;
const width = scene.canvas.clientWidth;
const height = scene.canvas.clientHeight;
const halfWidth = width * 0.5;
const halfHeight = height * 0.5;
return (position, result) => {
if (!position)
return Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
result,
);
const { x, y, z } = position;
// Eye coordinates, as Matrix4.multiplyByVector computes them (w = 1).
const ex = v[0] * x + v[4] * y + v[8] * z + v[12];
const ey = v[1] * x + v[5] * y + v[9] * z + v[13];
const ez = v[2] * x + v[6] * y + v[10] * z + v[14];
const ew = v[3] * x + v[7] * y + v[11] * z + v[15];
// At the eye itself Cesium's own steps have no direction to take.
if (ex === 0 && ey === 0 && ez === 0)
return Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
result,
);
// Clip coordinates.
const cx = p[0] * ex + p[4] * ey + p[8] * ez + p[12] * ew;
const cy = p[1] * ex + p[5] * ey + p[9] * ez + p[13] * ew;
const cz = p[2] * ex + p[6] * ey + p[10] * ez + p[14] * ew;
const cw = p[3] * ex + p[7] * ey + p[11] * ez + p[15] * ew;
if (cz < 0) return undefined;
// The viewport transform of the canvas, then window y downward.
result.x = halfWidth * (cx / cw) + halfWidth;
result.y = height - (halfHeight * (cy / cw) + halfHeight);
return result;
};
}
+122
View File
@@ -0,0 +1,122 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createWindowProjector } from './windowProjection.js';
function sceneLooking(
lon,
lat,
heightM,
pitchDeg,
mode = Cesium.SceneMode.SCENE3D,
) {
const scene = {
canvas: { clientWidth: 1713, clientHeight: 941 },
drawingBufferWidth: 1713,
drawingBufferHeight: 941,
mapProjection: new Cesium.GeographicProjection(),
ellipsoid: Cesium.Ellipsoid.WGS84,
frameState: { mode, mapProjection: new Cesium.GeographicProjection() },
globe: undefined,
tweens: { add() {} },
screenSpaceCameraController: { minimumZoomDistance: 1 },
};
scene.camera = new Cesium.Camera(scene);
scene.camera.frustum.aspectRatio = 1713 / 941;
scene.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
orientation: {
heading: 0.3,
pitch: Cesium.Math.toRadians(pitchDeg),
roll: 0,
},
});
return scene;
}
function positionsAround(lon, lat, spreadDeg, count) {
let seed = 7;
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
return Array.from({ length: count }, () =>
Cesium.Cartesian3.fromDegrees(
lon + (rnd() - 0.5) * spreadDeg,
lat + (rnd() - 0.5) * spreadDeg,
rnd() * 50,
),
);
}
test('a 3D perspective projector gives the same numbers Cesium gives', () => {
for (const [pitch, spread, heightM] of [
[-90, 1, 60_000],
[-35, 4, 60_000],
[-5, 40, 60_000],
// Just above the sea, points near and behind the near plane.
[-10, 0.002, 3],
]) {
const scene = sceneLooking(4.1, 51.95, heightM, pitch);
const project = createWindowProjector(scene);
let behind = 0;
for (const position of positionsAround(4.1, 51.95, spread, 2000)) {
const expected = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
new Cesium.Cartesian2(),
);
const actual = project(position, new Cesium.Cartesian2());
if (!expected) {
behind++;
assert.equal(actual, undefined);
continue;
}
assert.equal(actual.x, expected.x);
assert.equal(actual.y, expected.y);
}
if (pitch === -5)
assert.ok(behind > 0, 'some positions fall behind the camera');
}
});
test('outside a 3D scene the projector asks Cesium', () => {
const scene = sceneLooking(
4.1,
51.95,
60_000,
-90,
Cesium.SceneMode.COLUMBUS_VIEW,
);
const calls = [];
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
Cesium.SceneTransforms.worldToWindowCoordinates = (...args) => {
calls.push(args);
return args[2];
};
try {
const result = new Cesium.Cartesian2();
const position = Cesium.Cartesian3.fromDegrees(4.1, 51.95);
assert.equal(createWindowProjector(scene)(position, result), result);
assert.equal(calls.length, 1);
assert.equal(calls[0][1], position);
} finally {
Cesium.SceneTransforms.worldToWindowCoordinates = original;
}
});
test('at the eye itself, or with no position, the projector asks Cesium', () => {
const scene = sceneLooking(4.1, 51.95, 60_000, -90);
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
const asked = [];
Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => {
asked.push(position);
return undefined;
};
try {
const project = createWindowProjector(scene);
const eye = Cesium.Cartesian3.clone(scene.camera.positionWC);
assert.equal(project(eye, new Cesium.Cartesian2()), undefined);
assert.equal(project(undefined, new Cesium.Cartesian2()), undefined);
assert.deepEqual(asked, [eye, undefined]);
} finally {
Cesium.SceneTransforms.worldToWindowCoordinates = original;
}
});
+21 -22
View File
@@ -55,37 +55,36 @@ export function vesselPositionAt(record, tMs) {
const RAD = Math.PI / 180;
/** The point `fraction` of the way from one position to another. */
/** The point `fraction` of the way from one position to another. It runs
* for every drawn vessel as the clock plays, so it builds no arrays. */
function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
const p1 = unit(lat1, lon1);
const p2 = unit(lat2, lon2);
const dot = Math.min(
1,
Math.max(-1, p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]),
);
const phi1 = lat1 * RAD;
const lambda1 = lon1 * RAD;
const phi2 = lat2 * RAD;
const lambda2 = lon2 * RAD;
const cos1 = Math.cos(phi1);
const cos2 = Math.cos(phi2);
const x1 = cos1 * Math.cos(lambda1);
const y1 = cos1 * Math.sin(lambda1);
const z1 = Math.sin(phi1);
const x2 = cos2 * Math.cos(lambda2);
const y2 = cos2 * Math.sin(lambda2);
const z2 = Math.sin(phi2);
const dot = Math.min(1, Math.max(-1, x1 * x2 + y1 * y2 + z1 * z2));
const angle = Math.acos(dot);
if (angle < 1e-12) return { lat: lat2, lon: lon2 };
const a = Math.sin((1 - fraction) * angle) / Math.sin(angle);
const b = Math.sin(fraction * angle) / Math.sin(angle);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
const sinAngle = Math.sin(angle);
const a = Math.sin((1 - fraction) * angle) / sinAngle;
const b = Math.sin(fraction * angle) / sinAngle;
const x = a * x1 + b * x2;
const y = a * y1 + b * y2;
const z = a * z1 + b * z2;
return {
lat: Math.atan2(z, Math.hypot(x, y)) / RAD,
lon: Math.atan2(y, x) / RAD,
};
}
function unit(lat, lon) {
const phi = lat * RAD;
const lambda = lon * RAD;
return [
Math.cos(phi) * Math.cos(lambda),
Math.cos(phi) * Math.sin(lambda),
Math.sin(phi),
];
}
// Whether each fixes array moves, read once per array: records keep theirs
// until a snapshot brings new ones.
const moving = new WeakMap();
+4 -1
View File
@@ -58,6 +58,9 @@ function stampFix(record, receivedAtMs, feedLatestEpoch) {
record.fixFeedEpoch = feedLatestEpoch;
}
/** A fix's time, as the fixes are merged (one function for every vessel). */
const fixTime = (fix) => fix.atMs;
function positiveNumber(value) {
const number = finiteNumber(value);
return number !== null && number > 0 ? number : null;
@@ -164,7 +167,7 @@ export class VesselRecords {
? mergeTimelineRuns(
record.fixes ?? [],
next.fixes,
(fix) => fix.atMs,
fixTime,
(next.lastPositionEpoch ?? 0) * 1000,
)
: null;
+277 -6
View File
@@ -325,8 +325,7 @@ test('following the clock moves drawn vessels in place each world time, prepares
const before = visuals.map((visual) => ({ ...visual.position }));
const positions = visuals.map((visual) => visual.position);
// The first pass also moves hidden vessels, so the next stays within
// HIDDEN_FOLLOW_MS of it.
// The first pass moves hidden vessels too.
layer.testing._runClockPassForTest(10_000);
mono += 16;
layer.testing._runClockPassForTest(20_000);
@@ -337,10 +336,7 @@ test('following the clock moves drawn vessels in place each world time, prepares
assert.ok(missing.billboard.position, 'a missing visual is prepared');
assert.equal(timers.size, 1, 'moving vessels ask for a frame');
// The hidden vessel waits for HIDDEN_FOLLOW_MS.
mono += 16;
layer.testing._runClockPassForTest(30_000);
assert.deepEqual({ ...visuals[1].position }, hiddenAt);
// Hidden vessels move a share each pass, each within HIDDEN_FOLLOW_MS.
mono += 250;
layer.testing._runClockPassForTest(40_000);
assert.notDeepEqual({ ...visuals[1].position }, hiddenAt);
@@ -375,3 +371,278 @@ test('following the clock moves drawn vessels in place each world time, prepares
layer.testing._runClockPassForTest(80_000);
assert.equal(timers.size, 0);
});
test('following the clock, drawn vessels move again once the fastest would have moved half a pixel, a second has gone by or the camera changed height', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera } = setup();
// 20 km above, in a 1,000 px tall view about 57° tall: half a pixel is
// about 11 m. The vessel makes about 1.9 m a second of world time.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const at = () => ({ ...visual.position });
const pass = (atMs, wallMs = 16) => {
mono += wallMs;
layer.testing._runClockPassForTest(atMs);
};
// Two passes a world second apart measure how fast it moves on screen.
pass(10_000);
pass(11_000);
let drawn = at();
// A few metres more stay under half a pixel: it is left where it is.
pass(12_000);
pass(14_000);
assert.deepEqual(at(), drawn);
// About 13 m on from where it was drawn: it moves.
pass(18_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
// Under half a pixel, but a second later: it moves.
pass(19_000, 1_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
pass(20_000);
assert.deepEqual(at(), drawn);
// Under half a pixel, but the camera came down by half: it moves.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 10_000);
pass(21_000);
assert.notDeepEqual(at(), drawn);
// Scrubbed well back, it moves back at once.
drawn = at();
pass(1_000);
assert.notDeepEqual(at(), drawn);
});
test('a vessel is drawn lifted above the sea surface, its waterline on it, as Cesium places them', () => {
const { layer, camera } = setup();
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {} },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const heightOf = (position) =>
Cesium.Ellipsoid.WGS84.cartesianToCartographic(position).height;
const close = (actual, expected) =>
assert.ok(
Cesium.Cartesian3.distance(actual, expected) < 1e-6,
`${actual} is not ${expected}`,
);
close(visual.surfacePosition, Cesium.Cartesian3.fromDegrees(4.05, 51.93, 0));
close(
visual.position,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.position)),
);
close(
visual.waterline,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.waterline)),
);
assert.ok(heightOf(visual.position) > heightOf(visual.waterline));
});
test('following the clock, a pass moves hidden vessels in proportion to the wall time since the last, so all move within HIDDEN_FOLLOW_MS', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera } = setup();
const records = Array.from({ length: 100 }, (_, i) => ({
mmsi: String(i),
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: false, position: null },
}));
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records,
});
const visuals = records.map((record) =>
layer.testing._prepareVesselVisualForTest(record),
);
layer.testing._runClockPassForTest(10_000);
const moved = (atMs) => visuals.filter((v) => v.followedAtMs === atMs).length;
assert.equal(moved(10_000), 100, 'the first pass moves them all');
mono += 25;
layer.testing._runClockPassForTest(20_000);
assert.equal(moved(20_000), 10, 'a tenth of HIDDEN_FOLLOW_MS, a tenth');
for (let i = 0; i < 9; i += 1) {
mono += 25;
layer.testing._runClockPassForTest(20_000);
}
assert.equal(moved(20_000), 100, 'all within HIDDEN_FOLLOW_MS');
});
test('following the clock, the step gate measures each vessel from when it was drawn, and reopens for a pan, a zoom or a pause', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera } = setup();
const above = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.positionWC = above;
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const at = () => ({ ...visual.position });
const pass = (atMs) => {
mono += 16;
layer.testing._runClockPassForTest(atMs);
};
// About 0.08 px a world second: measured over a second.
pass(10_000);
pass(11_000);
pass(13_000);
// A snapshot draws it afresh just before the next pass: the pass after
// it measures the move over that short time, not since 11 s.
layer.testing._followClockForTest(17_900);
layer.testing._prepareVesselVisualForTest(record);
pass(18_000);
let drawn = at();
pass(19_000);
assert.deepEqual(at(), drawn, 'the speed it measured is still its own');
pass(24_500);
assert.notDeepEqual(at(), drawn, 'and it moves once half a pixel is up');
// Panned sideways by more than a tenth of the camera's height: it moves.
drawn = at();
pass(25_000);
assert.deepEqual(at(), drawn);
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.1, 51.93, 20_000);
pass(25_500);
assert.notDeepEqual(at(), drawn);
// Zoomed in by narrowing the view: it moves.
drawn = at();
pass(26_000);
assert.deepEqual(at(), drawn);
camera.frustum = { fovy: 0.5 };
pass(26_500);
assert.notDeepEqual(at(), drawn);
// Paused just after a pass that left it short: the next frame at the same
// time draws it where it is.
drawn = at();
pass(27_000);
assert.deepEqual(at(), drawn);
pass(27_000);
assert.notDeepEqual(at(), drawn);
const where = at();
pass(27_000);
assert.deepEqual(at(), where, 'then holds');
});
test('following the clock, a vessel the visibility pass shows before the clock passes moved it is drawn at the time', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { layer, camera } = setup();
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const vessel = (mmsi) => ({
mmsi,
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 52.93,
toLon: 4.05,
toMs: 3_600_000,
},
billboard: { show: false, position: null },
});
const records = Array.from({ length: 40 }, (_, i) => vessel(String(i)));
const last = records.at(-1);
layer.testing._setVesselStateForTest({
// No scene: the labels are not placed.
viewer: { camera, scene: null, canvas: { clientHeight: 1000 } },
records,
});
layer.testing._followClockForTest(0);
const visual = layer.testing._prepareVesselVisualForTest(last);
for (const record of records.slice(0, -1))
layer.testing._prepareVesselVisualForTest(record);
layer.testing._runClockPassForTest(10_000);
// Paused, a seek far on: the next frame moves only a share of the hidden
// vessels, not the last.
mono += 16;
layer.testing._runClockPassForTest(11_000);
mono += 16;
layer.testing._runClockPassForTest(1_800_000);
assert.notEqual(visual.followedAtMs, 1_800_000);
layer.testing._runVisibilityPassForTest(true);
assert.equal(last.billboard.show, true);
const { latitude } = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
visual.surfacePosition,
);
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
});
+329 -97
View File
@@ -31,6 +31,12 @@ import {
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
import { createWindowProjector } from '../../data/windowProjection.js';
// Label grid cells are keyed by column * LABEL_CELL_ROW + row, unique while
// rows stay within half of it either side; a cell further off screen is keyed
// by its text.
const LABEL_CELL_ROW = 1 << 20;
/** A moving vessel's next frame is asked for once it would move this far on
* screen (pixels), so it glides when it moves visibly and the scene idles
@@ -38,13 +44,26 @@ import { isAidToNavigation } from '../../data/vesselTypes.js';
const VESSEL_STEP_PX = 0.5;
/** A frame is asked for at least this often while any drawn vessel moves. */
const PLACEMENT_FRAME_MS = 1000;
/** How often vessels not drawn move on as the world clock plays (wall ms),
* so one that comes into view is judged where it is. */
/** How often each vessel not drawn moves on as the world clock plays (wall
* ms), so one that comes into view is judged where it is. */
const HIDDEN_FOLLOW_MS = 250;
/** How often the vessels near enough for a model are gathered again (wall ms). */
const MODEL_CANDIDATES_MS = 500;
/** How far the camera may move or change height, as a share of its height,
* before vessels following the world clock move again however little they
* moved. */
const CAMERA_STEP = 0.1;
/** The least height that share is taken of (metres), so a camera just above
* the sea, or below the ellipsoid, still lets vessels rest between steps. */
const CAMERA_STEP_FLOOR_M = 100;
const DEG_TO_RAD = Math.PI / 180;
/** Scratch for the camera's position. */
const _cameraCartographic = new Cesium.Cartographic();
/** Scratch for where a moved vessel was drawn. */
const _movedFrom = new Cesium.Cartesian3();
@@ -57,6 +76,7 @@ export function createRendering({
}) {
const { state } = vesselState;
let visualRecords = new WeakMap();
const labelScreenScratch = new Cesium.Cartesian2();
// The fallback preserves helper calls with externally supplied render records.
function getVisual(record) {
@@ -75,60 +95,54 @@ export function createRendering({
? vesselPositionAt(record, vesselState.worldNow())
: (services.placement?.place(record.id, vesselState._aisRuntime.now()) ??
record);
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
visual.position = Cesium.Cartesian3.fromDegrees(lon, lat, heightM);
// A ship model's origin is its waterline: the sea surface, unlifted.
visual.waterline = Cesium.Cartesian3.fromDegrees(
lon,
lat,
heightM - VESSEL_LIFT_M,
);
visual.surfacePosition = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
visual.normal = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
visual.position,
new Cesium.Cartesian3(),
);
visual.drawnLat = lat;
visual.drawnLon = lon;
visual.position = new Cesium.Cartesian3();
visual.waterline = new Cesium.Cartesian3();
visual.surfacePosition = new Cesium.Cartesian3();
writeVesselPositions(visual, lat, lon);
// The world time it is drawn at, while it follows the clock.
visual.drawnAtMs = followsClock(vesselState)
? vesselState.worldNow()
: Number.NaN;
return visual;
}
/**
* Move a prepared vessel visual to `lat`/`lon`, writing into its own
* positions rather than allocating new ones: the placement pass runs for
* every drawn vessel several times a second.
* Write where a vessel visual is drawn at `lat`/`lon` into its own
* positions: lifted VESSEL_LIFT_M above the sea surface, its waterline on
* it, and the surface point under it. The placement pass runs for every
* drawn vessel as it moves, so the surface point and its normal are worked
* out once (as Cesium.Cartesian3.fromDegrees does) and the other two are
* along the normal from it.
*/
function moveRecordVisual(visual, lat, lon) {
function writeVesselPositions(visual, lat, lon) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
const ellipsoid = Cesium.Ellipsoid.WGS84;
Cesium.Cartesian3.fromDegrees(
lon,
lat,
heightM,
ellipsoid,
visual.position,
);
Cesium.Cartesian3.fromDegrees(
lon,
lat,
heightM - VESSEL_LIFT_M,
ellipsoid,
visual.waterline,
);
Cesium.Cartesian3.fromDegrees(
lon,
lat,
0,
ellipsoid,
visual.surfacePosition,
);
ellipsoid.geodeticSurfaceNormal(visual.position, visual.normal);
const phi = lat * DEG_TO_RAD;
const lambda = lon * DEG_TO_RAD;
const cosPhi = Math.cos(phi);
const nx = cosPhi * Math.cos(lambda);
const ny = cosPhi * Math.sin(lambda);
const nz = Math.sin(phi);
const radiiSquared = Cesium.Ellipsoid.WGS84.radiiSquared;
const kx = radiiSquared.x * nx;
const ky = radiiSquared.y * ny;
const kz = radiiSquared.z * nz;
const gamma = Math.sqrt(nx * kx + ny * ky + nz * kz);
const surface = visual.surfacePosition;
surface.x = kx / gamma;
surface.y = ky / gamma;
surface.z = kz / gamma;
const position = visual.position;
position.x = surface.x + nx * heightM;
position.y = surface.y + ny * heightM;
position.z = surface.z + nz * heightM;
const waterlineM = heightM - VESSEL_LIFT_M;
const waterline = visual.waterline;
waterline.x = surface.x + nx * waterlineM;
waterline.y = surface.y + ny * waterlineM;
waterline.z = surface.z + nz * waterlineM;
visual.drawnLat = lat;
visual.drawnLon = lon;
}
@@ -433,12 +447,14 @@ export function createRendering({
// The layer does not hold the continuous render loop. Its passes run in
// preRender, which idle mode fires only for rendered frames: moving vessels
// ask for the frame that next moves them visibly (askMotionFrame), a forced
// pass (new data, selection) requests its frame, a frame that moved the
// camera but fell inside the 800 ms cadence leaves a trailing frame so the view the camera stopped on is always
// evaluated, and the continuous hold is kept only while focus emphasis is
// animating. The trailing frame is keyed to camera motion alone: the pass's
// own label publication requests a frame, and scheduling on that would loop.
// ask for the frame that next moves them visibly (askMotionFrame; while the
// world clock plays, the scene draws every frame anyway), a forced pass
// (new data, selection) requests its frame, a frame that moved the camera
// but fell inside the 800 ms cadence leaves a trailing frame so the view
// the camera stopped on is always evaluated, and the continuous hold is
// kept only while focus emphasis is animating. The trailing frame is keyed
// to camera motion alone: the pass's own label publication requests a
// frame, and scheduling on that would loop.
function installRuntime(viewer) {
if (state.preRenderRemover || !viewer) return;
state.preRenderRemover = viewer.scene.preRender.addEventListener(() => {
@@ -451,34 +467,183 @@ export function createRendering({
});
}
// As the world clock plays, vessels between two fixes move on along them:
// drawn ones every frame, each once per world time, hidden ones (which may
// come into view) every HIDDEN_FOLLOW_MS.
let hiddenFollowedAtWallMs = -Infinity;
// As the world clock plays, vessels between two fixes move on along them.
// Drawn ones move each world time once the fastest would have moved
// VESSEL_STEP_PX on screen, at least once a second, and at once when the
// camera moves or zooms (underClockStep). Hidden ones (which may come into
// view) move a share of them each pass, so each moves at least every
// HIDDEN_FOLLOW_MS without one frame moving them all. The scene renders as
// fast as the display while the clock plays, and moving thousands of
// vessels a fraction of a pixel each frame would take most of every frame.
let hiddenFollowedAtWallMs = null;
let hiddenCursor = 0;
let clockPassAtMs = null;
// Whether the last pass left drawn vessels short of its world time.
let drawnBehind = false;
function followClockPositions() {
const atMs = vesselState.worldNow();
const motion = startMotionPass();
const moveHidden =
motion.wallMs - hiddenFollowedAtWallMs >= HIDDEN_FOLLOW_MS;
if (moveHidden) hiddenFollowedAtWallMs = motion.wallMs;
for (const record of state.records.all) {
if (!record.motion && !fixesMove(record.fixes)) continue;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
} else {
const drawn = visual.billboard?.show || visual.modelOwnsVisual;
if (visual.followedAtMs === atMs || (!drawn && !moveHidden)) continue;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(visual, lat, lon, motion);
}
if (visual.billboard) visual.billboard.position = visual.position;
const wallMs = performance.now();
const all = state.records.all;
// Each vessel moves once per world time; drawn ones a pass left short
// move to it on the next, so a paused clock shows them where they are.
const sameTime = atMs === clockPassAtMs;
const moveDrawn = sameTime ? drawnBehind : !underClockStep(atMs, wallMs);
clockPassAtMs = atMs;
if (moveDrawn) drawnBehind = false;
else if (!sameTime) {
drawnBehind = true;
askFrameIn(PLACEMENT_FRAME_MS);
}
const motion = moveDrawn ? startMotionPass() : null;
if (moveDrawn)
for (const record of all) followRecord(record, atMs, true, motion);
// As much of the list as the wall time since the last pass is of
// HIDDEN_FOLLOW_MS, going round it.
const sinceMs =
hiddenFollowedAtWallMs === null
? HIDDEN_FOLLOW_MS
: wallMs - hiddenFollowedAtWallMs;
const share = Math.min(
all.length,
Math.ceil((all.length * Math.max(0, sinceMs)) / HIDDEN_FOLLOW_MS),
);
if (share > 0) hiddenFollowedAtWallMs = wallMs;
for (let k = 0; k < share; k += 1) {
if (hiddenCursor >= all.length) hiddenCursor = 0;
followRecord(all[hiddenCursor], atMs, false, motionPass);
hiddenCursor += 1;
}
if (!moveDrawn) return;
askMotionFrame(motion);
noteClockStep(atMs, motion);
}
/**
* Draw a vessel where it is at world time `atMs` if the clock passes have
* not yet; true when it moved.
*/
function catchUpVisual(record, atMs) {
const visual = visualRecords.get(record);
if (!visual?.position || visual.followedAtMs === atMs) return false;
if (!record.motion && !fixesMove(record.fixes)) return false;
visual.followedAtMs = atMs;
visual.drawnAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
if (lat === visual.drawnLat && lon === visual.drawnLon) return false;
writeVesselPositions(visual, lat, lon);
if (visual.billboard) visual.billboard.position = visual.position;
return true;
}
/**
* Move a vessel to where it is at world time `atMs`, if it is drawn
* (`drawn`) or hidden (not `drawn`) as asked; one with no visual yet is
* prepared either way. A hidden vessel's move notes nothing in `motion`.
*/
function followRecord(record, atMs, drawn, motion) {
if (!record.motion && !fixesMove(record.fixes)) return;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
} else {
const shown = Boolean(visual.billboard?.show || visual.modelOwnsVisual);
if (shown !== drawn || visual.followedAtMs === atMs) return;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
const elapsedMs = Math.abs(atMs - visual.drawnAtMs);
visual.drawnAtMs = atMs;
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) return;
moveDrawnVisual(visual, lat, lon, motion, elapsedMs);
}
if (visual.billboard) visual.billboard.position = visual.position;
}
// The clock pass that last moved drawn vessels: its world time and wall
// time, how fast the fastest drawn vessel moved on screen (pixels per world
// ms), and the camera then: where it was, its height and its view's size.
const clockStep = {
atMs: null,
wallMs: 0,
pxPerMs: Infinity,
heightM: 0,
eye: new Cesium.Cartesian3(),
fovy: Number.NaN,
width: Number.NaN,
};
/** Measure, after a pass that moved drawn vessels, how fast the fastest
* moved on screen: each over the world time since it was last drawn. */
function noteClockStep(atMs, motion) {
const camera = motion.camera;
if (!motion.moving || motion.unmeasured || !camera?.positionWC) {
clockStep.atMs = null;
return;
}
const pxPerMs = movedPixels({
camera,
angle: motion.angleRate,
metres: motion.metresRate,
});
clockStep.pxPerMs = pxPerMs > 0 ? pxPerMs : Infinity;
clockStep.atMs = atMs;
clockStep.wallMs = motion.wallMs;
clockStep.heightM = cameraHeightM();
Cesium.Cartesian3.clone(camera.positionWC, clockStep.eye);
clockStep.fovy = camera.frustum?.fovy;
clockStep.width = viewWidth(camera.frustum);
}
/** Forget how fast vessels moved, so the next clock pass moves the drawn
* ones however little they moved (they were drawn somewhere else). */
function forgetClockStep() {
clockStep.atMs = null;
clockPassAtMs = null;
}
const viewWidth = (frustum) =>
frustum ? frustum.right - frustum.left : Number.NaN;
const sameNumber = (a, b) => a === b || (Number.isNaN(a) && Number.isNaN(b));
/**
* Whether the fastest drawn vessel would have moved less than
* VESSEL_STEP_PX on screen since the clock pass that last moved them, at
* the speed it moved then: drawn vessels are left where they are. They
* move anyway once PLACEMENT_FRAME_MS has gone by, or once the camera has
* moved or changed height by more than CAMERA_STEP of its height, or its
* view has changed size (a pixel then covers another distance).
*/
function underClockStep(atMs, wallMs) {
if (clockStep.atMs === null || !(clockStep.pxPerMs < Infinity))
return false;
if (wallMs - clockStep.wallMs >= PLACEMENT_FRAME_MS) return false;
const camera = state.viewer?.camera;
if (!camera?.positionWC) return false;
const limitM =
CAMERA_STEP * Math.max(clockStep.heightM, CAMERA_STEP_FLOOR_M);
if (!(Math.abs(cameraHeightM() - clockStep.heightM) <= limitM))
return false;
if (
!(Cesium.Cartesian3.distance(camera.positionWC, clockStep.eye) <= limitM)
)
return false;
if (
!sameNumber(camera.frustum?.fovy, clockStep.fovy) ||
!sameNumber(viewWidth(camera.frustum), clockStep.width)
)
return false;
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
}
/** The camera's height above the ellipsoid (metres), NaN without one. */
function cameraHeightM() {
const eye = state.viewer?.camera?.positionWC;
if (!eye) return Number.NaN;
return (
Cesium.Ellipsoid.WGS84.cartesianToCartographic(eye, _cameraCartographic)
?.height ?? Number.NaN
);
}
// Live with a host-supplied placement, vessels move on between refreshes:
@@ -515,6 +680,9 @@ export function createRendering({
moving: false,
angle: 0,
metres: 0,
angleRate: 0,
metresRate: 0,
unmeasured: false,
};
function startMotionPass() {
const wallMs = performance.now();
@@ -525,22 +693,37 @@ export function createRendering({
motionPass.moving = false;
motionPass.angle = 0;
motionPass.metres = 0;
motionPass.angleRate = 0;
motionPass.metresRate = 0;
motionPass.unmeasured = false;
motionPassWallMs = wallMs;
return motionPass;
}
/** Move a drawn visual, noting how far it moved as seen from the camera. */
function moveDrawnVisual(visual, lat, lon, motion) {
/** Move a drawn visual, noting how far it moved as seen from the camera,
* and, given the world time since it was last drawn (`elapsedMs`), how
* fast. */
function moveDrawnVisual(visual, lat, lon, motion, elapsedMs) {
const from = Cesium.Cartesian3.clone(visual.position, _movedFrom);
moveRecordVisual(visual, lat, lon);
writeVesselPositions(visual, lat, lon);
if (!visual.billboard?.show && !visual.modelOwnsVisual) return;
motion.moving = true;
const metres = Cesium.Cartesian3.distance(from, visual.position);
motion.metres = Math.max(motion.metres, metres);
const timed = elapsedMs > 0;
if (elapsedMs !== undefined && !timed) motion.unmeasured = true;
if (timed)
motion.metresRate = Math.max(motion.metresRate, metres / elapsedMs);
const eye = motion.camera?.positionWC;
if (!eye) return;
const distance = Cesium.Cartesian3.distance(eye, from);
if (distance > 0) motion.angle = Math.max(motion.angle, metres / distance);
if (!(distance > 0)) return;
motion.angle = Math.max(motion.angle, metres / distance);
if (timed)
motion.angleRate = Math.max(
motion.angleRate,
metres / distance / elapsedMs,
);
}
/** How far the fastest drawn vessel moved on screen in a pass (pixels):
@@ -574,7 +757,12 @@ export function createRendering({
const movedPx = movedPixels(motion);
if (movedPx > 0 && motion.sinceMs > 0)
waitMs = Math.min(waitMs, (VESSEL_STEP_PX * motion.sinceMs) / movedPx);
// A frame already asked for no later than this one stands.
askFrameIn(waitMs);
}
/** Ask for a vessel frame `waitMs` from now; one already asked for no
* later stands. */
function askFrameIn(waitMs) {
const runtime = vesselState._aisRuntime;
const dueMs = runtime.now() + waitMs;
if (placementFrameTimer !== null) {
@@ -591,6 +779,9 @@ export function createRendering({
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
motionPassWallMs = null;
forgetClockStep();
drawnBehind = false;
hiddenFollowedAtWallMs = null;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
@@ -670,9 +861,21 @@ export function createRendering({
if (doRotations) vesselState._lastCamPoseSig = poseSig;
const occluder = makeOccluder();
const labelCandidates = [];
// The time the clock pass drew (a playing clock's time moves on within
// the frame), so only vessels it did not reach are moved.
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
for (const record of state.records.all) {
const visual = getVisual(record);
const visible = isVisible(visual.surfacePosition, occluder, record);
let visible = isVisible(visual.surfacePosition, occluder, record);
// One in view that the clock passes have not moved to the time yet
// (a seek while paused shows it before its turn) is moved there and
// judged again: no later pass would move it while the clock rests.
if (
visible &&
catchUpAtMs !== null &&
catchUpVisual(record, catchUpAtMs)
)
visible = isVisible(visual.surfacePosition, occluder, record);
if (visual.billboard) {
// The bridge camera sits on this sprite; showing it would fill the view.
// The same rule as billboardShown, its horizon test already made.
@@ -842,25 +1045,30 @@ export function createRendering({
return;
}
// Every vessel in view is projected, so the camera is read once and each
// is a few multiplications (see windowProjection.js) into one screen
// point; a cell gets a candidate only for the vessel that leads it.
const project = createWindowProjector(scene);
const cells = new Map();
for (const record of records) {
const visual = getVisual(record);
if (record === selected) continue;
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
visual.position,
);
const screen = project(getVisual(record).position, labelScreenScratch);
if (!screen) continue;
const key = `${Math.floor(screen.x / LABEL_GRID_PX)}:${Math.floor(screen.y / LABEL_GRID_PX)}`;
const candidate = {
record,
score: labelPriority(record, selected),
x: screen.x,
y: screen.y,
};
const column = Math.floor(screen.x / LABEL_GRID_PX);
const row = Math.floor(screen.y / LABEL_GRID_PX);
const key =
Math.abs(row) < LABEL_CELL_ROW / 2 && Math.abs(column) < LABEL_CELL_ROW
? column * LABEL_CELL_ROW + row
: `${column}:${row}`;
const score = labelPriority(record, selected);
const existing = cells.get(key);
if (!existing || candidate.score > existing.score) {
cells.set(key, candidate);
if (!existing) {
cells.set(key, { record, score, x: screen.x, y: screen.y });
} else if (score > existing.score) {
existing.record = record;
existing.score = score;
existing.x = screen.x;
existing.y = screen.y;
}
}
@@ -952,7 +1160,30 @@ export function createRendering({
return score;
}
// Whether a vessel's name is worth a card, kept per vessel until what it
// is judged from changes: the label pass asks for every vessel in view.
const usefulNames = new WeakMap();
function hasUsefulName(record) {
const known = usefulNames.get(record);
if (
known &&
known.name === record.name &&
known.mmsi === record.mmsi &&
known.id === record.id
)
return known.useful;
const useful = nameIsUseful(record);
usefulNames.set(record, {
name: record.name,
mmsi: record.mmsi,
id: record.id,
useful,
});
return useful;
}
function nameIsUseful(record) {
const text = String(record.name || '').trim();
return Boolean(
text &&
@@ -978,6 +1209,7 @@ export function createRendering({
}
return {
getVisual,
forgetClockStep,
prepareRecordVisual,
resetRecordVisuals,
renderRowLimit,
+2
View File
@@ -77,7 +77,9 @@ export function createTracking({
visual.drawnLat = NaN;
visual.drawnLon = NaN;
visual.followedAtMs = undefined;
visual.drawnAtMs = Number.NaN;
}
components.rendering.forgetClockStep();
}
/**
+35 -12
View File
@@ -82,43 +82,66 @@ export function mergeTimelineRuns(
centreMs,
limit = TIMELINE_FIXES_LIMIT,
) {
const first = newer.length ? timeOf(newer[0]) : Infinity;
const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity;
// Each entry's time is read once: a layer merges a run for every contact
// in a snapshot, each holding up to `limit` entries.
const olderTimes = new Array(older.length);
for (let k = 0; k < older.length; k++) olderTimes[k] = timeOf(older[k]);
const newerTimes = new Array(newer.length);
for (let k = 0; k < newer.length; k++) newerTimes[k] = timeOf(newer[k]);
const first = newer.length ? newerTimes[0] : Infinity;
const last = newer.length ? newerTimes[newer.length - 1] : -Infinity;
const newest = newer[newer.length - 1];
// The older entries before the newer run that the loop below would keep
// one by one, each far enough from the one before, are taken at once: a
// contact's kept entries mostly stand before each snapshot's run.
let lead = 0;
while (
lead < older.length &&
!(olderTimes[lead] >= first && olderTimes[lead] <= last) &&
(newer.length === 0 || olderTimes[lead] < first) &&
(lead === 0 ||
olderTimes[lead] - olderTimes[lead - 1] >= TIMELINE_FIX_SPACING_MS)
)
lead++;
// Both runs in order, the older entries within the newer run's time left
// out, thinned to the spacing.
const merged = [];
const take = (entry) => {
const merged = older.slice(0, lead);
const times = olderTimes.slice(0, lead);
const take = (entry, t) => {
const k = merged.length - 1;
if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= TIMELINE_FIX_SPACING_MS) {
if (k < 0 || t - times[k] >= TIMELINE_FIX_SPACING_MS) {
merged.push(entry);
times.push(t);
} else if (entry === newest) {
merged[k] = entry;
times[k] = t;
}
};
let i = 0;
let i = lead;
let j = 0;
while (i < older.length || j < newer.length) {
if (i < older.length) {
const t = timeOf(older[i]);
const t = olderTimes[i];
if (t >= first && t <= last) {
i++;
continue;
}
if (j >= newer.length || t < timeOf(newer[j])) {
take(older[i++]);
if (j >= newer.length || t < newerTimes[j]) {
take(older[i], t);
i++;
continue;
}
}
take(newer[j++]);
take(newer[j], newerTimes[j]);
j++;
}
if (merged.length <= limit) return merged;
// The window of `limit` entries nearest the centre.
let start = 0;
while (
start + limit < merged.length &&
Math.abs(timeOf(merged[start + limit]) - centreMs) <
Math.abs(timeOf(merged[start]) - centreMs)
Math.abs(times[start + limit] - centreMs) <
Math.abs(times[start] - centreMs)
)
start++;
return merged.slice(start, start + limit);
+93
View File
@@ -96,3 +96,96 @@ test('past the limit only the fixes nearest the centre are kept', () => {
[0, 1, 2, 3],
);
});
/** The merge as first written, a reference the faster one must match. */
function referenceMerge(older, newer, timeOf, centreMs, limit = 240) {
const SPACING = 20_000;
const first = newer.length ? timeOf(newer[0]) : Infinity;
const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity;
const newest = newer[newer.length - 1];
const merged = [];
const take = (entry) => {
const k = merged.length - 1;
if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= SPACING)
merged.push(entry);
else if (entry === newest) merged[k] = entry;
};
let i = 0;
let j = 0;
while (i < older.length || j < newer.length) {
if (i < older.length) {
const t = timeOf(older[i]);
if (t >= first && t <= last) {
i++;
continue;
}
if (j >= newer.length || t < timeOf(newer[j])) {
take(older[i++]);
continue;
}
}
take(newer[j++]);
}
if (merged.length <= limit) return merged;
let start = 0;
while (
start + limit < merged.length &&
Math.abs(timeOf(merged[start + limit]) - centreMs) <
Math.abs(timeOf(merged[start]) - centreMs)
)
start++;
return merged.slice(start, start + limit);
}
test('the merge keeps exactly what it always kept, for runs of every shape', () => {
let seed = 3;
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const run = (n, from, stepMs, sorted) => {
const out = Array.from({ length: n }, (_, k) => ({
atMs:
rnd() < 0.05
? Number.NaN
: from +
Math.round((sorted ? k : rnd() * n) * stepMs * (0.5 + rnd())),
}));
if (sorted) out.sort((a, b) => a.atMs - b.atMs);
return out;
};
for (let round = 0; round < 3000; round++) {
const sorted = round % 5 !== 0;
const older = run(
Math.floor(rnd() * 300),
Math.floor(rnd() * 4e6),
15_000 + rnd() * 50_000,
sorted,
);
const newer = run(
Math.floor(rnd() * 30),
Math.floor(rnd() * 6e6),
5_000 + rnd() * 70_000,
sorted,
);
// The newest of the newer run is sometimes an entry of the older one.
if (newer.length && older.length && rnd() < 0.1)
newer[newer.length - 1] = older[older.length - 1];
const centreMs = rnd() * 7e6;
const limit = rnd() < 0.5 ? 240 : 1 + Math.floor(rnd() * 40);
const expected = referenceMerge(
older,
newer,
(f) => f.atMs,
centreMs,
limit,
);
const actual = mergeTimelineRuns(
older,
newer,
(f) => f.atMs,
centreMs,
limit,
);
assert.equal(actual.length, expected.length, `round ${round}`);
for (let k = 0; k < expected.length; k++)
assert.equal(actual[k], expected[k], `round ${round} entry ${k}`);
}
});
+23 -4
View File
@@ -11,16 +11,29 @@ import * as Cesium from 'cesium';
* The clock's `currentTime` follows too, for anything that samples it.
* @param {Cesium.Viewer} viewer
* @param {() => number} readTime Epoch ms the sky is drawn at.
* @param {{subscribe?: Function, requestRender?: () => void}} [options]
* @param {{subscribe?: Function, requestRender?: () => void,
* onPlaying?: (playing: boolean) => void}} [options]
* A world clock to hear moves from, so a resting scene repaints when the
* world time jumps.
* world time jumps. `onPlaying` hears when the world clock starts and stops
* playing away from live (not stepped by a driver and not waiting for a
* layer's data), so the scene can draw every frame meanwhile.
* @returns {() => void} Stop following.
*/
export function followWorldTime(
viewer,
readTime,
{ subscribe, requestRender = () => viewer.scene.requestRender() } = {},
{
subscribe,
requestRender = () => viewer.scene.requestRender(),
onPlaying = () => {},
} = {},
) {
let playing = false;
const setPlaying = (next) => {
if (next === playing) return;
playing = next;
onPlaying(next);
};
const date = new Date();
const removePreUpdate = viewer.scene.preUpdate.addEventListener(
(_scene, time) => {
@@ -33,7 +46,12 @@ export function followWorldTime(
);
let last = readTime();
const unsubscribe =
subscribe?.(() => {
subscribe?.((state) => {
setPlaying(
Boolean(
state?.playing && !state.live && !state.stepping && !state.buffering,
),
);
const next = readTime();
if (next === last) return;
last = next;
@@ -42,5 +60,6 @@ export function followWorldTime(
return () => {
removePreUpdate();
unsubscribe();
setPlaying(false);
};
}
+59
View File
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { followWorldTime } from './viewerClock.js';
function fakeViewer() {
const listeners = new Set();
return {
clock: { currentTime: {} },
scene: {
requestRender() {},
preUpdate: {
addEventListener(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
},
},
},
};
}
test('the scene hears when the world time plays on its own, and when it stops', () => {
let listener = null;
const subscribe = (fn) => {
listener = fn;
return () => (listener = null);
};
const heard = [];
let at = 0;
const stop = followWorldTime(fakeViewer(), () => at, {
subscribe,
requestRender: () => {},
onPlaying: (playing) => heard.push(playing),
});
const state = (fields) => ({
live: false,
playing: false,
stepping: false,
buffering: false,
...fields,
});
listener(state({ live: true, playing: true }));
assert.deepEqual(heard, [], 'live time is not playback');
listener(state({ playing: true }));
listener(state({ playing: true }));
assert.deepEqual(heard, [true], 'heard once');
listener(state({ playing: true, buffering: true }));
assert.deepEqual(heard, [true, false], 'waiting for a layer: still');
listener(state({ playing: true }));
listener(state({ playing: true, stepping: true }));
assert.deepEqual(heard, [true, false, true, false], 'a driver steps it');
listener(state({ playing: true }));
stop();
assert.deepEqual(
heard,
[true, false, true, false, true, false],
'stopping releases',
);
assert.equal(listener, null);
});