Merge main into german/i18n-plurals-context

This commit is contained in:
German Khokhlov committed 2026-11-17 19:29:53 +04:00
commit 64b9cef14b
209 files changed
+35415 -701

No files matched your search

+6 -1
View File
@@ -222,9 +222,14 @@ export function createPanel({ state: layerState, parts }) {
ensurePanel();
layerState.panelRenders += 1;
const { subject, cohorts } = layerState.results;
const windowLabel = t('{distance} FLIGHT / VESSEL WINDOW', {
distance: presentAwarenessDistance(AWARENESS_RADIUS_M),
});
publish({
kind: 'results',
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
subject: `${subject.label} · ${windowLabel}`,
subjectIdentity: { layerId: subject.layerId, id: subject.id },
subjectLabel: subject.label,
subjectNames: presentNames(subject.memberNames),
photo: presentPhoto(subject),
navigation: presentNavigation(),
+41
View File
@@ -246,6 +246,19 @@ export function createQueries({
* routeDestination: string|null}}
*/
/** An airport at one end of a route, when it has a position. */
function routeEnd(airport) {
const lat = Number(airport?.lat ?? airport?.latitude);
const lon = Number(airport?.lon ?? airport?.longitude);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
return {
code: String(airport?.code ?? '').trim() || null,
name: String(airport?.name ?? airport?.municipality ?? '').trim() || null,
lat,
lon,
};
}
function mapAnalystRecord(
icao24,
info,
@@ -275,6 +288,9 @@ export function createQueries({
// A converted contact reports the class it RENDERS as, so an analyst
// filter/superlative agrees with the triangle on screen.
aircraftClass: tr3bAircraftClass(icao24, text(info?.klass)),
// What picks its fleet model, for the context card's turning model.
typeCode: text(info?.typeCode),
category: info?.category ?? null,
originCountry: text(info?.originCountry),
operator: text(info?.airline),
squawk: text(info?.squawk),
@@ -293,6 +309,19 @@ export function createQueries({
lastContactAtMs: num(info?.lastContactEpochMs),
routeOrigin: routeOk ? text(info?.route?.origin?.code) : null,
routeDestination: routeOk ? text(info?.route?.destination?.code) : null,
// The airports themselves, for the context card's route globe.
routeFrom: routeOk ? routeEnd(info?.route?.origin) : null,
routeTo: routeOk ? routeEnd(info?.route?.destination) : null,
// The scheduled route when it does not fit where the plane is (often
// another leg of the same flight number): the card shows it marked
// unverified, everything else still treats the flight as routeless.
routeScheduled:
!routeOk && info?.route?.origin?.code && info?.route?.destination?.code
? {
from: text(info.route.origin.code),
to: text(info.route.destination.code),
}
: null,
};
}
const methods = {
@@ -748,6 +777,18 @@ export function createQueries({
return result;
},
/**
* Ask for an aircraft's scheduled route (origin and destination airports),
* as tracking does; it lands on the record when the lookup answers.
* @param {string} icao24
*/
requestRoute(icao24) {
if (icao24)
parts.enrichment._requestRouteEnrichment(
String(icao24).trim().toLowerCase(),
);
},
/**
* Start camera-tracking an aircraft by ICAO24 address.
* @param {string} icao24 - ICAO 24-bit transponder address.
+8 -2
View File
@@ -163,7 +163,7 @@ export function createLifecycle({
// has none), cut short and in capitals as the mission index shows names.
// Registered once; off, the layer has no time to show, and each step tells
// the clock once it has settled.
worldClock.register({
const clockSource = {
id: 'rocket-launches',
coverage: () => {
if (!layerState._enabled) return null;
@@ -184,11 +184,15 @@ export function createLifecycle({
if (!marks.length) return null;
return { start: marks[0].time, end: marks.at(-1).time, marks };
},
});
};
// Unregistered on destroy, so a page that builds the app again holds no old layer; init
// registers it again.
let uncover = worldClock.register(clockSource);
const methods = {
init(viewer) {
layerState._viewer = viewer;
uncover ??= worldClock.register(clockSource);
layerState._enabled = false;
parts.panel.createMissionPanel();
parts.overlays.createReplayVehicleOverlay();
@@ -324,6 +328,8 @@ export function createLifecycle({
async destroy(viewer) {
hover?.destroy();
uncover?.();
uncover = null;
hover = null;
layerState._sourceController.abort();
releaseContinuousRender('rocket-launches'); // direct-destroy path (perf wave 2 fix)
+8 -2
View File
@@ -16,7 +16,7 @@ export function createLifecycle({
// While on with a catalog, satellites can be shown at any time in reach of
// their element sets. Registered once; off, the layer has no time to show,
// and each step tells the clock once it has settled.
worldClock.register({
const clockSource = {
id: 'satellites',
coverage: () => {
if (!layerState._enabled || !layerState._catalog.size) return null;
@@ -26,7 +26,10 @@ export function createLifecycle({
end: now + SATELLITE_COVERAGE_MS,
};
},
});
};
// Unregistered on destroy, so a page that builds the app again holds no old layer; init
// registers it again.
let uncover = worldClock.register(clockSource);
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { registerPickOwner, unregisterPickOwner } = services.picking;
@@ -39,6 +42,7 @@ export function createLifecycle({
// Catalog data refresh; propagation remains preRender-owned.
async init(viewer) {
uncover ??= worldClock.register(clockSource);
// Asked first: a viewer without one fails before anything is built.
const frame = frameOf(viewer);
parts.catalog._abortActiveUpdates();
@@ -154,6 +158,8 @@ export function createLifecycle({
destroy(viewer) {
parts.catalog._abortActiveUpdates();
uncover?.();
uncover = null;
releaseContinuousRender('satellites'); // direct-destroy path (perf wave 2 fix)
layerState._enabled = false;
parts.tracking._clearTracking();
+26
View File
@@ -5,6 +5,7 @@ import http from 'node:http';
import { EventEmitter, once } from 'node:events';
import test from 'node:test';
import * as Cesium from 'cesium';
import { worldClock } from '../../time/worldClock.js';
import { createSatelliteSource } from './source.js';
import { createState } from './state.js';
import { createControls } from './controls.js';
@@ -309,3 +310,28 @@ test('destroy aborts an in-flight response and initialization starts with new ow
assert.equal(f.stats().count, CORE.length);
assert.equal(f.feed(), 'nominal');
});
test('destroy takes the layer off the world clock, and init puts it back', async (t) => {
// Each registration the layer makes, while it stands.
const register = worldClock.register;
const standing = new Set();
worldClock.register = (source) => {
standing.add(source);
const off = register.call(worldClock, source);
return () => {
standing.delete(source);
off();
};
};
t.after(() => {
worldClock.register = register;
});
const f = await fixture(t);
const mine = () =>
[...standing].filter(({ id }) => id === 'satellites').length;
assert.equal(mine(), 1);
f.parts.lifecycle.methods.destroy(f.viewer);
assert.equal(mine(), 0);
await f.parts.lifecycle.methods.init(f.viewer);
assert.equal(mine(), 1);
});
+27 -1
View File
@@ -5,12 +5,23 @@ import {
transitDetectionClass,
transitDetectionId,
transitDetectionMetric,
vehicleReportTimeMs,
} from './policy.js';
import {
TRANSIT_ENABLED_FEEDS,
getRegisteredTransitFeed,
transitRouteLabel,
} from '../../data/transitFeeds.js';
import { transitModeTier } from '../../data/transitPresetStyle.js';
import { displayMotion } from './movement.js';
/** The display's motion word as a record field for the Context card. */
const MOTION_FIELD = Object.freeze({
'EN ROUTE': 'moving',
STOPPED: 'stopped',
WAITING: 'waiting',
'NO FIX': 'no-fix',
});
/** Regions, not feeds: one region can carry several feeds (Rio has two). */
const TRANSIT_REGION_COUNT = new Set(
@@ -211,10 +222,14 @@ export function createQueries({ state, parts }) {
* query engine. On demand only (once per spoken query); [] while the
* layer is off.
* @param {number} [maxCount=Infinity] Most records to return.
* @returns {Array<Object>} {id, label, routeId, mode, lat, lon, speedMps, courseDeg, status, occupancy}.
* @returns {Array<Object>} {id, label, routeId, mode, lat, lon, speedMps, courseDeg, status, occupancy},
* plus `key` (the layer's own vehicle key, which a map click carries),
* `route`, `operator`, `place`, `observedMs` and `motion` (what the
* display shows: moving, stopped, waiting or no-fix) for the Context card.
*/
getAnalystRecords(maxCount = Infinity) {
if (!state._enabled) return [];
const now = Date.now();
const num = (v) => (Number.isFinite(v) ? v : null);
const result = [];
for (const entry of state._vehicles.values()) {
@@ -222,6 +237,8 @@ export function createQueries({ state, parts }) {
const record = entry.record || {};
if (!Number.isFinite(record.lat) || !Number.isFinite(record.lon))
continue;
const feed = feedForEntry(state, entry);
const reportedMs = vehicleReportTimeMs(record, entry.fetchedAt);
result.push({
id: record.label || record.id || entry.key,
label: record.label || null,
@@ -233,6 +250,15 @@ export function createQueries({ state, parts }) {
courseDeg: num(entry.courseDeg ?? record.bearing),
status: record.status || null,
occupancy: record.occupancy || null,
key: entry.key,
route:
record.routeId && feed
? transitRouteLabel(feed, record.routeId)
: record.routeId || null,
operator: feed?.name || null,
place: feed?.region || null,
observedMs: Number.isFinite(reportedMs) ? reportedMs : null,
motion: MOTION_FIELD[displayMotion(entry, now).word] || null,
});
}
return result;
+41
View File
@@ -175,3 +175,44 @@ test('a vessel snapshot at a time the source drops for a newer one is no failure
assert.equal(probe.feed.loading, false);
assert.deepEqual(probe.applied, []);
});
test('back at live, the live poll goes out at once even while a snapshot at a time was still loading', async () => {
const queries = [];
const probe = ingestion({
getSnapshot(query, { signal }) {
queries.push(query);
if (query.atMs === undefined)
return Promise.resolve({
records: [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }],
observedAtMs: 5,
freshness: 'current',
complete: true,
transportStatus: 'live',
});
// A snapshot at a time answers only when dropped.
return new Promise((_, reject) =>
signal.addEventListener('abort', () => {
const error = new Error('aborted');
error.name = 'AbortError';
reject(error);
}),
);
},
});
probe.state.follows = true;
const timeline = new AbortController();
const atTime = probe.loadAt(5_000, {
signal: timeline.signal,
replace: true,
});
// The clock goes back to live: the timeline drops what loads and resumes
// the live poll in the same turn.
probe.state.follows = false;
timeline.abort();
const live = probe.loadLivePositions({});
await assert.rejects(atTime, { name: 'AbortError' });
await live;
assert.equal(queries.length, 2);
assert.equal(Object.hasOwn(queries[1], 'atMs'), false);
assert.equal(probe.applied.at(-1).rows.length, 1);
});
+20 -5
View File
@@ -27,9 +27,20 @@ export function createIngestion({
async function loadLivePositions(viewer) {
// Following the world clock, the layer shows the snapshots loadAt applies.
if (followsClock()) return;
// Back at live, a snapshot at a time still loading no longer applies:
// it would hold the live poll back until the next refresh.
if (feed.loading && feed.loadingAtTime) dropLoad();
await loadPositions(viewer);
}
/** Let go of the load in flight, so another can start now. */
function dropLoad() {
feed.abort?.abort();
feed.loading = false;
feed.loadingAtTime = false;
feed.abort = null;
}
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every vessel when `replace`. Resolves
@@ -41,11 +52,7 @@ export function createIngestion({
async function loadAt(atMs, { signal = null, replace = false } = {}) {
// Whatever polls or loads for another time no longer applies: the
// timeline asks for one time at a time.
if (feed.loading) {
feed.abort?.abort();
feed.loading = false;
feed.abort = null;
}
if (feed.loading) dropLoad();
return loadPositions(readViewer(), { atMs, replace, signal });
}
@@ -53,6 +60,7 @@ export function createIngestion({
const timed = atMs !== undefined;
if (!viewer || feed.loading) return false;
feed.loading = true;
feed.loadingAtTime = timed;
feed.loadingLabel = feed.loaded ? 'refreshing...' : 'loading...';
const requestController = new AbortController();
const requestSessionId = feed.sessionId;
@@ -113,6 +121,10 @@ export function createIngestion({
ownsAisRequest(requestController, requestSessionId) &&
error?.name !== 'AbortError'
) {
// The key is missing only while the source says so; any other
// failure is an outage, not a key to add.
feed.transportStatus =
error?.code === 'key-required' ? 'missing-key' : null;
markUnavailable(error?.message || msg('AIS live load failed'));
console.warn('[Data:ais-live-vessels]', feed.error, error);
}
@@ -123,6 +135,7 @@ export function createIngestion({
feed.sessionId === requestSessionId
) {
feed.loading = false;
feed.loadingAtTime = false;
feed.loadingLabel =
feed.firstConnectPhase === 'loading' ? AIS_FIRST_CONNECT_LABEL : '';
feed.abort = null;
@@ -267,6 +280,8 @@ export function createVesselFeed() {
return {
enabled: false,
loading: false,
/** Whether the load in flight is a snapshot at a time, not a poll. */
loadingAtTime: false,
loaded: false,
stale: false,
partial: false,
+38
View File
@@ -147,3 +147,41 @@ test('vessels are asked for by the area in view, and again only when the view mo
await ingestion.refreshIfMoved();
assert.deepEqual(asked.at(-1), { maxRows: 500 });
});
test('a source refusing for want of a key leaves the feed waiting for its key', async () => {
const keyless = Object.assign(new Error('AISSTREAM_API_KEY not set'), {
code: 'key-required',
});
const probe = setup({
getSnapshot: async () => {
throw keyless;
},
});
await probe.methods.update();
assert.equal(probe.feed.transportStatus, 'missing-key');
assert.equal(probe.feed.error, 'AISSTREAM_API_KEY not set');
const down = setup({
getSnapshot: async () => {
throw new Error('feed down');
},
});
await down.methods.update();
assert.notEqual(down.feed.transportStatus, 'missing-key');
});
test('a source failing for another reason after a missing key is an outage, not a key to add', async () => {
let fail = Object.assign(new Error('AISSTREAM_API_KEY not set'), {
code: 'key-required',
});
const probe = setup({
getSnapshot: async () => {
throw fail;
},
});
await probe.methods.update();
assert.equal(probe.feed.transportStatus, 'missing-key');
fail = new Error('feed down');
await probe.methods.update();
assert.equal(probe.feed.transportStatus, null);
assert.equal(probe.feed.error, 'feed down');
});
+4
View File
@@ -133,7 +133,11 @@ export function createLifecycle({
state.activeLabelCount = 0;
state.selectedRecord = null;
state.trail = null;
state.trailHeadOff?.();
state.trailHeadOff = null;
state.trailPositions = [];
state.trailTimes = [];
state.trailBodyCount = -1;
state.trailId = null;
state.trailBackfillToken = 0;
}
+85 -1
View File
@@ -54,10 +54,94 @@ export function vesselPositionAt(record, tMs) {
}
const RAD = Math.PI / 180;
/** The mean Earth radius (metres) a span's length is judged on. */
const EARTH_RADIUS_M = 6371008.8;
/**
* The stretch of a vessel's track around world time `tMs`, as
* vesselPositionAt draws it: between the last fix at or before the time and
* the next one (`move`, which always ends after `tMs`), or where it holds
* still (`hold`) before its first fix, after its last, or around a record's
* one move; from when (`fromMs`) until when (`untilMs`) the answer holds.
* Null for a vessel the clock never moves (no fixes and no move).
* @param {object} record
* @param {number} tMs
* @returns {{kind: 'move', lat0: number, lon0: number, t0: number,
* lat1: number, lon1: number, t1: number, metres: number}|
* {kind: 'hold', lat: number, lon: number, fromMs: number,
* untilMs: number}|null}
*/
export function vesselSpanAt(record, tMs) {
if (!Number.isFinite(tMs)) return null;
const fixes = record?.fixes;
if (fixes?.length >= 2) {
const first = fixes[0];
const last = fixes[fixes.length - 1];
if (tMs < first.atMs)
return hold(first.lat, first.lon, -Infinity, first.atMs);
if (tMs >= last.atMs) return hold(last.lat, last.lon, last.atMs, Infinity);
// The first fix after the time: the one before it is at or before it.
let low = 1;
let high = fixes.length - 1;
while (low < high) {
const mid = (low + high) >> 1;
if (fixes[mid].atMs <= tMs) low = mid + 1;
else high = mid;
}
const a = fixes[low - 1];
const b = fixes[low];
return move(a.lat, a.lon, a.atMs, b.lat, b.lon, b.atMs);
}
const motion = record?.motion;
if (!motion || !(motion.toMs > motion.fromMs)) return null;
if (tMs < motion.fromMs)
return hold(motion.fromLat, motion.fromLon, -Infinity, motion.fromMs);
if (tMs >= motion.toMs)
return hold(record.lat, record.lon, motion.toMs, Infinity);
return move(
motion.fromLat,
motion.fromLon,
motion.fromMs,
motion.toLat,
motion.toLon,
motion.toMs,
);
}
const hold = (lat, lon, fromMs, untilMs) => ({
kind: 'hold',
lat,
lon,
fromMs,
untilMs,
});
function move(lat0, lon0, t0, lat1, lon1, t1) {
return {
kind: 'move',
lat0,
lon0,
t0,
lat1,
lon1,
t1,
metres: greatCircleAngle(lat0, lon0, lat1, lon1) * EARTH_RADIUS_M,
};
}
/** The angle (radians) between two positions, seen from the Earth's centre. */
function greatCircleAngle(lat1, lon1, lat2, lon2) {
const phi1 = lat1 * RAD;
const phi2 = lat2 * RAD;
const s =
Math.sin((phi2 - phi1) / 2) ** 2 +
Math.cos(phi1) * Math.cos(phi2) * Math.sin(((lon2 - lon1) * RAD) / 2) ** 2;
return 2 * Math.asin(Math.min(1, Math.sqrt(s)));
}
/** 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) {
export function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
const phi1 = lat1 * RAD;
const lambda1 = lon1 * RAD;
const phi2 = lat2 * RAD;
+79 -1
View File
@@ -1,6 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fixesMove, vesselPositionAt } from './motion.js';
import {
fixesMove,
greatCircleAt,
vesselPositionAt,
vesselSpanAt,
} from './motion.js';
const record = {
lat: 1,
@@ -61,3 +66,76 @@ test('fixes that stay in one place do not move a vessel', () => {
);
assert.equal(fixesMove(null), false);
});
const fixes = [
{ atMs: 1_000, lat: 0, lon: 0 },
{ atMs: 2_000, lat: 0, lon: 1 },
{ atMs: 3_000, lat: 1, lon: 1 },
];
test('vesselSpanAt holds at the first fix before it, until it', () => {
assert.deepEqual(vesselSpanAt({ fixes }, 500), {
kind: 'hold',
lat: 0,
lon: 0,
fromMs: -Infinity,
untilMs: 1_000,
});
});
test('vesselSpanAt runs from the fix at or before the time to the next, ending after it', () => {
for (const [atMs, t0, t1] of [
[1_000, 1_000, 2_000],
[1_999, 1_000, 2_000],
[2_000, 2_000, 3_000],
[2_500, 2_000, 3_000],
]) {
const span = vesselSpanAt({ fixes }, atMs);
assert.equal(span.kind, 'move');
assert.deepEqual([span.t0, span.t1], [t0, t1], `at ${atMs}`);
assert.ok(span.t1 > atMs);
}
// A degree of longitude on the equator.
assert.ok(Math.abs(vesselSpanAt({ fixes }, 1_500).metres - 111_195) < 10);
});
test('vesselSpanAt holds at the last fix from it on', () => {
assert.deepEqual(vesselSpanAt({ fixes }, 3_000), {
kind: 'hold',
lat: 1,
lon: 1,
fromMs: 3_000,
untilMs: Infinity,
});
});
test("vesselSpanAt follows a record's one move, and nothing for none", () => {
assert.equal(vesselSpanAt(record, 500).untilMs, 1_000);
const span = vesselSpanAt(record, 1_500);
assert.equal(span.kind, 'move');
assert.deepEqual([span.lat0, span.lat1], [0, 1]);
assert.deepEqual(vesselSpanAt(record, 9_000), {
kind: 'hold',
lat: 1,
lon: 1,
fromMs: record.motion.toMs,
untilMs: Infinity,
});
assert.equal(vesselSpanAt({ lat: 1, lon: 1 }, 1_500), null);
});
test('vesselSpanAt agrees with vesselPositionAt along the span', () => {
for (const atMs of [1_000, 1_250, 2_000, 2_750]) {
const span = vesselSpanAt({ fixes }, atMs);
const at = greatCircleAt(
span.lat0,
span.lon0,
span.lat1,
span.lon1,
(atMs - span.t0) / (span.t1 - span.t0),
);
const expected = vesselPositionAt({ fixes }, atMs);
assert.ok(Math.abs(at.lat - expected.lat) < 1e-9);
assert.ok(Math.abs(at.lon - expected.lon) < 1e-9);
}
});
+284
View File
@@ -0,0 +1,284 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createVesselLayer } from './index.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
// Following the world clock on a renderer that moves icons along motion
// segments on its own clock, each vessel's icon is drawn along its track
// between two fixes, and the layer draws it again only when that runs out.
const noop = () => {};
function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const layer = createVesselLayer({
source: { getSnapshot: async () => ({ records: [] }) },
services: {
context: {
clearSelectedEntityContextForLayer: noop,
registerEntityContext: () => null,
},
trails: {
createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }),
},
labels: { formatKnots: (knots) => `${knots} kt` },
picking: { unregisterPickOwner: noop },
overlay: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
geoid: {},
sprites: {},
focus: {
focusNowMs: () => 0,
getFocusTarget: () => null,
focusPassIsNeeded: () => false,
forgetSpriteFocus: noop,
},
worldFocus: {},
render: {
holdContinuousRender: noop,
releaseContinuousRender: noop,
governorRequestRender: noop,
},
},
});
const camera = {
positionWC: { x: 0, y: 0, z: 7_000_000 },
heading: 0,
pitch: -1.2,
roll: 0,
};
const viewer = { camera, scene: {} };
const { draw } = bindFakeCesiumScene(viewer, { capabilities });
layer.testing._setVesselStateForTest({ viewer, icons: null });
layer.testing._setAisRuntimeForTest({
now: () => 0,
setTimeout: () => 0,
clearTimeout: noop,
});
const icons = () =>
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
);
return { layer, viewer, icons };
}
const T = 1_000_000;
/** Northbound off Rotterdam, a fix a minute (about 1.1 km apart). */
const row = (fixes) => ({
mmsi: '111',
lat: fixes.at(-1).lat,
lon: fixes.at(-1).lon,
last_position_epoch: fixes.at(-1).atMs / 1000,
fixes,
});
const minuteFixes = [
{ atMs: T, lat: 51.93, lon: 4.05 },
{ atMs: T + 60_000, lat: 51.94, lon: 4.05 },
{ atMs: T + 120_000, lat: 51.95, lon: 4.05 },
];
test('following the clock, an icon moves along its fixes on the scene clock and is drawn again only when that runs out', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T + 10_000);
const set = icons();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
let item = set.items.get('111');
assert.equal(item.motion.kind, 'lerp');
assert.deepEqual([item.motion.t0, item.motion.t1], [T, T + 60_000]);
const writes = set.writes;
// Within the stretch: the renderer moves it, the layer writes nothing.
for (let atMs = T + 11_000; atMs < T + 60_000; atMs += 1_000)
layer.testing._runClockPassForTest(atMs);
assert.equal(set.writes, writes);
// The stretch runs out: the next one is drawn, once.
layer.testing._runClockPassForTest(T + 60_000);
item = set.items.get('111');
assert.deepEqual([item.motion.t0, item.motion.t1], [T + 60_000, T + 120_000]);
assert.equal(set.writes, writes + 1);
// Past the last fix, it holds there for good.
layer.testing._runClockPassForTest(T + 200_000);
assert.equal(set.items.get('111').motion.kind, 'hold');
const held = set.writes;
layer.testing._runClockPassForTest(T + 900_000);
assert.equal(set.writes, held);
});
test('a time moved back before the stretch drawn draws the one it is in', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T + 90_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T + 90_000);
assert.equal(icons().items.get('111').motion.t0, T + 60_000);
layer.testing._runClockPassForTest(T + 30_000);
const item = icons().items.get('111');
assert.deepEqual([item.motion.t0, item.motion.t1], [T, T + 60_000]);
});
test('a long stretch between fixes is drawn a piece of at most 10 km at a time', (t) => {
const { layer, viewer, icons } = setup(t);
// About 55.6 km in an hour: six pieces of ten minutes.
const fixes = [
{ atMs: T, lat: 51.5, lon: 4.05 },
{ atMs: T + 3_600_000, lat: 52.0, lon: 4.05 },
];
layer.testing._followClockForTest(T + 700_000);
layer.testing._reconcileVesselsForTest(viewer, [row(fixes)]);
layer.testing._runClockPassForTest(T + 700_000);
const { motion } = icons().items.get('111');
assert.deepEqual([motion.t0, motion.t1], [T + 600_000, T + 1_200_000]);
});
test('going live, every icon holds again on the live clock', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T + 10_000);
assert.equal(icons().items.get('111').motion.kind, 'lerp');
layer.testing._followClockForTest(null);
layer.testing._runLiveFrameForTest();
assert.equal(icons().items.get('111').motion.kind, 'hold');
assert.equal(icons().spec.motionClock.kind, 'live');
});
test('a renderer without motion segments has the layer move each icon, as before', (t) => {
const { layer, viewer, icons } = setup(t, { capabilities: new Set() });
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T + 10_000);
assert.equal(icons().items.get('111').motion.kind, 'hold');
assert.equal(icons().spec.motionClock, undefined);
});
test('a vessel shows a minute before its first fix, and hides again when the time moves back before that', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T - 120_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T - 120_000);
assert.equal(icons().items.get('111').show, false);
layer.testing._runClockPassForTest(T - 60_000);
assert.equal(icons().items.get('111').show, true);
layer.testing._runClockPassForTest(T - 30_000);
assert.equal(icons().items.get('111').show, true);
layer.testing._runClockPassForTest(T - 90_000);
assert.equal(icons().items.get('111').show, false);
});
test('the detection overlay reads a vessel where it is at the time drawn', (t) => {
const { layer, viewer } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]);
layer.testing._runClockPassForTest(T + 10_000);
const record = layer.testing._vesselRecordForTest('111');
const visual = layer.testing._vesselVisualForTest(record);
visual.visible = true;
// Mid-stretch, with no pass reading this vessel since.
layer.testing._followClockForTest(T + 40_000);
const [object] = layer.getDetectableObjects();
assert.equal(object.sourceId, '111');
assert.ok(Math.abs(visual.drawnLat - (51.93 + 0.01 * (40 / 60))) < 1e-6);
});
/** Three vessels a little apart, each on the minute fixes. */
const fleet = () =>
['111', '222', '333'].map((mmsi, i) => ({
...row(minuteFixes.map((fix) => ({ ...fix, lon: fix.lon + i * 0.01 }))),
mmsi,
}));
const latAt = (atMs) => 51.93 + (0.01 * (atMs - T)) / 60_000;
test('positions asked of the layer are where the vessels are drawn at the time drawn', (t) => {
const { layer, viewer } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, fleet());
layer.testing._runClockPassForTest(T + 10_000);
// Mid-stretch, with no pass since.
layer.testing._followClockForTest(T + 40_000);
const latOf = (position) =>
Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(
new Cesium.Cartesian3(position.x, position.y, position.z),
).latitude,
);
const rows = layer.getAllPositions();
assert.equal(rows.length, 3);
for (const { id, position } of rows)
assert.ok(Math.abs(latOf(position) - latAt(T + 40_000)) < 1e-5, id);
// One vessel asked of by itself is brought there too.
const record = layer.testing._vesselRecordForTest('222');
const visual = layer.testing._vesselVisualForTest(record);
layer.findByQuery('222');
assert.ok(Math.abs(visual.drawnLat - latAt(T + 40_000)) < 1e-6);
});
test('going live, every icon holds where its segment last drew it', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, fleet());
layer.testing._runClockPassForTest(T + 10_000);
layer.testing._runClockPassForTest(T + 40_000);
layer.testing._followClockForTest(null);
layer.testing._runLiveFrameForTest();
for (const id of ['111', '222', '333']) {
const record = layer.testing._vesselRecordForTest(id);
const visual = layer.testing._vesselVisualForTest(record);
assert.ok(Math.abs(visual.drawnLat - latAt(T + 40_000)) < 1e-6, id);
assert.deepEqual(icons().items.get(id).pos, visual.position);
assert.equal(icons().items.get(id).motion.kind, 'hold');
}
});
test('a time on the end of a piece draws the next piece', (t) => {
const { layer, viewer, icons } = setup(t);
// About 55.6 km in a little under an hour: six pieces, the first of whose
// ends rounds into the piece before it.
const fixes = [
{ atMs: T, lat: 51.5, lon: 4.05 },
{ atMs: T + 3_599_002, lat: 52.0, lon: 4.05 },
];
layer.testing._followClockForTest(T);
layer.testing._reconcileVesselsForTest(viewer, [row(fixes)]);
for (let k = 1; k < 6; k += 1) {
const atMs = T + (3_599_002 * k) / 6;
layer.testing._runClockPassForTest(atMs);
const { motion } = icons().items.get('111');
assert.ok(motion.t0 <= atMs && atMs < motion.t1, `piece ${k}`);
}
});
test('going live, a vessel a live update has drawn since stays where that drew it', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._followClockForTest(T + 10_000);
layer.testing._reconcileVesselsForTest(viewer, fleet());
// A later fix while following: each record keeps the move to it.
const later = { atMs: T + 180_000, lat: 51.96, lon: 4.05 };
layer.testing._reconcileVesselsForTest(
viewer,
fleet()
.map((r) => row([...r.fixes, { ...later, lon: r.lon }]))
.map((r, i) => ({ ...r, mmsi: ['111', '222', '333'][i] })),
);
layer.testing._runClockPassForTest(T + 10_000);
layer.testing._runClockPassForTest(T + 40_000);
layer.testing._followClockForTest(null);
// The live feed lands before the next frame, the ship further north.
const live = fleet().map((row) => ({ ...row, lat: 52.1 }));
layer.testing._reconcileVesselsForTest(viewer, live);
layer.testing._runLiveFrameForTest();
for (const id of ['111', '222', '333']) {
const record = layer.testing._vesselRecordForTest(id);
const visual = layer.testing._vesselVisualForTest(record);
assert.equal(visual.drawnLat, 52.1, id);
assert.deepEqual(icons().items.get(id).pos, visual.position);
}
});
+18
View File
@@ -601,3 +601,21 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async ()
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
});
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
let current = snapshot([], {
transportStatus: 'missing-key',
complete: false,
});
const { layer } = setup({
async getSnapshot() {
return current;
},
});
assert.equal(layer.requiresKeyId, 'aisstream');
await layer.update();
assert.equal(layer.getStats().keyRequired, true);
current = snapshot([observation('111')]);
await layer.update();
assert.equal(layer.getStats().keyRequired, false);
});
+6
View File
@@ -53,6 +53,12 @@ export const TRAIL_MAX_POINTS = 400;
export const TRAIL_MIN_MOVE_M = 25;
/** Longest head (m) drawn from the trail's last drawn fix to the vessel: a
* farther vessel (the clock jumped past the fixes the trail holds) keeps no
* head until its fixes arrive. */
export const TRAIL_HEAD_MAX_M = 20000;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (vesselState) =>
+6 -2
View File
@@ -299,6 +299,8 @@ export function createQueries({
icon: '◭',
source: 'AISStream',
// Without an AISStream key the feed cannot start; the panel names the key.
requiresKeyId: 'aisstream',
updateInterval: REFRESH_MS,
@@ -366,7 +368,7 @@ export function createQueries({
for (const record of records) {
if (!Number.isFinite(record.lat) || !Number.isFinite(record.lon))
continue;
const position = components.rendering.iconPosition(record);
const position = components.rendering.drawnPositionNow(record);
if (!position) continue;
const distanceM = distance(centerCartesian, position);
if (!Number.isFinite(distanceM) || distanceM > range) continue;
@@ -471,7 +473,7 @@ export function createQueries({
for (const record of records) {
if (result.length >= cap) break;
const position = components.rendering.iconPosition(record);
const position = components.rendering.drawnPositionNow(record);
if (!position) continue;
result.push({
id: record.id,
@@ -664,6 +666,7 @@ export function createQueries({
!visual.modelOwnsVisual
)
continue;
components.rendering.readVesselNow(record);
const position = visual.position;
if (!position) continue;
result.push({
@@ -712,6 +715,7 @@ export function createQueries({
? 'unavailable'
: undefined,
transportStatus: state.feed.transportStatus,
keyRequired: state.feed.transportStatus === 'missing-key',
lastMessageAt: state.feed.lastMessageAt,
rawRowCount: state.feed.rawRowCount,
acceptedRowCount: state.feed.acceptedRowCount,
+268 -11
View File
@@ -16,6 +16,7 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { poseSignature } from '../../render/camera/poseSignature.js';
import { createVesselIconBook } from './iconBook.js';
@@ -29,7 +30,12 @@ import {
CARD_MIN_SEP_PX,
followsClock,
} from './policy.js';
import { fixesMove, vesselPositionAt } from './motion.js';
import {
fixesMove,
greatCircleAt,
vesselPositionAt,
vesselSpanAt,
} from './motion.js';
import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js';
import {
fleetModelSet,
@@ -68,6 +74,11 @@ const CAMERA_STEP_FLOOR_M = 100;
/** Scratch for where a moved vessel was drawn. */
const _movedFrom = vec();
/** The longest piece (metres) of the track between two fixes an icon is
* drawn along as one straight line on the renderer's clock: at 10 km the
* line runs under 2 m inside the great circle the layer reads it on. */
const SEGMENT_PIECE_M = 10000;
export function createRendering({
vesselState,
services,
@@ -83,11 +94,27 @@ export function createRendering({
return visualRecords.get(record) || record;
}
/** Where a record's icon is drawn: its row holds at the visual position. */
/** Where a record's icon is drawn: its row holds at the visual position
* (brought up to the time drawn while the renderer moves the icons). */
function iconPosition(record) {
readVesselNow(record);
return getVisual(record).position;
}
/**
* Where a record's icon is drawn now, for a reader of many vessels at
* once: while the renderer moves the icons, its segment at the world time
* (a new position each call); else the visual position, as iconPosition.
*/
function drawnPositionNow(record) {
const visual = getVisual(record);
if (!segmentsOn() || !visual.position) return visual.position;
return (
state.icons?.position(visual.iconId, vesselState.worldNow()) ??
visual.position
);
}
function prepareRecordVisual(record) {
let visual = visualRecords.get(record);
if (!visual) {
@@ -172,7 +199,9 @@ export function createRendering({
fromDegreesInto(lon, lat, heightM - VESSEL_LIFT_M, visual.waterline);
visual.drawnLat = lat;
visual.drawnLon = lon;
syncRecordIcon(record);
// Moving on the renderer's clock, its icon is where it is already.
if (segmentsOn()) visual.cullPosition = liftedForHorizon(visual.position);
else syncRecordIcon(record);
}
// Reused projection buffers for the card pass, grown to the candidates.
@@ -226,6 +255,9 @@ export function createRendering({
function ensureCollections(viewer) {
ensureModels(viewer);
if (!viewer || state.icons) return;
const capabilities = rendererOf(viewer)?.capabilities ?? null;
iconMotion = capabilities?.has('motionSegments') === true;
segmentsWere = segmentsOn();
const set = drawOf(viewer).icons({
id: `ais-vessels:${++instances}`,
// Translucent, as its billboards were: overlapping chevrons keep
@@ -233,18 +265,118 @@ export function createRendering({
blend: 'translucent',
horizonCull: true,
drawOrder: spriteDrawOrder?.('ais') ?? 0,
...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null),
});
// Columns of no rows put the set's host in the scene now, rather than
// with its first vessel.
set.setColumns?.({ ids: [] });
state.icons = createVesselIconBook(set);
iconSet = set;
state.icons = createVesselIconBook(set, { capabilities });
state.icons.show = state.feed.enabled;
}
// The icon draw set, and whether its renderer moves icons along motion
// segments on its own clock.
let iconSet = null;
let iconMotion = false;
// Whether the icons last moved on the renderer's clock.
let segmentsWere = false;
// The record drawn under each icon id, for replanning an id.
const iconRecords = new Map();
// From when (world ms) each planned icon's motion holds: one planned
// after the time drawn is planned again when the time moves back.
const planFrom = new Map();
// The world time the icons were last checked against.
let replannedAtMs = -Infinity;
/**
* Whether vessel icons move on the renderer's clock: following the world
* clock, each is drawn along its track between two fixes as a segment the
* renderer moves every frame on the scene's time, and the layer writes an
* icon only when its segment runs out, rather than moving every drawn
* icon each frame. Live, a host placement moves them as before.
*/
function segmentsOn() {
return iconMotion && followsClock(vesselState);
}
/** The set's motion clock: the scene's time while following the clock. */
const motionClock = (scene) =>
scene ? { kind: 'scene' } : { kind: 'live', delayMs: 0 };
/**
* The segment a vessel's icon moves along at world time `atMs`: the piece
* of its track between two fixes the time is in (at most SEGMENT_PIECE_M
* long), or where it holds; with when it runs out and from when it holds.
* Null for a vessel the clock does not move: it holds where it is drawn.
*/
function planMotion(record, atMs) {
if (!record.motion && !fixesMove(record.fixes)) return null;
const span = vesselSpanAt(record, atMs);
if (!span) return null;
if (span.kind === 'hold') {
// Before its first fix it is drawn from TIMELINE_UNSEEN_MS ahead of
// it (seenYet): drawn again when the time crosses that.
let { fromMs, untilMs } = span;
const shownFromMs = record.fixes?.[0]?.atMs - TIMELINE_UNSEEN_MS;
if (fromMs === -Infinity && shownFromMs < untilMs) {
if (atMs < shownFromMs) untilMs = shownFromMs;
else fromMs = shownFromMs;
}
return {
motion: null,
pos: anchorAt(span.lat, span.lon),
expiresAt: untilMs,
validFrom: fromMs,
};
}
const n = Math.max(1, Math.ceil(span.metres / SEGMENT_PIECE_M));
const spanMs = span.t1 - span.t0;
const pieceEnd = (i) => (i === n ? span.t1 : span.t0 + (spanMs * i) / n);
let k = Math.min(
n - 1,
Math.max(0, Math.floor(((atMs - span.t0) / spanMs) * n)),
);
// A time on a piece's end belongs to the next piece, whatever rounding
// says, so a segment is never drawn already run out.
while (k < n - 1 && pieceEnd(k + 1) <= atMs) k += 1;
while (k > 0 && pieceEnd(k) > atMs) k -= 1;
const t0 = pieceEnd(k);
const t1 = pieceEnd(k + 1);
const at = (i) =>
i === 0
? { lat: span.lat0, lon: span.lon0 }
: i === n
? { lat: span.lat1, lon: span.lon1 }
: greatCircleAt(span.lat0, span.lon0, span.lat1, span.lon1, i / n);
const a = at(k);
const b = at(k + 1);
const to = anchorAt(b.lat, b.lon);
const courseDeg = vesselCourseDeg(record);
return {
motion: {
kind: 'lerp',
from: anchorAt(a.lat, a.lon),
to,
t0,
t1,
course0Deg: courseDeg,
courseSlopeDeg: 0,
},
pos: to,
expiresAt: t1,
validFrom: t0,
};
}
/** Let the icon draw set go (the layer is destroyed). */
function disposeCollections() {
state.icons?.dispose();
state.icons = null;
iconSet = null;
iconRecords.clear();
planFrom.clear();
replannedAtMs = -Infinity;
}
/** Whether the Cockpit's bridge camera rides this record's ship. */
@@ -276,20 +408,25 @@ export function createRendering({
const courseDeg = vesselCourseDeg(record);
// Following the clock, not there yet at the time drawn.
visual.seen = seenYet(record);
const plan = segmentsOn()
? planMotion(record, vesselState.worldNow())
: null;
visual.plan = plan;
return {
id: visual.iconId,
// Hidden while the bridge camera rides it, its model draws it, or it
// is not there yet.
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
pos: visual.position,
pos: plan?.pos ?? visual.position,
image: shipIcon(record, selected),
size: [SHIP_ICON_PX, SHIP_ICON_PX],
// Selection changes the colour only, never the size.
scale: shipScale(record),
rotationMode: 'course',
// Held on course; `course` for renderers without motion segments.
// Held on course, or along its track on the renderer's clock;
// `course` for renderers without motion segments.
course: courseDeg,
motion: { kind: 'hold', courseDeg },
motion: plan?.motion ?? { kind: 'hold', courseDeg },
focus: state.icons?.focus(visual.iconId) ?? 1,
disableDepthTest: Infinity,
meta: visual.meta,
@@ -308,7 +445,8 @@ export function createRendering({
const visual = getVisual(record);
// The pick meta, and the key of the vessel's focus emphasis.
visual.meta = { layer: 'ais-live-vessels', id: visual.iconId };
state.icons.put({ ...iconItem(record, visual), focus: 1 });
iconRecords.set(visual.iconId, record);
putIcon(visual, { ...iconItem(record, visual), focus: 1 });
if (visual.position)
visual.cullPosition = liftedForHorizon(visual.position);
visual.visible = isVisible(visual.cullPosition, occluder, record);
@@ -325,10 +463,23 @@ export function createRendering({
function syncRecordIcon(record) {
const visual = getVisual(record);
if (!state.icons?.has(visual.iconId) || !visual.position) return;
state.icons.put(iconItem(record, visual));
putIcon(visual, iconItem(record, visual));
visual.cullPosition = liftedForHorizon(visual.position);
}
/** Draw a vessel's icon item, with when its segment runs out while the
* icons move on the renderer's clock. */
function putIcon(visual, item) {
if (!segmentsOn()) {
planFrom.delete(item.id);
state.icons.put(item, { expiresAt: null });
return;
}
const plan = visual.plan;
planFrom.set(item.id, plan?.validFrom ?? -Infinity);
state.icons.put(item, { expiresAt: plan?.expiresAt ?? Infinity });
}
/**
* Remove a record's icon row.
* @param {Object} record - Vessel record to tear down.
@@ -341,6 +492,8 @@ export function createRendering({
if (!icons?.has(visual.iconId)) return;
forgetSpriteFocus(icons.item(visual.iconId).meta);
icons.remove(visual.iconId);
iconRecords.delete(visual.iconId);
planFrom.delete(visual.iconId);
}
function shipScale(record) {
@@ -548,7 +701,8 @@ export function createRendering({
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => {
if (state.feed.enabled) {
if (followsClock(vesselState)) followClockPositions();
syncSegments();
if (followsClock(vesselState)) followClock();
else if (services.placement) followPlacements();
}
updateVisibility();
@@ -569,6 +723,102 @@ export function createRendering({
let clockPassAtMs = null;
// Whether the last pass left drawn vessels short of its world time.
let drawnBehind = false;
/** One world-clock pass: icons on the renderer's clock when it moves
* them, else moved by the layer. */
function followClock() {
syncSegments();
if (segmentsOn()) followClockSegments();
else followClockPositions();
}
/**
* Once a frame: when the icons start or stop moving on the renderer's
* clock (the layer starts or stops following the world clock), put the
* set on that clock and draw every icon again, along its segment or held.
*/
function syncSegments() {
const on = segmentsOn();
if (on === segmentsWere) return;
segmentsWere = on;
iconSet?.setOptions?.({ motionClock: motionClock(on) });
// Leaving the clock, each icon holds where its segment last drew it;
// one a live update has drawn since (no world time drawn) stays there.
const lastAtMs = on ? -Infinity : replannedAtMs;
replannedAtMs = -Infinity;
for (const record of state.records.all) {
const drawnAtMs = visualRecords.get(record)?.drawnAtMs;
if (
lastAtMs > -Infinity &&
Number.isFinite(drawnAtMs) &&
catchUpVisual(record, lastAtMs)
)
continue;
syncRecordIcon(record);
}
}
// The vessels drawn with a card (and the selected one): their cards are
// anchored at where the layer reads them, so it reads them every frame.
const carded = new Set();
/**
* As the world clock plays with the icons on the renderer's clock: the
* renderer moves each icon along its segment, and the layer draws again
* only those whose segment ran out (or, the time moved back, started after
* it). Where the layer reads a vessel (its cards, picks, the horizon, its
* model) moves on by itself: every frame for the vessels drawn with a
* card or a model and the one the bridge camera rides, and for the rest a
* share of them each pass, so each moves at least every HIDDEN_FOLLOW_MS.
*/
function followClockSegments() {
const atMs = vesselState.worldNow();
if (atMs < replannedAtMs)
for (const [id, from] of planFrom) if (from > atMs) replanIcon(id, atMs);
replannedAtMs = atMs;
for (const id of state.icons?.due(atMs) ?? []) replanIcon(id, atMs);
for (const record of carded) catchUpVisual(record, atMs);
for (const item of modelItems.values()) catchUpVisual(item.record, atMs);
const ridden = state.cockpitSubjectId
? state.records.byId.get(state.cockpitSubjectId)
: null;
if (ridden) catchUpVisual(ridden, atMs);
const all = state.records.all;
const wallMs = performance.now();
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;
const record = all[hiddenCursor];
if (visualRecords.get(record)?.position) catchUpVisual(record, atMs);
else followRecord(record, atMs, false, motionPass);
hiddenCursor += 1;
}
}
/**
* Bring where the layer reads a vessel up to the world time, for a reader
* that needs it where it is drawn now (the detection overlay): while the
* icons move on the renderer's clock, only some are read every frame.
*/
function readVesselNow(record) {
if (segmentsOn()) catchUpVisual(record, vesselState.worldNow());
}
/** Draw an icon's vessel again where it is at `atMs`. */
function replanIcon(id, atMs) {
const record = iconRecords.get(id);
if (!record) return;
catchUpVisual(record, atMs);
syncRecordIcon(record);
}
function followClockPositions() {
const atMs = vesselState.worldNow();
const wallMs = performance.now();
@@ -1039,7 +1289,7 @@ export function createRendering({
const visual = getVisual(record);
const id = visual?.iconId;
const item = icons?.item(id);
const position = visual?.position;
const position = item ? drawnPositionNow(record) : visual?.position;
if (!item || !position) continue;
const sprite = item.meta;
// Most of a worldwide feed sits behind the horizon. A hidden icon with
@@ -1121,6 +1371,8 @@ export function createRendering({
? [components.cards.buildSelectedVesselCard(selected)]
: [];
const maxLabels = labelRowLimit();
carded.clear();
if (selectedCarded) carded.add(selected);
if (!query || !records.length || maxLabels <= 0) {
state.activeLabelCount = entries.length;
@@ -1183,6 +1435,7 @@ export function createRendering({
continue;
accepted.push({ x: candidate.x, y: candidate.y });
entries.push(components.cards.buildVesselCard(candidate.record));
carded.add(candidate.record);
}
state.activeLabelCount = entries.length;
publishVesselOverlayEntries(entries);
@@ -1273,6 +1526,7 @@ export function createRendering({
return {
getVisual,
iconPosition,
drawnPositionNow,
forgetClockStep,
prepareRecordVisual,
anchorPosition,
@@ -1292,7 +1546,10 @@ export function createRendering({
cancelTrailingVisibilityPass,
cancelPlacementFrame,
followPlacements,
followClock,
followClockPositions,
readVesselNow,
syncSegments,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
+2 -2
View File
@@ -90,9 +90,9 @@ export function createVesselSnapshotRenderer({
},
},
);
// The selected vessel at the new time: its trail starts there.
// The selected vessel at the new time: its trail is drawn to it.
if (replace && state.selectedRecord && state.trailId)
tracking.startSelectedVesselTrail(state.selectedRecord);
tracking.retimeSelectedVesselTrail(state.selectedRecord);
state.lastVisibilityUpdate = 0;
rendering.updateVisibility(true);
}
+7
View File
@@ -97,6 +97,13 @@ export function createVesselState({ source, services }) {
trail: null,
/** @type {{x: number, y: number, z: number}[]} Chronological ECEF trail vertices (oldest first) */
trailPositions: [],
/** @type {number[]} Epoch ms of each trail vertex (NaN: undated, drawn
* at any time), parallel to trailPositions. */
trailTimes: [],
/** How many trail vertices the body draws now, or -1 before it draws. */
trailBodyCount: -1,
/** @type {(() => void)|null} Stops drawing the trail's head each frame. */
trailHeadOff: null,
/** @type {string|null} Id of the vessel that owns the active selected-vessel trail. */
trailId: null,
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
+20 -4
View File
@@ -62,6 +62,7 @@ export function createTesting({
state.trailPositions = Array.isArray(options.trailPositions)
? [...options.trailPositions]
: [];
state.trailTimes = state.trailPositions.map(() => Number.NaN);
state.feed.transportStatus = options.transportStatus || null;
state.feed.lastMessageAt = options.lastMessageAt ?? null;
state.feed.rawRowCount = Number.isFinite(options.rawRowCount)
@@ -182,18 +183,32 @@ export function createTesting({
components.rendering.followPlacements();
}
/**
* Run what one live frame runs (not following the clock): settle whether
* icons move on the renderer's clock, then the placement pass. Test-only
* seam.
*/
function _runLiveFrameForTest() {
components.rendering.syncSegments();
components.rendering.followPlacements();
}
/** Run one world-clock pass at world time `atMs`. Test-only seam. */
function _runClockPassForTest(atMs) {
vesselState.worldNow = () => atMs;
components.rendering.followClockPositions();
components.rendering.followClock();
}
/** Follow the world clock, standing at world time `atMs`. Test-only seam. */
/**
* Follow the world clock, standing at world time `atMs`; `null` goes back
* to live. Test-only seam.
*/
function _followClockForTest(atMs) {
vesselState.timeline = { active: () => true };
vesselState.worldNow = () => atMs;
vesselState.timeline = { active: () => atMs !== null };
vesselState.worldNow = () => atMs ?? 0;
}
/** True while a trailing visibility frame is scheduled. Test-only seam. */
@@ -240,6 +255,7 @@ export function createTesting({
_vesselVisualForTest,
_runPlacementPassForTest,
_runClockPassForTest,
_runLiveFrameForTest,
_hasTrailingVisibilityPassForTest,
};
}
+126 -13
View File
@@ -1,13 +1,22 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import { findFrame } from '../../render/rendererOf.js';
import {
TRAIL_HEIGHT_M,
TRAIL_COLOR,
TRAIL_HEAD_MAX_M,
TRAIL_MAX_POINTS,
TRAIL_MIN_MOVE_M,
followsClock,
} from './policy.js';
/** A vessel record's own fix time, epoch ms (NaN when it gives none). */
function recordFixMs(record) {
const epoch = record?.lastPositionEpoch;
if (Number.isFinite(epoch)) return epoch * 1000;
return Number.isFinite(record?.receivedAtMs) ? record.receivedAtMs : NaN;
}
export function createTracking({
vesselState,
services,
@@ -89,18 +98,94 @@ export function createTracking({
state.trailBackfillToken += 1;
state.trailId = record.id;
state.trailPositions = [];
state.trailTimes = [];
const current = vesselTrailPosition(record);
if (current) state.trailPositions.push(current);
if (current) {
state.trailPositions.push(current);
state.trailTimes.push(recordFixMs(record));
}
if (!state.trail && state.viewer) {
state.trail = createTrail(state.viewer, {
color: TRAIL_COLOR,
width: 2.5,
});
}
if (state.trail) state.trail.setPositions(state.trailPositions);
if (!state.trailHeadOff && state.viewer)
state.trailHeadOff =
findFrame(state.viewer)?.on('preRender', drawSelectedVesselTrail) ??
null;
drawTrailBody();
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference);
}
/**
* The world clock moved to another time: the trail keeps what it holds,
* drawn up to the new time, until the vessel's track at that time
* replaces it. Clearing it would blank the trail at every step of the clock.
* @param {Object} record - The selected vessel at the new time.
*/
function retimeSelectedVesselTrail(record) {
if (state.trailId !== record.id || !state.trail) {
startSelectedVesselTrail(record);
return;
}
state.trailAbort?.abort();
state.trailAbort = new AbortController();
state.trailBackfillToken += 1;
drawSelectedVesselTrail();
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference, {
replace: true,
});
}
/** The world time the selected vessel is drawn at; Infinity live, where
* every fix is behind it. */
function drawnTimeMs() {
return followsClock(vesselState) ? vesselState.worldNow() : Infinity;
}
/** How many trail vertices are at or before `atMs` (undated ones always). */
function bodyCountAt(atMs) {
let count = state.trailTimes.length;
while (count > 0 && state.trailTimes[count - 1] > atMs) count -= 1;
return count;
}
/** Draw the trail's body: its fixes up to the time the vessel is drawn at.
* A fix ahead of the vessel would draw the trail in front of it. */
function drawTrailBody() {
if (!state.trail) return;
state.trailBodyCount = bodyCountAt(drawnTimeMs());
state.trail.setPositions(
state.trailPositions.slice(0, state.trailBodyCount),
);
}
/** The head: the body's last vertex to where the vessel is drawn, or none
* (no vessel drawn, or one too far from the body to be on its path). */
function trailHeadPositions() {
const record = state.selectedRecord;
if (!record || record.id !== state.trailId || state.trailBodyCount < 1)
return null;
// Where its icon is drawn now (the renderer's, while it moves the icons).
const at = components.rendering.drawnPositionNow(record);
const last = state.trailPositions[state.trailBodyCount - 1];
if (!at || !last) return null;
const metres = distance(last, at);
if (metres < 1 || metres > TRAIL_HEAD_MAX_M) return null;
return [last, { x: at.x, y: at.y, z: at.z }];
}
/**
* Each frame before it draws: the body moved on when the drawn time has
* passed a fix, then the head to where the vessel is drawn now.
*/
function drawSelectedVesselTrail() {
if (!state.trail || !state.trailId) return;
if (bodyCountAt(drawnTimeMs()) !== state.trailBodyCount) drawTrailBody();
state.trail.setHead?.(trailHeadPositions());
}
/**
* Fire-and-forget backfill from the server-side per-vessel ring buffer
* (PRD F3 — "recent path" since server boot, not voyage history). Older
@@ -112,7 +197,12 @@ export function createTracking({
* @returns {Promise<void>}
*/
async function backfillVesselTrail(id, token, reference = id) {
async function backfillVesselTrail(
id,
token,
reference = id,
{ replace = false } = {},
) {
const owner = state.trailAbort;
// Following the world clock, the track ends at the world's time.
const atMs = followsClock(vesselState) ? vesselState.worldNow() : undefined;
@@ -139,6 +229,7 @@ export function createTracking({
if (state.trailId !== id) return;
const older = [];
const olderTimes = [];
for (const sample of samples) {
const lat = Number(sample?.latitude);
const lon = Number(sample?.longitude);
@@ -156,16 +247,29 @@ export function createTracking({
TRAIL_HEIGHT_M,
);
older.push(fromDegrees(lon, lat, heightM));
}
if (!older.length) return;
state.trailPositions = older.concat(state.trailPositions);
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
state.trailPositions = state.trailPositions.slice(
state.trailPositions.length - TRAIL_MAX_POINTS,
olderTimes.push(
Number.isFinite(sample?.observedAtMs) ? sample.observedAtMs : NaN,
);
}
if (state.trail) state.trail.setPositions(state.trailPositions);
if (replace) {
// The track at the new time, then the vessel's own fix at it.
const record = state.selectedRecord;
const current = record?.id === id ? vesselTrailPosition(record) : null;
state.trailPositions = current ? [...older, current] : older;
state.trailTimes = current
? [...olderTimes, recordFixMs(record)]
: olderTimes;
} else {
if (!older.length) return;
state.trailPositions = older.concat(state.trailPositions);
state.trailTimes = olderTimes.concat(state.trailTimes);
}
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
const drop = state.trailPositions.length - TRAIL_MAX_POINTS;
state.trailPositions = state.trailPositions.slice(drop);
state.trailTimes = state.trailTimes.slice(drop);
}
drawTrailBody();
}
/**
@@ -181,9 +285,12 @@ export function createTracking({
const last = state.trailPositions[state.trailPositions.length - 1];
if (last && distance(last, next) <= TRAIL_MIN_MOVE_M) return;
state.trailPositions.push(next);
if (state.trailPositions.length > TRAIL_MAX_POINTS)
state.trailTimes.push(recordFixMs(record));
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
state.trailPositions.shift();
state.trail.setPositions(state.trailPositions);
state.trailTimes.shift();
}
drawTrailBody();
}
/**
@@ -196,6 +303,10 @@ export function createTracking({
state.trailBackfillToken += 1;
state.trailId = null;
state.trailPositions = [];
state.trailTimes = [];
state.trailBodyCount = -1;
state.trailHeadOff?.();
state.trailHeadOff = null;
if (state.trail) state.trail.clear();
}
@@ -215,6 +326,8 @@ export function createTracking({
vesselTrailPosition,
refloorVesselRecords,
startSelectedVesselTrail,
retimeSelectedVesselTrail,
drawSelectedVesselTrail,
backfillVesselTrail,
appendSelectedVesselTrailFix,
clearSelectedVesselTrail,
+134 -3
View File
@@ -5,10 +5,12 @@ import { createTracking } from './tracking.js';
import { TRAIL_HEIGHT_M, TRAIL_MAX_POINTS } from './policy.js';
/** One tracking part over a fake trail and geoid; `geoidN` is N everywhere. */
function setup({ geoidN = 40, track = null } = {}) {
function setup({ geoidN = 40, track = null, clockAt = null } = {}) {
const drawn = [];
const heads = [];
const trail = {
setPositions: (positions) => drawn.push([...positions]),
setHead: (positions) => heads.push(positions),
clear() {},
destroy() {},
};
@@ -16,7 +18,12 @@ function setup({ geoidN = 40, track = null } = {}) {
const records = [];
const vesselState = {
_geoidReady: true,
_source: { getTrack: async () => track },
_source: {
getTrack: async (reference, options) =>
typeof track === 'function' ? track(options) : track,
},
timeline: { active: () => clockAt !== null },
worldNow: () => clockAt,
state: {
viewer: {},
trail: null,
@@ -34,6 +41,17 @@ function setup({ geoidN = 40, track = null } = {}) {
},
rendering: {
getVisual: (record) => visuals.get(record) ?? record,
// Drawn where its visual says, at the trail's height in these tests.
drawnPositionNow: (record) => {
const visual = visuals.get(record);
return visual
? Cesium.Cartesian3.fromDegrees(
visual.drawnLon,
visual.drawnLat,
geoidN + TRAIL_HEIGHT_M,
)
: null;
},
anchorPosition: (record) => ({ anchoredAt: [record.lon, record.lat] }),
syncRecordIcon: (record) => synced.push(record),
forgetClockStep: () => synced.push('forgetClockStep'),
@@ -51,7 +69,16 @@ function setup({ geoidN = 40, track = null } = {}) {
layer: {},
options: {},
});
return { tracking, vesselState, drawn, synced, records, visuals, renders };
return {
tracking,
vesselState,
drawn,
heads,
synced,
records,
visuals,
renders,
};
}
const near = (a, b) =>
@@ -172,3 +199,107 @@ test('a long backfill keeps the newest TRAIL_MAX_POINTS vertices', async () => {
'the live fix stays newest',
);
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
const at = (lat, lon) =>
Cesium.Cartesian3.fromDegrees(lon, lat, 40 + TRAIL_HEIGHT_M);
test('following the clock, the trail ends at the vessel: fixes after its time wait, and a head joins the last one to it', async () => {
const T = 1_800_000_000_000;
const track = {
records: [
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
{ latitude: 51.81, longitude: 4.0, observedAtMs: T - 60_000 },
],
};
const { tracking, vesselState, drawn, heads, visuals } = setup({
track,
clockAt: T,
});
const record = {
id: 'v',
reference: 'v',
lat: 51.83,
lon: 4.0,
lastPositionEpoch: (T + 120_000) / 1000,
};
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.815, drawnLon: 4.0, drawnAtMs: T });
tracking.startSelectedVesselTrail(record);
await settle();
assert.equal(drawn.at(-1).length, 2, 'the fixes before the time');
assert.ok(near(drawn.at(-1)[1], at(51.81, 4.0)));
tracking.drawSelectedVesselTrail();
const head = heads.at(-1);
assert.ok(near(head[0], at(51.81, 4.0)), 'from the last drawn fix');
assert.ok(near(head[1], at(51.815, 4.0)), 'to the vessel as drawn');
// The clock passes the vessel's own fix: the body takes it on the next
// frame, and the vessel holds there.
vesselState.worldNow = () => T + 150_000;
visuals.get(record).drawnLat = 51.83;
tracking.drawSelectedVesselTrail();
assert.equal(drawn.at(-1).length, 3);
assert.equal(heads.at(-1), null, 'no head with the vessel on its fix');
});
test('a clock jump keeps the trail drawn to the new time until the track at it arrives', async () => {
const T = 1_800_000_000_000;
let release;
const later = new Promise((resolve) => (release = resolve));
let asked = 0;
const first = {
records: [
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
{ latitude: 51.81, longitude: 4.0, observedAtMs: T - 60_000 },
],
};
const { tracking, vesselState, drawn, visuals } = setup({
track: () => (asked++ === 0 ? first : later),
clockAt: T,
});
const record = {
id: 'v',
reference: 'v',
lat: 51.815,
lon: 4.0,
lastPositionEpoch: T / 1000,
};
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.815, drawnLon: 4.0, drawnAtMs: T });
tracking.startSelectedVesselTrail(record);
await settle();
const before = drawn.length;
// Back a minute and a half: one fix is behind the vessel then.
vesselState.worldNow = () => T - 90_000;
tracking.retimeSelectedVesselTrail(record);
assert.ok(
drawn.slice(before).every((positions) => positions.length >= 1),
'never blanked',
);
assert.equal(drawn.at(-1).length, 1, 'cut to the new time');
release({
records: [
{ latitude: 51.79, longitude: 4.0, observedAtMs: T - 180_000 },
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
],
});
await settle();
assert.equal(drawn.at(-1).length, 2, 'the track at the new time');
assert.ok(near(drawn.at(-1)[0], at(51.79, 4.0)));
});
test('live, the head joins the last fix to the vessel where it is placed, and not across a jump', () => {
const { tracking, vesselState, heads, visuals } = setup();
const record = { id: 'v', reference: 'v', lat: 51.8, lon: 4.0 };
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.801, drawnLon: 4.0 });
tracking.startSelectedVesselTrail(record);
tracking.drawSelectedVesselTrail();
assert.ok(near(heads.at(-1)[0], at(51.8, 4.0)));
assert.ok(near(heads.at(-1)[1], at(51.801, 4.0)));
// Drawn 100 km on: no head across that.
visuals.get(record).drawnLat = 52.7;
tracking.drawSelectedVesselTrail();
assert.equal(heads.at(-1), null);
});