Merge upstream main into pr/street-level-show-action

Locale conflicts: main's catalogs plus the PR's 10 street-level strings.
This commit is contained in:
Said Turksever committed 2026-11-09 00:11:38 +00:00
commit b7531e655d
84 files changed
+7506 -244

No files matched your search

+3
View File
@@ -67,6 +67,9 @@ export function createOrbitRendering({
return Boolean(
layerState._enabled &&
layerState._dataSource?.show &&
!layerState.launchHidden(
layerState._missionOverlayRecords.get(launchId)?.launch,
) &&
(!layerState._selectedLaunchId ||
layerState._selectedLaunchId === launchId),
);
+4 -1
View File
@@ -411,8 +411,11 @@ export function createOverlays({ state: layerState, services, parts, source }) {
false,
);
layerState._selectedMissionOverlayTimeText = null;
const records = [...layerState._missionOverlayRecords.values()].filter(
(record) => !layerState.launchHidden(record.launch),
);
const entries = selectRocketMissionMarkerOverlayCohort(
Array.from(layerState._missionOverlayRecords.values(), (record) => {
records.map((record) => {
const entry = createRocketMissionMarkerOverlayEntry(
record.launch,
record.anchorPosition,
+37 -10
View File
@@ -22,6 +22,25 @@ export function createRendering({
if (current !== next) graphic.show = next;
}
// Away from live, a launch shows from its lift-off on, so scrubbing the
// world time forward brings the launches up in the order they flew. The
// selected mission stays, whenever it flies.
function syncPendingLaunches() {
const pending = new Set();
for (const { launch } of layerState._missionOverlayRecords.values()) {
if (layerState.launchHidden(launch)) pending.add(launch.id);
}
const previous = layerState._pendingLaunchIds;
if (
pending.size === previous.size &&
[...pending].every((id) => previous.has(id))
)
return;
layerState._pendingLaunchIds = pending;
parts.overlays.syncMissionOverlayEntries();
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
}
function updateMissionFrame() {
if (
!layerState._enabled ||
@@ -31,6 +50,7 @@ export function createRendering({
parts.overlays.hideReplayVehicleOverlay();
return;
}
syncPendingLaunches();
parts.panel.updateMissionTelemetry();
const time = Cesium.JulianDate.now(layerState._declutterTime);
layerState._declutterOccluder.cameraPosition =
@@ -39,21 +59,28 @@ export function createRendering({
parts.overlays.refreshSelectedMissionOverlayText();
for (const entity of layerState._dataSource.entities.values) {
if (!entity.show) continue;
if (!entity.position) continue;
const id = parts.selection.entityLaunchId(entity);
if (!id) continue;
const pending = layerState._pendingLaunchIds.has(id);
if (entity.polyline)
setGraphicVisibility(entity.polyline, !pending, time);
if (!entity.position) continue;
const position = entity.position.getValue(time);
let horizonVisible = Boolean(
position && layerState._declutterOccluder.isPointVisible(position),
);
let horizonVisible =
!pending &&
Boolean(
position && layerState._declutterOccluder.isPointVisible(position),
);
const launchAnchor = entity.id.startsWith('rocket-launch:');
if (launchAnchor) {
horizonVisible = parts.overlays.missionAnchorVisible(
layerState._viewer.scene.camera.positionWC,
position,
id,
layerState._selectedLaunchId,
);
horizonVisible =
!pending &&
parts.overlays.missionAnchorVisible(
layerState._viewer.scene.camera.positionWC,
position,
id,
layerState._selectedLaunchId,
);
// Keep entity.show reserved for mission-selection isolation. Horizon
// state is applied to the individual graphics below so a rear-side
// anchor remains eligible for reevaluation as the camera moves.
+20
View File
@@ -169,6 +169,26 @@ export function createState({ services }) {
state.coverageChanged = () => worldClock.coverageChanged();
/**
* Whether a launch has yet to lift off at the world time. While live none
* has, so the layer shows every launch in its window as it always did.
*/
state.launchPending = (launch) => {
if (worldClock.isLive()) return false;
const launchMs = Date.parse(launch?.launchTime);
return Number.isFinite(launchMs) && launchMs > state.now();
};
/** Whether a launch is hidden for lifting off after the world time. */
state.launchHidden = (launch) =>
launch?.id !== state._selectedLaunchId && state.launchPending(launch);
/** The launches hidden at the last frame, by id, to spot a change. */
state._pendingLaunchIds = new Set();
state._missionOrbitPatternRegistered = false;
state._pathDistanceCache = new WeakMap();
+102
View File
@@ -0,0 +1,102 @@
// Away from live, a launch shows from its lift-off on, so scrubbing the world
// time brings the launches up in the order they flew.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { worldClock } from '../../time/worldClock.js';
import { createState } from './state.js';
import { createRendering } from './rendering.js';
import { createSelection } from './selection.js';
const noop = () => {};
const LAUNCH_MS = Date.UTC(2026, 9, 20, 12);
function scene(t) {
t.after(() => worldClock.goLive());
const state = createState({
services: {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
},
});
const launch = {
id: 'ceres-1',
launchTime: new Date(LAUNCH_MS).toISOString(),
};
state._enabled = true;
state._dataSource = new Cesium.CustomDataSource('launches');
state._viewer = {
scene: { camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) } },
};
state._missionOverlayRecords.set(launch.id, { launch });
const position = Cesium.Cartesian3.fromDegrees(0, 0);
const anchor = state._dataSource.entities.add({
id: `rocket-launch:${launch.id}`,
position,
point: { pixelSize: 5 },
});
const path = state._dataSource.entities.add({
id: `rocket-transfer:${launch.id}`,
polyline: { positions: [position, Cesium.Cartesian3.fromDegrees(1, 1)] },
});
const syncs = { labels: 0, orbits: 0 };
const parts = {
panel: { updateMissionTelemetry: noop },
overlays: {
hideReplayVehicleOverlay: noop,
updateReplayVehicleOverlay: noop,
refreshSelectedMissionOverlayText: noop,
missionAnchorVisible: () => true,
syncMissionOverlayEntries: () => syncs.labels++,
},
orbitRendering: {
syncMissionOrbitPrimitiveVisibility: () => syncs.orbits++,
},
};
const services = {
geometry: { getKeyholeGeometry: noop },
satellites: {},
};
parts.selection = createSelection({ state, services, parts });
const rendering = createRendering({ state, services, parts });
const shown = () => {
rendering.updateMissionFrame();
const time = Cesium.JulianDate.now();
return {
marker: anchor.point.show.getValue(time),
path: path.polyline.show?.getValue(time) ?? true,
};
};
return { state, launch, syncs, shown };
}
test('live shows every launch in the window, lifted off or not', (t) => {
const { state, launch, shown } = scene(t);
assert.equal(state.launchPending(launch), false);
assert.deepEqual(shown(), { marker: true, path: true });
});
test('away from live a launch shows from its lift-off on', (t) => {
const { state, launch, syncs, shown } = scene(t);
worldClock.seek(LAUNCH_MS - 60_000);
assert.equal(state.launchPending(launch), true);
assert.deepEqual(shown(), { marker: false, path: false });
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'its label and orbit go');
shown();
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'once, not each frame');
worldClock.seek(LAUNCH_MS);
assert.equal(state.launchPending(launch), false);
assert.deepEqual(shown(), { marker: true, path: true });
assert.deepEqual(syncs, { labels: 2, orbits: 2 });
});
test('the selected mission stays whenever it flies', (t) => {
const { state, launch, shown } = scene(t);
state._selectedLaunchId = launch.id;
worldClock.seek(LAUNCH_MS - 60_000);
assert.deepEqual(shown(), { marker: true, path: true });
});
+142
View File
@@ -0,0 +1,142 @@
/**
* The selected vessel as a Cockpit bridge subject: identity, motion, its
* displayed type and a representative bridge eye height from the AIS type.
* The Cockpit owns camera placement; this module owns what AIS says.
*/
import { normalizeVesselType } from '../../data/vesselTypes.js';
import { displayVesselType } from '../../data/vesselLabels.js';
/** The layer id a vessel subject carries through Cockpit events and state. */
export const VESSEL_COCKPIT_LAYER_ID = 'ais-live-vessels';
/** Knots to metres per second, as the AIS source uses. */
const KNOTS_TO_MPS = 0.514444;
/**
* Bridge eye height above the waterline by normalized AIS type family. AIS
* reports no hull height, so these are representative values: deep-sea
* cargo and tanker bridges, passenger and cruise ship bridges, harbour
* craft, small craft. River and harbour ferries, matched by name in the
* patterns below, sit low. Text types from non-numeric feeds fall through
* to the patterns.
*/
const EYE_HEIGHT_BY_FAMILY = Object.freeze({
CARGO: 30,
TANKER: 30,
PASSENGER: 25,
MILITARY: 18,
'HIGH-SPEED': 8,
DREDGER: 10,
TOWING: 7,
TUG: 7,
PILOT: 6,
SAR: 6,
'PORT TENDER': 6,
'ANTI-POLLUTION': 7,
'LAW ENFORCE': 7,
MEDICAL: 7,
'DIVE OPS': 5,
FISHING: 6,
SAILING: 3,
PLEASURE: 3,
// AIS "Other" (90-99) is mostly small craft such as river boats. Only
// that type takes it (see isAisOther).
OTHER: 4,
});
const EYE_HEIGHT_PATTERNS = Object.freeze([
{ pattern: /tanker|cargo|container|bulk|carrier/i, heightM: 30 },
{ pattern: /passenger|cruise|ro-?ro/i, heightM: 25 },
// River and harbour ferries: a low wheelhouse just above the water.
{ pattern: /ferry/i, heightM: 4 },
{ pattern: /tug|tow|pilot|supply|service/i, heightM: 7 },
{ pattern: /fishing|trawler/i, heightM: 6 },
{ pattern: /sail|pleasure|yacht/i, heightM: 3 },
]);
/**
* Whether a raw type is AIS "Other" proper: codes 90 to 99, or a feed's text
* type. normalizeVesselType also files the reserved, wing-in-ground and
* spare codes (1-29, 38-39, 56-57, 59) under OTHER, but they name no family.
*/
function isAisOther(type) {
const text = String(type ?? '').trim();
if (!/^\d+$/.test(text)) return true;
const code = Number(text);
return code >= 90 && code <= 99;
}
/**
* Representative bridge eye height for an AIS vessel type.
* @param {string|number} type Raw AIS type: a numeric code or feed text.
* @returns {number|null} Metres above the waterline, or null when the type
* names no known family (the Cockpit then uses its default).
*/
export function vesselEyeHeightM(type) {
const family = normalizeVesselType(type).toUpperCase();
if (family === 'OTHER' && !isAisOther(type)) return null;
if (Object.hasOwn(EYE_HEIGHT_BY_FAMILY, family))
return EYE_HEIGHT_BY_FAMILY[family];
const matched = EYE_HEIGHT_PATTERNS.find((entry) =>
entry.pattern.test(family),
);
return matched ? matched.heightM : null;
}
function finiteOrNull(value) {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
}
/**
* Normalize a selected vessel record into Cockpit subject info.
*
* `track` is where the camera looks and `motionCourse` is where the hull
* moves: a ship faces its true heading while current and wind set it along
* its course over ground. Either falls back to the other when one is missing.
* @param {object|null} record Vessel record from the vessel layer.
* @returns {object|null} Subject info, or null without a usable fix.
*/
export function vesselCockpitInfo(record) {
if (!record?.mmsi) return null;
const latitude = Number(record.lat);
const longitude = Number(record.lon);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
const heading = finiteOrNull(record.heading);
const course = finiteOrNull(record.course);
const speedKt = finiteOrNull(record.speed);
const epochSec = finiteOrNull(record.lastPositionEpoch);
const feedEpochSec = finiteOrNull(record.fixFeedEpoch);
return {
kind: 'vessel',
layerId: VESSEL_COCKPIT_LAYER_ID,
id: String(record.mmsi),
mmsi: String(record.mmsi),
name: String(record.name || record.mmsi),
type: String(record.type || ''),
typeLabel: displayVesselType(record.type),
destination: String(record.destination || '').trim(),
latitude,
longitude,
heading,
course,
speedKt,
velocityMps: speedKt === null ? null : Math.max(0, speedKt) * KNOTS_TO_MPS,
track: heading ?? course,
// What `track` is: the true heading, or course over ground standing in
// for a ship that reports none. The HUD says which.
trackSource:
heading !== null ? 'heading' : course !== null ? 'course' : null,
motionCourse: course ?? heading,
fixEpochMs: epochSec === null ? null : epochSec * 1000,
// When this client first received the fix (its own clock) and the
// newest fix in that refresh (the feed's clock): the fix's age without
// clock skew, still ageing while the feed re-serves it.
receivedAtMs: finiteOrNull(record.fixReceivedAtMs),
feedEpochMs: feedEpochSec === null ? null : feedEpochSec * 1000,
eyeHeightM: vesselEyeHeightM(record.type),
stale: (record.missedRefreshes || 0) > 0,
onGround: false,
};
}
+113
View File
@@ -0,0 +1,113 @@
// src/layers/vessels/cockpitSubject.test.mjs — bridge eye heights by AIS
// type and the selected vessel as Cockpit subject info.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
VESSEL_COCKPIT_LAYER_ID,
vesselCockpitInfo,
vesselEyeHeightM,
} from './cockpitSubject.js';
test('bridge eye height follows the AIS type family', () => {
assert.equal(vesselEyeHeightM('71'), 30, 'cargo');
assert.equal(vesselEyeHeightM('84'), 30, 'tanker');
assert.equal(vesselEyeHeightM('60'), 25, 'passenger');
assert.equal(vesselEyeHeightM('52'), 7, 'tug');
assert.equal(vesselEyeHeightM('30'), 6, 'fishing');
assert.equal(vesselEyeHeightM('37'), 3, 'pleasure');
assert.equal(vesselEyeHeightM('36'), 3, 'sailing');
});
test('text vessel types resolve through the same families', () => {
assert.equal(vesselEyeHeightM('Container Ship'), 30);
assert.equal(vesselEyeHeightM('Cruise ship'), 25);
assert.equal(vesselEyeHeightM('Ferry'), 4);
assert.equal(vesselEyeHeightM(99), 4, 'AIS Other');
assert.equal(vesselEyeHeightM('90'), 4, 'AIS Other');
assert.equal(vesselEyeHeightM('Other'), 4, 'a feed text type Other');
assert.equal(vesselEyeHeightM('Yacht'), 3);
});
test('codes filed under OTHER that are not AIS Other keep the default', () => {
// Reserved (1-19), wing in ground (20-29), reserved (38-39), spare
// (56-57) and local (59) codes name no family.
for (const type of ['1', '19', '20', '29', '38', '39', '56', '57', '59'])
assert.equal(vesselEyeHeightM(type), null, type);
});
test('an unknown or missing type has no eye height of its own', () => {
for (const type of ['', '0', '255', 'Research vessel', null]) {
assert.equal(vesselEyeHeightM(type), null, String(type));
}
});
test('vessel info faces the true heading and moves along course over ground', () => {
const info = vesselCockpitInfo({
mmsi: '211000000',
name: 'NORDIC STAR',
type: '70',
destination: ' KIEL ',
lat: 54.5,
lon: 10.2,
speed: 12,
course: 95,
heading: 90,
lastPositionEpoch: 1_700_000_000,
missedRefreshes: 0,
});
assert.equal(info.kind, 'vessel');
assert.equal(info.layerId, VESSEL_COCKPIT_LAYER_ID);
assert.equal(info.id, '211000000');
assert.equal(info.typeLabel, 'CARGO');
assert.equal(info.track, 90);
assert.equal(info.motionCourse, 95);
assert.equal(info.destination, 'KIEL');
assert.equal(info.eyeHeightM, 30);
assert.equal(info.fixEpochMs, 1_700_000_000_000);
assert.ok(Math.abs(info.velocityMps - 12 * 0.514444) < 1e-9);
assert.equal(info.stale, false);
assert.equal(info.onGround, false);
});
test('a missing heading or course falls back to the other', () => {
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
assert.equal(vesselCockpitInfo({ ...base, course: 40 }).track, 40);
assert.equal(vesselCockpitInfo({ ...base, heading: 50 }).motionCourse, 50);
const neither = vesselCockpitInfo(base);
assert.equal(neither.track, null);
assert.equal(neither.motionCourse, null);
});
test('the subject says whether its track is the heading or the course', () => {
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
assert.equal(
vesselCockpitInfo({ ...base, heading: 50, course: 40 }).trackSource,
'heading',
);
assert.equal(
vesselCockpitInfo({ ...base, course: 40 }).trackSource,
'course',
);
// A heading of 0 is due north, not a missing heading.
assert.equal(
vesselCockpitInfo({ ...base, heading: 0 }).trackSource,
'heading',
);
assert.equal(vesselCockpitInfo(base).trackSource, null);
});
test('a vessel without identity or position is not a subject', () => {
assert.equal(vesselCockpitInfo(null), null);
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
assert.equal(vesselCockpitInfo({ mmsi: '1', lat: 'x', lon: 1 }), null);
});
test('a vessel missing from recent refreshes reads as stale', () => {
const info = vesselCockpitInfo({
mmsi: '1',
lat: 1,
lon: 1,
missedRefreshes: 2,
});
assert.equal(info.stale, true);
});
+106
View File
@@ -1,5 +1,8 @@
import * as Cesium from 'cesium';
import { t, msg } from '../../i18n/index.js';
import { vesselCockpitInfo } from './cockpitSubject.js';
import { vesselTypeCss } from '../../data/vesselLabels.js';
import { greatCircleMeters } from '../../geoDistance.js';
// ingestion.js is a portable export (package.json) and writes English labels
// into state; translate the known ones here, pass anything else through.
@@ -20,6 +23,7 @@ import {
AIS_STATUS_REASON,
REFRESH_MS,
FOCUS_EVIDENCE_DEV,
VESSEL_LIFT_M,
} from './policy.js';
export function createQueries({
@@ -346,6 +350,59 @@ export function createQueries({
return entries.slice(0, cap);
},
/**
* Vessels around a point for the Cockpit bridge radar, nearest first.
* The ship whose bridge the Cockpit occupies is left out. Distances are
* great-circle from the AIS positions, so no rendered visual is needed.
* @param {number} lat Latitude of the centre, degrees.
* @param {number} lon Longitude of the centre, degrees.
* @param {number} rangeM Max distance in metres.
* @param {number} [maxCount=60] Maximum entries to return.
* @returns {Array<{ id: string, name: string, latitude: number,
* longitude: number, course: number|null, heading: number|null,
* type: string, color: string, stale: boolean }>} Empty while the
* layer is off. A ship with no MMSI has an `unkeyed:` id.
*/
getRadarContacts(lat, lon, rangeM, maxCount = 60) {
const records = state.records.all;
if (!state.feed.enabled || !Array.isArray(records) || !records.length)
return [];
if (!Number.isFinite(rangeM) || rangeM <= 0) return [];
const cap =
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 60;
const center = { lat, lon };
const subject = state.cockpitSubjectMmsi;
const finite = (value) => {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
const entries = [];
records.forEach((record, index) => {
if (subject && String(record.mmsi) === subject) return;
const distanceM = greatCircleMeters(center, {
lat: record.lat,
lon: record.lon,
});
if (!(distanceM <= rangeM)) return;
entries.push({ record, index, distanceM });
});
entries.sort((a, b) => a.distanceM - b.distanceM);
return entries.slice(0, cap).map(({ record, index }) => ({
// A ship with no MMSI still needs a key of its own on the scope.
id: record.mmsi ? String(record.mmsi) : `unkeyed:${index}`,
name: String(record.name || record.mmsi || ''),
latitude: record.lat,
longitude: record.lon,
course: finite(record.course),
heading: finite(record.heading),
type: String(record.type || ''),
color: vesselTypeCss(record.type),
stale: (record.missedRefreshes || 0) > 0,
}));
},
/**
* Get positions of all currently loaded vessels.
* @param {number} [maxCount=800] Maximum entries to return.
@@ -462,6 +519,55 @@ export function createQueries({
};
},
/**
* Describe the selected vessel for the Cockpit bridge view.
* @returns {object|null} `vesselCockpitInfo` fields plus `seaSurfaceHeightM`
* (the local geoid height the sprite datum uses) and `markHeightM` (the
* height the sprite is drawn at), or null when the layer is off or
* nothing is selected.
*/
getCockpitSubject() {
if (!state.feed.enabled) return null;
const info = vesselCockpitInfo(state.selectedRecord);
if (!info) return null;
const geoidN = components.tracking.currentGeoidN(
info.latitude,
info.longitude,
);
return {
...info,
seaSurfaceHeightM: vesselDatumHeightM(geoidN, 0),
markHeightM: vesselDatumHeightM(geoidN, VESSEL_LIFT_M),
};
},
/**
* Mark the vessel whose bridge the Cockpit camera occupies, or release it.
* Its sprite, card and detection bracket stay hidden while it is held.
* @param {string|number|null} mmsi Subject MMSI, or null to release.
* @returns {boolean} Always true.
*/
setCockpitSubject(mmsi) {
const next = normalizeSelectionMmsi(mmsi);
if (state.cockpitSubjectMmsi === next) return true;
state.cockpitSubjectMmsi = next;
// The ridden ship's trail runs from under the eye: hidden, its history
// kept, while the bridge holds the ship it belongs to.
state.trail?.setVisible?.(!next || next !== state.trailMmsi);
components.rendering.updateVisibility(true);
return true;
},
/**
* Return the camera to the selected vessel's map view, as a click on it does.
* @returns {boolean} True when a selected vessel took the camera.
*/
focusSelectedVessel() {
const record = state.selectedRecord;
if (!record || !state.feed.enabled) return false;
return components.selection.selectAndFocusVessel(record);
},
/**
* Return a subset of vessels for the universal detection overlay.
* Deterministic stride sampling distributes selections evenly across the
+148
View File
@@ -0,0 +1,148 @@
// src/layers/vessels/radarContacts.test.mjs — the vessels the Cockpit bridge
// radar draws: within range, nearest first, without the ship it rides; and
// the ridden ship's own trail, hidden while the bridge holds it.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { vesselTypeCss } from '../../data/vesselLabels.js';
const noop = () => {};
function services() {
return {
context: {
clearSelectedEntityContextForLayer: noop,
registerEntityContext: () => null,
},
trails: {
createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }),
},
labels: {},
picking: { unregisterPickOwner: noop },
overlay: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
geoid: {},
sprites: {},
focus: {
focusNowMs: (now) => now,
getFocusTarget: () => null,
focusPassIsNeeded: () => false,
forgetSpriteFocus: noop,
},
worldFocus: {},
render: {
holdContinuousRender: noop,
releaseContinuousRender: noop,
governorRequestRender: noop,
},
};
}
/** A vessel `northNm` nautical miles north of 54.5°N 10.2°E. */
function record(mmsi, northNm, extra = {}) {
return {
mmsi,
name: `SHIP ${mmsi}`,
type: '70',
lat: 54.5 + northNm / 60,
lon: 10.2,
speed: 10,
course: 45,
heading: 40,
missedRefreshes: 0,
...extra,
};
}
function layerWith(records, options = {}) {
const layer = createVesselLayer({
source: { getSnapshot: noop },
services: services(),
});
layer.testing._setVesselStateForTest({
viewer: {},
records,
billboardCollection: { add: (entry) => ({ ...entry }), remove: noop },
...options,
});
return layer;
}
test('radar contacts are within range, nearest first and capped', () => {
const layer = layerWith([
record('3', 5),
record('1', 1),
record('far', 20),
record('2', 3, { course: null, heading: '', missedRefreshes: 2 }),
]);
const contacts = layer.getRadarContacts(54.5, 10.2, 6 * 1852, 60);
assert.deepEqual(
contacts.map((entry) => entry.id),
['1', '2', '3'],
);
assert.deepEqual(contacts[0], {
id: '1',
name: 'SHIP 1',
latitude: 54.5 + 1 / 60,
longitude: 10.2,
course: 45,
heading: 40,
type: '70',
color: vesselTypeCss('70'),
stale: false,
});
assert.equal(contacts[1].course, null);
assert.equal(contacts[1].heading, null);
assert.equal(contacts[1].stale, true);
assert.deepEqual(
layer.getRadarContacts(54.5, 10.2, 6 * 1852, 2).map((entry) => entry.id),
['1', '2'],
);
});
test('the ship whose bridge the Cockpit rides is not its own contact', () => {
const layer = layerWith([record('own', 0), record('other', 2)]);
layer.setCockpitSubject('own');
assert.deepEqual(
layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((entry) => entry.id),
['other'],
);
layer.setCockpitSubject(null);
assert.equal(layer.getRadarContacts(54.5, 10.2, 6 * 1852).length, 2);
});
test('ships with no MMSI each keep a key of their own', () => {
const layer = layerWith([
record('', 1, { name: 'A' }),
record('', 2, { name: 'B' }),
]);
const ids = layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((c) => c.id);
assert.equal(ids.length, 2);
assert.equal(new Set(ids).size, 2, ids.join(', '));
assert.ok(ids.every((id) => id.startsWith('unkeyed:')));
});
test("the ridden ship's trail is hidden while the bridge holds it", () => {
const shown = [];
const trail = {
setPositions() {},
clear() {},
destroy() {},
setVisible: (visible) => shown.push(visible),
};
const layer = layerWith([record('own', 0), record('other', 2)], {
trail,
trailMmsi: 'own',
});
layer.setCockpitSubject('own');
assert.deepEqual(shown, [false]);
layer.setCockpitSubject(null);
assert.deepEqual(shown, [false, true]);
});
test('a disabled layer has no radar contacts', () => {
const layer = layerWith([record('1', 1)], { enabled: false });
assert.deepEqual(layer.getRadarContacts(54.5, 10.2, 6 * 1852), []);
});
+31
View File
@@ -26,6 +26,18 @@ export function normalizeVessel(row) {
};
}
/**
* Note when a fix was first received (`fixReceivedAtMs`, this client's
* clock) and the newest fix in that refresh (`fixFeedEpoch`, the feed's
* clock): its age is then read on each clock separately, so neither a
* skewed client clock nor a re-served cached row hides how old it is.
* `receivedAtMs` stays the time the row was last seen, for retention.
*/
function stampFix(record, receivedAtMs, feedLatestEpoch) {
record.fixReceivedAtMs = receivedAtMs;
record.fixFeedEpoch = feedLatestEpoch;
}
function finiteNumber(value) {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
@@ -46,6 +58,18 @@ export class VesselRecords {
effects,
) {
const receivedAtMs = this.now();
// The newest fix in the batch: the feed's own "now", so a fix's age can
// be read on the feed's clock rather than against this client's (see
// stampFix).
let feedLatestEpoch = null;
for (const row of rows) {
const epoch = finiteNumber(row?.last_position_epoch);
if (
epoch !== null &&
(feedLatestEpoch === null || epoch > feedLatestEpoch)
)
feedLatestEpoch = epoch;
}
for (const record of this.unkeyed) effects.remove(record, false);
this.unkeyed = [];
const seen = new Set();
@@ -53,6 +77,7 @@ export class VesselRecords {
const next = normalizeVessel(row);
if (!next) continue;
next.receivedAtMs = receivedAtMs;
stampFix(next, receivedAtMs, feedLatestEpoch);
if (!next.mmsi) {
effects.add(next);
this.unkeyed.push(next);
@@ -63,6 +88,12 @@ export class VesselRecords {
const record = this.byMmsi.get(next.mmsi);
if (record) {
const before = effects.beforeUpdate(record);
// A feed re-serving a cached row repeats its fix: the fix keeps the
// time it was first received, so it goes on ageing.
if (next.lastPositionEpoch !== record.lastPositionEpoch) {
record.fixReceivedAtMs = next.fixReceivedAtMs;
record.fixFeedEpoch = next.fixFeedEpoch;
}
record.reference = next.reference;
record.receivedAtMs = next.receivedAtMs;
record.lat = next.lat;
+30
View File
@@ -111,3 +111,33 @@ test('unkeyed records rebuild on each refresh and numeric coercion keeps unknown
assert.equal(probe.store.all.length, 1);
assert.equal(normalizeVessel(row('bad', { lon: Infinity })), null);
});
test("each fix keeps when it was first received and its refresh's newest fix", () => {
const probe = setup();
probe.reconcile([
row('111', { last_position_epoch: 1_800_000_000 }),
row('222', { last_position_epoch: 1_800_000_030 }),
row('333'),
]);
for (const mmsi of ['111', '222', '333']) {
const record = probe.store.byMmsi.get(mmsi);
assert.equal(record.fixFeedEpoch, 1_800_000_030, mmsi);
assert.equal(record.fixReceivedAtMs, 1000, mmsi);
}
// A new fix is stamped afresh.
probe.advance(60_000);
probe.reconcile([row('111', { last_position_epoch: 1_800_000_050 })]);
const record = probe.store.byMmsi.get('111');
assert.equal(record.fixFeedEpoch, 1_800_000_050);
assert.equal(record.fixReceivedAtMs, 61_000);
// The same fix re-served by later polls keeps its first receipt, while
// the row itself counts as seen for retention.
probe.advance(30_000);
probe.reconcile([
row('111', { last_position_epoch: 1_800_000_050 }),
row('222', { last_position_epoch: 1_800_000_090 }),
]);
assert.equal(record.fixReceivedAtMs, 61_000);
assert.equal(record.fixFeedEpoch, 1_800_000_050);
assert.equal(record.receivedAtMs, 91_000);
});
+9 -3
View File
@@ -286,7 +286,9 @@ export function createRendering({
const visual = getVisual(record);
const visible = isVisible(visual.surfacePosition, occluder);
if (visual.billboard) {
visual.billboard.show = visible;
// The bridge camera sits on this sprite; showing it would fill the view.
visual.billboard.show =
visible && record.mmsi !== state.cockpitSubjectMmsi;
if (visible && doRotations && scene) {
const rot = screenProjectedRotation(
scene,
@@ -422,7 +424,11 @@ export function createRendering({
const viewer = state.viewer;
const scene = viewer?.scene;
const selected = state.selectedRecord;
const entries = selected
// From the bridge, the selected vessel is the viewer; its card would be
// pinned to the camera position.
const selectedCarded =
selected && selected.mmsi !== state.cockpitSubjectMmsi;
const entries = selectedCarded
? [components.cards.buildSelectedVesselCard(selected)]
: [];
const maxLabels = labelRowLimit();
@@ -458,7 +464,7 @@ export function createRendering({
// Greedy min-separation pass over the priority-ranked cell winners: the
// selected card's anchor seeds the accepted set so ambient cards keep clear.
const accepted = [];
if (selected) {
if (selectedCarded) {
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
getVisual(selected).billboard?.position || getVisual(selected).position,
+3
View File
@@ -37,6 +37,9 @@ export function createSelection({
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (!state.feed.enabled) return;
// The bridge view owns the selection: a click on open water must not
// deselect the vessel the camera is riding.
if (state.cockpitSubjectMmsi) return;
const picked = pickContact
? pickContact(viewer.scene, click.position)
: viewer.scene.pick(click.position);
+2
View File
@@ -72,6 +72,8 @@ export function createVesselState({ source, services }) {
activeFocusCount: 0,
activeLabelCount: 0,
selectedRecord: null,
/** @type {string|null} MMSI whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
cockpitSubjectMmsi: null,
/** @type {{setPositions: Function, clear: Function, destroy: Function}|null} Selected-vessel fading trail */
trail: null,
/** @type {Cesium.Cartesian3[]} Chronological trail vertices (oldest first) */
+94 -4
View File
@@ -4,6 +4,15 @@ export const RADAR_MAX_GAP_MS = 30 * 60_000;
export const REGIONAL_INFRARED_MAX_GAP_MS = 30 * 60_000;
export const GLOBAL_INFRARED_MAX_GAP_MS = 3 * 60 * 60_000;
export const LIGHTNING_MAX_GAP_MS = 30 * 60_000;
/** The longest play waits on a frame before it goes on without it. */
export const PLAY_WAIT_MS = 8_000;
// Playing on its own, the world does not wait on the frame it is at: that
// frame loads as play goes on. Play holds only at the next frame while the
// one before it still loads, then goes on to it once it shows, so every frame
// shows, play stops only for a load that is slow, and a frame loaded ahead
// costs play nothing.
let clocks = 0;
/**
* Transient observed time. Products must honor the signal before installing a
@@ -33,6 +42,34 @@ export function createWeatherClock({
let generation = 0;
let timer = null;
let pending = null;
// This clock's name on the world, for its holds and its gate.
const holdId = `weather:${++clocks}`;
// While the world plays, the hold on it at the next frame as the one before
// it loads, and the timer that lets play go on should that frame never
// come; and whether the move to the next frame waits on it.
let waiting = null;
let waitTimer = null;
let deferred = false;
const stopWaiting = () => {
const release = waiting;
waiting = null;
if (waitTimer !== null) clearTimeout(waitTimer);
waitTimer = null;
release?.();
};
const startWaiting = () => {
if (waiting || destroyed || !registry.size) return;
waiting = world.wait(holdId);
waitTimer = setTimeout(() => {
waitTimer = null;
stopWaiting();
// The frame that never came gives way to the one play is at.
if (deferred) void transition();
}, PLAY_WAIT_MS);
};
// Playing on its own, the world waits for frames as they load.
const worldPlaysOn = (state = world.getState()) =>
state.playing && !state.live && !state.stepping;
let destroyed = false;
const timesFor = (product) =>
[...new Set(product.getTimes())]
@@ -65,6 +102,9 @@ export function createWeatherClock({
mode,
target,
playing,
// Frames come on one after another: this clock replays them, or the world
// plays on through them, so the next is worth loading ahead.
advancing: playing || worldPlaysOn(),
timeline: getTimeline(),
products: [...registry.values()].map(({ product }) => ({
id: product.id,
@@ -130,7 +170,10 @@ export function createWeatherClock({
cancelTimer();
const owner = ++generation;
if (!canPlay()) stopPlaying();
// A scrub drops what loads and moves on; play goes on as this loads.
applied = selections();
deferred = false;
stopWaiting();
for (const entry of registry.values()) entry.controller?.abort();
// Start all products together; a rejection must not skip the settle barrier.
const tasks = [...registry.values()].map((entry) => {
@@ -144,10 +187,13 @@ export function createWeatherClock({
});
const result = Promise.allSettled(tasks).then(() => {
if (destroyed || owner !== generation) return false;
stopWaiting();
pending = null;
if (!canPlay()) stopPlaying();
notify();
schedule();
// Play held at the next frame for this one goes on to it.
if (deferred) void transition();
return true;
});
pending = result;
@@ -269,8 +315,10 @@ export function createWeatherClock({
},
refresh() {
if (destroyed) return Promise.resolve(false);
// New frames, or products added or dropped.
// New frames, or products added or dropped, and with them the next.
world.coverageChanged();
gated = undefined;
gateNext(world.getState());
if (!canPlay()) {
stopPlaying();
cancelTimer();
@@ -289,6 +337,8 @@ export function createWeatherClock({
stopPlaying();
destroyed = true;
++generation;
stopWaiting();
world.gate(holdId, null);
cancelTimer();
unfollowWorld();
// The last weather clock leaves the world live, as a new one expects.
@@ -306,18 +356,58 @@ export function createWeatherClock({
// changes the mode or a product's frame.
function followWorld(state) {
if (destroyed) return;
gateNext(state);
// Play starting or stopping changes whether the next frame loads ahead.
const playsOn = worldPlaysOn(state);
const playChanged = playsOn !== playedOn;
playedOn = playsOn;
const nextMode = state.live ? 'latest' : 'history';
const nextTarget = state.live
? null
: new Date(Math.floor(state.timeMs)).toISOString();
const key = nextTarget ?? 'latest';
if (key === seen) return;
if (key === seen) {
if (playChanged) notify();
return;
}
seen = key;
const modeChanged = nextMode !== mode;
mode = nextMode;
target = nextTarget;
if (moving || modeChanged || selections() !== applied) void transition();
else notify();
if (!moving && !modeChanged && selections() === applied) {
// Back at the frame that loads, play need not hold for it.
if (deferred) {
deferred = false;
stopWaiting();
}
// Played through, the time moves each frame with nothing new to show:
// listeners hear of the frames as they change.
if (!playsOn || playChanged) notify();
return;
}
// Playing on into the next frame while the one before it loads, the
// world holds here until that one shows.
if (!moving && !modeChanged && pending && playsOn) {
deferred = true;
startWaiting();
notify();
return;
}
void transition();
}
// Playing on its own, the world stops at each next frame to load it rather
// than run past frames between its ticks.
let gated = null;
let playedOn = false;
function gateNext(state) {
const next = worldPlaysOn(state)
? (getTimeline()
.map((time) => Date.parse(time))
.find((time) => time > Math.floor(state.timeMs)) ?? null)
: null;
if (next === gated) return;
gated = next;
world.gate(holdId, next);
}
const unfollowWorld = world.subscribe(followWorld);
driver = world.attachDriver({
+214
View File
@@ -6,6 +6,7 @@ import {
REGIONAL_INFRARED_MAX_GAP_MS,
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
PLAY_WAIT_MS,
} from './clock.js';
import { createWorldClock } from '../../time/worldClock.js';
@@ -493,3 +494,216 @@ test('a clock destroyed while it registers a product lets go of it', (t) => {
assert.equal(world.coverage(), null);
assert.equal(world.getState().supported, false);
});
// A radar whose frames load only when the test says.
function slowRadar(minutes) {
const radar = product('radar', minutes);
radar.loads = [];
radar.apply = (selected, { signal }) =>
new Promise((resolve) => {
radar.loads.push({
selected,
signal,
done() {
radar.shown = selected;
resolve(true);
},
});
});
return radar;
}
test('play stops at the next frame, not past it, until it shows', async (t) => {
const { clock, world, tick } = harness(t);
const radar = slowRadar([0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(1)));
await flush();
radar.loads.at(-1).done();
await flush();
world.play({ rate: 3_600, continuous: true });
world.coverageChanged();
tick(1_000);
assert.equal(
world.now(),
Date.parse(time(10)),
'an hour on, but held at the frame',
);
});
test('playing, a frame loads as play goes on, and play holds at the next until it shows', async (t) => {
const { clock, world, tick } = harness(t);
const radar = slowRadar([0, 10, 20, 30]);
clock.register(radar);
world.seek(Date.parse(time(9)));
await flush();
radar.loads.at(-1).done();
await flush();
world.play({ rate: 60, continuous: true });
// Into the next frame (the page's frames tell of it): it loads as play goes on.
tick(2_000);
world.coverageChanged();
await flush();
assert.equal(radar.loads.at(-1).selected, time(10));
assert.equal(
world.getState().buffering,
false,
'no hold for the frame play is at',
);
// At the frame after while that one still loads, play holds there.
tick(10_000);
world.coverageChanged();
await flush();
assert.equal(world.now(), Date.parse(time(20)));
assert.equal(world.getState().buffering, true);
assert.equal(
radar.loads.at(-1).selected,
time(10),
'the frame before still loads',
);
tick(5_000);
assert.equal(world.now(), Date.parse(time(20)), 'held while it loads');
radar.loads.at(-1).done();
await flush();
assert.equal(
radar.loads.at(-1).selected,
time(20),
'and on to the next once it shows',
);
assert.equal(world.getState().buffering, false);
tick(1_000);
assert.equal(world.now(), Date.parse(time(20)) + 60_000);
// A scrub aborts what loads and loads where the hand is, with no wait.
world.pause();
world.seek(Date.parse(time(30)));
await flush();
const scrubbed = radar.loads.at(-1);
world.seek(Date.parse(time(0)));
await flush();
assert.equal(scrubbed.signal.aborted, true);
assert.equal(radar.loads.at(-1).selected, time(0));
assert.equal(world.getState().buffering, false);
});
test('a frame that never comes holds play only so long', async (t) => {
const { clock, world, tick } = harness(t);
const radar = slowRadar([0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(9)));
await flush();
radar.loads.at(-1).done();
await flush();
world.play({ rate: 60, continuous: true });
tick(2_000);
world.coverageChanged();
await flush();
tick(10_000);
world.coverageChanged();
await flush();
assert.equal(world.getState().buffering, true);
const stuck = radar.loads.at(-1);
tick(PLAY_WAIT_MS);
await flush();
assert.equal(world.getState().buffering, false, 'play goes on without it');
assert.equal(stuck.signal.aborted, true);
assert.equal(radar.loads.at(-1).selected, time(20), 'loading where play is');
});
test('held at the next frame, a scrub back to the one loading lets play go', async (t) => {
const { clock, world, tick } = harness(t);
const radar = slowRadar([0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(9)));
await flush();
radar.loads.at(-1).done();
await flush();
world.play({ rate: 60, continuous: true });
tick(2_000);
world.coverageChanged();
await flush();
tick(10_000);
world.coverageChanged();
await flush();
assert.equal(world.getState().buffering, true);
world.pause();
world.seek(Date.parse(time(11)));
await flush();
world.play({ rate: 60, continuous: true });
assert.equal(
world.getState().buffering,
false,
'no hold for the frame it is at',
);
const at = world.now();
tick(1_000);
assert.equal(world.now(), at + 60_000);
});
test('a frame in flight as play starts loads as it goes on; a refresh does not hold', async (t) => {
const { clock, world } = harness(t);
const radar = slowRadar([0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(5)));
await flush();
world.play({ continuous: true });
assert.equal(world.getState().buffering, false);
radar.loads.at(-1).done();
await flush();
void clock.refresh();
await flush();
assert.equal(world.getState().buffering, false, 'the same frames, no hold');
radar.loads.at(-1).done();
});
test('weather clocks sharing a world gate it each on their own', async (t) => {
let mono = 0;
const world = createWorldClock({
now: () => Date.parse(time(30)),
monotonicNow: () => mono,
setInterval: () => 0,
clearInterval() {},
});
const a = createWeatherClock({ world, now: () => Date.parse(time(30)) });
const b = createWeatherClock({ world, now: () => Date.parse(time(30)) });
t.after(() => {
a.destroy();
b.destroy();
});
a.register(product('radar', [0, 10]));
b.register(product('clouds', [0, 15]));
world.seek(Date.parse(time(1)));
await flush();
world.play({ rate: 3_600, continuous: true });
world.coverageChanged();
b.destroy();
world.coverageChanged();
mono += 1_000;
assert.equal(
world.now(),
Date.parse(time(10)),
'the other clock’s gate stays',
);
});
test('played through, listeners hear of frames as they change, and of play stopping', async (t) => {
const { clock, world, tick } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(1)));
await flush();
world.play({ rate: 60, continuous: true });
await flush();
const heard = [];
clock.subscribe((state) => heard.push(state));
// Seconds of world time within one frame: nothing new to show.
for (let i = 0; i < 5; i++) {
tick(100);
world.coverageChanged();
}
await flush();
assert.equal(heard.length, 0);
world.pause();
await flush();
assert.equal(heard.at(-1)?.advancing, false, 'heard play stop');
});
+3 -2
View File
@@ -109,7 +109,8 @@ export function createWeatherLayer({
const notify = () => listener?.();
const shownTime = () => (noFrame ? null : rendering?.getDiagnostics().time);
const unsubscribeClock = clock?.subscribe(() => {
if (!clock.getState().playing || suspended()) rendering?.cancelPrefetch?.();
if (!clock.getState().advancing || suspended())
rendering?.cancelPrefetch?.();
notify();
});
const observationDelayed = () =>
@@ -211,7 +212,7 @@ export function createWeatherLayer({
if (
!enabled ||
suspended() ||
!(clock ? clock.getState().playing : playing)
!(clock ? clock.getState().advancing : playing)
)
return;
const times = manifest?.times ?? [];