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

gevActions.test.mjs: keep the PR's street-level tests and main's analyst display tests.
This commit is contained in:
Said Turksever committed 2026-11-10 14:59:39 +00:00
commit 5370b8a268
258 files changed
+20257 -734

No files matched your search

+2 -1
View File
@@ -1,7 +1,8 @@
import { normalizeDisplayText } from '../../data/displayText.js';
import { QUERY_LIMIT, QUERY_SNAP_DEGREES } from './policy.js';
function textTag(value) {
const t = String(value ?? '').trim();
const t = normalizeDisplayText(value);
return t || null;
}
+23
View File
@@ -182,6 +182,28 @@ export function createPanel({ state: layerState, parts }) {
: null;
}
/** The tracked airliner's photo with its credit, or null. The subject
* refresh resolves it; only the subject it was resolved for shows it. */
function presentPhoto(subject) {
const held = layerState.subjectPhoto;
if (
!held ||
held.layerId !== subject.layerId ||
String(held.id) !== String(subject.id)
)
return null;
const { photo } = held;
return {
src: photo.src,
width: photo.width ?? null,
height: photo.height ?? null,
link: photo.link,
credit: t('Photo © {photographer}', {
photographer: photo.photographer,
}),
};
}
function renderResults() {
if (!layerState.enabled || !layerState.results) return hidePanel();
ensurePanel();
@@ -191,6 +213,7 @@ export function createPanel({ state: layerState, parts }) {
kind: 'results',
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
subjectNames: presentNames(subject.memberNames),
photo: presentPhoto(subject),
navigation: presentNavigation(),
rows: cohorts.map(presentRow),
note: t(
+117
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createPanel } from './panel.js';
import { createSubject } from './subject.js';
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
const cohort = (id, source, sourceStatus) => ({
@@ -36,3 +37,119 @@ test('a Contacts row names its provider as the Layers panel does, with its feed
);
state.offPanelLocale?.();
});
const PHOTO = Object.freeze({
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/n123ab',
});
/** The published Contacts view for one subject and the refresh's photo. */
function photoView(subject, subjectPhoto) {
const state = {
enabled: true,
results: { subject, cohorts: [] },
subjectPhoto,
cohortPages: new Map(),
panelListeners: new Set(),
panelSignature: '',
navigationIndex: 0,
};
const parts = {
navigation: { canNavigateNext: () => false },
rendering: { hideDirectionOverlay() {} },
};
createPanel({ state, parts }).renderResults();
state.offPanelLocale?.();
return state.panelView;
}
const FLIGHT = Object.freeze({
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
});
test('the Contacts view carries the tracked flight’s photo with its credit', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: PHOTO,
});
assert.deepEqual(view.photo, {
src: PHOTO.src,
width: 280,
height: 186,
link: PHOTO.link,
credit: 'Photo © Jane Doe',
});
});
test('the Contacts view has no photo without one, or with another subject’s', () => {
assert.equal(photoView(FLIGHT, null).photo, null);
assert.equal(
photoView(FLIGHT, { layerId: 'flights', id: 'def456', photo: PHOTO }).photo,
null,
);
assert.equal(
photoView(
{ layerId: 'ais-live-vessels', id: 'abc123', label: 'VESSEL' },
{ layerId: 'flights', id: 'abc123', photo: PHOTO },
).photo,
null,
);
});
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
const tracked = {
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
photo: PHOTO,
};
let current = tracked;
let lookups = 0;
const flights = {
getTrackedSubject: () => {
lookups += 1;
return current;
},
};
const military = {
getTrackedSubject: () => ({ ...tracked, layerId: 'military' }),
};
const { resolveSubjectPhoto } = createSubject({
state: {},
services: { flights, military, vessels: {}, installations: {} },
parts: {
navigation: {
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
},
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }),
PHOTO,
);
assert.equal(lookups, 1);
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'def456' }), null);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military-installations', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military', id: 'abc123' }),
null,
);
assert.equal(resolveSubjectPhoto(null), null);
current = null;
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
current = { ...tracked, photo: null };
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
});
+2
View File
@@ -29,6 +29,8 @@ export function createState({ services }) {
/** Stops following the manager's adoptions (see watchAdoptions). */
unwatchAdoptions: null,
subject: null,
/** The tracked flight's photo with the subject it belongs to, or null. */
subjectPhoto: null,
results: null,
visual: null,
/** Whether layer views replace the panel's initial markup yet. */
+52 -8
View File
@@ -378,19 +378,48 @@ export function createSubject({ state: layerState, services, parts, source }) {
*
* Identity (`subject.id`) is NEVER re-derived — only the rendered string.
* @param {{layerId: string, id: string, label: string}} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it (see trackedSubjectOf).
* @returns {string} The current label, or the cached one when the owning layer
* has no tracked subject (e.g. a cross-layer handoff is in flight).
*/
function resolveSubjectLabel(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId))
return subject?.label;
function resolveSubjectLabel(subject, tracked = trackedSubjectOf(subject)) {
return tracked?.label || subject?.label;
}
/**
* The owning flight layer's tracked-subject descriptor when it describes
* this subject, else null. Built once per refresh and shared by the label
* and the photo.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @returns {?{id: string, label: string, photo?: ?object}}
*/
function trackedSubjectOf(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId)) return null;
const layer =
subject.layerId === 'flights' ? flightsLayer : militaryFlightsLayer;
const tracked = layer.getTrackedSubject?.();
if (tracked?.label && String(tracked.id) === String(subject.id))
return tracked.label;
return subject.label;
return tracked && String(tracked.id) === String(subject.id)
? tracked
: null;
}
/**
* The tracked airliner's Planespotters photo, for the Contacts panel.
*
* Only the flights layer looks photos up, and only for the plane it tracks;
* a vessel, an installation, a military aircraft or an untracked flight has
* none.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it.
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
*/
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
return subject?.layerId === 'flights' && tracked?.photo
? tracked.photo
: null;
}
/** Refresh proximity counts/distances against the subject's current live position. */
@@ -417,8 +446,21 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (presence === SUBJECT_PRESENCE.LIVE) layerState.subjectMissing = false;
else if (presence === SUBJECT_PRESENCE.MISSING)
layerState.subjectMissing = true;
const nextLabel = resolveSubjectLabel(layerState.subject);
const tracked = trackedSubjectOf(layerState.subject);
const nextLabel = resolveSubjectLabel(layerState.subject, tracked);
const labelChanged = nextLabel !== layerState.subject.label;
// The panel reads the photo from here, with the subject it belongs to.
const photo = resolveSubjectPhoto(layerState.subject, tracked);
layerState.subjectPhoto = photo
? {
layerId: layerState.subject.layerId,
id: layerState.subject.id,
photo,
}
: null;
// A photo arriving after selection is render-worthy on its own, as a label.
const photoChanged =
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
layerState.subject = { ...layerState.subject, position, label: nextLabel };
const movementM = layerState.lastEvaluatedPosition
? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position)
@@ -439,7 +481,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// kept the ICAO hex until unrelated movement, a source-revision bump, or
// page rotation happened to repaint it. Gated on an ACTUAL change so the
// common no-op refresh (every 750 ms) still costs no repaint.
if (labelChanged) parts.panel.renderResults();
if (labelChanged || photoChanged) parts.panel.renderResults();
parts.rendering.scheduleDirectionOverlayUpdate(force);
return;
}
@@ -502,6 +544,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
militaryInstallationsLayer.setContextAnchor?.(null);
layerState.autoFocusRetryPending = false;
layerState.subject = null;
layerState.subjectPhoto = null;
layerState.subjectMissing = false;
layerState.results = null;
layerState.navigationHistory = [];
@@ -528,6 +571,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
resolveSubjectPosition,
collectionSubjectPosition,
resolveSubjectLabel,
resolveSubjectPhoto,
refreshSelectedSubject,
subjectFromContext,
markSubjectEvicted,
+37 -4
View File
@@ -1,5 +1,6 @@
import { msg, t } from '../../i18n/index.js';
import { STATUS_POLL_MS } from './policy.js';
import { ACTIVATION_ENTER_ALTITUDE_M, STATUS_POLL_MS } from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
@@ -13,6 +14,14 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: STATUS_POLL_MS,
/**
* Kept so camera moves can repaint the row before the next status poll.
* @param {object} dataManager DataLayerManager instance.
*/
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
},
/**
* Return a sampled array of detectable station objects for HUD overlay rendering.
* @param {Object} [options] - Sampling options (maxCount, seed).
@@ -57,15 +66,39 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Return current layer statistics for the UI status display.
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean }}
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean, status?: string, statusMessage?: string }}
*/
getStats() {
// A city in range without points is loading even before its fetch
// starts: the row repaints on entry, ahead of beginLoading().
const loading =
layerState._loading ||
[...layerState._activeCityIds].some(
(cityId) =>
!layerState._cityRuntime.has(cityId) &&
!layerState._failedCityIds.has(cityId),
);
const stats = {
count: layerState._count,
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
loading,
};
if (layerState._loading) {
// No system in range: the camera is too high or no system is near. A
// failed city also leaves range empty and reports its failure below.
if (
layerState._enabled &&
!loading &&
layerState._activeCityIds.size === 0 &&
layerState._failedCityIds.size === 0
) {
// English: the analyst's empty note and the row's prompt, both shown
// through translateStatusMessage (ui/statusText.js).
const note = layerState._altitudeGateEnabled
? `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered city`;
return { ...stats, status: 'zoom-in', statusMessage: note };
}
if (loading) {
stats.loadingLabel =
layerState._activeCityIds.size > 0
? t('syncing {count} city feeds...', {
+1
View File
@@ -169,6 +169,7 @@ export function createLifecycle({
viewer.scene.primitives.remove(layerState._pointCollection);
layerState._pointCollection = null;
}
layerState._dataManager = null;
layerState._viewer = null;
},
};
+366
View File
@@ -0,0 +1,366 @@
// Bike Share's Layers row. With no system in range it says why instead of
// "never" and keeps no date for data it no longer draws. After the camera
// settles, the last row the panel painted must match what the layer reports
// now. Each case drives the real viewport,
// ingestion, rendering and controls; the manager is a spy that records the
// row text (LayerPanel._buildMetaText) at every refreshLayerStats() call.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { CITY_BY_ID, GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
const BOSTON_ID = 'boston-bluebikes';
const TORONTO_ID = 'toronto-bike-share';
const BUFFALO_ID = 'buffalo-reddy';
const LONDON = { lat: 51.5072, lon: -0.1276 };
const BOSTON = { lat: 42.3601, lon: -71.0589 };
const BOSTON_NUDGED = { lat: 42.37, lon: -71.05 };
const BETWEEN = { lat: 43.25, lon: -79.1 };
const TORONTO_ONLY = { lat: 43.7, lon: -79.6 };
const LOW_M = 10_000;
globalThis.document ??= {
addEventListener() {},
removeEventListener() {},
};
function deferred() {
let resolve;
const promise = new Promise((res) => {
resolve = res;
});
return { promise, resolve };
}
function makeSource() {
const cityOf = (url) => {
for (const [id, city] of CITY_BY_ID) {
if (url === city.stationInformationUrl) return { id, kind: 'info' };
if (url === city.stationStatusUrl) return { id, kind: 'status' };
}
throw new Error(`unexpected GBFS url ${url}`);
};
const source = {
dead: new Set(),
/** `${cityId}:${kind}` → deferred that gates the answer. */
gates: new Map(),
async getStations(url, { signal } = {}) {
const { id, kind } = cityOf(url);
const gate = source.gates.get(`${id}:${kind}`);
if (gate) {
await new Promise((resolve, reject) => {
gate.promise.then(resolve);
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
);
});
} else {
await new Promise((resolve) => setTimeout(resolve, 1));
}
signal?.throwIfAborted();
if (source.dead.has(id)) throw new Error('GBFS HTTP 503');
const city = CITY_BY_ID.get(id);
if (kind === 'info') {
return {
data: {
stations: [
{
station_id: `${id}-1`,
name: `${id} dock`,
lat: city.centerLat,
lon: city.centerLon,
capacity: 10,
},
],
},
};
}
return {
data: {
stations: [
{
station_id: `${id}-1`,
num_bikes_available: 3,
num_docks_available: 7,
is_installed: true,
is_renting: true,
is_returning: true,
},
],
},
};
},
};
return source;
}
/** The row as the panel draws it: state chip, count, meta text. */
const rowText = (raw) => {
const stats = {
count: 0,
lastUpdate: null,
...raw,
loading: raw.loading === true,
};
const meta = LayerPanel.prototype._buildMetaText({
id: 'bikeshare',
source: 'GBFS',
enabled: true,
lifecycleState: 'enabled',
stats,
});
return `${layerFeedState(stats)} | ${stats.count || '—'} | ${meta}`;
};
function makeLiveLayer() {
const source = makeSource();
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
};
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.ingestion = createIngestion(context);
parts.model = createModel(context);
parts.viewport = createViewport(context);
parts.rendering = createRendering(context);
parts.selection = {
_installClickHandler() {},
_clearSelection() {},
_onKeyDown() {},
};
parts.queries = { collectDetectableStations: () => [] };
parts.lifecycle = createLifecycle(context);
const { methods: controls } = createControls(context);
const camera = { ...LONDON, height: LOW_M };
const viewer = {
camera: {
get positionCartographic() {
return Cesium.Cartographic.fromDegrees(
camera.lon,
camera.lat,
camera.height,
);
},
computeViewRectangle: () => undefined,
changed: { addEventListener() {}, removeEventListener() {} },
},
scene: { globe: {}, primitives: { add() {}, remove() {} } },
};
parts.lifecycle.methods.init(viewer);
const painted = [];
controls.attachDataManager({
refreshLayerStats() {
painted.push(rowText(controls.getStats()));
},
});
return {
state,
source,
painted,
lastPainted: () => painted.at(-1),
stats: () => controls.getStats(),
live: () => rowText(controls.getStats()),
moveTo(place, height = LOW_M) {
Object.assign(camera, place, { height });
return parts.viewport.runProximityCheck();
},
async enable() {
parts.lifecycle.methods.enable(viewer);
await settle();
},
};
}
async function settle() {
for (let i = 0; i < 5; i += 1)
await new Promise((resolve) => setTimeout(resolve, 2));
}
test('entering a city paints the loading row, not "never"', async () => {
const layer = makeLiveLayer();
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const before = layer.painted.length;
const entering = layer.moveTo(BOSTON);
assert.ok(layer.painted.length > before, 'entering repainted');
const atEntry = layer.lastPainted();
const liveAfter = layer.live();
info.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('re-entering a city with cached station info paints loading', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
await layer.moveTo(LONDON);
await settle();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
const entering = layer.moveTo(BOSTON);
const atEntry = layer.lastPainted();
await Promise.resolve();
await Promise.resolve();
const liveAfter = layer.live();
status.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('leaving a city mid-load does not leave the row on LOADING', async () => {
const layer = makeLiveLayer();
layer.source.gates.set(`${BOSTON_ID}:info`, deferred());
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.equal(layer.state._loading, true);
await layer.moveTo(LONDON);
await entering;
await settle();
assert.equal(layer.state._loading, false);
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('a camera nudge during the first load still repaints the drawn stations', async () => {
const layer = makeLiveLayer();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.ok(layer.state._cityRuntime.has(BOSTON_ID), 'points are drawn');
await layer.moveTo(BOSTON_NUDGED);
status.resolve();
await entering;
await settle();
assert.equal(layer.state._count, 1, 'one station on the map');
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving a city whose load failed repaints the error away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BOSTON_ID);
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.match(layer.lastPainted(), /GBFS fetch error/i);
await layer.moveTo(LONDON);
await settle();
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving the failed city of two repaints DEGRADED away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BUFFALO_ID);
await layer.enable();
await layer.moveTo(BETWEEN);
await settle();
assert.match(layer.lastPainted(), /^degraded/);
await layer.moveTo(TORONTO_ONLY);
await settle();
assert.doesNotMatch(layer.live(), /^degraded/);
assert.equal(layer.lastPainted(), layer.live());
});
test('above the altitude gate the row says how low to fly', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(LONDON, 2_000_000);
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(stats.statusMessage, 'Fly below 48 km to a covered city');
assert.equal(stats.error, undefined);
});
test('a city with no system says so and counts the ones there are', async () => {
const layer = makeLiveLayer();
await layer.enable();
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(
stats.statusMessage,
`No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`,
);
assert.equal(stats.count, 0);
});
test('a city in range, loading, failed or a disabled layer gets no prompt', async () => {
const layer = makeLiveLayer();
assert.equal(layer.stats().status, undefined, 'disabled');
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const entering = layer.moveTo(BOSTON);
assert.equal(layer.stats().status, undefined, 'loading');
info.resolve();
await entering;
await settle();
assert.equal(layer.stats().status, undefined, 'loaded');
// Left mid-load: range is empty, but the aborted load still owns the row.
const leaving = makeLiveLayer();
leaving.source.gates.set(`${BOSTON_ID}:info`, deferred());
await leaving.enable();
const loading = leaving.moveTo(BOSTON);
await settle();
const left = leaving.moveTo(LONDON);
assert.equal(leaving.state._activeCityIds.size, 0);
assert.equal(leaving.stats().loading, true);
assert.equal(leaving.stats().status, undefined, 'leaving mid-load');
await Promise.all([loading, left]);
const failed = makeLiveLayer();
failed.source.dead.add(BOSTON_ID);
await failed.enable();
await failed.moveTo(BOSTON);
await settle();
assert.equal(failed.stats().status, undefined, 'failed');
assert.equal(failed.stats().error, 'GBFS fetch error');
});
test('leaving every system behind drops the date of the data it drew', async () => {
for (const height of [LOW_M, 2_000_000]) {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.ok(layer.stats().lastUpdate, 'Boston is dated');
await layer.moveTo(LONDON, height);
assert.equal(layer.stats().lastUpdate, null, `at ${height} m`);
}
});
+4
View File
@@ -19,6 +19,10 @@ export function createState({ services }) {
layerState._viewer = null;
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} Manager that repaints the layer's row. */
layerState._dataManager = null;
/** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */
layerState._pointCollection = null;
+25 -3
View File
@@ -116,6 +116,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
parts.rendering.removeCityPoints(cityId);
}
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
function refreshRow() {
layerState._dataManager?.refreshLayerStats?.('bikeshare');
}
/** Deactivate all currently active cities and clear the active set. */
function deactivateAllCities() {
@@ -125,6 +130,8 @@ export function createViewport({ state: layerState, services, parts, source }) {
// A failure belongs to a city in range; none are once everything is off.
layerState._failedCityIds.clear();
layerState._count = 0;
// Nothing is left on the map to date.
layerState._lastUpdate = null;
}
/**
@@ -203,9 +210,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
const generation = ++layerState._proximityGeneration;
const altitude = getCameraAltitude(layerState._viewer);
const wasGateEnabled = layerState._altitudeGateEnabled;
// Altitude gate: disable all cities when camera is too high
if (!shouldActivateAtAltitude(altitude)) {
deactivateAllCities();
if (wasGateEnabled) refreshRow();
return;
}
@@ -220,15 +229,25 @@ export function createViewport({ state: layerState, services, parts, source }) {
}
}
// A failure never outlives its city's range.
let failureCleared = false;
for (const cityId of layerState._failedCityIds) {
if (!nextActive.has(cityId)) layerState._failedCityIds.delete(cityId);
if (!nextActive.has(cityId)) {
layerState._failedCityIds.delete(cityId);
failureCleared = true;
}
}
const changed =
!wasGateEnabled ||
failureCleared ||
nextActive.size !== layerState._activeCityIds.size ||
[...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId));
layerState._activeCityIds = nextActive;
if (layerState._activeCityIds.size === 0) {
if (nextActive.size === 0) {
layerState._count = 0;
return;
layerState._lastUpdate = null;
}
if (changed) refreshRow();
// Only activate cities that don't already have rendered points
const toActivate = [];
@@ -240,6 +259,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
await Promise.all(
toActivate.map((cityId) => activateCity(cityId, generation)),
);
// Superseded loads repaint too: a newer check may have painted the row
// while this one was still loading, or found nothing to load itself.
if (layerState._enabled) refreshRow();
}
/** Schedule a debounced proximity check after camera movement. */
+1 -1
View File
@@ -448,7 +448,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
// Photoreal regime. Sampling is delegated to the shared coarse-cell
// sampler. It remains event-driven, one-shot per cell, and keeps its
// sampler. It remains event-driven, a few probes per cell, and keeps its
// existing acceptance window; CCTV adds no rooftop rejection policy.
if (sampleGround && parts.model.projectionTilesReady()) {
record.groundMeshSampleRequestCount =
+111 -7
View File
@@ -1,5 +1,6 @@
import { classifyAircraft } from '../../data/aircraftClass.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
import * as Cesium from 'cesium';
import {
ENRICH_MAX_INFLIGHT,
@@ -8,6 +9,7 @@ import {
ENRICH_AMBIENT_REFILL_TOKENS,
ENRICH_AMBIENT_REFILL_WINDOW_MS,
ENRICH_AMBIENT_PER_SWEEP,
ENRICH_RETRY_COOLDOWN_MS,
} from './policy.js';
export function createEnrichment({
@@ -17,11 +19,62 @@ export function createEnrichment({
layer,
resolveAsset,
}) {
function _enqueueEnrich(key, query, onData, priority = false) {
const { isMilitaryIcao } = services.militaryRegistry;
const { isTr3b } = services.aircraftPresentation;
/**
* Whether `key` is answered, queued, or cooling down after a failure. A
* key past its cool-down is released here so it can be asked again.
* @param {string} key Lookup key.
* @returns {boolean}
*/
function _enrichHeld(key) {
if (flightState._enrichSeen.has(key)) return true;
const retryAfter = flightState._enrichRetryAfter.get(key);
if (retryAfter === undefined) return false;
if (Date.now() < retryAfter) return true;
flightState._enrichRetryAfter.delete(key);
return false;
}
/**
* Whether a source failure is permanent: an unsupported lookup, or an HTTP
* 4xx other than 401/403 (an authorization refusal that may clear), 408
* (timeout) and 429 (rate limited). Anything else, including an error without a
* status, is temporary.
* @param {*} error The rejection, as `LiveSourceError` / `httpError` carry it.
* @returns {boolean}
*/
function _enrichFailureIsFinal(error) {
if (error?.code === 'unsupported') return true;
const status = Number(error?.status);
return (
Number.isInteger(status) &&
status >= 400 &&
status < 500 &&
status !== 401 &&
status !== 403 &&
status !== 408 &&
status !== 429
);
}
/**
* Ask each key at most once per session, except that a lookup whose source
* failed temporarily (rejected or threw) may be asked again after
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
* refusal (see _enrichFailureIsFinal) are final.
* @param {string} key Session-unique lookup key.
* @param {object} query The source's enrichment query.
* @param {function(object):void} onData Receives a `found` answer.
* @param {boolean} [priority] Front of the queue.
* @param {function(*):?object} [read] Reads the source's answer first, for
* a lookup whose answer may arrive in more than one shape.
*/
function _enqueueEnrich(key, query, onData, priority = false, read = null) {
if (flightState.lifetime.signal.aborted) return;
if (flightState._enrichSeen.has(key)) return;
if (_enrichHeld(key)) return;
flightState._enrichSeen.add(key);
const job = { query, onData };
const job = { key, query, onData, read };
// Priority (tracked / model-eligible) goes to the FRONT so a deep ambient
// backlog can never delay the plane the user just clicked or zoomed into.
if (priority) flightState._enrichQueue.unshift(job);
@@ -61,9 +114,24 @@ export function createEnrichment({
signal: lifetime.signal,
});
})
.then((data) => {
if (!lifetime.signal.aborted && data && data.found) job.onData(data);
})
.then(
(answer) => {
const data = job.read ? job.read(answer) : answer;
if (!lifetime.signal.aborted && data && data.found)
job.onData(data);
},
(error) => {
// The source failed: release the key after a cool-down. A layer
// teardown is not a failure and schedules nothing, and a
// permanent refusal is as final as an answer.
if (lifetime.signal.aborted || _enrichFailureIsFinal(error)) return;
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
);
},
)
.catch(() => {
/* enrichment never surfaces errors */
})
@@ -119,6 +187,14 @@ export function createEnrichment({
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return;
// A late answer for a callsign the plane no longer flies is dropped.
if (
String(meta.callsign || '')
.trim()
.toUpperCase() !== cs
)
return;
meta.routeCallsign = cs;
meta.airline = data.airline || meta.airline;
if (data.origin && data.destination)
meta.route = { origin: data.origin, destination: data.destination };
@@ -129,6 +205,31 @@ export function createEnrichment({
); // route lookups only fire for the TRACKED plane — front of the queue
}
/** The tracked plane's photo from Planespotters, asked once per hex at the
* front of the queue like its route. A miss is final; a temporary failure
* is asked again after the cool-down. A military aircraft or a converted
* TR-3B is never looked up. The answer is read with
* `parsePlanespottersPhoto` whatever shape the source returns (the upstream
* answer, a server's cached shape, or an already-read photo), so only a
* checked photo is ever stored. */
function _requestPhotoEnrichment(icao24) {
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
const id = icao24.toLowerCase();
if (isMilitaryIcao(id) || isTr3b(id)) return;
_enqueueEnrich(
`p:${id}`,
{ kind: 'photo', id },
(data) => {
const meta = flightState.records.data.get(id);
if (!meta) return; // evicted while the lookup was in flight
const { src, width, height, photographer, link } = data;
meta.photo = { src, width, height, photographer, link };
},
true,
parsePlanespottersPhoto,
);
}
/** QA seam: headless harnesses (scripts/qa-enrich-ambient.mjs) shrink the
* bucket knobs via window.__GEV_ENRICH_AMBIENT_QA = {ceil, refillTokens,
* windowMs} — they cannot wait out a real 5-minute window. Read lazily each
@@ -196,7 +297,9 @@ export function createEnrichment({
);
const cand = [];
for (const [icao24, bb] of flightState._billboards) {
if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session
// Answered, queued, negative this session, or cooling down after a
// failure: never spend a token on it.
if (_enrichHeld(`t:${icao24}`)) continue;
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
if (!bb.position || !occluder.isPointVisible(bb.position)) continue; // beyond the limb
@@ -233,6 +336,7 @@ export function createEnrichment({
_drainEnrich,
_requestTypeEnrichment,
_requestRouteEnrichment,
_requestPhotoEnrichment,
_ambientBudgetKnobs,
_refillAmbientBudget,
_sweepAmbientEnrichment,
+1
View File
@@ -312,6 +312,7 @@ export function createLifecycle({
flightState._displayFloorState.clear();
flightState._enrichQueue.length = 0;
flightState._enrichSeen.clear();
flightState._enrichRetryAfter.clear();
if (flightState._enrichDripTimer) {
clearTimeout(flightState._enrichDripTimer);
flightState._enrichDripTimer = null;
+24 -5
View File
@@ -37,6 +37,22 @@ import {
DISPLAY_CORRIDOR_FAIR_SHARE,
} from './policy.js';
/** Half a coarse floor cell (0.001°), less a margin so rounding keeps a
* clamped coordinate inside the cell. */
const HALF_CELL_DEG = 0.00049;
/**
* A coordinate held within half a cell of the cell's centre (the short way
* round for longitude), so a read lands in the given cell.
* @param {number} deg @param {number} centreDeg
* @returns {number}
*/
function clampToCell(deg, centreDeg) {
let d = deg - centreDeg;
d -= 360 * Math.round(d / 360);
return centreDeg + Math.max(-HALF_CELL_DEG, Math.min(HALF_CELL_DEG, d));
}
export function createMotion({
flightState,
services,
@@ -865,12 +881,15 @@ export function createMotion({
);
// Boundary hysteresis: a position jittering across a cell edge would flip
// floors at fleet-tick rate (see stickyFloorCell).
const cell = stickyFloorCell(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
state?.cell,
const latDeg = Cesium.Math.toDegrees(carto.latitude);
const lonDeg = Cesium.Math.toDegrees(carto.longitude);
const cell = stickyFloorCell(latDeg, lonDeg, state?.cell);
// A cell holds rendered-surface readings at the points they were taken,
// so the floor is read where the contact is, held inside its sticky cell.
const floor = cachedGroundFloor(
clampToCell(latDeg, cell.lat),
clampToCell(lonDeg, cell.lon),
);
const floor = cachedGroundFloor(cell.lat, cell.lon);
const next = state || {
cell,
in: new Cesium.Cartesian3(),
+352 -2
View File
@@ -4,6 +4,7 @@ import { createCivilFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createEnrichment } from './enrichment.js';
import { createTracking } from './tracking.js';
import { LiveSourceError } from '../../sources/live/contract.js';
function services() {
const names = [
@@ -29,6 +30,14 @@ function services() {
};
}
/** The services enrichment reads: which hexes are military or a TR-3B. */
function enrichServices({ military = [], tr3b = [] } = {}) {
return {
militaryRegistry: { isMilitaryIcao: (id) => military.includes(id) },
aircraftPresentation: { isTr3b: (id) => tr3b.includes(id) },
};
}
test('constructing independent flight layers performs no source request and isolates selection', () => {
let requests = 0;
const source = {
@@ -90,7 +99,11 @@ test('aborted enrichment cannot write into a later lifecycle or decrement its ac
},
};
const flightState = createFlightState({ source, services: services() });
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
let writes = 0;
enrichment._enqueueEnrich(
'test',
@@ -118,7 +131,11 @@ test('a synchronous enrichment failure stays bounded and releases its slot', asy
},
},
});
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
assert.doesNotThrow(() =>
enrichment._enqueueEnrich('test', {}, () => assert.fail()),
);
@@ -146,3 +163,336 @@ test('voice context reads a track that rounds to north as 0°, not 360°', () =>
'0°',
);
});
test('the tracked plane’s photo is asked once per hex and lands on its record', async () => {
const queries = [];
let answer = {
found: true,
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg',
width: 420,
height: 280,
photographer: 'Jan Seler',
link: 'https://www.planespotters.net/photo/1745410/x?utm_source=api',
};
const flightState = createFlightState({
services: services(),
source: {
async getEnrichment(query) {
queries.push(query);
if (answer instanceof Error) throw answer;
return answer;
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
flightState.records.data.set('a0f1bb', { callsign: 'AAL1' });
flightState._trackedIcao = 'a0f1bb';
flightState._trackedEntity = {};
enrichment._requestPhotoEnrichment('A0F1BB');
enrichment._requestPhotoEnrichment('a0f1bb');
await new Promise((done) => setImmediate(done));
assert.deepEqual(queries, [{ kind: 'photo', id: 'a0f1bb' }]);
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, {
src: answer.src,
width: 420,
height: 280,
photographer: 'Jan Seler',
link: answer.link,
});
// A failure is not asked again within its cool-down.
answer = new Error('outage');
flightState.records.data.set('abc123', {});
enrichment._requestPhotoEnrichment('abc123');
await new Promise((done) => setTimeout(done, 300));
enrichment._requestPhotoEnrichment('abc123');
await new Promise((done) => setImmediate(done));
assert.equal(queries.length, 2);
assert.equal(flightState.records.data.get('abc123').photo, undefined);
enrichment._requestPhotoEnrichment('not-hex');
assert.equal(queries.length, 2);
flightState.lifetime.abort();
});
test('a military aircraft or a converted TR-3B is never looked up for a photo', async () => {
const queries = [];
const flightState = createFlightState({
services: services(),
source: {
async getEnrichment(query) {
queries.push(query);
return { found: false };
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices({ military: ['ae1234'], tr3b: ['a0f1bb'] }),
parts: {},
});
for (const id of ['ae1234', 'a0f1bb']) {
flightState.records.data.set(id, {});
enrichment._requestPhotoEnrichment(id);
}
enrichment._requestPhotoEnrichment('AE1234');
await new Promise((done) => setImmediate(done));
assert.deepEqual(queries, []);
assert.equal(flightState._enrichSeen.size, 0);
flightState.lifetime.abort();
});
test('a photo answer in the upstream shape or a server’s cached shape lands checked', async () => {
const SRC = 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg';
const LINK = 'https://www.planespotters.net/photo/1745410/x?utm_source=api';
const answers = {
a0f1bb: {
photos: [
{
thumbnail_large: { src: SRC, size: { width: 420, height: 280 } },
link: LINK,
photographer: 'Jan Seler',
},
],
},
abc123: {
found: true,
thumbnail: { src: SRC, width: 420, height: 280 },
photographer: 'Jan Seler',
link: LINK,
},
def456: {
found: true,
thumbnail: { src: 'https://evil.example/a.jpg', width: 1, height: 1 },
photographer: 'Jan Seler',
link: LINK,
},
fed789: { photos: [] },
};
const flightState = createFlightState({
services: services(),
source: { getEnrichment: async ({ id }) => answers[id] },
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
const ids = Object.keys(answers);
for (const id of ids) flightState.records.data.set(id, {});
for (const id of ids) {
enrichment._requestPhotoEnrichment(id);
// One dispatch per drip gap.
await new Promise((done) => setTimeout(done, 250));
}
const photo = {
src: SRC,
width: 420,
height: 280,
photographer: 'Jan Seler',
link: LINK,
};
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, photo);
assert.deepEqual(flightState.records.data.get('abc123').photo, photo);
assert.equal(flightState.records.data.get('def456').photo, undefined);
assert.equal(flightState.records.data.get('fed789').photo, undefined);
flightState.lifetime.abort();
});
/** An enrichment queue over `answer(query)` with a hand-driven clock. */
function enrichmentClock(t, answer) {
let now = 1_000_000;
t.mock.method(Date, 'now', () => now);
const queries = [];
const flightState = createFlightState({
services: services(),
source: {
getEnrichment(query) {
queries.push(query.id);
return answer(query);
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: { tracking: { _updateTrackedLabelModel() {} } },
});
const settle = () => new Promise((done) => setImmediate(done));
const advance = (ms) => {
now += ms;
};
return { flightState, enrichment, queries, settle, advance };
}
test('a failed lookup is asked again only after its cool-down', async (t) => {
let fail = true;
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async () => {
if (fail) throw new Error('503');
return { found: true, typeCode: 'A321' };
},
);
flightState.records.data.set('a0f1bb', {});
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb']);
advance(59_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb'], 'not within the cool-down');
fail = false;
advance(1_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb'], 'asked again after it');
assert.equal(flightState.records.data.get('a0f1bb').typeCode, 'A321');
advance(120_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2, 'an answer is final');
assert.equal(flightState._enrichActive, 0);
flightState.lifetime.abort();
});
test('a synchronous source failure cools down like a rejected one', async (t) => {
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
() => {
throw new Error('boom');
},
);
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
advance(60_000);
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb']);
flightState.lifetime.abort();
});
test('a "not found" answer is never asked again', async (t) => {
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async ({ kind }) => (kind === 'photo' ? { photos: [] } : { found: false }),
);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
advance(1_000); // past the dispatch drip
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2);
advance(3_600_000);
enrichment._requestTypeEnrichment('a0f1bb');
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2);
assert.equal(flightState._enrichRetryAfter.size, 0);
flightState.lifetime.abort();
});
test('a lookup cut off by the layer’s teardown schedules no retry', async (t) => {
let release;
const { flightState, enrichment, settle } = enrichmentClock(
t,
(query) =>
new Promise((_resolve, reject) => {
release = () => reject(new DOMException('aborted', 'AbortError'));
}),
);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
flightState.lifetime.abort();
release();
await settle();
assert.equal(flightState._enrichRetryAfter.size, 0);
assert.equal(flightState._enrichSeen.has('t:a0f1bb'), true);
});
test('a permanent refusal is final; a timeout, rate limit, outage or authorization refusal cools down', async (t) => {
const errors = {
aaaaa1: new LiveSourceError('denied', 'adsbdb HTTP 404', { status: 404 }),
aaaaa2: new LiveSourceError('unsupported', 'Enrichment unavailable'),
aaaaa3: new LiveSourceError('limited', 'adsbdb rate limited', {
status: 429,
}),
aaaaa4: new LiveSourceError('unavailable', 'adsbdb HTTP 503', {
status: 503,
}),
aaaaa5: new LiveSourceError('unavailable', 'adsbdb HTTP 408', {
status: 408,
}),
aaaaa6: new Error('network'),
aaaaa7: new LiveSourceError('denied', 'Unauthorized', { status: 401 }),
aaaaa8: new LiveSourceError('denied', 'Forbidden', { status: 403 }),
};
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async ({ id }) => {
throw errors[id];
},
);
const ids = Object.keys(errors);
for (const id of ids) {
enrichment._requestTypeEnrichment(id);
await settle();
advance(1_000); // past the dispatch drip
}
assert.deepEqual(queries, ids);
advance(60_000);
for (const id of ids) {
enrichment._requestTypeEnrichment(id);
await settle();
advance(1_000);
}
assert.deepEqual(
queries.slice(ids.length),
['aaaaa3', 'aaaaa4', 'aaaaa5', 'aaaaa6', 'aaaaa7', 'aaaaa8'],
'a 404 and an unsupported lookup are never asked again',
);
assert.equal(flightState._enrichSeen.has('t:aaaaa1'), true);
assert.equal(flightState._enrichRetryAfter.has('t:aaaaa1'), false);
flightState.lifetime.abort();
});
test('a route answer for a callsign the plane no longer flies is dropped', async (t) => {
const pending = [];
const { flightState, enrichment, settle, advance } = enrichmentClock(
t,
(query) => new Promise((resolve) => pending.push({ query, resolve })),
);
const meta = { callsign: 'UAL9' };
flightState.records.data.set('a0f1bb', meta);
enrichment._requestRouteEnrichment('a0f1bb');
await settle();
meta.callsign = 'UAL10'; // the next poll's callsign
advance(1_000);
enrichment._requestRouteEnrichment('a0f1bb');
await settle();
assert.deepEqual(
pending.map(({ query }) => query.id),
['UAL9', 'UAL10'],
);
const route = (code) => ({
found: true,
airline: `${code} Air`,
origin: { code: `${code}O` },
destination: { code: `${code}D` },
});
pending[0].resolve(route('OLD'));
await settle();
assert.equal(meta.route, undefined, 'the late UAL9 answer is ignored');
assert.equal(meta.airline, undefined);
pending[1].resolve(route('NEW'));
await settle();
assert.deepEqual(meta.route, {
origin: { code: 'NEWO' },
destination: { code: 'NEWD' },
});
assert.equal(meta.routeCallsign, 'UAL10');
flightState.lifetime.abort();
});
+5
View File
@@ -254,6 +254,11 @@ export const ENRICH_MAX_INFLIGHT = 4;
export const ENRICH_DISPATCH_GAP_MS = 200;
/** A lookup whose source failed (an outage, a timeout, a restarting server) may
* be asked again after this long; a real "not found" answer never is. */
export const ENRICH_RETRY_COOLDOWN_MS = 60_000;
// ---------------------------------------------------------------------------
// Ambient fleet type enrichment (2026-07-02 field data: OpenSky's live
// category field is 0/"no info" for ~94% of planes, so ambient classification
+13 -3
View File
@@ -24,7 +24,8 @@ export function createQueries({
layer,
resolveAsset,
}) {
const { tr3bTypeLabel, tr3bAircraftClass } = services.aircraftPresentation;
const { isTr3b, tr3bTypeLabel, tr3bAircraftClass } =
services.aircraftPresentation;
const { formatFlightLevel } = services.labels;
const { isMilitaryIcao } = services.militaryRegistry;
const { applyTrackedCameraFrame } = services.camera;
@@ -208,6 +209,12 @@ export function createQueries({
destination: { ...info.route.destination },
}
: null,
// The airframe's Planespotters photo for the Context panel; a military
// aircraft or a converted TR-3B (it would name the real one) shows none.
photo:
info?.photo && !isTr3b(icao24) && !isMilitaryIcao(icao24)
? { ...info.photo }
: null,
};
}
@@ -875,8 +882,9 @@ export function createQueries({
/**
* Describe the currently tracked aircraft at its dead-reckoned position.
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* Tracked aircraft info, or null when nothing is tracked.
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null, photo: {src: string, width: number|null, height: number|null, photographer: string, link: string}|null}|null}
* Tracked aircraft info, or null when nothing is tracked. `photo` is the
* airframe's credited Planespotters photo, or null.
*/
getTrackedInfo() {
if (!flightState._trackedIcao) return null;
@@ -906,6 +914,8 @@ export function createQueries({
_toCleanText(described.registration) ||
described.icao24,
position: Cesium.Cartesian3.clone(described.position),
// The airframe's photo for the Context panel, or null.
photo: described.photo,
};
},
+12 -3
View File
@@ -198,10 +198,16 @@ export class FlightRecords {
!!prevMeta && (prevMeta.onGround === true) !== onGround;
// Store flight metadata for click-to-track labels
const cat = stickyNumber(category, prevMeta?.category, null);
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
// A route (and its airline) belongs to the callsign it was looked up for;
// a new callsign drops it, so an old flight's route never shows under it.
const routeHeld =
Boolean(prevMeta?.routeCallsign) &&
prevMeta.routeCallsign === nextCallsign.toUpperCase();
const meta = {
sourceReference: observation.reference,
observedReceiptMs: Date.now(),
callsign: stickyText(callsign, prevMeta?.callsign),
callsign: nextCallsign,
altitude: alt,
// geoAltitudeM/renderAltitudeM are ADDITIVE fields alongside the
// untouched aviation `altitude` — never rename/replace it (labels,
@@ -256,8 +262,11 @@ export class FlightRecords {
typeCode: prevMeta?.typeCode ?? null,
typeName: prevMeta?.typeName ?? null,
registration: prevMeta?.registration ?? null,
airline: prevMeta?.airline ?? null,
route: prevMeta?.route ?? null,
airline: routeHeld ? (prevMeta.airline ?? null) : null,
route: routeHeld ? (prevMeta.route ?? null) : null,
routeCallsign: routeHeld ? prevMeta.routeCallsign : null,
// Planespotters photo of the tracked airframe (Core asks it directly).
photo: prevMeta?.photo ?? null,
// The RAW poll fix lat/lon (this tick's OpenSky state-vector
// coords, pre-dead-reckon) — kept distinct from the continuously
// dead-reckoned billboard position for any consumer that needs the
+24
View File
@@ -39,6 +39,7 @@ test('civil records keep aviation units separate from render height and survive
assert.equal(first.meta.renderAltitudeM, 1040);
assert.equal(first.fixEpochMs, 1700000000000);
first.meta.typeCode = 'B738';
first.meta.photo = { src: 'https://t.plnspttrs.net/1/2_280.jpg' };
const second = store.receive(
observation({
callsign: '',
@@ -55,6 +56,7 @@ test('civil records keep aviation units separate from render height and survive
assert.equal(second.meta.velocity, 120);
assert.equal(second.meta.true_track, 90);
assert.equal(second.meta.typeCode, 'B738');
assert.equal(second.meta.photo, first.meta.photo, 'the photo survives polls');
assert.equal(Object.hasOwn(second.meta, 'cullPosition'), false);
assert.deepEqual(JSON.parse(JSON.stringify(second.meta)), second.meta);
});
@@ -140,3 +142,25 @@ test('civil emergency status follows the latest poll instead of sticking', () =>
assert.equal(next.meta.squawk, '2000');
assert.equal(next.meta.emergency, null);
});
test('a route belongs to its callsign: a new callsign drops it, a blank one keeps it', () => {
const store = records();
store.geoidReady = true;
const first = store.receive(observation({ callsign: 'UAL9' }), view());
first.meta.route = { origin: { code: 'AUS' }, destination: { code: 'DEN' } };
first.meta.airline = 'United';
first.meta.routeCallsign = 'UAL9';
const same = store.receive(observation({ callsign: 'UAL9 ' }), view());
assert.equal(same.meta.route, first.meta.route);
const blank = store.receive(observation({ callsign: '' }), view());
assert.equal(
blank.meta.route,
first.meta.route,
'a dropped callsign is sticky',
);
assert.equal(blank.meta.airline, 'United');
const next = store.receive(observation({ callsign: 'UAL10' }), view());
assert.equal(next.meta.route, null, 'the old route never shows under UAL10');
assert.equal(next.meta.airline, null);
assert.equal(next.meta.routeCallsign, null);
});
+9 -2
View File
@@ -230,6 +230,13 @@ export function createFlightSnapshotRenderer({
// (position updates automatically via dead-reckoning CallbackProperty)
if (isTracked && flightState._trackedEntity) {
tracking._updateTrackedLabelModel(icao24);
// Re-ask the tracked plane's lookups each poll. Answered and queued
// keys return at once; a lookup whose source failed runs again once
// its cool-down has passed, and the route uses the callsign this
// snapshot just recorded.
enrichment._requestTypeEnrichment(icao24, true);
enrichment._requestRouteEnrichment(icao24);
enrichment._requestPhotoEnrichment(icao24);
}
}
@@ -300,8 +307,8 @@ export function createFlightSnapshotRenderer({
// floor cells collected in the loop (fire-and-forget, single-flight;
// read synchronously by NEXT poll's clamp — the military-layer pattern).
warmGroundFloor(floorWarmPoints);
// Round 4: sample the RENDERED mesh for those same cells (one-shot per
// cell, budget-capped, viewer-proximate, google-3d regime only). Own
// Round 4: sample the RENDERED mesh for those same cells (a few probes
// per cell, budget-capped, viewer-proximate, google-3d regime only). Own
// billboards/models are excluded so a vertical probe can't land on an
// aircraft instead of the pavement.
sampleMeshFloorCells(flightState._viewer?.scene, floorWarmPoints, {
+4
View File
@@ -342,6 +342,10 @@ export function createFlightState({ source, services }) {
flightState._enrichSeen = new Set();
/** Lookup key -> epoch ms before which a failed lookup is not asked again. */
flightState._enrichRetryAfter = new Map();
flightState._enrichAmbientBudget = ENRICH_AMBIENT_BUDGET_CEIL;
/** Epoch ms the bucket last accounted a refill window from (0 = unset). */
+14 -1
View File
@@ -190,8 +190,20 @@ export function createTesting({
);
}
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
/** Forget every enrichment lookup and the dispatch clock, so a test that
* moved `Date.now` leaves no future-dated drip or cool-down behind. */
function _resetEnrichmentForTest() {
flightState._enrichQueue.length = 0;
flightState._enrichSeen.clear();
flightState._enrichRetryAfter.clear();
flightState._enrichLastDispatchMs = 0;
if (flightState._enrichDripTimer) {
clearTimeout(flightState._enrichDripTimer);
flightState._enrichDripTimer = null;
}
}
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
async function _ensureFleetModelForTest(icao24) {
await parts.rendering._ensureModel(icao24);
return flightState._models.get(icao24) || null;
@@ -212,5 +224,6 @@ export function createTesting({
_trackedBillboardColorForTest,
_driveFleetModelHandoffForTest,
_ensureFleetModelForTest,
_resetEnrichmentForTest,
};
}
+1
View File
@@ -1060,6 +1060,7 @@ export function createTracking({
// starts one.
parts.enrichment._requestTypeEnrichment(icao24, true); // tracked plane — front of the enrichment queue
parts.enrichment._requestRouteEnrichment(icao24);
parts.enrichment._requestPhotoEnrichment(icao24);
// Round 2 (owner): grounded contacts get trails too — a landed-but-taxiing
// aircraft's history is retrievable on select. Grounded flights positions
// are already surface-clamped (the surfaceM chain), so seeds/appends drape.
+35
View File
@@ -164,6 +164,41 @@ export function createControls({ state: layerState, services, parts, source }) {
);
},
/**
* A loaded mapped installation by id, as `getNearby` returns it (with its
* drawn `position`), or null while the layer is off or the id is not
* loaded. Read-only: nothing is selected.
* @param {string} id Source-backed installation id.
* @returns {object|null}
*/
getById(id) {
if (!layerState.enabled || id === null || id === undefined) return null;
const record = layerState.recordById.get(String(id));
if (!record || record.kind !== 'installation') return null;
return {
...record,
position: Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
parts.rendering.installationSurfaceHeightM(record),
),
};
},
/**
* The mapped installation a `scene.pick()` result landed on: a named
* marker point (`{ installationId }`) or a site entity, as this layer's
* own click selection reads them. Null for anything else.
* @param {object|null|undefined} picked
* @returns {object|null} As {@link getById}.
*/
findByPick(picked) {
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
return id ? methods.getById(id) : null;
},
/**
* Select and frame a mapped installation from another contextual UI.
* @param {string} id Source-backed installation id.
+2 -2
View File
@@ -228,8 +228,8 @@ export function createMilitarySnapshotRenderer({
const bbStale = flightState._billboards.get(icao24);
if (bbStale) bbStale.position = liftedPos;
}
// Round 4: sample the RENDERED mesh for those cells (one-shot per cell,
// budget-capped, viewer-proximate, google-3d regime only), excluding
// Round 4: sample the RENDERED mesh for those cells (a few probes per
// cell, budget-capped, viewer-proximate, google-3d regime only), excluding
// this layer's own billboards/models from the probe.
{
const viewerCarto =
+2 -1
View File
@@ -159,7 +159,8 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
// the known cause, behavior and complexity values and the wording around them.
const facts = [];
if (Number.isFinite(row.acres)) {
const acres = Math.round(row.acres);
const acres =
row.acres < 1 ? Math.round(row.acres * 100) / 100 : Math.round(row.acres);
facts.push(
tn(acres, '{acres} ac', '{acres} ac', { acres: formatNumber(acres) }),
);
+31
View File
@@ -302,3 +302,34 @@ test('partial incident details render only the facts that exist', () => {
'Catron County · $85K to date',
]);
});
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
const row = {
stableId: 'x',
name: 'Grey',
acres: 0.25,
containedPct: null,
state: 'US-WA',
category: 'WF',
discoveredTime: null,
updatedTime: null,
cause: null,
behavior: null,
personnel: null,
county: null,
costToDate: null,
complexity: null,
};
assert.equal(
buildIncidentCard(row, 1758000000000).details[0],
'0.25 ac · containment unknown · US-WA',
);
assert.equal(
buildIncidentCard({ ...row, acres: 0.01 }, 1758000000000).details[0],
'0.01 ac · containment unknown · US-WA',
);
assert.equal(
buildIncidentCard({ ...row, acres: 1.4 }, 1758000000000).details[0],
'1 ac · containment unknown · US-WA',
);
});
+3
View File
@@ -124,10 +124,13 @@ export function createCatalog({ state: layerState, services, parts, source }) {
satrec,
group: 'dense',
launchYear: tleLineLaunchYear(entry.line1),
line1: entry.line1,
line2: entry.line2,
// The dense feed is CelesTrak's Starlink group.
satelliteClass: 'starlink',
ucs: null,
satcat: null,
sensor: null,
});
const point = layerState._pointCollection.add({
position: Cesium.Cartesian3.fromDegrees(
+457 -1
View File
@@ -231,6 +231,13 @@ export function classifySatellite({
return 'probes';
}
/** Whether a class may be ridden in the Cockpit's orbital view. */
export function satelliteClassEnterable(satelliteClass) {
return (
SATELLITE_CLASS_IDS.includes(satelliteClass) && satelliteClass !== 'debris'
);
}
/**
* Merge a partial class-visibility request into the current choice.
* Unknown keys and non-boolean values are ignored.
@@ -250,6 +257,451 @@ export function mergeClassVisibility(
return next;
}
// ISO 3166-1 alpha-2 code → short English name, for every owner below.
const COUNTRY_NAMES = Object.freeze({
AE: 'United Arab Emirates',
AM: 'Armenia',
AO: 'Angola',
AR: 'Argentina',
AT: 'Austria',
AU: 'Australia',
AZ: 'Azerbaijan',
BD: 'Bangladesh',
BE: 'Belgium',
BG: 'Bulgaria',
BH: 'Bahrain',
BM: 'Bermuda',
BO: 'Bolivia',
BR: 'Brazil',
BT: 'Bhutan',
BW: 'Botswana',
BY: 'Belarus',
CA: 'Canada',
CH: 'Switzerland',
CL: 'Chile',
CN: 'China',
CO: 'Colombia',
CR: 'Costa Rica',
CZ: 'Czechia',
DE: 'Germany',
DJ: 'Djibouti',
DK: 'Denmark',
DZ: 'Algeria',
EC: 'Ecuador',
EE: 'Estonia',
EG: 'Egypt',
ES: 'Spain',
ET: 'Ethiopia',
FI: 'Finland',
FR: 'France',
GB: 'United Kingdom',
GH: 'Ghana',
GR: 'Greece',
GT: 'Guatemala',
HR: 'Croatia',
HU: 'Hungary',
ID: 'Indonesia',
IE: 'Ireland',
IL: 'Israel',
IN: 'India',
IQ: 'Iraq',
IR: 'Iran',
IT: 'Italy',
JO: 'Jordan',
JP: 'Japan',
KE: 'Kenya',
KP: 'North Korea',
KR: 'South Korea',
KW: 'Kuwait',
KZ: 'Kazakhstan',
LA: 'Laos',
LK: 'Sri Lanka',
LT: 'Lithuania',
LU: 'Luxembourg',
MA: 'Morocco',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MM: 'Myanmar',
MN: 'Mongolia',
MU: 'Mauritius',
MX: 'Mexico',
MY: 'Malaysia',
NG: 'Nigeria',
NL: 'Netherlands',
NO: 'Norway',
NP: 'Nepal',
NZ: 'New Zealand',
PE: 'Peru',
PH: 'Philippines',
PK: 'Pakistan',
PL: 'Poland',
PT: 'Portugal',
PY: 'Paraguay',
QA: 'Qatar',
RO: 'Romania',
RU: 'Russia',
RW: 'Rwanda',
SA: 'Saudi Arabia',
SB: 'Solomon Islands',
SD: 'Sudan',
SE: 'Sweden',
SG: 'Singapore',
SI: 'Slovenia',
SN: 'Senegal',
TH: 'Thailand',
TM: 'Turkmenistan',
TN: 'Tunisia',
TR: 'Türkiye',
TW: 'Taiwan',
UA: 'Ukraine',
US: 'United States',
UY: 'Uruguay',
VA: 'Vatican City',
VE: 'Venezuela',
VN: 'Vietnam',
ZA: 'South Africa',
ZW: 'Zimbabwe',
});
/**
* Every owner country a satellite can be marked with, sorted: the flags
* `scripts/build-owner-flags.mjs` draws into the owner flag sheet.
*/
export const OWNER_COUNTRY_CODES = Object.freeze(
Object.keys(COUNTRY_NAMES).sort(),
);
// UCS "Country of Operator/Owner" → ISO code. Joint owners ("USA/Japan") and
// organisations are not countries and resolve through ORGANISATIONS or as a
// joint label.
const UCS_COUNTRIES = Object.freeze({
Algeria: 'DZ',
Angola: 'AO',
Argentina: 'AR',
Australia: 'AU',
Austria: 'AT',
Azerbaijan: 'AZ',
Bangladesh: 'BD',
Belarus: 'BY',
Belgium: 'BE',
Bolivia: 'BO',
Brazil: 'BR',
Bulgaria: 'BG',
Canada: 'CA',
Chile: 'CL',
China: 'CN',
Colombia: 'CO',
'Czech Republic': 'CZ',
Denmark: 'DK',
Ecuador: 'EC',
Egypt: 'EG',
Estonia: 'EE',
Ethiopia: 'ET',
Finland: 'FI',
France: 'FR',
Germany: 'DE',
Greece: 'GR',
Hungary: 'HU',
India: 'IN',
Indonesia: 'ID',
Iran: 'IR',
Iraq: 'IQ',
Israel: 'IL',
Italy: 'IT',
Japan: 'JP',
Jordan: 'JO',
Kazakhstan: 'KZ',
Kenya: 'KE',
Kuwait: 'KW',
Laos: 'LA',
Lithuania: 'LT',
Luxembourg: 'LU',
Malaysia: 'MY',
Mexico: 'MX',
Monaco: 'MC',
Morocco: 'MA',
Nepal: 'NP',
Netherlands: 'NL',
'New Zealand': 'NZ',
Nigeria: 'NG',
Norway: 'NO',
Pakistan: 'PK',
Peru: 'PE',
Poland: 'PL',
Russia: 'RU',
'Saudi Arabia': 'SA',
Sinapore: 'SG',
Singapore: 'SG',
Slovenia: 'SI',
'South Africa': 'ZA',
'South Korea': 'KR',
Spain: 'ES',
Sudan: 'SD',
Sweden: 'SE',
Switzerland: 'CH',
Taiwan: 'TW',
Thailand: 'TH',
Tunisia: 'TN',
Turkey: 'TR',
UK: 'GB',
USA: 'US',
Ukraine: 'UA',
'United Arab Emirates': 'AE',
'United Kingdom': 'GB',
Venezuela: 'VE',
Vietnam: 'VN',
});
// CelesTrak SATCAT OWNER code → ISO code (https://celestrak.org/satcat/sources.php).
// CIS (former USSR) is filed under Russia, its continuing state.
const SATCAT_COUNTRIES = Object.freeze({
ALG: 'DZ',
ANG: 'AO',
ARGN: 'AR',
ARM: 'AM',
ASRA: 'AT',
AUS: 'AU',
AZER: 'AZ',
BEL: 'BE',
BELA: 'BY',
BERM: 'BM',
BGD: 'BD',
BHR: 'BH',
BHUT: 'BT',
BOL: 'BO',
BRAZ: 'BR',
BUL: 'BG',
BWA: 'BW',
CA: 'CA',
CHLE: 'CL',
CIS: 'RU',
COL: 'CO',
CRI: 'CR',
CZCH: 'CZ',
DEN: 'DK',
DJI: 'DJ',
ECU: 'EC',
EGYP: 'EG',
EST: 'EE',
ETH: 'ET',
FIN: 'FI',
FR: 'FR',
GER: 'DE',
GHA: 'GH',
GREC: 'GR',
GUAT: 'GT',
HRV: 'HR',
HUN: 'HU',
IND: 'IN',
INDO: 'ID',
IRAN: 'IR',
IRAQ: 'IQ',
IRL: 'IE',
ISRA: 'IL',
ISRO: 'IN',
IT: 'IT',
JPN: 'JP',
KAZ: 'KZ',
KEN: 'KE',
LAOS: 'LA',
LKA: 'LK',
LTU: 'LT',
LUXE: 'LU',
MA: 'MA',
MALA: 'MY',
MCO: 'MC',
MDA: 'MD',
MEX: 'MX',
MMR: 'MM',
MNE: 'ME',
MNG: 'MN',
MUS: 'MU',
NETH: 'NL',
NIG: 'NG',
NKOR: 'KP',
NOR: 'NO',
NPL: 'NP',
NZ: 'NZ',
PAKI: 'PK',
PERU: 'PE',
POL: 'PL',
POR: 'PT',
PRC: 'CN',
PRY: 'PY',
QAT: 'QA',
ROC: 'TW',
ROM: 'RO',
RP: 'PH',
RWA: 'RW',
SAFR: 'ZA',
SAUD: 'SA',
SDN: 'SD',
SEN: 'SN',
SING: 'SG',
SKOR: 'KR',
SLB: 'SB',
SPN: 'ES',
SVN: 'SI',
SWED: 'SE',
SWTZ: 'CH',
THAI: 'TH',
TUN: 'TN',
TURK: 'TR',
UAE: 'AE',
UK: 'GB',
UKR: 'UA',
URY: 'UY',
US: 'US',
VAT: 'VA',
VENZ: 'VE',
VTNM: 'VN',
ZWE: 'ZW',
});
// Organisations, by SATCAT code and by UCS name: no flag, a short label.
const ORGANISATIONS = Object.freeze({
AB: 'Arabsat',
ABS: 'ABS',
AC: 'AsiaSat',
ESA: 'ESA',
ESRO: 'ESRO',
EUME: 'EUMETSAT',
EUTE: 'Eutelsat',
GLOB: 'Globalstar',
IM: 'Inmarsat',
IRID: 'Iridium',
ISS: 'ISS partners',
ITSO: 'Intelsat',
NATO: 'NATO',
NICO: 'New ICO',
O3B: 'O3b',
ORB: 'ORBCOMM',
RASC: 'RascomStar-QAF',
SEAL: 'Sea Launch',
SES: 'SES',
Multinational: 'Multinational',
});
// SATCAT codes for joint ownership, as their parts.
const SATCAT_JOINT = Object.freeze({
CHBZ: ['CN', 'BR'],
CHTU: ['CN', 'TR'],
FGER: ['FR', 'DE'],
FRIT: ['FR', 'IT'],
GRSA: ['GR', 'SA'],
PRES: ['CN', 'ESA'],
SGJP: ['SG', 'JP'],
STCT: ['SG', 'TW'],
TMMC: ['TM', 'MC'],
USBZ: ['US', 'BR'],
});
function country(code) {
return COUNTRY_NAMES[code]
? { countryCode: code, label: COUNTRY_NAMES[code] }
: null;
}
function joint(parts) {
const labels = parts.map(
(part) => COUNTRY_NAMES[part] || ORGANISATIONS[part] || part,
);
return { countryCode: null, label: labels.join(' / ') };
}
/**
* Normalise a UCS owner country ("USA", "China/France", "ESA",
* "Multinational") to `{ countryCode, label }`.
* @param {string|null|undefined} text
* @returns {{countryCode: string|null, label: string}|null}
*/
export function ownerFromUcs(text) {
const value = String(text || '').trim();
if (!value) return null;
if (UCS_COUNTRIES[value]) return country(UCS_COUNTRIES[value]);
if (ORGANISATIONS[value])
return { countryCode: null, label: ORGANISATIONS[value] };
if (value.includes('/'))
return joint(
value
.split('/')
.map((part) => part.trim())
.map((part) => UCS_COUNTRIES[part] || part),
);
return { countryCode: null, label: value };
}
/**
* Normalise a CelesTrak SATCAT OWNER code ("US", "PRC", "CIS", "ITSO") to
* `{ countryCode, label }`; null for TBD, UNK and blanks.
* @param {string|null|undefined} code
* @returns {{countryCode: string|null, label: string}|null}
*/
export function ownerFromSatcat(code) {
const value = String(code || '')
.trim()
.toUpperCase();
if (!value || value === 'TBD' || value === 'UNK') return null;
if (SATCAT_COUNTRIES[value]) return country(SATCAT_COUNTRIES[value]);
if (ORGANISATIONS[value])
return { countryCode: null, label: ORGANISATIONS[value] };
if (SATCAT_JOINT[value]) return joint(SATCAT_JOINT[value]);
return null;
}
/**
* Who owns a satellite: UCS names the operator's country, SATCAT the
* registering owner; UCS wins where both exist. Starlink without either is
* SpaceX's, so United States.
* @returns {{countryCode: string|null, label: string}|null}
*/
export function satelliteOwner({
ucs = null,
satcat = null,
satelliteClass,
} = {}) {
return (
ownerFromUcs(ucs?.operatorCountry) ||
ownerFromSatcat(satcat?.owner) ||
(satelliteClass === 'starlink' ? country('US') : null)
);
}
/** Who operates a satellite: UCS's operator, or SpaceX for Starlink. */
export function satelliteOperator({ ucs = null, satelliteClass } = {}) {
if (ucs?.operator) return ucs.operator;
return satelliteClass === 'starlink' ? 'SpaceX' : null;
}
/**
* The international designator (COSPAR id) from TLE line 1, columns 10–17:
* `98067A` → `1998-067A`. Two-digit years below 57 are 20xx.
* @param {string|null|undefined} line1
* @returns {string|null}
*/
export function cosparIdFromTleLine1(line1) {
const field = String(line1 || '')
.slice(9, 17)
.trim();
const match = /^(\d{2})(\d{3})([A-Z]{1,3})$/.exec(field);
if (!match) return null;
const yy = Number(match[1]);
return `${yy < 57 ? 2000 + yy : 1900 + yy}-${match[2]}${match[3]}`;
}
/**
* The TLE's epoch as epoch milliseconds, from satellite.js's Julian date.
* @param {{jdsatepoch?: number, jdsatepochF?: number}|null|undefined} satrec
* @returns {number|null}
*/
export function tleEpochMs(satrec) {
const jd = Number(satrec?.jdsatepoch) + (Number(satrec?.jdsatepochF) || 0);
return Number.isFinite(jd) && jd > 0
? Math.round((jd - 2440587.5) * 86_400_000)
: null;
}
/** Split one RFC 4180 CSV line (quoted fields may hold commas). */
function csvFields(line) {
const fields = [];
@@ -277,7 +729,7 @@ function csvFields(line) {
* Parse CelesTrak SATCAT CSV into records keyed by NORAD number.
* @param {string} text `records.php?…&FORMAT=CSV` body.
* @returns {Map<number, {objectType: string, opsStatus: string,
* launchDate: string|null}>}
* owner: string, cosparId: string|null, launchDate: string|null}>}
*/
export function parseSatcatCsv(text) {
const records = new Map();
@@ -291,6 +743,8 @@ export function parseSatcatCsv(text) {
norad: at('NORAD_CAT_ID'),
type: at('OBJECT_TYPE'),
status: at('OPS_STATUS_CODE'),
owner: at('OWNER'),
id: at('OBJECT_ID'),
launch: at('LAUNCH_DATE'),
};
if (col.norad < 0 || col.type < 0) return records;
@@ -302,6 +756,8 @@ export function parseSatcatCsv(text) {
records.set(noradId, {
objectType: text(col.type).toUpperCase(),
opsStatus: text(col.status),
owner: text(col.owner),
cosparId: text(col.id) || null,
launchDate: text(col.launch) || null,
});
}
+96 -110
View File
@@ -1,20 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { twoline2satrec } from 'satellite.js';
import {
DEFAULT_SATELLITE_CLASSES,
PRESUMED_DEAD_AFTER_YEARS,
SATELLITE_CLASS_DISPLAY,
SATELLITE_CLASS_IDS,
classifySatellite,
cosparIdFromTleLine1,
mergeClassVisibility,
ownerFromSatcat,
ownerFromUcs,
parseSatcatCsv,
satelliteClassEnterable,
satelliteOperator,
satelliteOwner,
tleEpochMs,
} from './classes.js';
import { CATALOG_GROUPS } from './policy.js';
const NOW = 2026;
const classify = (subject) => classifySatellite({ nowYear: NOW, ...subject });
test('six classes, every one but Starlink on by default', () => {
test('six classes, with stations and imaging on by default and the rest off', () => {
assert.deepEqual(SATELLITE_CLASS_IDS, [
'stations',
'imaging',
@@ -37,28 +45,16 @@ test('six classes, every one but Starlink on by default', () => {
test('SATCAT object type and status file debris first, overruling UCS', () => {
const imaging = { purpose: 'Earth Observation' };
for (const objectType of ['R/B', 'DEB', 'UNK'])
assert.equal(
classify({ name: 'X', satcat: { objectType, opsStatus: '' } }),
'debris',
objectType,
);
assert.equal(classify({ name: 'X', satcat: { objectType, opsStatus: '' } }), 'debris', objectType);
// A satellite UCS listed in 2023 that SATCAT now calls dead or decayed.
for (const opsStatus of ['-', 'D'])
assert.equal(
classify({
name: 'OLDSAT',
ucs: imaging,
satcat: { objectType: 'PAY', opsStatus },
}),
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus } }),
'debris',
opsStatus,
);
assert.equal(
classify({
name: 'OLDSAT',
ucs: imaging,
satcat: { objectType: 'PAY', opsStatus: '+' },
}),
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus: '+' } }),
'imaging',
);
// SATCAT calls a new launch's objects UNK until it names them: only an
@@ -86,33 +82,15 @@ test('SATCAT object type and status file debris first, overruling UCS', () => {
test('the ISS is a station whatever else says', () => {
assert.equal(
classify({
noradId: 25544,
name: 'ISS (ZARYA)',
group: 'visual',
satcat: { objectType: 'DEB' },
}),
classify({ noradId: 25544, name: 'ISS (ZARYA)', group: 'visual', satcat: { objectType: 'DEB' } }),
'stations',
);
});
test('stations: crewed stations and visiting vehicles by name', () => {
assert.equal(
classify({ name: 'CSS (TIANHE)', group: 'stations' }),
'stations',
);
assert.equal(
classify({ name: 'ISS (NAUKA)', group: 'stations' }),
'stations',
);
for (const name of [
'SHENZHOU-21',
'TIANZHOU-9',
'SOYUZ-MS 28',
'PROGRESS-MS 31',
'CREW DRAGON 11',
'CYGNUS NG-23',
])
assert.equal(classify({ name: 'CSS (TIANHE)', group: 'stations' }), 'stations');
assert.equal(classify({ name: 'ISS (NAUKA)', group: 'stations' }), 'stations');
for (const name of ['SHENZHOU-21', 'TIANZHOU-9', 'SOYUZ-MS 28', 'PROGRESS-MS 31', 'CREW DRAGON 11', 'CYGNUS NG-23'])
assert.equal(classify({ name, group: 'visual' }), 'stations', name);
});
@@ -133,11 +111,7 @@ test('UCS purpose decides imaging, telecom and probes', () => {
['Unknown', 'probes'],
];
for (const [purpose, expected] of table)
assert.equal(
classify({ name: 'UNNAMED-1', group: 'visual', ucs: { purpose } }),
expected,
purpose,
);
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', ucs: { purpose } }), expected, purpose);
});
test('satellites launched after the UCS snapshot are classed by name', () => {
@@ -156,42 +130,20 @@ test('satellites launched after the UCS snapshot are classed by name', () => {
['STARLINK-34012', 'starlink'],
];
for (const [name, expected] of table)
assert.equal(
classify({ name, group: 'visual', launchYear: 2025 }),
expected,
name,
);
assert.equal(classify({ name, group: 'visual', launchYear: 2025 }), expected, name);
});
test('the group the TLE came in is the last resort', () => {
assert.equal(
classify({ name: 'UNNAMED-1', group: 'resource', launchYear: 2024 }),
'imaging',
);
assert.equal(
classify({ name: 'UNNAMED-1', group: 'geo', launchYear: 2024 }),
'telecom',
);
assert.equal(
classify({ name: 'UNNAMED-1', group: 'science', launchYear: 2024 }),
'probes',
);
assert.equal(classify({ name: 'UNNAMED-1', group: 'resource', launchYear: 2024 }), 'imaging');
assert.equal(classify({ name: 'UNNAMED-1', group: 'geo', launchYear: 2024 }), 'telecom');
assert.equal(classify({ name: 'UNNAMED-1', group: 'science', launchYear: 2024 }), 'probes');
assert.equal(classify({ name: 'STARLINK-1', group: 'dense' }), 'starlink');
assert.equal(
classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 2024 }),
'probes',
);
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 2024 }), 'probes');
});
test('CubeSats deployed from the ISS are not stations', () => {
// They ride in CelesTrak's stations group under the ISS's 1998 designator.
for (const name of [
'DUPLEX',
'KNACKSAT-2',
'GXIBA-1',
'LEOPARD',
'HMU-SAT2',
]) {
for (const name of ['DUPLEX', 'KNACKSAT-2', 'GXIBA-1', 'LEOPARD', 'HMU-SAT2']) {
assert.equal(
classify({ name, group: 'stations', launchYear: 1998 }),
'probes',
@@ -209,11 +161,7 @@ test('CubeSats deployed from the ISS are not stations', () => {
);
}
assert.equal(
classify({
name: 'UNNAMED-1',
group: 'stations',
ucs: { purpose: 'Earth Observation' },
}),
classify({ name: 'UNNAMED-1', group: 'stations', ucs: { purpose: 'Earth Observation' } }),
'imaging',
);
});
@@ -226,53 +174,89 @@ test('an unknown old payload is presumed dead; a recognisable one is not', () =>
'without a SATCAT record (a failed read) nothing is presumed',
);
assert.equal(
classify({
name: 'ATLAS CENTAUR 2',
group: 'visual',
launchYear: 1963,
satcat: { objectType: 'PAY', opsStatus: '' },
}),
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963, satcat: { objectType: 'PAY', opsStatus: '' } }),
'debris',
'a blank SATCAT status is no evidence of life',
);
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: old + 1 }), 'probes');
assert.equal(classify({ name: 'NOAA 15', group: 'weather', launchYear: 1998 }), 'imaging');
assert.equal(
classify({ name: 'UNNAMED-1', group: 'visual', launchYear: old + 1 }),
'probes',
);
assert.equal(
classify({ name: 'NOAA 15', group: 'weather', launchYear: 1998 }),
'imaging',
);
assert.equal(
classify({
name: 'UNNAMED-1',
group: 'visual',
launchYear: 1990,
satcat: { objectType: 'PAY', opsStatus: '+' },
}),
classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 1990, satcat: { objectType: 'PAY', opsStatus: '+' } }),
'probes',
'SATCAT says it works',
);
});
test('only debris is refused the Cockpit', () => {
for (const id of SATELLITE_CLASS_IDS)
assert.equal(satelliteClassEnterable(id), id !== 'debris', id);
assert.equal(satelliteClassEnterable('nonsense'), false);
});
test('class visibility merges booleans and ignores everything else', () => {
const next = mergeClassVisibility({
telecom: true,
imaging: false,
debris: 'yes',
bogus: true,
});
assert.deepEqual(next, {
...DEFAULT_SATELLITE_CLASSES,
telecom: true,
imaging: false,
});
assert.deepEqual(mergeClassVisibility(null), {
...DEFAULT_SATELLITE_CLASSES,
});
const next = mergeClassVisibility({ telecom: true, imaging: false, debris: 'yes', bogus: true });
assert.deepEqual(next, { ...DEFAULT_SATELLITE_CLASSES, telecom: true, imaging: false });
assert.deepEqual(mergeClassVisibility(null), { ...DEFAULT_SATELLITE_CLASSES });
assert.equal(Object.hasOwn(next, 'bogus'), false);
});
test('UCS owner countries normalise to ISO codes, organisations and joint owners', () => {
assert.deepEqual(ownerFromUcs('USA'), { countryCode: 'US', label: 'United States' });
assert.deepEqual(ownerFromUcs('United Kingdom'), { countryCode: 'GB', label: 'United Kingdom' });
assert.deepEqual(ownerFromUcs('Sinapore'), { countryCode: 'SG', label: 'Singapore' }, 'UCS typo');
assert.deepEqual(ownerFromUcs('Turkey'), { countryCode: 'TR', label: 'Türkiye' });
assert.deepEqual(ownerFromUcs('ESA'), { countryCode: null, label: 'ESA' });
assert.deepEqual(ownerFromUcs('Multinational'), { countryCode: null, label: 'Multinational' });
assert.deepEqual(ownerFromUcs('China/France'), { countryCode: null, label: 'China / France' });
assert.deepEqual(ownerFromUcs('United Kingdom/ESA'), { countryCode: null, label: 'United Kingdom / ESA' });
assert.equal(ownerFromUcs(''), null);
assert.equal(ownerFromUcs(null), null);
});
test('SATCAT owner codes normalise the same way', () => {
assert.deepEqual(ownerFromSatcat('US'), { countryCode: 'US', label: 'United States' });
assert.deepEqual(ownerFromSatcat('PRC'), { countryCode: 'CN', label: 'China' });
assert.deepEqual(ownerFromSatcat('CIS'), { countryCode: 'RU', label: 'Russia' }, 'former USSR');
assert.deepEqual(ownerFromSatcat('ISRO'), { countryCode: 'IN', label: 'India' });
assert.deepEqual(ownerFromSatcat('itso'), { countryCode: null, label: 'Intelsat' });
assert.deepEqual(ownerFromSatcat('EUME'), { countryCode: null, label: 'EUMETSAT' });
assert.deepEqual(ownerFromSatcat('PRES'), { countryCode: null, label: 'China / ESA' });
assert.deepEqual(ownerFromSatcat('TMMC'), { countryCode: null, label: 'Turkmenistan / Monaco' });
for (const code of ['TBD', 'UNK', '', null, 'ZZZZ']) assert.equal(ownerFromSatcat(code), null, String(code));
});
test('owner prefers UCS, falls back to SATCAT, and Starlink is American', () => {
assert.deepEqual(
satelliteOwner({ ucs: { operatorCountry: 'ESA' }, satcat: { owner: 'FR' } }),
{ countryCode: null, label: 'ESA' },
);
assert.deepEqual(satelliteOwner({ satcat: { owner: 'FR' } }), { countryCode: 'FR', label: 'France' });
assert.deepEqual(satelliteOwner({ satelliteClass: 'starlink' }), { countryCode: 'US', label: 'United States' });
assert.equal(satelliteOwner({}), null);
assert.equal(satelliteOperator({ ucs: { operator: 'Planet Labs, Inc.' } }), 'Planet Labs, Inc.');
assert.equal(satelliteOperator({ satelliteClass: 'starlink' }), 'SpaceX');
assert.equal(satelliteOperator({ satelliteClass: 'imaging' }), null);
});
const ISS_LINE1 = '1 25544U 98067A 24001.50000000 .00016717 00000-0 30370-3 0 9993';
const ISS_LINE2 = '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579432323';
test('COSPAR ids come from TLE line 1, across the 1957 century pivot', () => {
assert.equal(cosparIdFromTleLine1(ISS_LINE1), '1998-067A');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '24123BC ')), '2024-123BC');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '57001A ')), '1957-001A');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', ' ')), null);
assert.equal(cosparIdFromTleLine1(null), null);
});
test('the TLE epoch is read as epoch milliseconds', () => {
const satrec = twoline2satrec(ISS_LINE1, ISS_LINE2);
// Day 001.5 of 2024: 1 January 2024, 12:00 UTC.
assert.ok(Math.abs(tleEpochMs(satrec) - Date.UTC(2024, 0, 1, 12)) < 1000);
assert.equal(tleEpochMs(null), null);
assert.equal(tleEpochMs({}), null);
});
test('SATCAT CSV parses, quoted commas included, keyed by NORAD id', () => {
const csv = [
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER,LAUNCH_DATE',
@@ -286,6 +270,8 @@ test('SATCAT CSV parses, quoted commas included, keyed by NORAD id', () => {
assert.deepEqual(records.get(25544), {
objectType: 'PAY',
opsStatus: '+',
owner: 'ISS',
cosparId: '1998-067A',
launchDate: '1998-11-20',
});
assert.equal(records.get(733).objectType, 'R/B');
+332
View File
@@ -0,0 +1,332 @@
import * as Cesium from 'cesium';
import { satelliteClassText } from '../../data/satelliteClass.js';
import {
classifySatellite,
cosparIdFromTleLine1,
satelliteClassEnterable,
satelliteOperator,
satelliteOwner,
tleEpochMs,
} from './classes.js';
import { ISS_NORAD } from './policy.js';
/** The layer id a satellite subject carries through Cockpit events and state. */
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
/**
* While the Cockpit rides a satellite, every other orbit ring (the ISS ring
* included) draws at this fraction of its normal alpha, so the rings stay
* legible without competing with the nadir picture.
*/
export const COCKPIT_ORBIT_DIM_FACTOR = 0.3;
/**
* Write an orbit ring's alpha as a multiple of the alpha it was built with.
* The ring's per-instance attributes exist only once Cesium has updated the
* primitive; until then nothing is written and the next tick retries.
* @param {{primitive: object, instanceId: string, baseColor: Cesium.Color,
* baseDepthFailColor: Cesium.Color, alphaFactor: number}} path
* @param {number} factor 1 restores the built colours exactly.
* @returns {boolean} True when the ring now carries `factor`.
*/
export function applyOrbitPathAlpha(path, factor) {
if (!path?.primitive || !path.baseColor) return false;
if ((path.alphaFactor ?? 1) === factor) return true;
let attributes;
try {
attributes = path.primitive.getGeometryInstanceAttributes?.(
path.instanceId,
);
} catch {
return false;
}
if (!attributes) return false;
const scaled = (color) => color.withAlpha(color.alpha * factor);
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseColor : scaled(path.baseColor),
);
attributes.depthFailColor = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseDepthFailColor : scaled(path.baseDepthFailColor),
);
path.alphaFactor = factor;
return true;
}
/**
* Who and what a catalog entry is: class, COSPAR id, TLE, owner, operator.
* Fixed for the entry's life, so it is worked out once and kept on it.
* @param {number} noradId
* @param {object} sat Catalog entry.
*/
function satelliteIdentity(noradId, sat) {
if (sat.cockpitIdentity) return sat.cockpitIdentity;
const satelliteClass =
sat.satelliteClass ||
classifySatellite({ noradId, name: sat.name, group: sat.group });
const epochMs = tleEpochMs(sat.satrec);
const identity = Object.freeze({
satelliteClass,
cosparId: sat.satcat?.cosparId || cosparIdFromTleLine1(sat.line1),
tle:
sat.line1 && sat.line2 && epochMs !== null
? Object.freeze({ line1: sat.line1, line2: sat.line2, epochMs })
: null,
owner: freezeOwner(
satelliteOwner({ ucs: sat.ucs, satcat: sat.satcat, satelliteClass }),
),
operator: satelliteOperator({ ucs: sat.ucs, satelliteClass }),
// src/layers/satellites/sensors.js entry, or null: the orbital view's sensor swath.
sensor: sat.sensor ?? null,
});
sat.cockpitIdentity = identity;
return identity;
}
function freezeOwner(owner) {
return owner
? Object.freeze({
countryCode: owner.countryCode ?? null,
label: owner.label ?? null,
})
: null;
}
/**
* Normalize the tracked satellite and its per-frame fix into Cockpit subject
* info, in the shape every Cockpit subject kind shares.
* @param {number} noradId NORAD catalog number.
* @param {{name?: string, group?: string}|null} sat Catalog entry.
* @param {{latitude: number, longitude: number, altitude: number,
* speedMps?: number|null, groundTrackDeg?: number|null, atMs?: number}|null}
* fix Per-frame SGP4 sample (orbits.js propagatePosition), at `atMs`.
* @returns {object|null} Subject info, or null without a usable fix.
*/
export function satelliteCockpitInfo(noradId, sat, fix) {
if (!sat || !fix) return null;
const { latitude, longitude, altitude } = fix;
if (![latitude, longitude, altitude].every(Number.isFinite)) return null;
const isIss = noradId === ISS_NORAD;
const identity = satelliteIdentity(noradId, sat);
return {
kind: 'satellite',
layerId: SATELLITE_COCKPIT_LAYER_ID,
id: String(noradId),
noradId,
name: sat.name?.trim() || `SAT-${noradId}`,
// Localized at read time, as the vessel layer's type label is.
classLabel: satelliteClassText(identity.satelliteClass, sat.group, {
isIss,
}),
latitude,
longitude,
altitudeM: altitude,
// SGP4's TEME velocity: the inertial orbital speed, not ground speed.
velocityMps: Number.isFinite(fix.speedMps) ? fix.speedMps : null,
// The time the position is at (epoch ms), the satellites' world-clock
// time; null when the sample does not say.
atMs: Number.isFinite(fix.atMs) ? fix.atMs : null,
// Degrees clockwise from north; null for a geostationary satellite.
groundTrackDeg: Number.isFinite(fix.groundTrackDeg)
? fix.groundTrackDeg
: null,
stale: false,
// src/layers/satellites/classes.js: 'stations'|'imaging'|'telecom'|'starlink'|
// 'probes'|'debris'.
satelliteClass: identity.satelliteClass,
// Whether its class may be ridden in the orbital view (debris may not);
// the Cockpit's entry gate reads it (orbitEntryAllowed).
enterable: satelliteClassEnterable(identity.satelliteClass),
// International designator, e.g. '1998-067A'.
cosparId: identity.cosparId,
tle: identity.tle,
// { countryCode: ISO 3166-1 alpha-2 or null (organisations, joint
// owners), label: English name } or null.
owner: identity.owner,
operator: identity.operator,
sensor: identity.sensor,
};
}
/**
* The tracked satellite as a Cockpit orbital-view subject, and the hold that
* hides its own marks while the Cockpit camera rides it.
*
* While held, the tracked dot is hidden (it would sit on the lens), as are
* the point primitives of docked companions (they share the position within
* 2 km) and the subject's orbit ring: a nadir camera on the ring sees its far
* side, dimmed by the ring's depth-fail appearance, drawn straight across the
* Earth's disk. The detection overlay skips the subject too. The tracked
* card needs nothing here: its overlay source already hides in Cockpit mode.
* Every other orbit ring is dimmed to COCKPIT_ORBIT_DIM_FACTOR of its alpha
* while a subject is set; other satellites' points and labels stay as they
* are. Scene clicks and the layer's Escape are ignored while held, so the
* picture cannot untrack its own subject. Release restores exactly what the
* hold hid or dimmed.
*/
export function createCockpitSubject({ state: layerState, parts }) {
/** The subject is held only while it is the tracked satellite. */
function _cockpitHeld() {
return (
layerState._cockpitSubjectNorad !== null &&
layerState._cockpitSubjectNorad === layerState._trackedNorad
);
}
function _setPointShown(noradId, show) {
const point = layerState._points.get(noradId);
// Released points go back to their class's visibility.
if (point) point.show = show && parts.controls._classVisible(noradId);
}
/**
* Apply or release the hold. Idempotent, and cheap enough for the preRender
* tick, which re-applies it while held so catalog rebuilds, enable and the
* orbit toggle cannot re-show what the hold hides.
* @returns {void}
*/
function _syncCockpitSubjectVisuals() {
const held = _cockpitHeld();
const tracked = layerState._trackedNorad;
const dot = layerState._trackedEntity?.point;
if (held) {
if (dot) dot.show = false;
layerState._cockpitHiddenDot = true;
} else if (layerState._cockpitHiddenDot) {
if (dot) dot.show = true;
layerState._cockpitHiddenDot = false;
}
const hiddenPoints = layerState._cockpitHiddenPoints;
const companions = held ? layerState._dockedCompanions : new Set();
for (const noradId of [...hiddenPoints]) {
if (companions.has(noradId)) continue;
hiddenPoints.delete(noradId);
// The tracked primitive stays hidden: its entity draws the dot.
if (noradId !== tracked) _setPointShown(noradId, true);
}
// Re-applied every sync: a catalog rebuild replaces the point
// primitives, and the new ones arrive shown.
for (const noradId of companions) {
if (noradId === tracked) continue;
hiddenPoints.add(noradId);
_setPointShown(noradId, false);
}
if (held) {
const trackedPoint = layerState._points.get(tracked);
if (trackedPoint) trackedPoint.show = false;
}
const hiddenPath = layerState._cockpitHiddenPath;
if (hiddenPath !== null && (!held || hiddenPath !== tracked)) {
const path = layerState._orbitPaths.get(hiddenPath);
// The ISS's ring also follows its class (and its tracking).
if (path && hiddenPath === ISS_NORAD) parts.controls._syncIssOrbit();
else if (path)
path.primitive.show = parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
layerState._cockpitHiddenPath = null;
}
if (held) {
const path = layerState._orbitPaths.get(tracked);
if (path) {
path.primitive.show = false;
layerState._cockpitHiddenPath = tracked;
}
}
// Every other ring is dimmed for the whole session and restored on
// release; rebuilt rings arrive at full alpha and are dimmed again here.
const subject = layerState._cockpitSubjectNorad;
for (const [noradId, path] of layerState._orbitPaths) {
const dim = subject !== null && noradId !== subject;
applyOrbitPathAlpha(path, dim ? COCKPIT_ORBIT_DIM_FACTOR : 1);
}
}
const methods = {
/**
* The tracked satellite as Cockpit subject info, from the same per-frame
* SGP4 sample the dot and the follow camera use.
* @returns {{kind: 'satellite', layerId: 'satellites', id: string,
* noradId: number, name: string, classLabel: string,
* latitude: number, longitude: number, altitudeM: number,
* velocityMps: number|null, stale: false,
* satelliteClass: 'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris',
* cosparId: string|null,
* tle: {line1: string, line2: string, epochMs: number}|null,
* owner: {countryCode: string|null, label: string|null}|null,
* operator: string|null}|null} Null while the layer is off or nothing
* is tracked.
*/
getCockpitSubject() {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
const noradId = layerState._trackedNorad;
return satelliteCockpitInfo(
noradId,
layerState._catalog.get(noradId),
parts.tracking._getTrackedFramePosition(),
);
},
/**
* The tracked satellite's Earth-fixed position this frame: the per-frame
* cache the dot and follow camera read, never a separate propagation.
* @param {Cesium.Cartesian3} [result] Receives the position.
* @returns {Cesium.Cartesian3|null} Null while the layer is off, nothing
* is tracked or no sample has propagated.
*/
getCockpitPosition(result) {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
if (!parts.tracking._getTrackedFramePosition()) return null;
return Cesium.Cartesian3.clone(layerState._trackedFrameCartesian, result);
},
/**
* Mark the satellite whose position the Cockpit camera occupies, or
* release it. The hold applies while that satellite is tracked.
* @param {string|number|null} noradId Subject NORAD id, or null to release.
* @returns {boolean} Always true.
*/
setCockpitSubject(noradId) {
const next =
noradId === null || noradId === undefined
? null
: parts.tracking._normalizeTrackedNorad(noradId);
if (layerState._cockpitSubjectNorad === next) return true;
layerState._cockpitSubjectNorad = next;
_syncCockpitSubjectVisuals();
return true;
},
/**
* Put the follow camera back on the tracked satellite after the Cockpit
* released it, without re-tracking (no new selection or context events).
* @param {string|number} noradId The satellite the Cockpit rode.
* @returns {boolean} True when that satellite is still tracked and the
* follow camera was restored.
*/
refocusTrackedById(noradId) {
const id = parts.tracking._normalizeTrackedNorad(noradId);
const viewer = layerState._viewer;
const entity = layerState._trackedEntity;
if (
id === null ||
id !== layerState._trackedNorad ||
!viewer ||
!entity ||
!viewer.entities?.contains?.(entity)
)
return false;
viewer.camera?.cancelFlight?.();
viewer.trackedEntity = entity;
return true;
},
};
return { _cockpitHeld, _syncCockpitSubjectVisuals, methods };
}
@@ -0,0 +1,604 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createOrbits } from './orbits.js';
import { createLabels } from './labels.js';
import { createTracking } from './tracking.js';
import { createRendering } from './rendering.js';
import { createCatalog } from './catalog.js';
import { createLifecycle } from './lifecycle.js';
import { createInteraction } from './interaction.js';
import { createIngestion } from './ingestion.js';
import {
COCKPIT_ORBIT_DIM_FACTOR,
applyOrbitPathAlpha,
createCockpitSubject,
satelliteCockpitInfo,
} from './cockpitSubject.js';
import { groundTrackBearingDeg } from './orbits.js';
import { indexImagingSensors } from './sensors.js';
import { ISS_NORAD } from './policy.js';
const COMPANION = 25545;
const GPS = 32711;
function tle(name, id, motion = '15.48899044', inclination = ' 51.6326') {
// Owned synthetic element sets; never live requests. The station pair
// share elements, so the companion is docked to the ISS.
return `${name}\n1 ${id}U 98067A 26289.78971908 .00007803 00000+0 15012-3 0 9995\n2 ${id} ${inclination} 58.3278 0006748 271.9059 88.1156 ${motion}590607`;
}
const GROUP_TEXT = {
stations: [
tle('ISS (ZARYA)', ISS_NORAD),
tle('PROGRESS-MS 31', COMPANION),
].join('\n'),
'gps-ops': tle('GPS FIXTURE', GPS, ' 2.00563000', ' 55.0000'),
};
/** Whether the tracked entity draws its dot (an unset show is shown). */
function dotShown(f) {
const show = f.state._trackedEntity.point.show;
return show === undefined ? true : show.getValue();
}
const SATCAT_HEADER =
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER';
const SATCAT_TEXT = {
stations: [
SATCAT_HEADER,
`ISS (ZARYA),1998-067A,${ISS_NORAD},PAY,+,ISS`,
`PROGRESS-MS 31,2026-001A,${COMPANION},PAY,+,CIS`,
].join('\n'),
// No designator: the TLE's is used.
'gps-ops': [SATCAT_HEADER, `GPS FIXTURE,,${GPS},PAY,+,US`].join('\n'),
};
const UCS = new Map([
[
ISS_NORAD,
{
noradId: ISS_NORAD,
operator: 'NASA/Multinational',
operatorCountry: 'Multinational',
purpose: 'Space Science',
},
],
]);
// One sensor entry, matched by NORAD number, for the orbital zoom cap.
const SENSORS = indexImagingSensors({
entries: [
{
id: 'fixture-imager',
label: 'Fixture imager',
match: { norad: [GPS] },
narrowestSwathKm: 50,
swathConfirmed: true,
sources: ['https://example.test/spec'],
},
],
});
async function fixture(t) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
return { ok: true, status: 200, text, stale: false };
},
async readSatcat(group) {
return { ok: true, status: 200, text: SATCAT_TEXT[group] || '' };
},
readUcs: async () => UCS,
readSensors: async () => SENSORS,
};
const noop = () => {};
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
layerState: { isExplicitLayerStateOrigin: () => false },
focus: {
clearFocusTarget: noop,
publishFocusTargetFromCachedPosition: noop,
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
},
context: {
clearTrackedSubjectContext: noop,
getContextStore: () => ({ entities: new Map() }),
refreshTrackedSubjectContext: noop,
selectTrackedSubjectContext: noop,
},
readout: { refreshTrackedReadout: noop },
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
};
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
for (const [name, factory] of Object.entries({
controls: createControls,
orbits: createOrbits,
labels: createLabels,
tracking: createTracking,
rendering: createRendering,
catalog: createCatalog,
interaction: createInteraction,
lifecycle: createLifecycle,
ingestion: createIngestion,
cockpit: createCockpitSubject,
})) {
parts[name] = factory(context);
}
const viewer = {
trackedEntity: undefined,
entities: new Cesium.EntityCollection(),
scene: {
canvas: new EventTarget(),
primitives: new Cesium.PrimitiveCollection(),
preRender: new Cesium.Event(),
frameState: { frameNumber: 1 },
},
trackedEntityChanged: new Cesium.Event(),
};
const { log, warn } = console;
console.log = noop;
console.warn = noop;
await parts.lifecycle.methods.init(viewer);
await parts.ingestion.methods.update(viewer);
parts.lifecycle.methods.enable(viewer);
// GPS is TELECOM; these tests need its point on screen whatever the default.
parts.controls.methods.setParams({ classes: { telecom: true } });
Object.assign(console, { log, warn });
t.after(() => {
console.log = noop;
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer);
console.log = log;
viewer.scene.primitives.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
const methods = { ...parts.controls.methods, ...parts.cockpit.methods };
return {
state,
parts,
viewer,
methods,
track(id) {
const log = console.log;
console.log = noop;
try {
return methods.trackById(id);
} finally {
console.log = log;
}
},
nextFrame() {
viewer.scene.frameState.frameNumber += 1;
parts.rendering._preRenderTick();
},
ring: (id) => state._orbitPaths.get(id)?.primitive,
detected: () =>
methods.getDetectableObjects().map((object) => object.sourceId),
};
}
test('no subject while the layer is off or nothing is tracked', async (t) => {
const f = await fixture(t);
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
assert.equal(f.track(ISS_NORAD), true);
f.state._enabled = false;
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
});
test('the tracked satellite is a subject read from the per-frame sample', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const propagate = f.parts.orbits.propagatePosition;
let propagations = 0;
f.parts.orbits.propagatePosition = (...args) => {
propagations += 1;
return propagate(...args);
};
f.viewer.scene.frameState.frameNumber += 1;
const subject = f.methods.getCockpitSubject();
const position = f.methods.getCockpitPosition();
f.methods.getCockpitSubject();
assert.equal(propagations, 1, 'one SGP4 sample per frame for every reader');
assert.equal(subject.kind, 'satellite');
assert.equal(subject.layerId, 'satellites');
assert.equal(subject.id, String(ISS_NORAD));
assert.equal(subject.noradId, ISS_NORAD);
assert.equal(subject.name, 'ISS (ZARYA)');
assert.equal(subject.classLabel, 'STATIONS · ISS');
assert.equal(subject.stale, false);
assert.ok(subject.altitudeM > 150e3 && subject.altitudeM < 1000e3);
assert.ok(subject.velocityMps > 7000 && subject.velocityMps < 8000);
// The same point the tracked dot and follow camera use, as a copy.
const cached = f.state._trackedFrameCartesian;
assert.ok(Cesium.Cartesian3.equals(position, cached));
assert.notEqual(position, cached);
const target = new Cesium.Cartesian3();
assert.equal(f.methods.getCockpitPosition(target), target);
const geodetic = Cesium.Cartographic.fromCartesian(position);
assert.ok(
Math.abs(Cesium.Math.toDegrees(geodetic.latitude) - subject.latitude) <
1e-6,
);
f.parts.orbits.propagatePosition = propagate;
});
test('the subject says what it is, which TLE it flies, and who owns and runs it', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const iss = f.methods.getCockpitSubject();
assert.equal(iss.satelliteClass, 'stations');
assert.equal(iss.cosparId, '1998-067A');
assert.match(iss.tle.line1, /^1 25544U/);
assert.match(iss.tle.line2, /^2 25544 /);
// Day 289.789… of 2026.
assert.ok(
Math.abs(
iss.tle.epochMs - (Date.UTC(2026, 0, 1) + 288.78971908 * 86_400_000),
) < 1000,
);
assert.deepEqual(
iss.owner,
{ countryCode: null, label: 'Multinational' },
'UCS before SATCAT',
);
assert.equal(iss.operator, 'NASA/Multinational');
assert.equal(
f.methods.getCockpitSubject().owner,
iss.owner,
'worked out once',
);
f.track(GPS);
const gps = f.methods.getCockpitSubject();
assert.equal(gps.satelliteClass, 'telecom');
assert.equal(
gps.cosparId,
'1998-067A',
'from TLE line 1 when SATCAT has none',
);
assert.deepEqual(gps.owner, { countryCode: 'US', label: 'United States' });
assert.equal(gps.operator, null);
// The sensor pack is matched once, at ingestion.
assert.equal(gps.sensor?.id, 'fixture-imager');
assert.equal(gps.sensor.narrowestSwathKm, 50);
assert.equal(iss.sensor, null, 'no sensor entry, no extra zoom');
// A bare catalog entry still answers every field.
const bare = satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(bare.satelliteClass, 'telecom');
// An imaging satellite CelesTrak lists among the brightest objects names
// its class, not the 'visual' group it came in.
const landsat = satelliteCockpitInfo(
49260,
{ name: 'LANDSAT 9', group: 'visual', satelliteClass: 'imaging' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(landsat.classLabel, 'IMAGING');
assert.equal(bare.tle, null);
assert.equal(bare.owner, null);
assert.equal(bare.operator, null);
assert.equal(bare.cosparId, null);
});
test('a GNSS satellite carries its class and an orbital speed', async (t) => {
const f = await fixture(t);
f.track(GPS);
const subject = f.methods.getCockpitSubject();
assert.equal(subject.classLabel, 'TELECOM · GPS');
assert.ok(subject.altitudeM > 19e6 && subject.altitudeM < 21.5e6);
assert.ok(subject.velocityMps > 3500 && subject.velocityMps < 4200);
assert.equal(
satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{
latitude: 1,
longitude: 2,
altitude: 3,
},
).velocityMps,
null,
);
assert.equal(satelliteCockpitInfo(GPS, null, { latitude: 0 }), null);
});
test('holding the subject hides its dot, ring, docked companions and bracket', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
assert.ok(f.state._dockedCompanions.has(COMPANION));
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.ok(f.detected().includes(ISS_NORAD));
assert.equal(f.methods.setCockpitSubject(String(ISS_NORAD)), true);
assert.equal(dotShown(f), false);
assert.equal(f.ring(ISS_NORAD).show, false);
assert.equal(f.state._points.get(COMPANION).show, false);
assert.equal(f.state._points.get(GPS).show, true);
assert.ok(!f.detected().includes(ISS_NORAD));
// Toggling orbits on again cannot bring the ring back while held.
f.methods.setParams({ showOrbits: true });
assert.equal(f.ring(ISS_NORAD).show, true);
f.nextFrame();
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.setCockpitSubject(null);
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
// The tracked primitive stays hidden: the tracked entity draws the dot.
assert.equal(f.state._points.get(ISS_NORAD).show, false);
assert.ok(f.detected().includes(ISS_NORAD));
});
test('a subject that is not tracked holds nothing', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(ISS_NORAD);
f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.ring(ISS_NORAD).show, true);
});
test('untracking a held subject gives its marks back', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.stopTracking();
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._points.get(ISS_NORAD).show, true);
});
test('a catalog refresh while held keeps the subject and its companions hidden', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
const log = console.log;
console.log = () => {};
try {
await f.parts.ingestion.methods.update(f.viewer);
} finally {
console.log = log;
}
f.nextFrame();
assert.equal(f.state._points.get(COMPANION).show, false, 'companion');
assert.equal(f.state._points.get(ISS_NORAD).show, false, 'tracked point');
f.methods.setCockpitSubject(null);
assert.equal(f.state._points.get(COMPANION).show, true, 'given back');
});
test('untracking a held ISS leaves its ring hidden while Stations is off', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
f.methods.setParams({ classes: 'itpd' });
f.nextFrame();
f.methods.stopTracking();
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.setParams({ classes: 'sitpd' });
assert.equal(f.ring(ISS_NORAD).show, true);
});
test('tracking without a Cockpit subject keeps its marks', async (t) => {
const f = await fixture(t);
f.track(GPS);
for (let i = 0; i < 3; i++) f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._cockpitHiddenPoints.size, 0);
assert.equal(f.state._cockpitHiddenPath, null);
});
/**
* Give a ring the per-instance attributes Cesium creates on its first
* update, starting from the colours it was built with. Rings in this
* fixture are never rendered, so the test stands in for that update.
*/
function readyRing(f, id) {
const path = f.state._orbitPaths.get(id);
const attributes = {
color: Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.toValue(
path.baseDepthFailColor,
),
};
path.primitive.getGeometryInstanceAttributes = (instanceId) =>
instanceId === path.instanceId ? attributes : undefined;
return attributes;
}
/** A colour attribute's alpha byte. */
const alphaByte = (value) => value[3];
test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.nextFrame();
assert.ok(f.ring(ISS_NORAD), 'the ISS ring is drawn beside the tracked one');
const iss = readyRing(f, ISS_NORAD);
const gps = readyRing(f, GPS);
const builtColor = [...iss.color];
const builtDepthFail = [...iss.depthFailColor];
const gpsBuilt = [...gps.color];
f.methods.setCockpitSubject(GPS);
const dimmed = (byte) => Math.round(byte * COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(Math.abs(alphaByte(iss.color) - dimmed(builtColor[3])) <= 1);
assert.ok(
Math.abs(alphaByte(iss.depthFailColor) - dimmed(builtDepthFail[3])) <= 1,
);
assert.deepEqual([...iss.color].slice(0, 3), builtColor.slice(0, 3));
assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible');
assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden');
assert.deepEqual([...gps.color], gpsBuilt, 'the ridden ring is not dimmed');
// Other satellites' points stay as they are.
assert.equal(f.state._points.get(COMPANION).show, true);
// A rebuilt ring arrives at full alpha and is dimmed again on the tick.
f.parts.rendering._hideOrbitPath(ISS_NORAD);
f.parts.rendering._showOrbitPath(ISS_NORAD, Cesium.Color.YELLOW);
const rebuilt = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.ok(alphaByte(rebuilt.color) < builtColor[3]);
f.methods.setCockpitSubject(null);
assert.deepEqual(
[...rebuilt.color],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseColor,
),
],
'released rings get their built colours back exactly',
);
assert.deepEqual(
[...rebuilt.depthFailColor],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseDepthFailColor,
),
],
);
assert.equal(f.ring(GPS).show, true);
assert.deepEqual([...gps.color], gpsBuilt);
});
test('a ring not yet updated by Cesium is dimmed once it is', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(GPS);
const path = f.state._orbitPaths.get(ISS_NORAD);
assert.equal(path.alphaFactor, 1, 'nothing written before the first update');
const iss = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.equal(path.alphaFactor, COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(alphaByte(iss.color) < 100);
assert.equal(applyOrbitPathAlpha(path, 1), true);
assert.deepEqual(
[...iss.color],
[...Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor)],
);
});
test('a held subject ignores the layer Escape; refocus restores the follow', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, ISS_NORAD, 'the Cockpit owns Escape');
// The Cockpit took the follow camera off the entity; refocus puts it back.
f.viewer.trackedEntity = undefined;
f.methods.setCockpitSubject(null);
assert.equal(f.methods.refocusTrackedById(GPS), false, 'not the tracked one');
assert.equal(f.viewer.trackedEntity, undefined);
assert.equal(f.methods.refocusTrackedById(String(ISS_NORAD)), true);
assert.equal(f.viewer.trackedEntity, f.state._trackedEntity);
assert.equal(f.state._trackedNorad, ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, null, 'released, Escape untracks again');
assert.equal(f.methods.refocusTrackedById(ISS_NORAD), false);
});
test('the ground track bearing comes from the SGP4 velocity, less the Earth turning', () => {
const near = (actual, expected) =>
assert.ok(Math.abs(actual - expected) < 0.2, `${actual} vs ${expected}`);
// An ISS-like orbit (51.6°, 7.66 km/s) crossing the equator northbound at
// 0°E: inertially 38.4° from north, but the ground turns east beneath it,
// so the track runs closer to north.
const inclination = (51.6 * Math.PI) / 180;
const iss = {
position: { x: 6771, y: 0, z: 0 },
velocity: {
x: 0,
y: 7.66 * Math.cos(inclination),
z: 7.66 * Math.sin(inclination),
},
};
near(groundTrackBearingDeg(iss.position, iss.velocity, 0, 0, 0), 35.4);
// The same state given in TEME a quarter sidereal turn on (GMST 90°):
// still over 0°E, so the same ground track.
near(
groundTrackBearingDeg(
{ x: 0, y: 6771, z: 0 },
{ x: -iss.velocity.y, y: 0, z: iss.velocity.z },
Math.PI / 2,
0,
0,
),
35.4,
);
// Geostationary: it turns with the Earth, so there is no ground track.
assert.equal(
groundTrackBearingDeg(
{ x: 42164, y: 0, z: 0 },
{ x: 0, y: 3.0747, z: 0 },
0,
0,
0,
),
null,
);
assert.equal(groundTrackBearingDeg(iss.position, null, 0, 0, 0), null);
// The subject passes the sample's track through.
const sat = { name: 'X', group: 'stations' };
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
assert.equal(
satelliteCockpitInfo(1, sat, { ...fix, groundTrackDeg: 35.4 })
.groundTrackDeg,
35.4,
);
assert.equal(satelliteCockpitInfo(1, sat, fix).groundTrackDeg, null);
});
test('the subject says whether its class may be ridden', () => {
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
const subject = (satelliteClass) =>
satelliteCockpitInfo(
1,
{ name: 'X', group: 'visual', satelliteClass },
fix,
);
assert.equal(subject('debris').enterable, false);
for (const satelliteClass of [
'stations',
'imaging',
'telecom',
'starlink',
'probes',
])
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
});
+72 -2
View File
@@ -48,12 +48,13 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Show or hide every point by its class. The tracked satellite's point
* stays hidden (its entity draws the dot). The ISS's ring and label go
* with its class.
* stays hidden (its entity draws the dot), as do points a Cockpit hold hid.
* The ISS's ring and label go with its class.
*/
function _applyClassVisibility() {
for (const [noradId, point] of layerState._points) {
if (noradId === layerState._trackedNorad) continue;
if (layerState._cockpitHiddenPoints?.has(noradId)) continue;
point.show = _classVisible(noradId);
}
_syncIssOrbit();
@@ -253,6 +254,9 @@ export function createControls({ state: layerState, services, parts, source }) {
// that card instead. Only members of the tracked cluster are affected —
// unrelated nearby satellites are never suppressed.
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
// The Cockpit camera rides a held subject; a bracket on it would sit
// on the lens.
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
const cat = layerState._catalog.get(noradId);
let object = layerState._detectionObjects.get(noradId);
if (!object) {
@@ -367,6 +371,72 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* The shown satellites nearest a position, nearest first, from per-point
* state (no SGP4 re-propagation): a bounded pass that keeps only the
* nearest `maxCount`, and reads latitude and longitude for those alone.
* Dense extras are left out, as in `getAllPositions`.
* @param {Cesium.Cartesian3} center Earth-fixed position.
* @param {number} [maxCount=8] Most entries to return.
* @param {{excludeIds?: Array<number|string>,
* excludeClasses?: Array<string>}} [options] Satellites, and classes
* (e.g. 'debris'), to leave out.
* @returns {Array<{ id: number, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, satelliteClass: string|null, distanceM: number }>}
*/
getNearestPositions(
center,
maxCount = 8,
{ excludeIds = [], excludeClasses = [] } = {},
) {
const nearest = [];
const cap = Number.isFinite(maxCount) ? Math.floor(maxCount) : 8;
if (
cap < 1 ||
!center ||
!layerState._points ||
layerState._points.size === 0
)
return nearest;
const excluded = new Set(excludeIds.map(String));
const classes = new Set(excludeClasses);
const dense = layerState._denseIds.length > 0;
for (const [noradId, point] of layerState._points) {
const p = point.position;
if (!p || excluded.has(String(noradId))) continue;
if (!_classVisible(noradId)) continue;
const sat = layerState._catalog.get(noradId);
if (dense && sat?.group === 'dense') continue;
if (classes.size && classes.has(sat?.satelliteClass)) continue;
const dx = p.x - center.x;
const dy = p.y - center.y;
const dz = p.z - center.z;
const distanceSq = dx * dx + dy * dy + dz * dz;
if (nearest.length === cap && distanceSq >= nearest[cap - 1].distanceSq)
continue;
// Insertion into a short sorted list: no copy or sort of the rest.
let at = nearest.length;
while (at > 0 && nearest[at - 1].distanceSq > distanceSq) at -= 1;
nearest.splice(at, 0, { noradId, point, sat, distanceSq });
if (nearest.length > cap) nearest.pop();
}
const result = [];
for (const { noradId, point, sat, distanceSq } of nearest) {
const carto = Cesium.Cartographic.fromCartesian(point.position);
if (!carto) continue;
result.push({
id: noradId,
label: sat ? sat.name.trim() : String(noradId),
position: point.position,
latitude: Cesium.Math.toDegrees(carto.latitude),
longitude: Cesium.Math.toDegrees(carto.longitude),
altitudeM: carto.height,
satelliteClass: sat?.satelliteClass ?? null,
distanceM: Math.sqrt(distanceSq),
});
}
return result;
},
/**
* Track a satellite by NORAD id (camera follow + orbit path + highlight),
* same path as clicking its point.
+3
View File
@@ -1,5 +1,6 @@
import { createControls } from './controls.js';
import { createCatalog } from './catalog.js';
import { createCockpitSubject } from './cockpitSubject.js';
import { createLabels } from './labels.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
@@ -29,9 +30,11 @@ export function createSatellitesLayer({ services, source }) {
parts.interaction = createInteraction(context);
parts.lifecycle = createLifecycle(context);
parts.ingestion = createIngestion(context);
parts.cockpit = createCockpitSubject(context);
return Object.assign(
{},
parts.controls.methods,
parts.cockpit.methods,
parts.lifecycle.methods,
parts.ingestion.methods,
{
+38 -11
View File
@@ -4,6 +4,7 @@ import { msg } from '../../i18n/index.js';
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
import { CATALOG_GROUPS, ISS_NORAD, POINT_STYLES } from './policy.js';
import { classifySatellite, parseSatcatCsv } from './classes.js';
import { matchImagingSensor } from './sensors.js';
/**
* How long a catalog rebuild waits for SATCAT before it classifies without
@@ -26,20 +27,38 @@ export function createIngestion({
source,
}) {
/**
* The local pack the classes are read from: the UCS pack. It is not needed
* to render: a failed read leaves the last pack (or none) and
* classification falls back to names and groups.
* The local packs the classes and zoom steps are read from: the UCS pack
* and the imaging-sensor pack. Neither is needed to render: a failed read
* leaves the last pack (or none) and classification falls back to names
* and groups.
*/
async function _readLocalEvidence() {
if (layerState._ucs) return;
const pack = await Promise.resolve()
.then(() => source.readUcs?.())
.then((loaded) => (loaded instanceof Map ? loaded : null))
.catch((error) => {
console.warn('[Data:Satellites] UCS pack unavailable:', error);
return null;
});
const ucs = layerState._ucs
? Promise.resolve(layerState._ucs)
: Promise.resolve()
.then(() => source.readUcs?.())
.then((pack) => (pack instanceof Map ? pack : null))
.catch((error) => {
console.warn('[Data:Satellites] UCS pack unavailable:', error);
return null;
});
// The sensor pack only adds zoom steps in the orbital view; without it
// every satellite keeps the base steps.
const sensors = layerState._sensors
? Promise.resolve(layerState._sensors)
: Promise.resolve()
.then(() => source.readSensors?.())
.then((index) => (index?.byNorad instanceof Map ? index : null))
.catch((error) => {
console.warn(
'[Data:Satellites] Imaging sensor pack unavailable:',
error,
);
return null;
});
const [pack, sensorIndex] = await Promise.all([ucs, sensors]);
if (pack) layerState._ucs = pack;
if (sensorIndex) layerState._sensors = sensorIndex;
}
/**
@@ -118,6 +137,8 @@ export function createIngestion({
const satcat = layerState._satcat.get(noradId) || null;
if (satcat === sat.satcat) continue;
sat.satcat = satcat;
// The Cockpit identity (owner, COSPAR id) reads SATCAT too.
sat.cockpitIdentity = undefined;
const next = classifySatellite({
noradId,
name: sat.name,
@@ -322,6 +343,8 @@ export function createIngestion({
groups,
// satellite.js does not keep the designator the year match reads.
launchYear,
line1: entry.line1,
line2: entry.line2,
satelliteClass: classifySatellite({
noradId,
name: entry.name,
@@ -333,6 +356,10 @@ export function createIngestion({
}),
ucs,
satcat,
sensor: matchImagingSensor(layerState._sensors, {
noradId,
name: entry.name,
}),
});
coreStale ||= entry.stale;
+20
View File
@@ -293,3 +293,23 @@ test('a current SATCAT read is kept between updates; a failed one is asked again
await update();
assert.equal(reads, 3 * perUpdate, 'a failed read is asked again');
});
test('a failed imaging-sensor pack is warned about, as the UCS pack is', async (t) => {
t.mock.method(console, 'log', () => {});
const warn = t.mock.method(console, 'warn', () => {});
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
source: {
readSensors: async () => {
throw new Error('chunk failed');
},
},
});
await update();
assert.ok(
warn.mock.calls.some((call) =>
/sensor pack unavailable/i.test(call.arguments[0]),
),
'the failure is not swallowed',
);
assert.equal(state._catalog.get(40115).sensor, null, 'base zoom steps');
});
+5
View File
@@ -10,6 +10,8 @@ export function createInteraction({
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
function _onKeyDown(e) {
// The Cockpit owns Escape while it rides the tracked satellite.
if (parts.cockpit?._cockpitHeld()) return;
if (layerState._enabled && e.key === 'Escape' && layerState._trackedNorad) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._clearTracking(false, { origin: 'user' });
@@ -50,6 +52,9 @@ export function createInteraction({
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (!layerState._enabled) return;
// The Cockpit camera rides the tracked satellite: a click on the
// picture below must not untrack it or switch satellites.
if (parts.cockpit?._cockpitHeld()) return;
const picked = viewer.scene.pick(click.position);
if (picked) {
+4
View File
@@ -51,6 +51,10 @@ export function createLifecycle({
layerState._trackedFrameNumber = -1;
layerState._trackedFrameGeo = null;
layerState._trackedFrameNowForTest = null;
// The new catalog's points and rings carry no hold.
layerState._cockpitHiddenPoints = new Set();
layerState._cockpitHiddenPath = null;
layerState._cockpitHiddenDot = false;
layerState._lastFocusUpdate = 0;
layerState._activeFocusCount = 0;
layerState._enabled = false;
@@ -0,0 +1,70 @@
// src/layers/satellites/nearestPositions.test.mjs — the satellites nearest a
// position: bounded to the nearest few, nearest first, hidden classes,
// dense extras and asked-for exclusions left out.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createControls } from './controls.js';
function controlsWith(satellites, { classes, dense = [] } = {}) {
const state = {
_points: new Map(),
_catalog: new Map(),
_denseIds: dense,
_params: classes ? { classes } : {},
};
for (const sat of satellites) {
state._points.set(sat.id, {
position: Cesium.Cartesian3.fromDegrees(sat.lon, sat.lat, sat.alt),
});
state._catalog.set(sat.id, {
name: `${sat.name} `,
satelliteClass: sat.cls,
group: sat.group,
});
}
return createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: {},
}).methods;
}
const SATELLITES = [
{ id: 1, name: 'NEAR', lat: 30.5, lon: -97, alt: 500_000, cls: 'imaging' },
{ id: 2, name: 'MID', lat: 33, lon: -97, alt: 500_000, cls: 'stations' },
{ id: 3, name: 'FAR', lat: -40, lon: 80, alt: 500_000, cls: 'imaging' },
{ id: 4, name: 'DEB', lat: 30.1, lon: -97, alt: 500_000, cls: 'debris' },
{ id: 5, name: 'TELECOM', lat: 30.2, lon: -97, alt: 500_000, cls: 'telecom' },
{ id: 6, name: 'SELF', lat: 30, lon: -97, alt: 420_000, cls: 'stations' },
{ id: 7, name: 'EXTRA', lat: 30.3, lon: -97, alt: 500_000, cls: 'imaging', group: 'dense' },
];
const CENTRE = Cesium.Cartesian3.fromDegrees(-97, 30, 420_000);
test('the nearest shown satellites come first, bounded, with their distance', () => {
const methods = controlsWith(SATELLITES, {
classes: { stations: true, imaging: true, debris: true, telecom: false },
dense: [7],
});
const nearest = methods.getNearestPositions(CENTRE, 3, {
excludeIds: [6],
excludeClasses: ['debris'],
});
assert.deepEqual(
nearest.map((entry) => entry.label),
['NEAR', 'MID', 'FAR'],
'no self, debris, hidden telecom or dense extra',
);
for (let i = 1; i < nearest.length; i += 1)
assert.ok(nearest[i].distanceM >= nearest[i - 1].distanceM);
const exact = Cesium.Cartesian3.distance(CENTRE, nearest[0].position);
assert.ok(Math.abs(nearest[0].distanceM - exact) < 1e-6);
assert.ok(Math.abs(nearest[0].latitude - 30.5) < 1e-6);
assert.equal(nearest[0].satelliteClass, 'imaging');
assert.equal(methods.getNearestPositions(CENTRE, 1, { excludeIds: [6] })[0].label, 'DEB');
assert.deepEqual(methods.getNearestPositions(null, 3), []);
assert.deepEqual(methods.getNearestPositions(CENTRE, 0), []);
assert.deepEqual(methods.getNearestPositions(CENTRE, 0.5), []);
assert.equal(methods.getNearestPositions(CENTRE, 2.5).length, 2);
});
+62 -2
View File
@@ -15,6 +15,57 @@ import {
} from '../../sources/tle.js';
import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js';
/** The Earth's rotation rate, rad/s (WGS84). */
const EARTH_ROTATION_RAD_S = 7.292115e-5;
/** Below this ground speed a satellite holds still over the ground (GEO), m/s. */
const GROUND_TRACK_MIN_SPEED_MPS = 10;
/**
* The ground track's bearing, degrees clockwise from north, from one SGP4
* state: the inertial velocity turned into the Earth-fixed frame, less the
* Earth's rotation under the satellite, read in the east/north plane at the
* sub-satellite point. Null without a velocity, or for a satellite that holds
* still over the ground (geostationary).
* @param {{x: number, y: number, z: number}} positionKm TEME position, km.
* @param {{x: number, y: number, z: number}|null} velocityKmS TEME velocity, km/s.
* @param {number} gmst Greenwich mean sidereal time, radians.
* @param {number} latitudeDeg Sub-satellite latitude.
* @param {number} longitudeDeg Sub-satellite longitude.
* @returns {number|null}
*/
export function groundTrackBearingDeg(
positionKm,
velocityKmS,
gmst,
latitudeDeg,
longitudeDeg,
) {
if (!positionKm || !velocityKmS || !Number.isFinite(gmst)) return null;
const cosG = Math.cos(gmst);
const sinG = Math.sin(gmst);
// TEME to Earth-fixed is a turn about z by GMST.
const rx = cosG * positionKm.x + sinG * positionKm.y;
const ry = -sinG * positionKm.x + cosG * positionKm.y;
const vx =
(cosG * velocityKmS.x + sinG * velocityKmS.y + EARTH_ROTATION_RAD_S * ry) *
1000;
const vy =
(-sinG * velocityKmS.x + cosG * velocityKmS.y - EARTH_ROTATION_RAD_S * rx) *
1000;
const vz = velocityKmS.z * 1000;
const φ = (latitudeDeg * Math.PI) / 180;
const λ = (longitudeDeg * Math.PI) / 180;
const east = -Math.sin(λ) * vx + Math.cos(λ) * vy;
const north =
-Math.sin(φ) * Math.cos(λ) * vx -
Math.sin(φ) * Math.sin(λ) * vy +
Math.cos(φ) * vz;
if (![east, north].every(Number.isFinite)) return null;
if (Math.hypot(east, north) < GROUND_TRACK_MIN_SPEED_MPS) return null;
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
}
export function createOrbits({ state: layerState, services, parts, source }) {
/**
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
@@ -68,11 +119,20 @@ export function createOrbits({ state: layerState, services, parts, source }) {
? Math.hypot(velocity.x, velocity.y, velocity.z) * 1000
: null;
const latitude = degreesLat(geo.latitude);
const longitude = degreesLong(geo.longitude);
return {
longitude: degreesLong(geo.longitude),
latitude: degreesLat(geo.latitude),
longitude,
latitude,
altitude: geo.height * 1000, // km → meters
speedMps: Number.isFinite(speedMps) ? speedMps : null,
groundTrackDeg: groundTrackBearingDeg(
posVel.position,
velocity,
gmst,
latitude,
longitude,
),
};
} catch {
return null;
+17 -6
View File
@@ -52,21 +52,23 @@ export function createRendering({
if (basePositions.length < 2) return;
const pathColor = color || Cesium.Color.CYAN;
// Kept so the Cockpit's orbit dim (cockpitSubject.js) restores exactly.
const baseColor = pathColor.withAlpha(0.6);
const baseDepthFailColor = pathColor.withAlpha(0.35);
const instanceId = `satellite-orbit:${noradId}`;
const primitive = new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
id: instanceId,
geometry: new Cesium.PolylineGeometry({
positions: basePositions,
width: noradId === ISS_NORAD ? 2.5 : 2.0,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.6),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.35),
),
color: Cesium.ColorGeometryInstanceAttribute.fromColor(baseColor),
depthFailColor:
Cesium.ColorGeometryInstanceAttribute.fromColor(baseDepthFailColor),
},
}),
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
@@ -86,6 +88,11 @@ export function createRendering({
// GMST value (gstime is pure), so delta starts at exactly 0 and the
// initial identity modelMatrix is correct until the first ring tick.
gmstAtBake: gstime(bakeDate),
instanceId,
baseColor,
baseDepthFailColor,
// The alpha multiple last written to the instance (1: as built).
alphaFactor: 1,
});
}
@@ -218,6 +225,10 @@ export function createRendering({
}
}
// While the Cockpit rides the tracked satellite, keep its marks hidden.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
_updatePointFocus(now);
// Hidden standalone orbit primitives do not need GMST matrix writes while
+100
View File
@@ -0,0 +1,100 @@
/**
* @file Imaging sensors: which Earth-observation platform a satellite is, and
* the swath its sensor images. The orbital view draws that swath to scale and
* lets a satellite zoom past 8x only as far as its sensor's narrowest
* standard swath (src/cockpitOrbital.js `orbitalMaxZoom`).
*
* Pure: no Cesium, no fetches; the bundled pack is loaded by
* src/data/imagingSensors.js.
*
* @module imagingSensors
*/
/**
* One sensor-pack entry as the app uses it.
* @typedef {{id: string, label: string, operator: string|null,
* sensor: string, type: string, altitudeKm: number|null,
* modes: Array<{name: string, swathKm: number|null, gsdM: number|null}>,
* narrowestSwathKm: number|null, swathConfirmed: boolean,
* sources: string[], unverified: string[]}} ImagingSensor
*/
/**
* Index the pack for matching: exact NORAD numbers first, then name patterns
* in pack order. A malformed pattern is skipped, not fatal.
* @param {{entries?: Array<object>}} pack Parsed `imaging_sensors.json`.
* @returns {{byNorad: Map<number, ImagingSensor>,
* patterns: Array<{pattern: RegExp, sensor: ImagingSensor}>}}
*/
export function indexImagingSensors(pack) {
const byNorad = new Map();
const patterns = [];
for (const entry of pack?.entries || []) {
if (!entry?.id) continue;
const sensor = Object.freeze({
id: entry.id,
label: entry.label || entry.id,
operator: entry.operator ?? null,
sensor: entry.sensor || '',
type: entry.type || '',
altitudeKm: Number.isFinite(entry.altitudeKm) ? entry.altitudeKm : null,
modes: Object.freeze(
(entry.modes || []).map((mode) => Object.freeze({ ...mode })),
),
narrowestSwathKm: Number.isFinite(entry.narrowestSwathKm)
? entry.narrowestSwathKm
: null,
swathConfirmed: entry.swathConfirmed === true,
sources: Object.freeze([...(entry.sources || [])]),
unverified: Object.freeze([...(entry.unverified || [])]),
});
for (const noradId of entry.match?.norad || []) {
if (Number.isInteger(noradId) && !byNorad.has(noradId))
byNorad.set(noradId, sensor);
}
if (entry.match?.nameRegex) {
try {
patterns.push({ pattern: new RegExp(entry.match.nameRegex), sensor });
} catch {
// A bad pattern only loses its name match; NORAD ids still work.
}
}
}
return { byNorad, patterns };
}
/**
* The sensor entry for a satellite: by NORAD number, else by its CelesTrak
* name (upper-cased, trimmed).
* @param {ReturnType<typeof indexImagingSensors>|null|undefined} index
* @param {{noradId?: number, name?: string}} satellite
* @returns {ImagingSensor|null}
*/
export function matchImagingSensor(index, { noradId, name } = {}) {
if (!index) return null;
const byId = index.byNorad?.get(noradId);
if (byId) return byId;
const text = String(name || '')
.trim()
.toUpperCase();
if (!text) return null;
for (const { pattern, sensor } of index.patterns || [])
if (pattern.test(text)) return sensor;
return null;
}
/**
* The swath the orbital view may zoom to: the narrowest standard swath, only
* when it was confirmed on a cited page. An unconfirmed swath keeps the
* satellite at the base zoom steps.
* @param {ImagingSensor|null|undefined} sensor
* @returns {number|null} Kilometres.
*/
export function zoomableSwathKm(sensor) {
const swathKm = sensor?.narrowestSwathKm;
return sensor?.swathConfirmed === true &&
Number.isFinite(swathKm) &&
swathKm > 0
? swathKm
: null;
}
+154
View File
@@ -0,0 +1,154 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
indexImagingSensors,
matchImagingSensor,
zoomableSwathKm,
} from './sensors.js';
import { loadImagingSensors } from '../../data/imagingSensors.js';
const PACK_URL = new URL(
'../../data/local_data/imaging_sensors/imaging_sensors.json',
import.meta.url,
);
const PACK = {
entries: [
{
id: 'worldview-3',
label: 'WorldView-3',
match: { norad: [40115], nameRegex: '^WORLDVIEW-3' },
narrowestSwathKm: 13.1,
swathConfirmed: true,
},
{
id: 'iceye',
label: 'ICEYE',
match: { nameRegex: '^ICEYE-X\\d+' },
narrowestSwathKm: 5,
swathConfirmed: true,
},
{
id: 'broken',
label: 'Broken pattern',
match: { norad: [1], nameRegex: '([' },
narrowestSwathKm: 9,
swathConfirmed: true,
},
{
id: 'blacksky',
label: 'BlackSky',
match: { nameRegex: '^GLOBAL-\\d+$' },
narrowestSwathKm: null,
swathConfirmed: false,
},
],
};
test('a satellite matches its sensor by NORAD number, then by name', () => {
const index = indexImagingSensors(PACK);
assert.equal(
matchImagingSensor(index, { noradId: 40115 })?.id,
'worldview-3',
);
// An id match wins over a name that says otherwise.
assert.equal(
matchImagingSensor(index, { noradId: 40115, name: 'ICEYE-X9' })?.id,
'worldview-3',
);
assert.equal(
matchImagingSensor(index, { noradId: 99999, name: ' iceye-x14 ' })?.id,
'iceye',
);
assert.equal(matchImagingSensor(index, { noradId: 1 })?.id, 'broken');
assert.equal(matchImagingSensor(index, { name: 'STARLINK-1007' }), null);
assert.equal(matchImagingSensor(null, { noradId: 40115 }), null);
});
test('only a confirmed swath opens zoom steps past 8x', () => {
const index = indexImagingSensors(PACK);
assert.equal(
zoomableSwathKm(matchImagingSensor(index, { noradId: 40115 })),
13.1,
);
assert.equal(
zoomableSwathKm(matchImagingSensor(index, { name: 'GLOBAL-21' })),
null,
);
assert.equal(zoomableSwathKm(null), null);
assert.equal(
zoomableSwathKm({ swathConfirmed: true, narrowestSwathKm: 0 }),
null,
'no swath to zoom to',
);
});
test('the bundled pack is well formed and cites its sources', () => {
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
assert.ok(pack.entries.length >= 40);
assert.ok(
readFileSync(PACK_URL).length < 60_000,
'small enough for the layer',
);
const ids = new Set();
for (const entry of pack.entries) {
assert.ok(entry.id && !ids.has(entry.id), `unique id ${entry.id}`);
ids.add(entry.id);
assert.ok(entry.match.norad || entry.match.nameRegex, entry.id);
if (entry.match.nameRegex) new RegExp(entry.match.nameRegex);
assert.ok(entry.sources.length > 0, `${entry.id} cites a source`);
if (entry.swathConfirmed) {
assert.ok(entry.narrowestSwathKm > 0, entry.id);
// The narrowest *standard* swath: sampling modes (Himawari's landmark
// area) and older generations (Dove Classic) may be narrower.
const swaths = entry.modes
.map((mode) => mode.swathKm)
.filter(Number.isFinite);
assert.ok(
swaths.includes(entry.narrowestSwathKm),
`${entry.id}: the narrowest swath is one of its modes`,
);
}
}
});
test('the pack cites no reseller, links its datasheets and names its own fields', () => {
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
// Resellers, Gunter's Space Page, and the Copernicus portal whose terms
// forbid reuse.
const excluded =
/euspaceimaging\.com|apollomapping\.com|landinfo\.com|satimagingcorp\.com|space\.skyrocket\.de|dataspace\.copernicus\.eu/;
const fields = new Set(['altitudeKm', 'narrowestSwathKm', 'swathKm', 'gsdM']);
for (const entry of pack.entries) {
for (const source of entry.sources)
assert.doesNotMatch(source, excluded, `${entry.id}: ${source}`);
// A bare file-host datasheet is cited beside the operator page that
// links it.
if (entry.sources.some((source) => /cdn\.sanity\.io/.test(source)))
assert.ok(
entry.sources.some((source) => /^https:\/\/vantor\.com\//.test(source)),
`${entry.id}: the Vantor page for its datasheet`,
);
// An unverified value is named by the pack's own field.
for (const note of entry.unverified) {
const [field] = /^[A-Za-z_]+/.exec(note) ?? [''];
if (/^[a-z]+(_[a-z]+)+$|^[a-z]+[A-Z]\w*$/.test(field))
assert.ok(fields.has(field), `${entry.id}: unknown field ${field}`);
}
}
});
test('the pack loads once and matches real catalog names', async () => {
const index = await loadImagingSensors();
assert.equal(index, await loadImagingSensors(), 'loaded once');
const cases = [
[{ noradId: 49260, name: 'LANDSAT 9' }, 'landsat-8-9'],
[{ noradId: 40115, name: 'WORLDVIEW-3 (WV-3)' }, 'worldview-3'],
[{ noradId: 1, name: 'FLOCK 4Q-12' }, 'planetscope'],
[{ noradId: 1, name: 'ICEYE-X40' }, 'iceye'],
[{ noradId: 1, name: 'SKYSAT-C19' }, 'skysat'],
];
for (const [satellite, id] of cases)
assert.equal(matchImagingSensor(index, satellite)?.id, id, satellite.name);
});
+12
View File
@@ -20,10 +20,17 @@ async function loadBundledUcs() {
return loadUcsSatellites();
}
/** The imaging-sensor pack, loaded on first use (see src/data/imagingSensors.js). */
async function loadBundledSensors() {
const { loadImagingSensors } = await import('../../data/imagingSensors.js');
return loadImagingSensors();
}
/** Read catalog text from the existing group endpoint using a supplied transport. */
export function createSatelliteSource({
fetchImpl = (...args) => globalThis.fetch(...args),
loadUcs = loadBundledUcs,
loadSensors = loadBundledSensors,
} = {}) {
return {
async readGroup(group, { signal } = {}) {
@@ -60,5 +67,10 @@ export function createSatelliteSource({
readUcs() {
return loadUcs();
},
/** The imaging-sensor pack, indexed by NORAD number and name pattern. */
readSensors() {
return loadSensors();
},
};
}
+15 -1
View File
@@ -15,7 +15,7 @@ export function createState({ services }) {
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
// Satellite catalog: { noradId → { name, satrec, group, launchYear,
// Satellite catalog: { noradId → { name, satrec, group, line1, line2,
// satelliteClass, ucs, satcat } } — class, UCS and SATCAT records from
// src/layers/satellites/classes.js and the sources the update read.
@@ -118,6 +118,9 @@ export function createState({ services }) {
/** The UCS pack by NORAD id, once loaded; null until then or if it failed. */
state._ucs = null;
/** The imaging-sensor index, once loaded; null until then or if it failed. */
state._sensors = null;
state._denseIds = [];
// norad ids of dense extras, round-robin order
@@ -174,6 +177,17 @@ export function createState({ services }) {
state._trackedFrameNowForTest = null;
// Cockpit orbital-view hold (cockpitSubject.js): the NORAD id the Cockpit
// camera rides, and what the hold hid so release restores exactly that.
state._cockpitSubjectNorad = null;
state._cockpitHiddenPoints = new Set();
state._cockpitHiddenPath = null;
state._cockpitHiddenDot = false;
/** The time satellites are propagated to, in epoch ms. */
state.now = worldTimeFor('satellites');
+9 -6
View File
@@ -120,6 +120,9 @@ export function createTracking({ state: layerState, services, parts, source }) {
}
layerState._trackedNorad = null;
parts.controls._syncIssOrbit?.();
// A held Cockpit subject that stops being tracked gets its marks back.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
parts.labels._syncIssOverlay();
clearTrackedSubjectContext('satellites');
layerState._contextRefreshedAtMs = 0;
@@ -152,13 +155,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
frameNumber !== layerState._trackedFrameNumber ||
layerState._trackedFrameGeo === null
) {
const pos = parts.orbits.propagatePosition(
sat.satrec,
layerState._trackedFrameNowForTest
? new Date(layerState._trackedFrameNowForTest())
: new Date(layerState.now()),
);
const atMs = layerState._trackedFrameNowForTest
? layerState._trackedFrameNowForTest()
: layerState.now();
const pos = parts.orbits.propagatePosition(sat.satrec, new Date(atMs));
if (!pos) return layerState._trackedFrameGeo; // propagation hiccup — keep last good sample
// The time the sample is at: the world clock's, not the wall clock's.
pos.atMs = atMs;
layerState._trackedFrameGeo = pos;
Cesium.Cartesian3.fromDegrees(
pos.longitude,
+219
View File
@@ -0,0 +1,219 @@
// Street Traffic road lines build one set at a time: rebuilds asked for while
// a set is building wait, and only the newest of them runs.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createRendering } from './rendering.js';
// Cesium tests a material's uniforms against these browser classes.
for (const name of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
])
globalThis[name] ??= class {};
// A line primitive's render state is checked against the context's limits,
// which only a WebGL context sets.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
/** A road with flow; `level` picks its bucket (0.1 jam, 0.6 slow, 1 free). */
function road(level = 1) {
return {
flow: { level, closure: false },
segmentDist: [100],
waypoints: Cesium.Cartesian3.fromDegreesArray([
-97.744, 30.267, -97.742, 30.267,
]),
};
}
/**
* Rendering over a scene that records its ground primitives. Each added
* primitive is replaced by a stand-in whose `ready` the test sets, as Cesium
* sets it once the asynchronous geometry is built.
*/
function harness() {
const scene = [];
const added = [];
let linesOn = true;
const state = {
_viewer: {
scene: {
globe: { show: true },
groundPrimitives: {
add(primitive) {
const line = {
ready: false,
roads: primitive.geometryInstances.length,
};
scene.push(line);
added.push(line);
return line;
},
remove(line) {
const index = scene.indexOf(line);
if (index >= 0) scene.splice(index, 1);
},
},
},
},
_liveMode: true,
_showLines: true,
_heatSupported: true,
_heatJamPrim: null,
_heatSlowPrim: null,
_heatFreePrim: null,
_heatRetired: [],
_heatPendingRoads: null,
_heatLineCount: 0,
};
const rendering = createRendering({
state,
services: {},
source: {},
parts: {
style: { heatlineOn: () => linesOn },
animation: { syncRenderDemand() {} },
},
});
return {
state,
rendering,
scene,
added,
setLines(on) {
linesOn = on;
state._showLines = on;
},
/** Finish every build in the scene, then run a frame. */
frame({ built = true } = {}) {
if (built) for (const line of scene) line.ready = true;
rendering.retireHeatLines();
},
};
}
const roads = (count) => Array.from({ length: count }, () => road());
test('rebuilds asked for while lines build do not start more builds', () => {
const { rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
assert.equal(added.length, 1);
// Progressive paints while the first set builds.
for (const count of [2, 3, 4]) rendering.rebuildHeatLines(roads(count));
frame({ built: false });
assert.equal(added.length, 1, 'no build started during a build');
assert.equal(scene.length, 1);
assert.deepEqual(scene[0].roads, 1);
});
test('the newest rebuild asked for during a build is the one that runs', () => {
const { state, rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
for (const count of [2, 3, 4]) rendering.rebuildHeatLines(roads(count));
frame();
// One build for the three requests, of the last one's roads.
assert.deepEqual(
added.map((line) => line.roads),
[1, 4],
);
assert.equal(state._heatLineCount, 4);
assert.equal(state._heatPendingRoads, null);
// The set it replaces stays drawn while it builds, then goes.
assert.deepEqual(
scene.map((line) => line.roads),
[1, 4],
);
frame();
assert.deepEqual(
scene.map((line) => line.roads),
[4],
);
// Nothing is waiting, so later frames start nothing.
frame();
assert.equal(added.length, 2);
});
test('a rebuild with nothing building starts at once', () => {
const { rendering, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
frame();
rendering.rebuildHeatLines(roads(2));
assert.deepEqual(
added.map((line) => line.roads),
[1, 2],
);
});
test('turning lines off during a build removes them at once and drops the waiting rebuild', () => {
const { state, rendering, scene, added, setLines, frame } = harness();
rendering.rebuildHeatLines(roads(1));
frame();
rendering.rebuildHeatLines(roads(2));
rendering.rebuildHeatLines(roads(3));
assert.equal(scene.length, 2, 'the drawn set and the building one');
setLines(false);
rendering.rebuildHeatLines(roads(3));
assert.deepEqual(scene, [], 'not deferred behind the build');
assert.equal(state._heatPendingRoads, null);
assert.equal(state._heatLineCount, 0);
frame();
assert.equal(added.length, 2, 'the waiting rebuild never runs');
assert.deepEqual(scene, []);
});
test('a rebuild right after a build finishes does not keep the lines that build replaced', () => {
const { rendering, scene } = harness();
rendering.rebuildHeatLines(roads(1));
for (const line of scene) line.ready = true;
rendering.rebuildHeatLines(roads(2));
// The second build finishes, and a third is asked for before a frame ran.
for (const line of scene) line.ready = true;
rendering.rebuildHeatLines(roads(3));
assert.deepEqual(
scene.map((line) => line.roads),
[2, 3],
);
});
test('removing the lines drops the waiting rebuild', () => {
const { state, rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
rendering.rebuildHeatLines(roads(2));
rendering.removeHeatLines();
assert.deepEqual(scene, []);
assert.equal(state._heatPendingRoads, null);
frame();
assert.equal(added.length, 1);
});
test('a stream of rebuilds never leaves more than two sets in the scene, and ends with one', () => {
const { rendering, scene, added, frame } = harness();
let most = 0;
const lines = [road(0.1), road(0.6), road(1)];
// Three primitives per set: one per flow bucket.
for (let paint = 0; paint < 40; paint += 1) {
rendering.rebuildHeatLines(lines);
most = Math.max(most, scene.length);
// A build takes several paints.
if (paint % 5 === 4) frame();
else frame({ built: false });
most = Math.max(most, scene.length);
}
frame();
frame();
assert.equal(most <= 6, true, `${most} primitives at once`);
assert.equal(scene.length, 3, 'only the current set remains');
assert.equal(
scene.every((line) => line.ready),
true,
);
// Without coalescing every paint builds: 40 sets, 120 primitives.
assert.equal(
added.length <= 3 * 10,
true,
`${added.length} primitives built`,
);
});
+39 -13
View File
@@ -59,24 +59,37 @@ export function createRendering({
/** Remove the heat-line / flow-line ground primitives from the scene. */
function removeHeatLines() {
layerState._heatPendingRoads = null;
removePrimitives(takeHeatLines());
removePrimitives(layerState._heatRetired || []);
layerState._heatRetired = [];
parts.animation.syncRenderDemand?.();
}
/** @returns {boolean} Whether a line primitive's geometry is still building. */
function linesBuilding() {
return LINE_KEYS.some((key) => layerState[key] && !layerState[key].ready);
}
/**
* Replaced lines stay drawn until their successors finish building
* (GroundPolylinePrimitive geometry is asynchronous), so a rebuild never
* blinks. Called every held frame.
* blinks. Once they have, the replaced lines go and the newest rebuild
* asked for in the meantime starts. Called every held frame.
*/
function retireHeatLines() {
if (!layerState._heatRetired?.length) return;
if (LINE_KEYS.some((key) => layerState[key] && !layerState[key].ready))
return;
removePrimitives(layerState._heatRetired);
layerState._heatRetired = [];
if (linesBuilding()) return;
if (layerState._heatRetired?.length) {
removePrimitives(layerState._heatRetired);
layerState._heatRetired = [];
}
const pending = layerState._heatPendingRoads;
if (pending) {
layerState._heatPendingRoads = null;
rebuildHeatLines(pending);
}
}
/**
@@ -95,24 +108,37 @@ export function createRendering({
* the globe is hidden (photoreal) and on terrain or tiles otherwise. No-op in
* sim mode, when both looks are off, or without ground-primitive support.
*
* One build runs at a time. A city loads in progressive paints, each asking
* for a rebuild, and every build drapes up to the cap of polylines
* asynchronously. A rebuild asked for while lines are building only replaces
* the one waiting, which retireHeatLines starts when the build finishes, so
* the scene never holds more than the lines drawn and the lines building.
* Turning the lines off is never deferred.
*
* @param {Array} roads - Road objects visible in the current render.
*/
function rebuildHeatLines(roads) {
const wanted =
layerState._viewer && layerState._liveMode && parts.style.heatlineOn();
if (wanted && linesBuilding()) {
layerState._heatPendingRoads = roads;
return;
}
layerState._heatPendingRoads = null;
// No build is left for replaced lines to wait for (it finished, or lines
// are going off), so they go first and never pile up behind this rebuild.
removePrimitives(layerState._heatRetired || []);
layerState._heatRetired = [];
const previous = takeHeatLines();
const finish = () => {
// Nothing new to wait for: the old lines go now.
if (LINE_KEYS.some((key) => layerState[key]))
(layerState._heatRetired ||= []).push(...previous);
// Nothing new to wait for: the old lines go now.
else removePrimitives(previous);
parts.animation.syncRenderDemand?.();
};
if (
!layerState._viewer ||
!layerState._liveMode ||
!parts.style.heatlineOn()
)
return finish();
if (!wanted) return finish();
if (layerState._heatSupported === null) {
layerState._heatSupported = Cesium.GroundPolylinePrimitive.isSupported(
layerState._viewer.scene,
+4
View File
@@ -200,6 +200,10 @@ export function createState({ services, source }) {
layerState._heatRetired = [];
/** @type {Array|null} Roads of the newest rebuild asked for while the lines were building. */
layerState._heatPendingRoads = null;
/** @type {number} Heat-lines in the current render (stats). */
layerState._heatLineCount = 0;
+15 -1
View File
@@ -124,7 +124,14 @@ export function createHeight({ state, services, parts }) {
const cells = new Map();
const collect = (point, answer) => {
if (!onGround) return;
if (!cells.has(answer.cell))
// A cell keeps the last point offered in it: the path is walked
// oldest first, so that is where the vehicle is now or about to be,
// and the mesh sampler reads the surface there.
const held = cells.get(answer.cell);
if (held) {
held.lat = point.lat;
held.lon = point.lon;
} else
cells.set(answer.cell, {
lat: point.lat,
lon: point.lon,
@@ -136,6 +143,13 @@ export function createHeight({ state, services, parts }) {
const newest = entry.fixes.at(-1);
const answer = requestHeight(newest.lat, newest.lon, entry);
entry.heightCell = answer.cell;
// The selected vehicle's path also offers its history, newest segment
// first; the vehicle's own cell is read where its newest fix is.
const own = cells.get(answer.cell);
if (own) {
own.lat = newest.lat;
own.lon = newest.lon;
}
if (answer.height !== null) {
entry.heightM = answer.height;
entry.heightResolved = true;
+7 -1
View File
@@ -401,7 +401,13 @@ export function createIngestion({ state, services, parts, source }) {
);
}
if (state._viewer)
registerDynamicCredit(state._viewer, transitFeedCredit(feed));
registerDynamicCredit(
state._viewer,
transitFeedCredit(feed, {
feedTimestamp: snapshot?.feedTimestamp,
fetchedAt,
}),
);
if (
state._selectedKey &&
state._vehicles.get(state._selectedKey)?.feedId === feed.id
+159
View File
@@ -2938,6 +2938,114 @@ test('mesh refinement reaches all 100 retained DEM cells within five poll budget
assert.equal(probed.size, 100);
});
test('mesh refinement probes the latest point the path offers in a cell', async (t) => {
const { createHeight } = await import('./height.js');
// Three points along one cell's stretch of path, oldest first.
const path = [
{ lat: 42.3611, lon: -71.0751 },
{ lat: 42.3612, lon: -71.0753 },
{ lat: 42.3614, lon: -71.0754 },
];
const entry = { key: 'train', to: path[0], fixes: [path.at(-1)] };
const probed = [];
const state = {
_enabled: true,
_selectedKey: null,
_visible: new Set([entry]),
_vehicles: new Map([[entry.key, entry]]),
_floorCursor: 0,
_heightDirty: new Set(),
_viewer: { camera: { positionCartographic: { height: 100 } } },
};
const height = createHeight({
state,
services: {
render: { governorRequestRender() {} },
ground: {
coarseFloorCoord: (lat, lon) => ({
lat: Number(lat.toFixed(3)),
lon: Number(lon.toFixed(3)),
}),
cachedGroundFloor: () => 10,
GROUND_FLOOR_LIFT_M: 1.5,
},
mesh: {
sampleMeshFloorCells(scene, points) {
probed.push(...points.map((p) => [p.lat, p.lon]));
},
},
},
parts: {
trails: {
prepareEntry(e, collect) {
if (collect)
for (const point of path)
collect(point, height.requestHeight(point.lat, point.lon));
},
},
rendering: { requestVisibility() {} },
},
});
t.after(() => height.clear());
height.anchorFloors();
assert.deepEqual(probed, [[42.3614, -71.0754]]);
});
test('the selected vehicle is probed at its newest fix in its own cell', async (t) => {
const { createHeight } = await import('./height.js');
// The selected path offers its active corridor first, then its history
// newest segment first, so the last offer in the cell is an older point.
const newest = { lat: 42.3614, lon: -71.0754 };
const offers = [
newest,
{ lat: 42.3612, lon: -71.0753 },
{ lat: 42.3611, lon: -71.0751 },
];
const entry = { key: 'train', to: offers[0], fixes: [newest] };
const probed = [];
const state = {
_enabled: true,
_selectedKey: entry.key,
_visible: new Set([entry]),
_vehicles: new Map([[entry.key, entry]]),
_floorCursor: 0,
_heightDirty: new Set(),
_viewer: { camera: { positionCartographic: { height: 100 } } },
};
const height = createHeight({
state,
services: {
render: { governorRequestRender() {} },
ground: {
coarseFloorCoord: (lat, lon) => ({
lat: Number(lat.toFixed(3)),
lon: Number(lon.toFixed(3)),
}),
cachedGroundFloor: () => 10,
GROUND_FLOOR_LIFT_M: 1.5,
},
mesh: {
sampleMeshFloorCells(scene, points) {
probed.push(...points.map((p) => [p.lat, p.lon]));
},
},
},
parts: {
trails: {
prepareEntry(e, collect) {
if (collect)
for (const point of offers)
collect(point, height.requestHeight(point.lat, point.lon));
},
},
rendering: { requestVisibility() {} },
},
});
t.after(() => height.clear());
height.anchorFloors();
assert.deepEqual(probed, [[42.3614, -71.0754]]);
});
test('selection churn releases past geometry on every retained vehicle', async (t) => {
const app = harness(t, { floorAt: () => 10 });
const { mergeHistory, seek } = await import('../../data/contactPlayback.js');
@@ -3983,3 +4091,54 @@ test('parked transit reprojects held and reported courses at the bounded camera
'selected unknown course also stays screen-up',
);
});
test('a view with no feed reads its coverage prompt, not an undated feed', async (t) => {
const app = harness(t);
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
assert.ok(app.layer.getStats().lastUpdate, 'Boston has a dated snapshot');
// London has no registered feed: the row prompts instead of dating Boston's
// last snapshot over an empty map.
app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 });
app.advance(1_000);
const away = app.layer.getStats();
assert.equal(away.status, 'zoom-in');
assert.equal(away.count, 0);
assert.equal(away.lastUpdate, null);
assert.match(
away.statusMessage,
/^No feed here yet · \d+ regions available$/,
);
assert.equal(away.coverage, away.statusMessage);
// Above the altitude gate the prompt says how low to fly.
app.viewer.camera.positionCartographic.height = 10_000_000;
app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 });
app.advance(1_000);
assert.equal(
app.layer.getStats().statusMessage,
'Fly below 2,850 km to a covered region',
);
});
test('the prompt names the altitude the gate opens at, not 3,000 km', async (t) => {
// 2,900 km is under ACTIVATION_ALTITUDE_M but above the enter threshold.
const app = harness(t, { altitude: 2_900_000 });
app.layer.enable(app.viewer);
await app.layer.update();
assert.deepEqual(app.requested, [], 'nothing loads over Boston');
assert.equal(
app.layer.getStats().statusMessage,
'Fly below 2,850 km to a covered region',
);
});
+8 -6
View File
@@ -1,5 +1,5 @@
import {
ACTIVATION_ALTITUDE_M,
ACTIVATION_ENTER_ALTITUDE_M,
FEED_STALE_AFTER_MS,
aggregateTransitFeedHealth,
transitDetectionClass,
@@ -245,17 +245,19 @@ export function createQueries({ state, parts }) {
const health = aggregateTransitFeedHealth(statuses, now);
const count = state._vehicles.size;
if (state._enabled && active.length === 0) {
// English: the analyst's empty note and the row's prompt, both shown
// through translateStatusMessage (ui/statusText.js).
const note = state._altitudeGateOpen
? `No feed here yet · ${TRANSIT_REGION_COUNT} regions available`
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`;
return {
count: 0,
lastUpdate: state._lastUpdate,
error: null,
source: 'GTFS-RT',
status: 'zoom-in',
// English data (the analyst's empty note to the model); the voice
// card shows it through NOTE_PATTERNS (voice/resultDisplay.js).
coverage: state._altitudeGateOpen
? `No feed here yet · ${TRANSIT_REGION_COUNT} regions available`
: `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`,
statusMessage: note,
coverage: note,
};
}
// Age is shown by the same rule the row state uses, so the text and the
@@ -0,0 +1,100 @@
// Transit: a manager tick that failed over Boston must not keep its error on
// the row the coverage repaint draws after the camera leaves for London.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createState } from './state.js';
import { createViewport } from './viewport.js';
import { createQueries } from './queries.js';
import { LayerLifecycle } from '../../data/lifecycle.js';
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
const rad = Math.PI / 180;
const LONDON = { lat: 51.5072, lon: -0.1276 };
const BOSTON = { lat: 42.3601, lon: -71.0589 };
function viewer(at, height) {
return {
camera: {
positionCartographic: {
height,
latitude: at.lat * rad,
longitude: at.lon * rad,
},
computeViewRectangle: () => undefined,
},
scene: { globe: {} },
};
}
test('leaving a feed whose tick failed repaints its error away', async () => {
const services = {
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
render: { governorRequestRender() {} },
};
const state = createState({ services });
const feedStatus = (feedId) => {
if (!state._feedStatus.has(feedId))
state._feedStatus.set(feedId, { count: 0, error: null, loading: false });
return state._feedStatus.get(feedId);
};
const parts = {
ingestion: {
feedStatus,
// As pollFeed's catch does when the proxy answers 503.
pollFeed(feed) {
Object.assign(feedStatus(feed.id), {
error: `${feed.name} feed unavailable`,
loading: false,
});
return Promise.resolve();
},
removeFeedVehicles() {},
sweepAgedVehicles() {},
},
rendering: { requestVisibility() {}, syncRenderHold() {} },
};
parts.viewport = createViewport({ state, services, parts });
const queries = createQueries({ state, parts }).methods;
state._enabled = true;
const lifecycle = new LayerLifecycle(null);
lifecycle.register({
id: 'transit',
name: 'Transit',
source: 'GTFS-RT',
getStats: () => queries.getStats(),
async update() {},
});
const entry = lifecycle.layers.get('transit');
entry.enabled = true;
entry.lifecycleState = 'enabled';
entry.initialized = true;
const row = () => {
const layer = lifecycle.getAll()[0];
return `${layerFeedState(layer.stats)} | ${LayerPanel.prototype._buildMetaText(layer)}`;
};
const painted = [];
state._dataManager = {
refreshLayerStats(layerId) {
lifecycle.refreshLayerStats(layerId);
painted.push(row());
},
};
state._viewer = viewer(BOSTON, 4_000);
parts.viewport.runProximityCheck();
await lifecycle.refreshLayer('transit');
assert.match(row(), /feed unavailable/, 'the tick recorded the failure');
const before = painted.length;
state._viewer = viewer(LONDON, 4_000);
parts.viewport.runProximityCheck();
assert.equal(queries.getStats().status, 'zoom-in');
assert.ok(painted.length > before, 'leaving Boston repainted the row');
assert.doesNotMatch(painted.at(-1), /feed unavailable/);
});
+1 -1
View File
@@ -115,7 +115,7 @@ export function createState({ services }) {
state._cockpitVision = false;
/** @type {Array<[string, EventListener]>} window listeners to remove on destroy. */
state._styleListeners = [];
/** @type {{ refreshLayerStats?: () => void }|null} */
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} */
state._dataManager = null;
/** @type {number|null} */
state._lastUpdate = null;
+8
View File
@@ -83,7 +83,9 @@ export function createViewport({ state, services, parts }) {
if (!state._enabled || !state._viewer) return;
refreshViewBounds();
const altitude = getCameraAltitude();
const wasGateOpen = state._altitudeGateOpen;
state._altitudeGateOpen = altitudeGateOpen(altitude);
let changed = state._altitudeGateOpen !== wasGateOpen;
const center = state._altitudeGateOpen ? getCameraCenterLatLon() : null;
const desired = new Map();
if (center) {
@@ -106,17 +108,23 @@ export function createViewport({ state, services, parts }) {
state._activeFeeds.delete(feedId);
state._feedStatus.delete(feedId);
parts.ingestion.removeFeedVehicles(feedId);
changed = true;
}
}
// Nothing is left on the map to date.
if (desired.size === 0) state._lastUpdate = null;
for (const [feedId, feed] of desired) {
if (!state._activeFeeds.has(feedId)) {
state._activeFeeds.set(feedId, feed);
void parts.ingestion.pollFeed(feed, state._generation);
changed = true;
}
}
parts.ingestion.sweepAgedVehicles(Date.now());
parts.rendering.syncRenderHold();
governorRequestRender('transit-proximity');
// Repaint now: the row follows the camera, the manager tick is 15 s.
if (changed) state._dataManager?.refreshLayerStats?.('transit');
}
function onCameraChanged() {
+5 -1
View File
@@ -25,6 +25,7 @@ import {
FOCUS_EVIDENCE_DEV,
VESSEL_LIFT_M,
} from './policy.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
export function createQueries({
vesselState,
@@ -575,7 +576,7 @@ export function createQueries({
* @param {Object} [options={}] - Options from the detection system.
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all).
* @param {number} [options.seed] - Seed offset for stride sampling.
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>}
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean, cardSourceId: string, cardEntryId: string}>}
*/
getDetectableObjects(options = {}) {
if (
@@ -610,6 +611,9 @@ export function createQueries({
id: record.name || record.mmsi || 'VESSEL',
type: 'SEA',
skipLabel: record === selected,
// Detection hides the callout while this card paints.
cardSourceId: VESSEL_OVERLAY_SOURCE_ID,
cardEntryId: components.cards.vesselOverlayEntryId(record),
klass: record.type
? String(record.type).toUpperCase().slice(0, 14)
: undefined,