mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge branch 'main' into feat/transit-icon-heading
This commit is contained in:
254 files changed
+26623
-843
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import {
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
lerpAngleDeg,
|
||||
@@ -156,7 +157,7 @@ export function createMotion({
|
||||
const renderTime =
|
||||
sampledRenderTime ??
|
||||
Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(flightState._scratchRenderTime),
|
||||
julianAt(flightState.now(), flightState._scratchRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -332,7 +333,7 @@ export function createMotion({
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
julianAt(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -12,6 +12,7 @@ function fixture() {
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
now: Date.now,
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
@@ -138,7 +139,7 @@ test('fleet render time is shared without resampling or mutating the supplied in
|
||||
assert.ok(Cesium.JulianDate.equals(renderTime, savedTime));
|
||||
});
|
||||
|
||||
test('tracked callers still sample a fresh delayed time without a fleet epoch', (t) => {
|
||||
test('tracked callers still sample a fresh delayed time without a fleet epoch', () => {
|
||||
const { flightState, motion } = fixture();
|
||||
const start = Cesium.JulianDate.fromIso8601('2026-10-24T12:00:00Z');
|
||||
const history = [
|
||||
@@ -156,10 +157,11 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
|
||||
flightState.records.data.set('tracked', { velocity: 100, true_track: 90 });
|
||||
flightState._positionHistory.set('tracked', history);
|
||||
let elapsed = 60;
|
||||
const spy = t.mock.method(Cesium.JulianDate, 'now', (result) => {
|
||||
assert.equal(result, flightState._scratchRenderTime);
|
||||
return Cesium.JulianDate.addSeconds(start, elapsed, result);
|
||||
});
|
||||
let reads = 0;
|
||||
flightState.now = () => {
|
||||
reads += 1;
|
||||
return Cesium.JulianDate.toDate(start).getTime() + elapsed * 1000;
|
||||
};
|
||||
const out = new Cesium.Cartesian3();
|
||||
close(
|
||||
motion._deadReckon('tracked', out),
|
||||
@@ -180,5 +182,5 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
);
|
||||
assert.equal(spy.mock.callCount(), 2);
|
||||
assert.equal(reads, 2);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import { cyberSonarBaseAlpha } from '../../cyberSonar.js';
|
||||
import { selectModelEligible } from '../../data/modelEligibility.js';
|
||||
import { civilAircraftModelSpec } from './modelSpec.js';
|
||||
@@ -871,7 +872,7 @@ export function createRendering({
|
||||
flightState._lastFleetTickMs = nowMs;
|
||||
// Every contact in this pass shares the same delayed display instant.
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(flightState._scratchFleetRenderTime),
|
||||
julianAt(flightState.now(), flightState._scratchFleetRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchFleetRenderTime,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { FlightRecords } from './records.js';
|
||||
import { createFlightFeed } from './ingestion.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
@@ -12,6 +13,8 @@ export function createFlightState({ source, services }) {
|
||||
...services.groundFloor,
|
||||
});
|
||||
flightState._cullPositions = new Map();
|
||||
/** The time contacts are drawn behind by the render delay, in epoch ms. */
|
||||
flightState.now = worldTimeFor('flights');
|
||||
|
||||
/** Per-class model spec. Hangar-fleet classes (CLASS_MODEL_REAL) ship GLBs
|
||||
* vertex-baked to real-world METERS in the airplane.glb axis convention, so
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import { formatNumber, t } from '../../i18n/index.js';
|
||||
import { unitLabel } from '../../ui/unitLabels.js';
|
||||
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
|
||||
@@ -383,7 +384,7 @@ export function createTracking({
|
||||
// would draw the trail in front of the plane. They join the trail via _appendTrailFix
|
||||
// as they age past the delay.
|
||||
const seedRenderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
julianAt(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -69,6 +69,8 @@ export function createGnssIntegrityLayer({
|
||||
source,
|
||||
viewAnchor = defaultGnssViewAnchor,
|
||||
now = () => Date.now(),
|
||||
// The end of the window shown; retries and receipt times stay on `now`.
|
||||
worldNow = now,
|
||||
monotonicNow = () => performance.now(),
|
||||
windowMs: requestedWindowMs,
|
||||
} = {}) {
|
||||
@@ -163,7 +165,7 @@ export function createGnssIntegrityLayer({
|
||||
|
||||
/** Age the store without new evidence, so expired cells leave the globe. */
|
||||
function expire() {
|
||||
pruneGnssObservations(_observations, now(), { windowMs });
|
||||
pruneGnssObservations(_observations, worldNow(), { windowMs });
|
||||
_cells = binGnssCells(_observations);
|
||||
render();
|
||||
}
|
||||
|
||||
Vendored
+35
@@ -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.
|
||||
|
||||
Vendored
+1
-1
@@ -29,7 +29,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
*/
|
||||
getAnalystRecords(maxCount = Infinity) {
|
||||
if (!layerState._enabled) return [];
|
||||
const now = Date.now();
|
||||
const now = layerState.now();
|
||||
const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
|
||||
const result = [];
|
||||
for (const launch of layerState._launches || []) {
|
||||
|
||||
@@ -224,6 +224,7 @@ export function createIngestion({
|
||||
}
|
||||
layerState._focusAfterActiveLookup = false;
|
||||
parts.panel.renderMissionPanel();
|
||||
layerState.coverageChanged();
|
||||
layerState._entryCameraView = null;
|
||||
} catch (error) {
|
||||
if (layerState._enabled && token === layerState._lifecycleToken) {
|
||||
|
||||
@@ -105,7 +105,7 @@ export function createLaunchPad({
|
||||
}
|
||||
const nowMs = Date.now();
|
||||
if (nowMs - layerState._lastMissionRingRotationMs >= 1000) {
|
||||
layerState._missionRingDate.setTime(nowMs);
|
||||
layerState._missionRingDate.setTime(layerState.orbitNow());
|
||||
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(
|
||||
layerState._missionRingDate,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
|
||||
const HOVER_PICK_INTERVAL_MS = 120;
|
||||
|
||||
@@ -156,6 +157,21 @@ export function createLifecycle({
|
||||
}) {
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
let hover = null;
|
||||
// While on, the launches loaded span the time from the first to the last,
|
||||
// each one a mark. Registered once; off, the layer has no time to show, and
|
||||
// each step tells the clock once it has settled.
|
||||
worldClock.register({
|
||||
id: 'rocket-launches',
|
||||
coverage: () => {
|
||||
if (!layerState._enabled) return null;
|
||||
const marks = layerState._launches
|
||||
.map((launch) => Date.parse(launch.launchTime))
|
||||
.filter(Number.isFinite)
|
||||
.sort((a, b) => a - b);
|
||||
if (!marks.length) return null;
|
||||
return { start: marks[0], end: marks.at(-1), marks };
|
||||
},
|
||||
});
|
||||
|
||||
const methods = {
|
||||
init(viewer) {
|
||||
@@ -231,6 +247,7 @@ export function createLifecycle({
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
async _enableBody() {
|
||||
@@ -297,6 +314,7 @@ export function createLifecycle({
|
||||
parts.overlays.clearMissionOverlaySources();
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
parts.panel.renderMissionPanel();
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
async destroy(viewer) {
|
||||
|
||||
@@ -67,6 +67,9 @@ export function createOrbitRendering({
|
||||
return Boolean(
|
||||
layerState._enabled &&
|
||||
layerState._dataSource?.show &&
|
||||
!layerState.launchHidden(
|
||||
layerState._missionOverlayRecords.get(launchId)?.launch,
|
||||
) &&
|
||||
(!layerState._selectedLaunchId ||
|
||||
layerState._selectedLaunchId === launchId),
|
||||
);
|
||||
@@ -124,7 +127,7 @@ export function createOrbitRendering({
|
||||
collection.show = missionOrbitPrimitiveVisible(launch.id);
|
||||
orbitFrameModelMatrix(
|
||||
satelliteTrack.gmstAtBake,
|
||||
new Date(),
|
||||
new Date(layerState.orbitNow()),
|
||||
collection.modelMatrix,
|
||||
);
|
||||
layerState._viewer.scene.primitives.add(collection);
|
||||
|
||||
@@ -411,8 +411,11 @@ export function createOverlays({ state: layerState, services, parts, source }) {
|
||||
false,
|
||||
);
|
||||
layerState._selectedMissionOverlayTimeText = null;
|
||||
const records = [...layerState._missionOverlayRecords.values()].filter(
|
||||
(record) => !layerState.launchHidden(record.launch),
|
||||
);
|
||||
const entries = selectRocketMissionMarkerOverlayCohort(
|
||||
Array.from(layerState._missionOverlayRecords.values(), (record) => {
|
||||
records.map((record) => {
|
||||
const entry = createRocketMissionMarkerOverlayEntry(
|
||||
record.launch,
|
||||
record.anchorPosition,
|
||||
|
||||
@@ -22,6 +22,25 @@ export function createRendering({
|
||||
if (current !== next) graphic.show = next;
|
||||
}
|
||||
|
||||
// Away from live, a launch shows from its lift-off on, so scrubbing the
|
||||
// world time forward brings the launches up in the order they flew. The
|
||||
// selected mission stays, whenever it flies.
|
||||
function syncPendingLaunches() {
|
||||
const pending = new Set();
|
||||
for (const { launch } of layerState._missionOverlayRecords.values()) {
|
||||
if (layerState.launchHidden(launch)) pending.add(launch.id);
|
||||
}
|
||||
const previous = layerState._pendingLaunchIds;
|
||||
if (
|
||||
pending.size === previous.size &&
|
||||
[...pending].every((id) => previous.has(id))
|
||||
)
|
||||
return;
|
||||
layerState._pendingLaunchIds = pending;
|
||||
parts.overlays.syncMissionOverlayEntries();
|
||||
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
|
||||
}
|
||||
|
||||
function updateMissionFrame() {
|
||||
if (
|
||||
!layerState._enabled ||
|
||||
@@ -31,6 +50,7 @@ export function createRendering({
|
||||
parts.overlays.hideReplayVehicleOverlay();
|
||||
return;
|
||||
}
|
||||
syncPendingLaunches();
|
||||
parts.panel.updateMissionTelemetry();
|
||||
const time = Cesium.JulianDate.now(layerState._declutterTime);
|
||||
layerState._declutterOccluder.cameraPosition =
|
||||
@@ -39,21 +59,28 @@ export function createRendering({
|
||||
parts.overlays.refreshSelectedMissionOverlayText();
|
||||
for (const entity of layerState._dataSource.entities.values) {
|
||||
if (!entity.show) continue;
|
||||
if (!entity.position) continue;
|
||||
const id = parts.selection.entityLaunchId(entity);
|
||||
if (!id) continue;
|
||||
const pending = layerState._pendingLaunchIds.has(id);
|
||||
if (entity.polyline)
|
||||
setGraphicVisibility(entity.polyline, !pending, time);
|
||||
if (!entity.position) continue;
|
||||
const position = entity.position.getValue(time);
|
||||
let horizonVisible = Boolean(
|
||||
position && layerState._declutterOccluder.isPointVisible(position),
|
||||
);
|
||||
let horizonVisible =
|
||||
!pending &&
|
||||
Boolean(
|
||||
position && layerState._declutterOccluder.isPointVisible(position),
|
||||
);
|
||||
const launchAnchor = entity.id.startsWith('rocket-launch:');
|
||||
if (launchAnchor) {
|
||||
horizonVisible = parts.overlays.missionAnchorVisible(
|
||||
layerState._viewer.scene.camera.positionWC,
|
||||
position,
|
||||
id,
|
||||
layerState._selectedLaunchId,
|
||||
);
|
||||
horizonVisible =
|
||||
!pending &&
|
||||
parts.overlays.missionAnchorVisible(
|
||||
layerState._viewer.scene.camera.positionWC,
|
||||
position,
|
||||
id,
|
||||
layerState._selectedLaunchId,
|
||||
);
|
||||
// Keep entity.show reserved for mission-selection isolation. Horizon
|
||||
// state is applied to the individual graphics below so a rear-side
|
||||
// anchor remains eligible for reevaluation as the camera moves.
|
||||
@@ -394,7 +421,7 @@ export function createRendering({
|
||||
orbitCurrent.latitude,
|
||||
orbitCurrent.altitude,
|
||||
);
|
||||
const liveTime = new Date();
|
||||
const liveTime = new Date(layerState.orbitNow());
|
||||
const liveTelemetry = { speedMps: null };
|
||||
layerState._satelliteTelemetry.set(launch.id, liveTelemetry);
|
||||
let liveFrameNumber = -1;
|
||||
@@ -405,7 +432,7 @@ export function createRendering({
|
||||
layerState._viewer?.scene?.frameState?.frameNumber ?? -1;
|
||||
if (frameNumber !== -1 && frameNumber === liveFrameNumber) return;
|
||||
liveFrameNumber = frameNumber;
|
||||
const nowMs = Date.now();
|
||||
const nowMs = layerState.orbitNow();
|
||||
liveTime.setTime(nowMs);
|
||||
if (satelliteTrack) {
|
||||
const propagated =
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
@@ -156,6 +157,38 @@ export function createState({ services }) {
|
||||
|
||||
state._missionRingDate = new Date(0);
|
||||
|
||||
/** The time the launch window ends at, in epoch ms. */
|
||||
|
||||
state.now = worldTimeFor('rocket-launches');
|
||||
|
||||
/** A launched mission's satellite flies on the satellites layer's time. */
|
||||
|
||||
state.orbitNow = worldTimeFor('satellites');
|
||||
|
||||
/** The launches loaded changed, and with them the time they cover. */
|
||||
|
||||
state.coverageChanged = () => worldClock.coverageChanged();
|
||||
|
||||
/**
|
||||
* Whether a launch has yet to lift off at the world time. While live none
|
||||
* has, so the layer shows every launch in its window as it always did.
|
||||
*/
|
||||
|
||||
state.launchPending = (launch) => {
|
||||
if (worldClock.isLive()) return false;
|
||||
const launchMs = Date.parse(launch?.launchTime);
|
||||
return Number.isFinite(launchMs) && launchMs > state.now();
|
||||
};
|
||||
|
||||
/** Whether a launch is hidden for lifting off after the world time. */
|
||||
|
||||
state.launchHidden = (launch) =>
|
||||
launch?.id !== state._selectedLaunchId && state.launchPending(launch);
|
||||
|
||||
/** The launches hidden at the last frame, by id, to spot a change. */
|
||||
|
||||
state._pendingLaunchIds = new Set();
|
||||
|
||||
state._missionOrbitPatternRegistered = false;
|
||||
|
||||
state._pathDistanceCache = new WeakMap();
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Away from live, a launch shows from its lift-off on, so scrubbing the world
|
||||
// time brings the launches up in the order they flew.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
import { createState } from './state.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createSelection } from './selection.js';
|
||||
|
||||
const noop = () => {};
|
||||
const LAUNCH_MS = Date.UTC(2026, 9, 20, 12);
|
||||
|
||||
function scene(t) {
|
||||
t.after(() => worldClock.goLive());
|
||||
const state = createState({
|
||||
services: {
|
||||
overlays: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
},
|
||||
});
|
||||
const launch = {
|
||||
id: 'ceres-1',
|
||||
launchTime: new Date(LAUNCH_MS).toISOString(),
|
||||
};
|
||||
state._enabled = true;
|
||||
state._dataSource = new Cesium.CustomDataSource('launches');
|
||||
state._viewer = {
|
||||
scene: { camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) } },
|
||||
};
|
||||
state._missionOverlayRecords.set(launch.id, { launch });
|
||||
const position = Cesium.Cartesian3.fromDegrees(0, 0);
|
||||
const anchor = state._dataSource.entities.add({
|
||||
id: `rocket-launch:${launch.id}`,
|
||||
position,
|
||||
point: { pixelSize: 5 },
|
||||
});
|
||||
const path = state._dataSource.entities.add({
|
||||
id: `rocket-transfer:${launch.id}`,
|
||||
polyline: { positions: [position, Cesium.Cartesian3.fromDegrees(1, 1)] },
|
||||
});
|
||||
const syncs = { labels: 0, orbits: 0 };
|
||||
const parts = {
|
||||
panel: { updateMissionTelemetry: noop },
|
||||
overlays: {
|
||||
hideReplayVehicleOverlay: noop,
|
||||
updateReplayVehicleOverlay: noop,
|
||||
refreshSelectedMissionOverlayText: noop,
|
||||
missionAnchorVisible: () => true,
|
||||
syncMissionOverlayEntries: () => syncs.labels++,
|
||||
},
|
||||
orbitRendering: {
|
||||
syncMissionOrbitPrimitiveVisibility: () => syncs.orbits++,
|
||||
},
|
||||
};
|
||||
const services = {
|
||||
geometry: { getKeyholeGeometry: noop },
|
||||
satellites: {},
|
||||
};
|
||||
parts.selection = createSelection({ state, services, parts });
|
||||
const rendering = createRendering({ state, services, parts });
|
||||
const shown = () => {
|
||||
rendering.updateMissionFrame();
|
||||
const time = Cesium.JulianDate.now();
|
||||
return {
|
||||
marker: anchor.point.show.getValue(time),
|
||||
path: path.polyline.show?.getValue(time) ?? true,
|
||||
};
|
||||
};
|
||||
return { state, launch, syncs, shown };
|
||||
}
|
||||
|
||||
test('live shows every launch in the window, lifted off or not', (t) => {
|
||||
const { state, launch, shown } = scene(t);
|
||||
assert.equal(state.launchPending(launch), false);
|
||||
assert.deepEqual(shown(), { marker: true, path: true });
|
||||
});
|
||||
|
||||
test('away from live a launch shows from its lift-off on', (t) => {
|
||||
const { state, launch, syncs, shown } = scene(t);
|
||||
worldClock.seek(LAUNCH_MS - 60_000);
|
||||
assert.equal(state.launchPending(launch), true);
|
||||
assert.deepEqual(shown(), { marker: false, path: false });
|
||||
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'its label and orbit go');
|
||||
shown();
|
||||
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'once, not each frame');
|
||||
|
||||
worldClock.seek(LAUNCH_MS);
|
||||
assert.equal(state.launchPending(launch), false);
|
||||
assert.deepEqual(shown(), { marker: true, path: true });
|
||||
assert.deepEqual(syncs, { labels: 2, orbits: 2 });
|
||||
});
|
||||
|
||||
test('the selected mission stays whenever it flies', (t) => {
|
||||
const { state, launch, shown } = scene(t);
|
||||
state._selectedLaunchId = launch.id;
|
||||
worldClock.seek(LAUNCH_MS - 60_000);
|
||||
assert.deepEqual(shown(), { marker: true, path: true });
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import {
|
||||
lerpAngleDeg,
|
||||
speedRamp,
|
||||
@@ -67,7 +68,7 @@ export function createMotion({
|
||||
// Render one poll interval behind real time so we interpolate between
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
julianAt(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -213,7 +214,7 @@ export function createMotion({
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
julianAt(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createMilitaryFeed } from './ingestion.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
const { createGroundSnap } = services.groundSnap;
|
||||
@@ -11,6 +12,8 @@ export function createFlightState({ source, services }) {
|
||||
...services.groundFloor,
|
||||
});
|
||||
flightState._cullPositions = new Map();
|
||||
/** The time contacts are drawn behind by the render delay, in epoch ms. */
|
||||
flightState.now = worldTimeFor('military');
|
||||
|
||||
/** Per-class model spec for THIS layer (2026-08-16, owner playtest ask:
|
||||
* military contacts should read as their WEIGHT CLASS, always in this layer's
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
|
||||
@@ -500,7 +501,7 @@ export function createTracking({
|
||||
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
|
||||
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
|
||||
const seedRenderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
julianAt(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -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) }),
|
||||
);
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
@@ -32,7 +32,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
1,
|
||||
Math.ceil(layerState._denseIds.length / DENSE_REFRESH_FRAMES),
|
||||
);
|
||||
const now = new Date();
|
||||
const now = new Date(layerState.now());
|
||||
for (let i = 0; i < perFrame; i++) {
|
||||
if (layerState._denseCursor >= layerState._denseIds.length)
|
||||
layerState._denseCursor = 0;
|
||||
@@ -97,7 +97,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
|
||||
const entries = parts.orbits.parseTLE(text);
|
||||
const style = POINT_STYLES.dense;
|
||||
const now = new Date();
|
||||
const now = new Date(layerState.now());
|
||||
let added = 0;
|
||||
|
||||
for (let start = 0; start < entries.length; start += DENSE_CREATE_CHUNK) {
|
||||
@@ -124,6 +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(
|
||||
@@ -165,6 +172,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
|
||||
layerState._count = layerState._points.size;
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
layerState._denseStatus = 'ready';
|
||||
console.log(
|
||||
`[Data:Satellites] Dense catalog: +${added} ${DENSE_GROUP_PATH} (points only)`,
|
||||
@@ -203,6 +211,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
if (token !== layerState._denseLoadToken) return;
|
||||
layerState._params.catalog = 'core';
|
||||
_removeDenseCatalog();
|
||||
// Back on core, Starlink is off: hide the core catalog's own Starlink
|
||||
// points again, and say so in the class choice.
|
||||
if (layerState._params.classes)
|
||||
layerState._params.classes = {
|
||||
...layerState._params.classes,
|
||||
starlink: false,
|
||||
};
|
||||
parts.controls._applyClassVisibility?.();
|
||||
layerState._denseStatus = 'failed';
|
||||
layerState._denseError = reason;
|
||||
parts.controls._notifyRowControls();
|
||||
@@ -232,6 +248,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
layerState._denseCursor = 0;
|
||||
layerState._count = layerState._points.size;
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
}
|
||||
return {
|
||||
_abortActiveUpdates,
|
||||
|
||||
@@ -0,0 +1,765 @@
|
||||
/**
|
||||
* @file Satellite classes: which of six KSP-style classes an object in orbit
|
||||
* belongs to, who owns it and who operates it.
|
||||
*
|
||||
* Classes, in legend order:
|
||||
* - stations: crewed stations and the craft that visit them (ISS, Tiangong,
|
||||
* Soyuz, Shenzhou, Dragon, Progress, Cygnus…), by name. The CubeSats
|
||||
* CelesTrak's stations group also carries after their deployment from the
|
||||
* ISS are classed like any other satellite. Retired stations and the
|
||||
* shuttles have re-entered, so they have no orbit to show.
|
||||
* - imaging: Earth observation of every kind (optical, radar, multispectral,
|
||||
* hyperspectral, weather, Earth science, surveillance).
|
||||
* - telecom: communications and navigation (GEO comsats, Iridium, OneWeb,
|
||||
* GPS, GLONASS, Galileo, BeiDou…), Starlink excepted.
|
||||
* - starlink: the Starlink constellation.
|
||||
* - probes: other working payloads (space science, technology development and
|
||||
* demonstration, education, unknown purpose).
|
||||
* - debris: rocket bodies, fragments, unknown objects and payloads that no
|
||||
* longer work. Shown and tracked on request, never ridden in the Cockpit.
|
||||
*
|
||||
* The evidence, strongest first: CelesTrak SATCAT's object type and
|
||||
* operational status (current, so it overrules UCS on a satellite that has
|
||||
* died since), the UCS Satellite Database's purpose (May 2023), name patterns
|
||||
* for satellites launched after it, and the CelesTrak group the TLE came in.
|
||||
* Pure: no Cesium, no fetches, so the tables are unit-tested directly.
|
||||
*
|
||||
* @module satelliteClasses
|
||||
*/
|
||||
|
||||
import { msg } from '../../i18n/index.js';
|
||||
|
||||
/** Class ids in legend order. */
|
||||
export const SATELLITE_CLASS_IDS = Object.freeze([
|
||||
'stations',
|
||||
'imaging',
|
||||
'telecom',
|
||||
'starlink',
|
||||
'probes',
|
||||
'debris',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Which classes show when nobody has chosen: everything the layer showed
|
||||
* before classes existed. Starlink stays off, as the DENSE switch was.
|
||||
*/
|
||||
export const DEFAULT_SATELLITE_CLASSES = Object.freeze({
|
||||
stations: true,
|
||||
imaging: true,
|
||||
telecom: true,
|
||||
starlink: false,
|
||||
probes: true,
|
||||
debris: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Point colour and the legend and chip text for each class. Colours reuse the
|
||||
* layer's established palette (src/data/satelliteClass.js); debris recedes.
|
||||
*/
|
||||
export const SATELLITE_CLASS_DISPLAY = Object.freeze({
|
||||
stations: Object.freeze({
|
||||
color: '#fff6e5',
|
||||
label: msg('STATIONS'),
|
||||
blurb: msg('Crewed stations and the craft that visit them'),
|
||||
}),
|
||||
imaging: Object.freeze({
|
||||
color: '#4fd8ff',
|
||||
label: msg('IMAGING'),
|
||||
blurb: msg('Earth observation: optical, radar, weather and science'),
|
||||
}),
|
||||
telecom: Object.freeze({
|
||||
color: '#c89bff',
|
||||
label: msg('TELECOM'),
|
||||
blurb: msg('Communications and navigation satellites, Starlink excepted'),
|
||||
}),
|
||||
starlink: Object.freeze({
|
||||
color: '#54697f',
|
||||
label: msg('STARLINK'),
|
||||
blurb: msg('The Starlink constellation (thousands of extra points)'),
|
||||
}),
|
||||
probes: Object.freeze({
|
||||
color: '#9fb3c4',
|
||||
label: msg('PROBES'),
|
||||
blurb: msg('Space science, technology demonstration and other payloads'),
|
||||
}),
|
||||
debris: Object.freeze({
|
||||
color: '#7d7468',
|
||||
label: msg('DEBRIS'),
|
||||
blurb: msg('Rocket bodies, fragments and dead satellites'),
|
||||
}),
|
||||
});
|
||||
|
||||
/** The ISS, a station whatever else says. */
|
||||
const ISS_NORAD = 25544;
|
||||
|
||||
/** SATCAT object types that are never a working payload. */
|
||||
const DEBRIS_OBJECT_TYPES = new Set(['R/B', 'DEB']);
|
||||
/**
|
||||
* SATCAT files a new launch's objects as UNK until it identifies them, so an
|
||||
* unknown object launched within this many calendar years (2: this year or
|
||||
* last) is not presumed debris. Years, not dates: the TLE designator, the
|
||||
* fallback when SATCAT has no launch date, carries only the year.
|
||||
*/
|
||||
export const UNIDENTIFIED_GRACE_YEARS = 2;
|
||||
/** SATCAT operational status: nonoperational, decayed. */
|
||||
const DEAD_STATUSES = new Set(['-', 'D']);
|
||||
/** SATCAT operational status left blank or unknown. */
|
||||
const UNKNOWN_STATUSES = new Set(['', '?']);
|
||||
/**
|
||||
* A payload whose SATCAT record gives no status, with no UCS record and no
|
||||
* recognisable name, that launched this many years ago is presumed dead (old
|
||||
* weather and science satellites the "visual" group keeps for their
|
||||
* brightness). Without a SATCAT record (a failed read) nothing is presumed.
|
||||
*/
|
||||
export const PRESUMED_DEAD_AFTER_YEARS = 20;
|
||||
|
||||
const DEBRIS_NAME = /\bR\/B\b|\bDEB\b|\bAKM\b|ROCKET BODY/i;
|
||||
const STATION_NAME =
|
||||
/^(ISS\b|TIANGONG|TIANHE|WENTIAN|MENGTIAN|CSS\b|SHENZHOU|TIANZHOU|SOYUZ|PROGRESS|CREW DRAGON|DRAGON|CYGNUS|STARLINER|HTV\b|AXIOM)/i;
|
||||
const STARLINK_NAME = /^STARLINK/i;
|
||||
const IMAGING_NAME =
|
||||
/^(SENTINEL|LANDSAT|WORLDVIEW|GEOEYE|PLEIADES|SPOT[ -]\d|ICEYE|CAPELLA|UMBRA|FLOCK|SKYSAT|PELICAN|SUPERDOVE|DOVE\b|NOAA[ -]?\d|GOES|METEOSAT|METOP|HIMAWARI|FENGYUN|FY-?\d|GAOFEN|JILIN|SUPERVIEW|KOMPSAT|RADARSAT|RCM-|TERRA\b|AQUA\b|SUOMI NPP|JPSS|CARTOSAT|RESOURCESAT|RISAT|EOS-\d|ALOS|COSMO-SKYMED|CSG-|TERRASAR|TANDEM-X|PAZ\b|SAOCOM|KANOPUS|RESURS|METEOR-M|ELEKTRO-L|ARKTIKA-M|YAOGAN|NUSAT|NEWSAT|BLACKSKY|GLOBAL-\d|GHGSAT|LEMUR|HAIYANG|HY-\d|ZIYUAN|ZY-\d|TIANHUI|SWOT|ICESAT|GRACE|CRYOSAT|SMAP|SMOS|PROBA-V|DEIMOS|THEOS|GOKTURK|EROS|OFEQ|OPTSAT|PRISMA|ENMAP|NISAR|BIOMASS|EARTHCARE|FORMOSAT|CBERS|AMAZONIA|SICH|DMSP|ELECTRO)/i;
|
||||
const TELECOM_NAME =
|
||||
/^(ONEWEB|IRIDIUM|GLOBALSTAR|ORBCOMM|INTELSAT|IS-\d|SES[ -]?\d|ASTRA|EUTELSAT|INMARSAT|VIASAT|ECHOSTAR|DIRECTV|SIRIUS|XM-|TDRS|NAVSTAR|GPS\b|GLONASS|GSAT0|GALILEO|BEIDOU|QZS|IRNSS|NVS-|KUIPER|LYNK|BLUEBIRD|O3B|TELESAT|ANIK|NIMIQ|AMAZONAS|HISPASAT|ARABSAT|NILESAT|TURKSAT|YAMAL|EXPRESS-|CHINASAT|ZHONGXING|APSTAR|ASIASAT|THAICOM|MEASAT|JCSAT|SUPERBIRD|OPTUS|SKYNET|WGS|MUOS|AEHF|MILSTAR|QIANFAN|GUOWANG|SPACEMOBILE|GONETS|MERIDIAN|LUCH|RADUGA|SKYTERRA|TERRESTAR|SPACEWAY|HYLAS|ARSAT|AMOS|BADR|KA-SAT|YAHSAT|THURAYA)/i;
|
||||
|
||||
const IMAGING_PURPOSE =
|
||||
/earth observation|earth\/space observation|earth science|meteorolog|surveillance/i;
|
||||
const TELECOM_PURPOSE = /communications|navigation|positioning/i;
|
||||
|
||||
/**
|
||||
* CelesTrak groups whose members are, by default, of one class. Not
|
||||
* stations: it also carries CubeSats deployed from the ISS.
|
||||
*/
|
||||
const GROUP_CLASS = Object.freeze({
|
||||
dense: 'starlink',
|
||||
starlink: 'starlink',
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
'gps-ops': 'telecom',
|
||||
glonass: 'telecom',
|
||||
'glo-ops': 'telecom',
|
||||
galileo: 'telecom',
|
||||
geo: 'telecom',
|
||||
science: 'probes',
|
||||
});
|
||||
|
||||
/** CelesTrak groups named for an orbit, not a mission: the last resort. */
|
||||
const ORBIT_GROUPS = new Set(['geo']);
|
||||
|
||||
/** The year of a SATCAT launch date (`2024-03-15`), or null. */
|
||||
function launchYearOf(launchDate) {
|
||||
const match = /^(\d{4})-/.exec(String(launchDate || ''));
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The class a satellite belongs to.
|
||||
* @param {{noradId?: number, name?: string, group?: string|null,
|
||||
* groups?: string[]|null,
|
||||
* ucs?: {purpose?: string|null}|null,
|
||||
* satcat?: {objectType?: string, opsStatus?: string,
|
||||
* launchDate?: string|null}|null,
|
||||
* launchYear?: number|null, nowYear?: number}} subject `groups` is every
|
||||
* CelesTrak group the TLE came in (`group` is the one it is shown under):
|
||||
* the first of them that names a class gives the last-resort class, so a
|
||||
* satellite in both `visual` and `resource` is still imaging. `launchYear` is
|
||||
* the TLE designator's; SATCAT's launch date wins where it has one (an
|
||||
* object deployed from the ISS carries the station's 1998 designator).
|
||||
* @returns {'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris'}
|
||||
*/
|
||||
export function classifySatellite({
|
||||
noradId,
|
||||
name = '',
|
||||
group = null,
|
||||
ucs = null,
|
||||
satcat = null,
|
||||
groups = null,
|
||||
launchYear = null,
|
||||
nowYear = new Date().getUTCFullYear(),
|
||||
} = {}) {
|
||||
if (noradId === ISS_NORAD) return 'stations';
|
||||
const label = String(name || '').trim();
|
||||
const objectType = satcat?.objectType || null;
|
||||
const status = satcat?.opsStatus ?? null;
|
||||
const launched = launchYearOf(satcat?.launchDate) ?? launchYear;
|
||||
const recent =
|
||||
Number.isFinite(launched) && nowYear - launched < UNIDENTIFIED_GRACE_YEARS;
|
||||
if (objectType && DEBRIS_OBJECT_TYPES.has(objectType)) return 'debris';
|
||||
if (objectType === 'UNK' && !recent) return 'debris';
|
||||
if (!objectType && DEBRIS_NAME.test(label)) return 'debris';
|
||||
if (status !== null && DEAD_STATUSES.has(status)) return 'debris';
|
||||
|
||||
// CelesTrak's stations group also carries the CubeSats deployed from the
|
||||
// ISS (they share its 1998-067 designator): only a station or a visiting
|
||||
// craft, by name, is a station.
|
||||
if (STATION_NAME.test(label)) return 'stations';
|
||||
if (group === 'dense' || STARLINK_NAME.test(label)) return 'starlink';
|
||||
|
||||
// UCS writes "Unknown" for a purpose it does not know: no evidence.
|
||||
const purpose = /^unknown$/i.test(ucs?.purpose || '')
|
||||
? ''
|
||||
: ucs?.purpose || '';
|
||||
if (IMAGING_PURPOSE.test(purpose)) return 'imaging';
|
||||
if (TELECOM_PURPOSE.test(purpose)) return 'telecom';
|
||||
if (purpose) return 'probes';
|
||||
|
||||
if (IMAGING_NAME.test(label)) return 'imaging';
|
||||
if (TELECOM_NAME.test(label)) return 'telecom';
|
||||
|
||||
// UCS lists working satellites only: a payload it never knew, whose SATCAT
|
||||
// record gives no status and whose launch is decades old, is presumed
|
||||
// dead. Without a SATCAT record (its read failed or has not landed) there
|
||||
// is no evidence either way, so nothing is presumed.
|
||||
if (
|
||||
satcat &&
|
||||
UNKNOWN_STATUSES.has(status ?? '') &&
|
||||
Number.isFinite(launched) &&
|
||||
nowYear - launched >= PRESUMED_DEAD_AFTER_YEARS
|
||||
)
|
||||
return 'debris';
|
||||
|
||||
// A mission group (weather, resource, science…) says more than an orbit
|
||||
// group: a weather satellite in geostationary orbit is in both.
|
||||
const memberships = groups?.length ? groups : [group];
|
||||
for (const membership of [
|
||||
...memberships.filter((m) => !ORBIT_GROUPS.has(m)),
|
||||
...memberships.filter((m) => ORBIT_GROUPS.has(m)),
|
||||
])
|
||||
if (GROUP_CLASS[membership]) return GROUP_CLASS[membership];
|
||||
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.
|
||||
* @param {Record<string, unknown>|null|undefined} request
|
||||
* @param {Record<string, boolean>} [current]
|
||||
* @returns {Record<string, boolean>}
|
||||
*/
|
||||
export function mergeClassVisibility(
|
||||
request,
|
||||
current = DEFAULT_SATELLITE_CLASSES,
|
||||
) {
|
||||
const next = {};
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const value = request?.[id];
|
||||
next[id] = typeof value === 'boolean' ? value : current[id] === true;
|
||||
}
|
||||
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 = [];
|
||||
let field = '';
|
||||
let quoted = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i];
|
||||
if (quoted) {
|
||||
if (ch === '"' && line[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else if (ch === '"') quoted = false;
|
||||
else field += ch;
|
||||
} else if (ch === '"') quoted = true;
|
||||
else if (ch === ',') {
|
||||
fields.push(field);
|
||||
field = '';
|
||||
} else field += ch;
|
||||
}
|
||||
fields.push(field);
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
* owner: string, cosparId: string|null, launchDate: string|null}>}
|
||||
*/
|
||||
export function parseSatcatCsv(text) {
|
||||
const records = new Map();
|
||||
const lines = String(text || '')
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.trim());
|
||||
if (!lines.length) return records;
|
||||
const header = csvFields(lines[0]).map((name) => name.trim());
|
||||
const at = (name) => header.indexOf(name);
|
||||
const col = {
|
||||
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;
|
||||
for (const line of lines.slice(1)) {
|
||||
const fields = csvFields(line);
|
||||
const noradId = Number(fields[col.norad]);
|
||||
if (!Number.isInteger(noradId) || noradId <= 0) continue;
|
||||
const text = (index) => (index < 0 ? '' : (fields[index] ?? '').trim());
|
||||
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,
|
||||
});
|
||||
}
|
||||
return records;
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
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, with stations and imaging on by default and the rest off', () => {
|
||||
assert.deepEqual(SATELLITE_CLASS_IDS, [
|
||||
'stations',
|
||||
'imaging',
|
||||
'telecom',
|
||||
'starlink',
|
||||
'probes',
|
||||
'debris',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
SATELLITE_CLASS_IDS.filter((id) => DEFAULT_SATELLITE_CLASSES[id]),
|
||||
['stations', 'imaging', 'telecom', 'probes', 'debris'],
|
||||
);
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const display = SATELLITE_CLASS_DISPLAY[id];
|
||||
assert.match(display.color, /^#[0-9a-f]{6}$/, id);
|
||||
assert.ok(display.label && display.blurb, id);
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
// 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 } }),
|
||||
'debris',
|
||||
opsStatus,
|
||||
);
|
||||
assert.equal(
|
||||
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus: '+' } }),
|
||||
'imaging',
|
||||
);
|
||||
// SATCAT calls a new launch's objects UNK until it names them: only an
|
||||
// old unknown object, or one with no launch date, is debris.
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'OBJECT C',
|
||||
group: 'resource',
|
||||
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2025-11-02' },
|
||||
}),
|
||||
'imaging',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'OBJECT C',
|
||||
group: 'resource',
|
||||
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2019-04-01' },
|
||||
}),
|
||||
'debris',
|
||||
);
|
||||
// Debris riding in the stations group (CelesTrak lists FREGAT DEB there).
|
||||
assert.equal(classify({ name: 'FREGAT DEB', group: 'stations' }), 'debris');
|
||||
assert.equal(classify({ name: 'SL-16 R/B', group: 'visual' }), 'debris');
|
||||
});
|
||||
|
||||
test('the ISS is a station whatever else says', () => {
|
||||
assert.equal(
|
||||
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, group: 'visual' }), 'stations', name);
|
||||
});
|
||||
|
||||
test('UCS purpose decides imaging, telecom and probes', () => {
|
||||
const table = [
|
||||
['Earth Observation', 'imaging'],
|
||||
['Earth Science', 'imaging'],
|
||||
['Meteorological', 'imaging'],
|
||||
['Surveillance', 'imaging'],
|
||||
['Earth Observation/Navigation', 'imaging'],
|
||||
['Earth/Space Observation', 'imaging'],
|
||||
['Communications', 'telecom'],
|
||||
['Navigation/Global Positioning', 'telecom'],
|
||||
['Navigation/Regional Positioning', 'telecom'],
|
||||
['Technology Development', 'probes'],
|
||||
['Technology Demonstration', 'probes'],
|
||||
['Space Science', 'probes'],
|
||||
['Unknown', 'probes'],
|
||||
];
|
||||
for (const [purpose, expected] of table)
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', ucs: { purpose } }), expected, purpose);
|
||||
});
|
||||
|
||||
test('satellites launched after the UCS snapshot are classed by name', () => {
|
||||
const table = [
|
||||
['ICEYE-X50', 'imaging'],
|
||||
['CAPELLA-17', 'imaging'],
|
||||
['FLOCK 4Y-12', 'imaging'],
|
||||
['PELICAN-3', 'imaging'],
|
||||
['SENTINEL-1C', 'imaging'],
|
||||
['LANDSAT 9', 'imaging'],
|
||||
['GOES 19', 'imaging'],
|
||||
['ONEWEB-0712', 'telecom'],
|
||||
['IRIDIUM 180', 'telecom'],
|
||||
['GPS BIII-8 (PRN 14)', 'telecom'],
|
||||
['KUIPER-00042', 'telecom'],
|
||||
['STARLINK-34012', 'starlink'],
|
||||
];
|
||||
for (const [name, expected] of table)
|
||||
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: 'STARLINK-1', group: 'dense' }), 'starlink');
|
||||
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']) {
|
||||
assert.equal(
|
||||
classify({ name, group: 'stations', launchYear: 1998 }),
|
||||
'probes',
|
||||
`${name} without SATCAT`,
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name,
|
||||
group: 'stations',
|
||||
launchYear: 1998,
|
||||
satcat: { objectType: 'PAY', opsStatus: '', launchDate: '2025-04-21' },
|
||||
}),
|
||||
'probes',
|
||||
`${name}: SATCAT's 2025 launch, not the designator's 1998`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
classify({ name: 'UNNAMED-1', group: 'stations', ucs: { purpose: 'Earth Observation' } }),
|
||||
'imaging',
|
||||
);
|
||||
});
|
||||
|
||||
test('an unknown old payload is presumed dead; a recognisable one is not', () => {
|
||||
const old = NOW - PRESUMED_DEAD_AFTER_YEARS;
|
||||
assert.equal(
|
||||
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963 }),
|
||||
'probes',
|
||||
'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: '' } }),
|
||||
'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: 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 });
|
||||
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',
|
||||
'ISS (ZARYA),1998-067A,25544,PAY,+,ISS,1998-11-20',
|
||||
'"THOR AGENA, D R/B",1964-002A,733,r/b,,US,1964-01-19',
|
||||
'BROKEN,,notanumber,PAY,+,US,',
|
||||
'',
|
||||
].join('\r\n');
|
||||
const records = parseSatcatCsv(csv);
|
||||
assert.deepEqual([...records.keys()], [25544, 733]);
|
||||
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');
|
||||
assert.equal(parseSatcatCsv('<html>busy</html>').size, 0);
|
||||
assert.equal(parseSatcatCsv('').size, 0);
|
||||
});
|
||||
|
||||
test('turning Stations off takes the ISS ring and label with its point', async () => {
|
||||
const { createControls } = await import('./controls.js');
|
||||
let overlaySyncs = 0;
|
||||
const ring = { primitive: { show: true } };
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_params: {
|
||||
catalog: 'core',
|
||||
showOrbits: true,
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, ring]]),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
};
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: { labels: { _syncIssOverlay: () => (overlaySyncs += 1) } },
|
||||
source: {},
|
||||
});
|
||||
controls._applyClassVisibility();
|
||||
assert.equal(state._points.get(25544).show, false);
|
||||
assert.equal(ring.primitive.show, false, 'the ring goes with the class');
|
||||
assert.ok(overlaySyncs >= 1, 'the label is re-synced');
|
||||
state._params.classes = { ...DEFAULT_SATELLITE_CLASSES };
|
||||
controls._applyClassVisibility();
|
||||
assert.equal(ring.primitive.show, true, 'and comes back with it');
|
||||
});
|
||||
|
||||
test('a failed Starlink load hides the core catalog Starlink points again', async () => {
|
||||
const { createCatalog } = await import('./catalog.js');
|
||||
let applied = 0;
|
||||
const state = {
|
||||
_params: {
|
||||
catalog: 'dense',
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, starlink: true },
|
||||
},
|
||||
_denseLoadToken: 3,
|
||||
_denseIds: [],
|
||||
_catalog: new Map(),
|
||||
_points: new Map(),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
_activeUpdateControllers: new Set(),
|
||||
coverageChanged() {},
|
||||
};
|
||||
const catalog = createCatalog({
|
||||
state,
|
||||
services: {},
|
||||
parts: {
|
||||
controls: {
|
||||
_applyClassVisibility: () => (applied += 1),
|
||||
_notifyRowControls() {},
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
catalog._denseLoadFailed(state._denseLoadToken, 'feed unreachable');
|
||||
assert.equal(state._params.catalog, 'core');
|
||||
assert.equal(state._params.classes.starlink, false, 'the choice says so');
|
||||
assert.ok(applied >= 1, 'class visibility is applied again');
|
||||
});
|
||||
|
||||
test('every ingested group names the class its unnamed members fall back to', () => {
|
||||
// A group added to CATALOG_GROUPS without a class would file its members
|
||||
// under PROBES, the catch-all.
|
||||
const expected = {
|
||||
stations: 'probes',
|
||||
visual: 'probes',
|
||||
'gps-ops': 'telecom',
|
||||
glonass: 'telecom',
|
||||
galileo: 'telecom',
|
||||
geo: 'telecom',
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
science: 'probes',
|
||||
};
|
||||
assert.deepEqual(
|
||||
Object.fromEntries(
|
||||
CATALOG_GROUPS.map(({ tag }) => [
|
||||
tag,
|
||||
classify({ noradId: 99999, name: 'UNNAMED-1', group: tag }),
|
||||
]),
|
||||
),
|
||||
expected,
|
||||
);
|
||||
});
|
||||
|
||||
test('enabling the layer leaves a hidden Stations class without its ISS ring', async () => {
|
||||
const { createLifecycle } = await import('./lifecycle.js');
|
||||
const iss = { primitive: { show: false } };
|
||||
const other = { primitive: { show: false } };
|
||||
let issVisible = false;
|
||||
const state = {
|
||||
_params: { showPoints: true, showOrbits: true },
|
||||
_orbitPaths: new Map([
|
||||
[25544, iss],
|
||||
[90001, other],
|
||||
]),
|
||||
_points: new Map(),
|
||||
coverageChanged() {},
|
||||
};
|
||||
const { methods } = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
focus: { clearFocusTarget() {} },
|
||||
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
|
||||
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
|
||||
},
|
||||
parts: {
|
||||
controls: {
|
||||
satelliteVisualsVisible: (enabled, on) => enabled && on !== false,
|
||||
_issOrbitVisible: () => issVisible,
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
interaction: { _installClickHandler() {} },
|
||||
tracking: { _applyPendingTrackingRestore() {} },
|
||||
rendering: {},
|
||||
},
|
||||
});
|
||||
methods.enable(null);
|
||||
assert.equal(iss.primitive.show, false, 'the ISS ring follows its class');
|
||||
assert.equal(other.primitive.show, true, 'other rings follow showOrbits');
|
||||
issVisible = true;
|
||||
methods.enable(null);
|
||||
assert.equal(iss.primitive.show, true);
|
||||
});
|
||||
|
||||
test('a mission group outranks an orbit group, and an Unknown UCS purpose is no evidence', () => {
|
||||
assert.equal(
|
||||
classify({ name: 'MTG-X1', group: 'geo', groups: ['geo', 'weather'] }),
|
||||
'imaging',
|
||||
);
|
||||
assert.equal(
|
||||
classify({ name: 'UNNAMED-1', group: 'geo', groups: ['geo'] }),
|
||||
'telecom',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'GPS BIII-9',
|
||||
group: 'visual',
|
||||
ucs: { purpose: 'Unknown' },
|
||||
}),
|
||||
'telecom',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'UNNAMED-1',
|
||||
group: 'resource',
|
||||
ucs: { purpose: 'Unknown' },
|
||||
}),
|
||||
'imaging',
|
||||
);
|
||||
});
|
||||
|
||||
test('a tracked ISS keeps its ring while Stations is hidden', async () => {
|
||||
const { createControls } = await import('./controls.js');
|
||||
const ring = { primitive: { show: true } };
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_params: {
|
||||
catalog: 'core',
|
||||
showOrbits: true,
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, ring]]),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
};
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: { labels: { _syncIssOverlay() {} } },
|
||||
source: {},
|
||||
});
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, false);
|
||||
state._trackedNorad = 25544;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, true, 'tracked, it keeps its ring');
|
||||
state._params.showOrbits = false;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, false, 'orbits off still hides it');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
Vendored
+304
-80
@@ -1,11 +1,14 @@
|
||||
import {
|
||||
tallySatelliteClasses,
|
||||
satelliteClassLabel,
|
||||
satelliteClassLegend,
|
||||
} from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { decodeSatelliteClassMask } from '../../data/satelliteClassMask.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { ISS_NORAD, POINT_STYLES } from './policy.js';
|
||||
import {
|
||||
DEFAULT_SATELLITE_CLASSES,
|
||||
SATELLITE_CLASS_DISPLAY,
|
||||
SATELLITE_CLASS_IDS,
|
||||
mergeClassVisibility,
|
||||
} from './classes.js';
|
||||
import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js';
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
const { isExplicitLayerStateOrigin } = services.layerState;
|
||||
@@ -19,7 +22,84 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
function _pointStyleFor(noradId, group) {
|
||||
if (noradId === ISS_NORAD) return POINT_STYLES.iss;
|
||||
return POINT_STYLES[group] || POINT_STYLES.visual;
|
||||
return classPointStyle(
|
||||
group,
|
||||
layerState._catalog.get(noradId)?.satelliteClass,
|
||||
);
|
||||
}
|
||||
|
||||
/** The class-visibility choice, defaults filled in. */
|
||||
function _classes() {
|
||||
return layerState._params.classes || DEFAULT_SATELLITE_CLASSES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a satellite's class is shown. Starlink follows the catalog mode:
|
||||
* its points exist only in dense mode. An unclassed entry shows.
|
||||
* @param {number} noradId NORAD catalog number.
|
||||
*/
|
||||
function _classVisible(noradId) {
|
||||
const satelliteClass = layerState._catalog.get(noradId)?.satelliteClass;
|
||||
if (!satelliteClass) return true;
|
||||
if (satelliteClass === 'starlink')
|
||||
return layerState._params.catalog === 'dense';
|
||||
return _classes()[satelliteClass] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show or hide every point by its class. The tracked satellite's point
|
||||
* 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();
|
||||
parts.labels?._syncIssOverlay?.();
|
||||
layerState._detectionObjects.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the ISS's ring shows: orbits on, the layer drawing, and its
|
||||
* class on or the ISS tracked (a tracked satellite keeps its ring).
|
||||
*/
|
||||
function _issOrbitVisible() {
|
||||
return (
|
||||
satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
) &&
|
||||
(_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD)
|
||||
);
|
||||
}
|
||||
|
||||
/** Show or hide the ISS's ring by _issOrbitVisible, if it is built. */
|
||||
function _syncIssOrbit() {
|
||||
const issPath = layerState._orbitPaths.get(ISS_NORAD);
|
||||
if (issPath) issPath.primitive.show = _issOrbitVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* The row's info line while the classes rest on old or missing SATCAT
|
||||
* evidence (`_satcatState`), and an empty one otherwise.
|
||||
* @returns {{info: string, infoTitle: string}}
|
||||
*/
|
||||
function classEvidenceNotice() {
|
||||
const evidence = layerState._satcatState;
|
||||
if (evidence !== 'stale' && evidence !== 'unavailable')
|
||||
return { info: '', infoTitle: '' };
|
||||
return {
|
||||
info:
|
||||
evidence === 'stale'
|
||||
? t('Classes may lag: SATCAT is a cached copy')
|
||||
: t('Classes may lag: SATCAT unavailable'),
|
||||
infoTitle: t(
|
||||
"CelesTrak SATCAT gives each object's type and status. Without a current copy the classes rest on the UCS database, names and CelesTrak groups, so a satellite that has died since may still show as working.",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Tell the manager to re-render this layer's row (chip state / legend counts). */
|
||||
@@ -46,14 +126,11 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
) {
|
||||
return layerState._classTallyCache.counts;
|
||||
}
|
||||
const entries = [];
|
||||
// Pass the ISS flag, not just the group: during a stations-feed outage the
|
||||
// ISS is ingested as `visual`, and the legend must file it exactly where its
|
||||
// card does (STATION) rather than letting STATION vanish from the legend.
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
entries.push({ group: sat.group, isIss: noradId === ISS_NORAD });
|
||||
const counts = Object.create(null);
|
||||
for (const sat of layerState._catalog.values()) {
|
||||
const satelliteClass = sat.satelliteClass || 'probes';
|
||||
counts[satelliteClass] = (counts[satelliteClass] || 0) + 1;
|
||||
}
|
||||
const counts = tallySatelliteClasses(entries);
|
||||
layerState._classTallyCache = {
|
||||
revision: layerState._catalogRevision,
|
||||
counts,
|
||||
@@ -88,6 +165,47 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
requestedCatalog !== currentCatalog
|
||||
);
|
||||
}
|
||||
/** The STARLINK chip: the dense catalog, with its load state. */
|
||||
function _starlinkChip() {
|
||||
const loading = layerState._denseStatus === 'loading';
|
||||
const failed = layerState._denseStatus === 'failed';
|
||||
const active =
|
||||
layerState._params.catalog === 'dense' &&
|
||||
layerState._denseStatus === 'ready';
|
||||
let title = t(
|
||||
'Add the full Starlink broadband shell (thousands of extra points)',
|
||||
);
|
||||
if (loading) title = t('Loading the Starlink shell…');
|
||||
else if (failed)
|
||||
title = t('Starlink {detail} — click to retry', {
|
||||
detail: layerState._denseError || t('load failed'),
|
||||
});
|
||||
else if (active)
|
||||
title = t(
|
||||
'Showing the full Starlink shell — click for the core catalog only',
|
||||
);
|
||||
return {
|
||||
id: 'catalog',
|
||||
label: loading
|
||||
? t('STARLINK ···')
|
||||
: failed
|
||||
? t('STARLINK ✕')
|
||||
: t('STARLINK'),
|
||||
active,
|
||||
busy: loading,
|
||||
disabled: loading,
|
||||
state: loading
|
||||
? 'loading'
|
||||
: failed
|
||||
? 'error'
|
||||
: active
|
||||
? 'active'
|
||||
: 'idle',
|
||||
title,
|
||||
params: { catalog: active ? 'core' : 'dense' },
|
||||
};
|
||||
}
|
||||
|
||||
const methods = {
|
||||
id: 'satellites',
|
||||
|
||||
@@ -129,11 +247,16 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
if (!shouldTake) continue;
|
||||
if (!point.position) continue;
|
||||
const isTracked = noradId === layerState._trackedNorad;
|
||||
// A hidden class is not on screen, so nothing is bracketed on it.
|
||||
if (!isTracked && !_classVisible(noradId)) continue;
|
||||
// A docked companion sits at the tracked subject's own position, so its
|
||||
// mark and label would stack underneath the tracked card. It is listed on
|
||||
// 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) {
|
||||
@@ -141,15 +264,16 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
sourceId: noradId,
|
||||
id: cat?.name || `SAT-${noradId}`,
|
||||
type: 'SAT',
|
||||
// Human class ("NAV · GPS"), not the raw CelesTrak tag ("GPS-OPS").
|
||||
// The detection canvas composites ABOVE the post-FX chain, so this
|
||||
// is how class survives NVG/FLIR once the dot colors are collapsed.
|
||||
klass: satelliteClassLabel(cat?.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
}),
|
||||
};
|
||||
layerState._detectionObjects.set(noradId, object);
|
||||
}
|
||||
// Human class ("TELECOM · GPS"), not the raw CelesTrak tag
|
||||
// ("GPS-OPS"). The detection canvas composites ABOVE the post-FX
|
||||
// chain, so this is how class survives NVG/FLIR once the dot colors
|
||||
// are collapsed. Read each time: SATCAT can reclassify a satellite.
|
||||
object.klass = satelliteClassText(cat?.satelliteClass, cat?.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
});
|
||||
object.position = point.position;
|
||||
object.skipLabel = isTracked;
|
||||
result.push(object);
|
||||
@@ -190,7 +314,10 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
if (noradId === null) return null;
|
||||
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
const pos = parts.orbits.propagatePosition(sat.satrec, new Date());
|
||||
const pos = parts.orbits.propagatePosition(
|
||||
sat.satrec,
|
||||
new Date(layerState.now()),
|
||||
);
|
||||
if (!pos) return null;
|
||||
|
||||
return {
|
||||
@@ -222,6 +349,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (result.length >= cap) break;
|
||||
if (!point.position) continue;
|
||||
if (!_classVisible(noradId)) continue;
|
||||
// Dense extras are points-only — keep voice/framing lists to the core catalog.
|
||||
if (
|
||||
layerState._denseIds.length > 0 &&
|
||||
@@ -243,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.
|
||||
@@ -380,9 +574,11 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Runtime params (DataLayerManager.setLayerParams path).
|
||||
* catalog: 'core' (default, ~840 sats) | 'dense' (adds the Starlink shell
|
||||
* as points-only extras on a relaxed propagation budget).
|
||||
* @param {{ catalog?: 'core'|'dense', showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
|
||||
* catalog: 'core' (default, about 1,300 satellites from the CelesTrak
|
||||
* groups) | 'dense' (adds the Starlink shell as points-only extras on a
|
||||
* relaxed propagation budget). classes: which of the six classes show
|
||||
* (src/layers/satellites/classes.js); Starlink's toggle is the dense catalog.
|
||||
* @param {{ catalog?: 'core'|'dense', classes?: Record<string, boolean>, showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
|
||||
*/
|
||||
setParams(params = {}, { origin = 'programmatic' } = {}) {
|
||||
if (
|
||||
@@ -391,9 +587,28 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
}
|
||||
const catalog = params.catalog;
|
||||
let catalog = params.catalog;
|
||||
if (catalog !== undefined && catalog !== 'core' && catalog !== 'dense')
|
||||
return false;
|
||||
// A saved or shared choice arrives as class letters (layerState.js).
|
||||
const requestedClasses =
|
||||
typeof params.classes === 'string'
|
||||
? decodeSatelliteClassMask(params.classes)
|
||||
: params.classes;
|
||||
if (params.classes !== undefined) {
|
||||
if (!requestedClasses || typeof requestedClasses !== 'object')
|
||||
return false;
|
||||
// Starlink's toggle is the dense catalog: its points load on demand.
|
||||
if (
|
||||
typeof requestedClasses.starlink === 'boolean' &&
|
||||
catalog === undefined
|
||||
)
|
||||
catalog = requestedClasses.starlink ? 'dense' : 'core';
|
||||
layerState._params.classes = mergeClassVisibility(
|
||||
requestedClasses,
|
||||
_classes(),
|
||||
);
|
||||
}
|
||||
const catalogChanged = satelliteCatalogModeChanged(
|
||||
layerState._params.catalog,
|
||||
catalog,
|
||||
@@ -411,11 +626,14 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
if (params.showOrbits !== undefined) {
|
||||
layerState._params.showOrbits = params.showOrbits !== false;
|
||||
for (const path of layerState._orbitPaths.values())
|
||||
path.primitive.show = satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
);
|
||||
for (const [noradId, path] of layerState._orbitPaths)
|
||||
path.primitive.show =
|
||||
noradId === ISS_NORAD
|
||||
? _issOrbitVisible()
|
||||
: satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
);
|
||||
parts.labels._syncIssOverlay();
|
||||
}
|
||||
if (catalogChanged && catalog === 'dense') {
|
||||
@@ -431,6 +649,13 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
if (catalogChanged)
|
||||
console.log(`[Data:Satellites] Catalog mode: ${catalog}`);
|
||||
if (params.classes !== undefined || catalogChanged) {
|
||||
layerState._params.classes = {
|
||||
..._classes(),
|
||||
starlink: layerState._params.catalog === 'dense',
|
||||
};
|
||||
_applyClassVisibility();
|
||||
}
|
||||
if (Object.hasOwn(params, 'selectedSatTrackingId')) {
|
||||
const requested = parts.tracking._normalizeTrackedNorad(
|
||||
params.selectedSatTrackingId,
|
||||
@@ -462,25 +687,29 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
catalog: layerState._params.catalog,
|
||||
showPoints: layerState._params.showPoints,
|
||||
showOrbits: layerState._params.showOrbits,
|
||||
classes: { ..._classes() },
|
||||
selectedSatTrackingId: layerState._trackedNorad,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Layer-row sub-controls (DataLayerManager row-controls contract): the DENSE
|
||||
* catalog chip plus a class legend so the point colors are learnable without
|
||||
* a new panel.
|
||||
* Layer-row sub-controls (DataLayerManager row-controls contract): one
|
||||
* toggle chip per satellite class (src/layers/satellites/classes.js), and a legend
|
||||
* of the classes on screen so the point colours are learnable.
|
||||
*
|
||||
* The chip is stateless — it declares the params to apply and the manager
|
||||
* Chips are stateless — each declares the params to apply and the manager
|
||||
* owns the write, so the Space Missions snapshot/restore path (which drives
|
||||
* the same `catalog` param) stays the single source of truth and the chip
|
||||
* the same `catalog` param) stays the single source of truth and a chip
|
||||
* always renders whatever the layer actually has.
|
||||
*
|
||||
* The chip reports the dense LOAD state, not the catalog param: the param
|
||||
* flips synchronously while the Starlink shell takes seconds to arrive and
|
||||
* frequently 502s, so ACTIVE means "dense points are on screen" and nothing
|
||||
* less. The legend tally is cached against the catalog revision.
|
||||
* @returns {{ chips: Array<object>, legend: Array<object> }} Row controls.
|
||||
* STARLINK is the dense catalog (chip id `catalog`) and reports the dense
|
||||
* LOAD state, not the param: the param flips synchronously while the shell
|
||||
* takes seconds to arrive and frequently 502s, so ACTIVE means "Starlink
|
||||
* points are on screen" and nothing less. The legend tally is cached
|
||||
* against the catalog revision. While SATCAT is stale or unavailable the
|
||||
* info line says the classes may lag (see `classEvidenceNotice`).
|
||||
* @returns {{ chips: Array<object>, legend: Array<object>, info: string,
|
||||
* infoTitle: string }} Row controls.
|
||||
*/
|
||||
getRowControls() {
|
||||
// A dependency owner (Space Missions) borrows this layer for TLE lookup
|
||||
@@ -489,48 +718,36 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
// restore. Surrender the row rather than lie about it.
|
||||
if (!layerState._params.showPoints) return { chips: [], legend: [] };
|
||||
|
||||
const loading = layerState._denseStatus === 'loading';
|
||||
const failed = layerState._denseStatus === 'failed';
|
||||
const active =
|
||||
layerState._params.catalog === 'dense' &&
|
||||
layerState._denseStatus === 'ready';
|
||||
let title = t(
|
||||
'Add the full Starlink broadband shell (thousands of extra points)',
|
||||
const classes = _classes();
|
||||
const chips = SATELLITE_CLASS_IDS.map((id) =>
|
||||
id === 'starlink'
|
||||
? _starlinkChip()
|
||||
: {
|
||||
id: `class-${id}`,
|
||||
label: t(SATELLITE_CLASS_DISPLAY[id].label),
|
||||
active: classes[id] === true,
|
||||
state: classes[id] === true ? 'active' : 'idle',
|
||||
title: t(SATELLITE_CLASS_DISPLAY[id].blurb),
|
||||
params: { classes: { [id]: classes[id] !== true } },
|
||||
},
|
||||
);
|
||||
if (loading) title = t('Loading the Starlink shell…');
|
||||
else if (failed)
|
||||
title = t('Starlink {detail} — click to retry', {
|
||||
detail: layerState._denseError || t('load failed'),
|
||||
const counts = _classTally();
|
||||
const legend = [];
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const shown =
|
||||
id === 'starlink'
|
||||
? layerState._params.catalog === 'dense'
|
||||
: classes[id] === true;
|
||||
if (!shown || !(counts[id] > 0)) continue;
|
||||
legend.push({
|
||||
klass: id,
|
||||
label: t(SATELLITE_CLASS_DISPLAY[id].label),
|
||||
color: SATELLITE_CLASS_DISPLAY[id].color,
|
||||
blurb: t(SATELLITE_CLASS_DISPLAY[id].blurb),
|
||||
count: counts[id],
|
||||
});
|
||||
else if (active)
|
||||
title = t(
|
||||
'Showing the full Starlink shell — click for the core catalog only',
|
||||
);
|
||||
return {
|
||||
chips: [
|
||||
{
|
||||
id: 'catalog',
|
||||
label: loading
|
||||
? t('DENSE ···')
|
||||
: failed
|
||||
? t('DENSE ✕')
|
||||
: t('DENSE'),
|
||||
active,
|
||||
busy: loading,
|
||||
disabled: loading,
|
||||
state: loading
|
||||
? 'loading'
|
||||
: failed
|
||||
? 'error'
|
||||
: active
|
||||
? 'active'
|
||||
: 'idle',
|
||||
title,
|
||||
params: { catalog: active ? 'core' : 'dense' },
|
||||
},
|
||||
],
|
||||
legend: satelliteClassLegend(_classTally()),
|
||||
};
|
||||
}
|
||||
return { chips, legend, ...classEvidenceNotice() };
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -559,6 +776,9 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
? 'stale'
|
||||
: 'nominal',
|
||||
error: layerState._lastError,
|
||||
// SATCAT refines the classes; when it is stale or unavailable the
|
||||
// classes rest on UCS, names and groups alone.
|
||||
classEvidence: layerState._satcatState,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -567,6 +787,10 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
_pointStyleFor,
|
||||
_notifyRowControls,
|
||||
_classTally,
|
||||
_classVisible,
|
||||
_applyClassVisibility,
|
||||
_issOrbitVisible,
|
||||
_syncIssOrbit,
|
||||
satelliteVisualsVisible,
|
||||
satelliteCatalogModeChanged,
|
||||
methods,
|
||||
|
||||
@@ -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,
|
||||
{
|
||||
|
||||
@@ -3,6 +3,22 @@ import * as Cesium from 'cesium';
|
||||
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
|
||||
* it, ms. SATCAT can hang for the proxy's whole upstream timeout (20 s); the
|
||||
* late answer reclassifies in place.
|
||||
*/
|
||||
export const SATCAT_WAIT_MS = 3000;
|
||||
|
||||
/**
|
||||
* How long a complete, current SATCAT read is kept before the layer asks
|
||||
* again, ms. SATCAT changes daily and the proxy caches it a day, so the
|
||||
* five-minute TLE update does not read all eleven groups each time.
|
||||
*/
|
||||
export const SATCAT_KEEP_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
export function createIngestion({
|
||||
state: layerState,
|
||||
@@ -10,6 +26,161 @@ export function createIngestion({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
/**
|
||||
* 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() {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* CelesTrak SATCAT for every core group: type and status, which refine the
|
||||
* classes. A group whose read failed gives null.
|
||||
* @returns {Promise<Array<{records: Map, stale: boolean}|null>>}
|
||||
*/
|
||||
function _readSatcat(signal) {
|
||||
if (typeof source.readSatcat !== 'function') return Promise.resolve([]);
|
||||
// A complete, current read is kept; a stale or failed one is asked again.
|
||||
if (
|
||||
layerState._satcatState === 'current' &&
|
||||
Date.now() - layerState._satcatReadAtMs < SATCAT_KEEP_MS
|
||||
)
|
||||
return Promise.resolve([]);
|
||||
return Promise.all(
|
||||
CATALOG_GROUPS.map((groupDef) =>
|
||||
source
|
||||
.readSatcat(groupDef.path, { signal })
|
||||
.then((res) =>
|
||||
res?.ok
|
||||
? { records: parseSatcatCsv(res.text), stale: Boolean(res.stale) }
|
||||
: null,
|
||||
)
|
||||
.catch((error) => {
|
||||
if (signal.aborted || error?.name === 'AbortError') throw error;
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge SATCAT reads and say how current they are: 'current', 'stale' (a
|
||||
* group came from the proxy's last copy) or 'unavailable' (a group failed;
|
||||
* its earlier records, if any, stay).
|
||||
*/
|
||||
function _mergeSatcat(groups) {
|
||||
let satcatState = 'current';
|
||||
for (const group of groups) {
|
||||
if (!group) {
|
||||
satcatState = 'unavailable';
|
||||
continue;
|
||||
}
|
||||
if (group.stale && satcatState === 'current') satcatState = 'stale';
|
||||
for (const [noradId, record] of group.records) {
|
||||
// A group served from the proxy's last copy never overrules a
|
||||
// current read of the same object, from this merge or an earlier one.
|
||||
const held = layerState._satcat.get(noradId);
|
||||
if (group.stale && held && !held.stale) continue;
|
||||
layerState._satcat.set(
|
||||
noradId,
|
||||
group.stale ? { ...record, stale: true } : record,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!groups.length) return;
|
||||
const changed = layerState._satcatState !== satcatState;
|
||||
layerState._satcatState = satcatState;
|
||||
layerState._satcatReadAtMs = Date.now();
|
||||
if (satcatState !== 'current')
|
||||
console.warn(`[Data:Satellites] SATCAT ${satcatState}: classes may lag`);
|
||||
// The row's info line says so (getRowControls).
|
||||
if (changed) parts.controls._notifyRowControls();
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the catalog again once SATCAT lands after it was built: only
|
||||
* entries whose SATCAT record changed are read again; a changed class
|
||||
* restyles its point and refreshes visibility, the legend and the overlay.
|
||||
*/
|
||||
function _reclassifyFromSatcat() {
|
||||
let changed = false;
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
if (sat.group === 'dense') continue;
|
||||
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,
|
||||
group: sat.group,
|
||||
groups: sat.groups,
|
||||
ucs: sat.ucs,
|
||||
satcat,
|
||||
launchYear: sat.launchYear,
|
||||
});
|
||||
if (next === sat.satelliteClass) continue;
|
||||
sat.satelliteClass = next;
|
||||
changed = true;
|
||||
const point = layerState._points.get(noradId);
|
||||
if (point) {
|
||||
const style = parts.controls._pointStyleFor(noradId, sat.group);
|
||||
point.pixelSize = style.pixelSize;
|
||||
point.color = style.color;
|
||||
point.outlineColor = style.outlineColor;
|
||||
point.outlineWidth = style.outlineWidth;
|
||||
}
|
||||
}
|
||||
if (!changed) return;
|
||||
parts.controls._applyClassVisibility();
|
||||
layerState._catalogRevision++;
|
||||
parts.controls._notifyRowControls();
|
||||
}
|
||||
|
||||
/** Resolve null after `ms`, or at once when `signal` aborts. */
|
||||
function _waitOrAbort(ms, signal) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms, null);
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
resolve(null);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
const trackingRefreshEpoch = ++layerState._trackingRefreshEpoch;
|
||||
@@ -27,6 +198,10 @@ export function createIngestion({
|
||||
updateSignal.throwIfAborted();
|
||||
// Load all core groups in parallel; a failed/empty group degrades
|
||||
// gracefully (parseTLE of an upstream error body yields []).
|
||||
const localEvidence = _readLocalEvidence();
|
||||
const satcat = _readSatcat(updateSignal);
|
||||
// An abort can reject this before the groups settle and it is awaited.
|
||||
satcat.catch(() => {});
|
||||
const results = await Promise.all(
|
||||
CATALOG_GROUPS.map(async (groupDef) => {
|
||||
try {
|
||||
@@ -49,7 +224,23 @@ export function createIngestion({
|
||||
}
|
||||
}),
|
||||
);
|
||||
await localEvidence;
|
||||
// SATCAT only refines classes: wait a moment for it, then classify
|
||||
// with what is held and let a late answer reclassify in place.
|
||||
const satcatInTime = await Promise.race([
|
||||
satcat.then((groups) => ({ groups })),
|
||||
_waitOrAbort(SATCAT_WAIT_MS, updateSignal),
|
||||
]).catch(() => null);
|
||||
updateSignal.throwIfAborted();
|
||||
if (satcatInTime) _mergeSatcat(satcatInTime.groups);
|
||||
else
|
||||
satcat
|
||||
.then((groups) => {
|
||||
if (updateSignal.aborted || !layerState._enabled) return;
|
||||
_mergeSatcat(groups);
|
||||
_reclassifyFromSatcat();
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
const failed = results.filter((r) => !r.ok).map((r) => r.path);
|
||||
if (failed.length > 0) {
|
||||
@@ -62,7 +253,7 @@ export function createIngestion({
|
||||
);
|
||||
|
||||
// CelesTrak outage guard (H3): if EVERY group failed, bail BEFORE clearing.
|
||||
// Wiping the collection + catalog here would blank all 838 satellites while
|
||||
// Wiping the collection + catalog here would blank every satellite while
|
||||
// the chip still read "just now". Keep the existing (stale) catalog on
|
||||
// screen and surface the outage instead — do NOT stamp _lastUpdate.
|
||||
if (results.every((r) => !r.ok)) {
|
||||
@@ -103,7 +294,7 @@ export function createIngestion({
|
||||
layerState._denseLoadToken++; // cancel any in-flight dense load against the old catalog
|
||||
parts.labels._syncIssOverlay();
|
||||
|
||||
const now = new Date();
|
||||
const now = new Date(layerState.now());
|
||||
|
||||
// Process all TLE entries in CATALOG_GROUPS order
|
||||
const allEntries = [];
|
||||
@@ -112,6 +303,18 @@ export function createIngestion({
|
||||
allEntries.push({ ...e, group: r.tag, stale: r.stale });
|
||||
}
|
||||
|
||||
// Every group each TLE came in, keyed by its catalog-number column:
|
||||
// the shown tag is the first, but classification reads them all.
|
||||
const groupsByNumber = new Map();
|
||||
for (const entry of allEntries) {
|
||||
const number = String(entry.line1 || '')
|
||||
.slice(2, 7)
|
||||
.trim();
|
||||
const groups = groupsByNumber.get(number);
|
||||
if (!groups) groupsByNumber.set(number, [entry.group]);
|
||||
else if (!groups.includes(entry.group)) groups.push(entry.group);
|
||||
}
|
||||
|
||||
// Deduplicate by NORAD ID — first (most specific) group tag wins
|
||||
const seen = new Set();
|
||||
let coreStale = false;
|
||||
@@ -125,12 +328,38 @@ export function createIngestion({
|
||||
seen.add(noradId);
|
||||
|
||||
// Store in catalog
|
||||
const launchYear = tleLineLaunchYear(entry.line1);
|
||||
const ucs = layerState._ucs?.get(noradId) || null;
|
||||
const satcat = layerState._satcat.get(noradId) || null;
|
||||
const groups = groupsByNumber.get(
|
||||
String(entry.line1 || '')
|
||||
.slice(2, 7)
|
||||
.trim(),
|
||||
) || [entry.group];
|
||||
layerState._catalog.set(noradId, {
|
||||
name: entry.name,
|
||||
satrec,
|
||||
group: entry.group,
|
||||
groups,
|
||||
// satellite.js does not keep the designator the year match reads.
|
||||
launchYear: tleLineLaunchYear(entry.line1),
|
||||
launchYear,
|
||||
line1: entry.line1,
|
||||
line2: entry.line2,
|
||||
satelliteClass: classifySatellite({
|
||||
noradId,
|
||||
name: entry.name,
|
||||
group: entry.group,
|
||||
groups,
|
||||
ucs,
|
||||
satcat,
|
||||
launchYear,
|
||||
}),
|
||||
ucs,
|
||||
satcat,
|
||||
sensor: matchImagingSensor(layerState._sensors, {
|
||||
noradId,
|
||||
name: entry.name,
|
||||
}),
|
||||
});
|
||||
|
||||
coreStale ||= entry.stale;
|
||||
@@ -156,6 +385,8 @@ export function createIngestion({
|
||||
scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6),
|
||||
id: noradId,
|
||||
});
|
||||
// Hidden classes keep their point, so a toggle needs no rebuild.
|
||||
point.show = parts.controls._classVisible(noradId);
|
||||
|
||||
layerState._points.set(noradId, point);
|
||||
}
|
||||
@@ -163,8 +394,7 @@ export function createIngestion({
|
||||
// Show ISS orbital path by default
|
||||
if (layerState._catalog.has(ISS_NORAD)) {
|
||||
parts.rendering._showOrbitPath(ISS_NORAD, POINT_STYLES.iss.color);
|
||||
const issPath = layerState._orbitPaths.get(ISS_NORAD);
|
||||
if (issPath) issPath.primitive.show = layerState._params.showOrbits;
|
||||
parts.controls._syncIssOrbit();
|
||||
|
||||
parts.labels._syncIssOverlay();
|
||||
}
|
||||
@@ -195,6 +425,7 @@ export function createIngestion({
|
||||
// the rebuild must not block on that.
|
||||
void parts.tracking._reconcileTrackedSubjectContext();
|
||||
parts.tracking._applyPendingTrackingRestore();
|
||||
layerState.coverageChanged();
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Satellite update aborted', 'AbortError');
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseTleText, tleLineLaunchYear } from '../../sources/tle.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import {
|
||||
SATCAT_KEEP_MS,
|
||||
SATCAT_WAIT_MS,
|
||||
createIngestion,
|
||||
} from './ingestion.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
// The ISS set (1 January 2024) with its catalog field swapped per satellite.
|
||||
const ISS_LINE1 =
|
||||
@@ -18,7 +23,7 @@ function tleSet(name, field) {
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function ingestionFor(catalogText) {
|
||||
function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
|
||||
const state = {
|
||||
_trackingRefreshEpoch: 0,
|
||||
_activeUpdateControllers: new Set(),
|
||||
@@ -33,6 +38,10 @@ function ingestionFor(catalogText) {
|
||||
_denseLoadToken: 0,
|
||||
_catalogRevision: 0,
|
||||
_params: { catalog: 'core', showOrbits: false },
|
||||
_satcat: new Map(),
|
||||
_ucs: null,
|
||||
now: Date.now,
|
||||
coverageChanged() {},
|
||||
};
|
||||
const parts = {
|
||||
orbits: {
|
||||
@@ -40,7 +49,17 @@ function ingestionFor(catalogText) {
|
||||
propagatePosition: () => ({ longitude: 0, latitude: 0, altitude: 4e5 }),
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
controls: { _pointStyleFor: () => ({}) },
|
||||
controls: {
|
||||
_pointStyleFor: () => ({}),
|
||||
_classVisible: () => true,
|
||||
_syncIssOrbit() {},
|
||||
_applyClassVisibility() {
|
||||
state.visibilityApplied = (state.visibilityApplied || 0) + 1;
|
||||
},
|
||||
_notifyRowControls() {
|
||||
state.rowNotified = (state.rowNotified || 0) + 1;
|
||||
},
|
||||
},
|
||||
rendering: { _showOrbitPath() {} },
|
||||
tracking: {
|
||||
async _reconcileTrackedSubjectContext() {},
|
||||
@@ -49,9 +68,12 @@ function ingestionFor(catalogText) {
|
||||
catalog: {},
|
||||
};
|
||||
const source = {
|
||||
async readGroup() {
|
||||
return { ok: true, text: catalogText };
|
||||
async readGroup(path) {
|
||||
const text =
|
||||
typeof catalogText === 'function' ? catalogText(path) : catalogText;
|
||||
return { ok: true, text };
|
||||
},
|
||||
...sourceExtras,
|
||||
};
|
||||
const { methods } = createIngestion({ state, services: {}, parts, source });
|
||||
return { state, update: () => methods.update({ scene: {} }) };
|
||||
@@ -119,3 +141,175 @@ test('a satellite with a blank designator keeps matching by name', async (t) =>
|
||||
69728,
|
||||
);
|
||||
});
|
||||
|
||||
test('a hanging SATCAT read neither holds the catalog nor is lost when it lands', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let answer;
|
||||
const satcatAnswer = new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
});
|
||||
const { state, update } = ingestionFor(
|
||||
(path) => (path === 'stations' ? tleSet('OLD STAGE', '40115') : ''),
|
||||
{ source: { readSatcat: () => satcatAnswer } },
|
||||
);
|
||||
state._enabled = true;
|
||||
const settle = async () => {
|
||||
for (let turn = 0; turn < 20; turn += 1)
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
};
|
||||
const rebuilt = update();
|
||||
await settle();
|
||||
t.mock.timers.tick(SATCAT_WAIT_MS);
|
||||
await rebuilt;
|
||||
// Built without SATCAT: neither name nor group says what it is (the
|
||||
// stations group alone makes no station).
|
||||
assert.equal(state._catalog.get(40115).satelliteClass, 'probes');
|
||||
const revision = state._catalogRevision;
|
||||
// SATCAT lands late: a rocket body.
|
||||
answer({
|
||||
ok: true,
|
||||
stale: true,
|
||||
text: 'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\nOLD STAGE,2014-048B,40115,R/B,,US',
|
||||
});
|
||||
await settle();
|
||||
assert.equal(state._catalog.get(40115).satelliteClass, 'debris');
|
||||
assert.equal(state._catalogRevision, revision + 1, 'the legend refreshes');
|
||||
assert.ok(state.visibilityApplied >= 1 && state.rowNotified >= 1);
|
||||
assert.equal(state._satcatState, 'stale', 'its staleness is kept');
|
||||
});
|
||||
|
||||
test('a satellite in visual and resource is imaging, whichever group shows it', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
// A name no pattern knows, no UCS record and no SATCAT: only its groups.
|
||||
const { state, update } = ingestionFor((path) =>
|
||||
path === 'visual' || path === 'resource'
|
||||
? tleSet('ZZ TESTSAT', '50001')
|
||||
: '',
|
||||
);
|
||||
await update();
|
||||
const sat = state._catalog.get(50001);
|
||||
assert.equal(sat.group, 'visual', 'shown under the first group');
|
||||
assert.deepEqual(sat.groups, ['visual', 'resource']);
|
||||
assert.equal(sat.satelliteClass, 'imaging');
|
||||
});
|
||||
|
||||
test('a stale SATCAT copy never overrules a current read of the same object', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const header =
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\n';
|
||||
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50002'), {
|
||||
source: {
|
||||
// visual is current and says it died; resource, a cached copy, still
|
||||
// says it works.
|
||||
readSatcat: async (path) =>
|
||||
path === 'visual'
|
||||
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,-,US` }
|
||||
: path === 'resource'
|
||||
? {
|
||||
ok: true,
|
||||
stale: true,
|
||||
text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,+,US`,
|
||||
}
|
||||
: { ok: true, text: header },
|
||||
},
|
||||
});
|
||||
await update();
|
||||
assert.equal(state._catalog.get(50002).satelliteClass, 'debris');
|
||||
});
|
||||
|
||||
test('a failed SATCAT read is told on the layer row, not only the console', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
|
||||
source: { readSatcat: async () => ({ ok: false, text: '' }) },
|
||||
});
|
||||
await update();
|
||||
assert.equal(state._satcatState, 'unavailable');
|
||||
assert.ok(state.rowNotified >= 1, 'the row repaints');
|
||||
const controls = createControls({
|
||||
state: {
|
||||
...state,
|
||||
_params: { ...state._params, showPoints: true },
|
||||
_classTallyCache: {},
|
||||
},
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
const row = controls.methods.getRowControls();
|
||||
assert.equal(row.info, 'Classes may lag: SATCAT unavailable');
|
||||
assert.match(row.infoTitle, /SATCAT/);
|
||||
const current = createControls({
|
||||
state: {
|
||||
...state,
|
||||
_satcatState: 'current',
|
||||
_params: { ...state._params, showPoints: true },
|
||||
_classTallyCache: {},
|
||||
},
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
assert.equal(current.methods.getRowControls().info, '');
|
||||
});
|
||||
|
||||
test('a current SATCAT read is kept between updates; a failed one is asked again', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const header =
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE\n';
|
||||
let reads = 0;
|
||||
let ok = true;
|
||||
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50003'), {
|
||||
source: {
|
||||
readSatcat: async () => {
|
||||
reads++;
|
||||
return ok
|
||||
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50003,PAY,-` }
|
||||
: { ok: false, text: '' };
|
||||
},
|
||||
},
|
||||
});
|
||||
await update();
|
||||
const perUpdate = reads;
|
||||
assert.ok(perUpdate > 0);
|
||||
await update();
|
||||
assert.equal(reads, perUpdate, 'a fresh read is not asked again');
|
||||
assert.equal(
|
||||
state._catalog.get(50003).satelliteClass,
|
||||
'debris',
|
||||
'the held records still class the rebuilt catalog',
|
||||
);
|
||||
|
||||
state._satcatReadAtMs -= SATCAT_KEEP_MS;
|
||||
ok = false;
|
||||
await update();
|
||||
assert.equal(reads, 2 * perUpdate, 'an old read is asked again');
|
||||
assert.equal(state._satcatState, 'unavailable');
|
||||
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');
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
@@ -83,6 +83,8 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
function _dockedCompanionNames() {
|
||||
const names = [];
|
||||
for (const noradId of layerState._dockedCompanions) {
|
||||
// A hidden class is not named on the tracked card either.
|
||||
if (parts.controls?._classVisible?.(noradId) === false) continue;
|
||||
names.push(
|
||||
layerState._catalog.get(noradId)?.name?.trim() || `SAT-${noradId}`,
|
||||
);
|
||||
@@ -102,6 +104,7 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedNorad !== ISS_NORAD &&
|
||||
!layerState._dockedCompanions.has(ISS_NORAD) &&
|
||||
layerState._catalog.has(ISS_NORAD) &&
|
||||
parts.controls?._classVisible?.(ISS_NORAD) !== false &&
|
||||
_issDisplayCached();
|
||||
if (!visible) {
|
||||
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { ISS_OVERLAY_SOURCE_ID } from './policy.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ISS_OVERLAY_SOURCE_ID,
|
||||
SATELLITE_COVERAGE_MS,
|
||||
} from './policy.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
@@ -8,6 +13,20 @@ export function createLifecycle({
|
||||
source,
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
// While on with a catalog, satellites can be shown at any time in reach of
|
||||
// their element sets. Registered once; off, the layer has no time to show,
|
||||
// and each step tells the clock once it has settled.
|
||||
worldClock.register({
|
||||
id: 'satellites',
|
||||
coverage: () => {
|
||||
if (!layerState._enabled || !layerState._catalog.size) return null;
|
||||
const now = worldClock.wallNow();
|
||||
return {
|
||||
start: now - SATELLITE_COVERAGE_MS,
|
||||
end: now + SATELLITE_COVERAGE_MS,
|
||||
};
|
||||
},
|
||||
});
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
@@ -32,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;
|
||||
@@ -46,6 +69,7 @@ export function createLifecycle({
|
||||
layerState._denseStatus = 'idle';
|
||||
layerState._denseError = null;
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
|
||||
// Point primitives for satellite dots
|
||||
layerState._pointCollection = new Cesium.PointPrimitiveCollection();
|
||||
@@ -72,11 +96,14 @@ export function createLifecycle({
|
||||
layerState._params.showPoints,
|
||||
);
|
||||
// Orbit ring primitives + persistent ISS host label — show them
|
||||
for (const path of layerState._orbitPaths.values())
|
||||
path.primitive.show = parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
);
|
||||
for (const [noradId, path] of layerState._orbitPaths)
|
||||
path.primitive.show =
|
||||
noradId === ISS_NORAD
|
||||
? parts.controls._issOrbitVisible()
|
||||
: parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
);
|
||||
parts.labels._syncIssOverlay();
|
||||
// Re-attach input handlers and preRender propagation
|
||||
parts.interaction._installClickHandler(viewer);
|
||||
@@ -92,6 +119,7 @@ export function createLifecycle({
|
||||
);
|
||||
}
|
||||
parts.tracking._applyPendingTrackingRestore();
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
disable(viewer) {
|
||||
@@ -119,6 +147,7 @@ export function createLifecycle({
|
||||
layerState._preRenderListener();
|
||||
layerState._preRenderListener = null;
|
||||
}
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
destroy(viewer) {
|
||||
@@ -176,6 +205,7 @@ export function createLifecycle({
|
||||
failedGroups: [],
|
||||
};
|
||||
layerState._viewer = null;
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
@@ -137,7 +197,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
lonDeg,
|
||||
minElevDeg = 10,
|
||||
requireVisible = false,
|
||||
fromMs = Date.now(),
|
||||
fromMs = layerState.now(),
|
||||
}) {
|
||||
return getNextSatellitePass(ISS_NORAD, {
|
||||
latDeg,
|
||||
@@ -167,7 +227,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
lonDeg,
|
||||
minElevDeg = 10,
|
||||
requireVisible = false,
|
||||
fromMs = Date.now(),
|
||||
fromMs = layerState.now(),
|
||||
},
|
||||
) {
|
||||
const id = Number(noradId);
|
||||
@@ -271,7 +331,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
function orbitTrackFromRecord(name, satrec) {
|
||||
const referenceDate = new Date();
|
||||
const referenceDate = new Date(layerState.now());
|
||||
const current = propagatePosition(satrec, referenceDate);
|
||||
if (!current) return null;
|
||||
return {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassColor } from '../../data/satelliteClass.js';
|
||||
import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
|
||||
|
||||
/**
|
||||
* Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation.
|
||||
*
|
||||
* Loads six CelesTrak groups (~840 sats): stations, visual, GPS, GLONASS,
|
||||
* Galileo, and the geosynchronous belt. Optional dense mode (setParams
|
||||
* catalog:'dense') adds the Starlink shell as points-only extras.
|
||||
* Loads eleven CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
|
||||
* geosynchronous belt, and the Earth resources, weather, Planet, SAR and
|
||||
* science groups. Each object is filed under one of six classes
|
||||
* (src/layers/satellites/classes.js) whose visibility the layer row toggles; dense mode
|
||||
* (setParams catalog:'dense', the STARLINK toggle) adds the Starlink shell as
|
||||
* points-only extras.
|
||||
* Renders positions via PointPrimitiveCollection, orbital paths as polylines.
|
||||
* Click any satellite to track it with camera follow + orbital path.
|
||||
*
|
||||
@@ -28,6 +32,15 @@ export const ORBIT_PATH_STEPS = 180;
|
||||
// points per orbital path
|
||||
|
||||
export const POSITION_UPDATE_MS = 1000;
|
||||
/** How far either side of now SGP4 on current element sets stays meaningful. */
|
||||
export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
|
||||
|
||||
/**
|
||||
* How far the world time may move from when an orbit ring was drawn before it
|
||||
* is drawn again: the Earth's turn is followed exactly, but the orbit's plane
|
||||
* drifts a few degrees a day.
|
||||
*/
|
||||
export const ORBIT_REBAKE_MS = 30 * 60_000;
|
||||
// re-propagate every 1s (SGP4 is smooth at this rate)
|
||||
|
||||
export const RING_ROTATION_MS = 1000;
|
||||
@@ -49,6 +62,13 @@ export const CATALOG_GROUPS = [
|
||||
{ tag: 'glonass', path: 'glo-ops' },
|
||||
{ tag: 'galileo', path: 'galileo' },
|
||||
{ tag: 'geo', path: 'geo' },
|
||||
// Earth observation launched after the UCS snapshot, and science probes.
|
||||
// Each object's class comes from src/layers/satellites/classes.js, not its group.
|
||||
{ tag: 'resource', path: 'resource' },
|
||||
{ tag: 'weather', path: 'weather' },
|
||||
{ tag: 'planet', path: 'planet' },
|
||||
{ tag: 'sar', path: 'sar' },
|
||||
{ tag: 'science', path: 'science' },
|
||||
];
|
||||
|
||||
// Dense-catalog mode (setParams({ catalog: 'dense' })): Starlink shell as
|
||||
@@ -157,6 +177,37 @@ export const POINT_STYLES = {
|
||||
},
|
||||
};
|
||||
|
||||
const CLASS_COLORS = Object.fromEntries(
|
||||
SATELLITE_CLASS_IDS.map((id) => [
|
||||
id,
|
||||
Cesium.Color.fromCssColorString(SATELLITE_CLASS_DISPLAY[id].color),
|
||||
]),
|
||||
);
|
||||
const _classStyles = new Map();
|
||||
|
||||
/**
|
||||
* A satellite's point style: its group's size and outline, in its class's
|
||||
* colour (src/layers/satellites/classes.js), so the dots match the class legend and
|
||||
* toggles. Styles are shared per group and class.
|
||||
* @param {string|undefined} group Catalog group tag.
|
||||
* @param {string|undefined} satelliteClass Class id.
|
||||
*/
|
||||
export function classPointStyle(group, satelliteClass) {
|
||||
const base = POINT_STYLES[group] || POINT_STYLES.visual;
|
||||
const color = CLASS_COLORS[satelliteClass];
|
||||
if (!color) return base;
|
||||
const key = `${group}|${satelliteClass}`;
|
||||
let style = _classStyles.get(key);
|
||||
if (!style) {
|
||||
style = Object.freeze({
|
||||
...base,
|
||||
color: group === 'dense' ? color.withAlpha(0.9) : color,
|
||||
});
|
||||
_classStyles.set(key, style);
|
||||
}
|
||||
return style;
|
||||
}
|
||||
|
||||
/**
|
||||
* Physically DOCKED vehicles are separate real tracks sharing one position: the
|
||||
* station and everything berthed to it sit within metres of each other. Their
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassLabel } from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
/**
|
||||
@@ -38,7 +38,10 @@ export function mapAnalystRecord(raw) {
|
||||
// must not leak onto a row that has no satellite identity.
|
||||
satelliteClass:
|
||||
noradId || group
|
||||
? satelliteClassLabel(group, { isIss, localize: false })
|
||||
? satelliteClassText(text(raw?.satelliteClass), group, {
|
||||
isIss,
|
||||
localize: false,
|
||||
})
|
||||
: null,
|
||||
group,
|
||||
};
|
||||
@@ -79,10 +82,16 @@ export function createRecords({ state, parts }) {
|
||||
const limit = Number.isFinite(maxCount)
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
const now = new Date();
|
||||
const now = new Date(state.now());
|
||||
const result = [];
|
||||
const emit = (noradId, sat) => {
|
||||
if (result.length >= limit) return false;
|
||||
// A class the user hid stays out of answers too; the tracked one stays.
|
||||
if (
|
||||
noradId !== state._trackedNorad &&
|
||||
parts.controls?._classVisible?.(noradId) === false
|
||||
)
|
||||
return true;
|
||||
const pos = analystGeo(noradId, sat, now);
|
||||
if (!pos) return true;
|
||||
result.push(
|
||||
@@ -90,6 +99,7 @@ export function createRecords({ state, parts }) {
|
||||
noradId,
|
||||
name: sat?.name,
|
||||
group: sat?.group,
|
||||
satelliteClass: sat?.satelliteClass,
|
||||
lat: pos.lat,
|
||||
lon: pos.lon,
|
||||
altitudeM: pos.altitudeM,
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { gstime } from 'satellite.js';
|
||||
import { ISS_NORAD, POSITION_UPDATE_MS, RING_ROTATION_MS } from './policy.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ORBIT_REBAKE_MS,
|
||||
POSITION_UPDATE_MS,
|
||||
RING_ROTATION_MS,
|
||||
} from './policy.js';
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
@@ -42,26 +47,28 @@ export function createRendering({
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
if (!sat || !layerState._viewer) return;
|
||||
|
||||
const bakeDate = new Date();
|
||||
const bakeDate = new Date(layerState.now());
|
||||
const basePositions = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
|
||||
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 }),
|
||||
@@ -75,10 +82,17 @@ export function createRendering({
|
||||
|
||||
layerState._orbitPaths.set(noradId, {
|
||||
primitive,
|
||||
color: pathColor,
|
||||
bakeMs: bakeDate.getTime(),
|
||||
// Same Date object as computeOrbitPath's internal fixedGmst → identical
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -113,8 +127,15 @@ export function createRendering({
|
||||
function _updateOrbitPathRotations(nowDate) {
|
||||
if (layerState._orbitPaths.size === 0) return;
|
||||
|
||||
for (const path of layerState._orbitPaths.values()) {
|
||||
for (const [noradId, path] of [...layerState._orbitPaths]) {
|
||||
if (!path.primitive) continue;
|
||||
// The rotation keeps the ring under the dot for minutes; the plane
|
||||
// itself precesses, so a world time moved far from the bake re-bakes.
|
||||
if (Math.abs(nowDate.getTime() - path.bakeMs) > ORBIT_REBAKE_MS) {
|
||||
_hideOrbitPath(noradId);
|
||||
_showOrbitPath(noradId, path.color);
|
||||
continue;
|
||||
}
|
||||
parts.orbits.orbitFrameModelMatrix(
|
||||
path.gmstAtBake,
|
||||
nowDate,
|
||||
@@ -138,12 +159,13 @@ export function createRendering({
|
||||
|
||||
/**
|
||||
* Propagate all CORE satellite positions and update point primitives.
|
||||
* (~840 sats ≈ 1.6 ms/pass — fine at the 1s/200ms cadence.) Dense extras are
|
||||
* (About 1,300 core satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms,
|
||||
* fine at the 1s/200ms cadence.) Dense extras are
|
||||
* excluded: they refresh on the round-robin budget in _propagateDenseChunk.
|
||||
*/
|
||||
|
||||
function _propagateAll() {
|
||||
const now = new Date();
|
||||
const now = new Date(layerState.now());
|
||||
let updated = 0;
|
||||
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
@@ -203,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
|
||||
@@ -211,7 +237,7 @@ export function createRendering({
|
||||
layerState._params.showOrbits &&
|
||||
now - layerState._lastRingRotation >= RING_ROTATION_MS
|
||||
) {
|
||||
_updateOrbitPathRotations(new Date(now));
|
||||
_updateOrbitPathRotations(new Date(layerState.now()));
|
||||
layerState._lastRingRotation = now;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -6,11 +6,31 @@ const GROUPS = new Set([
|
||||
'galileo',
|
||||
'geo',
|
||||
'starlink',
|
||||
// Imaging coverage beyond the UCS May 2023 snapshot, and science probes.
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
]);
|
||||
|
||||
/** The UCS pack, loaded on first use (see src/data/ucsSatellites.js). */
|
||||
async function loadBundledUcs() {
|
||||
const { loadUcsSatellites } = await import('../../data/ucsSatellites.js');
|
||||
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 } = {}) {
|
||||
@@ -24,5 +44,33 @@ export function createSatelliteSource({
|
||||
const stale = response.headers?.get?.('x-tle-cache') === 'STALE-ERROR';
|
||||
return { ok: response.ok, status: response.status, text, stale };
|
||||
},
|
||||
|
||||
/**
|
||||
* CelesTrak SATCAT records (CSV) for one group: object type, operational
|
||||
* status and owner, through the proxy's day-long cache.
|
||||
*/
|
||||
async readSatcat(group, { signal } = {}) {
|
||||
if (!GROUPS.has(group)) throw new TypeError('Unknown satellite group');
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl(`/api/celestrak-satcat/${group}`, {
|
||||
signal,
|
||||
});
|
||||
const text = response.ok ? await response.text() : '';
|
||||
signal?.throwIfAborted();
|
||||
// The proxy serves its last copy, marked STALE-ERROR, when CelesTrak
|
||||
// is down.
|
||||
const stale = response.headers?.get?.('x-satcat-cache') === 'STALE-ERROR';
|
||||
return { ok: response.ok, status: response.status, text, stale };
|
||||
},
|
||||
|
||||
/** The UCS Satellite Database pack, keyed by NORAD number. */
|
||||
readUcs() {
|
||||
return loadUcs();
|
||||
},
|
||||
|
||||
/** The imaging-sensor pack, indexed by NORAD number and name pattern. */
|
||||
readSensors() {
|
||||
return loadSensors();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -164,3 +164,24 @@ test('satellite pass prediction methods report no-tle on cold catalog and coerce
|
||||
{ status: 'no-tle' },
|
||||
);
|
||||
});
|
||||
|
||||
test('a SATCAT read says when the proxy served its last copy', async () => {
|
||||
const headers = (cache) => ({
|
||||
get: (name) => (name === 'x-satcat-cache' ? cache : null),
|
||||
});
|
||||
let cache = 'STALE-ERROR';
|
||||
const source = createSatelliteSource({
|
||||
fetchImpl: async (url) => {
|
||||
assert.equal(url, '/api/celestrak-satcat/visual');
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: headers(cache),
|
||||
text: async () => 'OBJECT_NAME,NORAD_CAT_ID,OBJECT_TYPE',
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal((await source.readSatcat('visual')).stale, true);
|
||||
cache = 'HIT';
|
||||
assert.equal((await source.readSatcat('visual')).stale, false);
|
||||
});
|
||||
@@ -24,7 +24,15 @@ const GROUPS = [
|
||||
'galileo',
|
||||
'geo',
|
||||
'starlink',
|
||||
// Added after Starlink so the fixture ids above keep their numbers.
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
];
|
||||
/** The core catalog's groups, one owned satellite each. */
|
||||
const CORE = GROUPS.filter((group) => group !== 'starlink');
|
||||
|
||||
function tle(id, invalid = false) {
|
||||
// Owned synthetic catalog IDs over one valid element set; never live requests.
|
||||
@@ -143,10 +151,10 @@ test('stale core records surface through actual HTTP, ingestion and feed state,
|
||||
const f = await fixture(t);
|
||||
await f.update();
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
assert.equal(f.stats().count, 6);
|
||||
f.policy.stale = new Set(GROUPS.slice(0, 6));
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
f.policy.stale = new Set(CORE);
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.policy.stale = new Set(['visual']);
|
||||
@@ -163,13 +171,13 @@ test('a stale duplicate cannot taint its earlier fresh winning record', async (t
|
||||
f.policy.stale.add('visual');
|
||||
f.policy.ids.visual = 25545;
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(f.state._catalog.get(25545).group, 'stations');
|
||||
assert.equal(f.stats().stale, false);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
f.policy.stale = new Set(['stations']);
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(
|
||||
f.stats().stale,
|
||||
true,
|
||||
@@ -182,7 +190,7 @@ test('invalid stale orbital elements are not admitted as provenance', async (t)
|
||||
f.policy.stale.add('visual');
|
||||
f.policy.invalid.add('visual');
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(f.state._catalog.has(25546), false);
|
||||
assert.equal(f.stats().stale, false);
|
||||
});
|
||||
@@ -194,17 +202,17 @@ test('failed and aborted core refreshes keep provenance of retained records', as
|
||||
const priorTime = f.stats().lastUpdate;
|
||||
f.policy.status = 503;
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.stats().status, 'unavailable');
|
||||
assert.equal(f.stats().lastUpdate, priorTime);
|
||||
f.policy.hold = true;
|
||||
const controller = new AbortController();
|
||||
const work = f.update({ signal: controller.signal });
|
||||
await f.waitHeld(6);
|
||||
await f.waitHeld(CORE.length);
|
||||
controller.abort();
|
||||
await assert.rejects(work, { name: 'AbortError' });
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.stats().lastUpdate, priorTime);
|
||||
assert.equal(f.state._activeUpdateControllers.size, 0);
|
||||
@@ -216,11 +224,11 @@ test('dense provenance belongs to its admitted records and clears on removal', a
|
||||
f.policy.stale.add('starlink');
|
||||
f.state._params.catalog = 'dense';
|
||||
assert.equal((await f.parts.catalog._loadDenseCatalog()).status, 'ready');
|
||||
assert.equal(f.stats().count, 7);
|
||||
assert.equal(f.stats().count, CORE.length + 1);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.state._params.catalog = 'core';
|
||||
f.parts.catalog._removeDenseCatalog();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
f.policy.stale = new Set(['stations']);
|
||||
await f.update();
|
||||
@@ -261,13 +269,13 @@ test('cancelling dense replacement preserves admitted stale extras until rebuild
|
||||
await f.waitHeld(1);
|
||||
controller.abort();
|
||||
assert.equal((await work).status, 'cancelled');
|
||||
assert.equal(f.stats().count, 7);
|
||||
assert.equal(f.stats().count, CORE.length + 1);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.policy.hold = false;
|
||||
f.policy.stale.clear();
|
||||
f.state._params.catalog = 'core';
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
});
|
||||
|
||||
@@ -277,7 +285,7 @@ test('destroy aborts an in-flight response and initialization starts with new ow
|
||||
await f.update();
|
||||
f.policy.hold = true;
|
||||
const work = f.update();
|
||||
await f.waitHeld(6);
|
||||
await f.waitHeld(CORE.length);
|
||||
const rejected = assert.rejects(work, { name: 'AbortError' });
|
||||
f.parts.lifecycle.methods.destroy(f.viewer);
|
||||
assert.equal(f.stats().count, 0);
|
||||
@@ -288,6 +296,6 @@ test('destroy aborts an in-flight response and initialization starts with new ow
|
||||
f.policy.hold = false;
|
||||
f.policy.stale.clear();
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { DEFAULT_SATELLITE_CLASSES } from './classes.js';
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
@@ -13,7 +15,9 @@ export function createState({ services }) {
|
||||
|
||||
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
|
||||
|
||||
// Satellite catalog: { noradId → { name, satrec, group } }
|
||||
// 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.
|
||||
|
||||
state._catalog = new Map();
|
||||
|
||||
@@ -42,6 +46,12 @@ export function createState({ services }) {
|
||||
|
||||
// Cache provenance belongs to admitted core and dense records separately.
|
||||
state._coreStale = false;
|
||||
// How current the SATCAT records behind the classes are: null before any
|
||||
// read, then 'current' | 'stale' | 'unavailable' (see ingestion.js).
|
||||
state._satcatState = null;
|
||||
// When _satcatState was last set (Date.now()); a current read is kept
|
||||
// SATCAT_KEEP_MS (src/layers/satellites/ingestion.js).
|
||||
state._satcatReadAtMs = Number.NEGATIVE_INFINITY;
|
||||
state._denseStale = false;
|
||||
|
||||
state._activeUpdateControllers = new Set();
|
||||
@@ -92,9 +102,25 @@ export function createState({ services }) {
|
||||
|
||||
// Runtime params (DataLayerManager.setLayerParams path)
|
||||
|
||||
state._params = { catalog: 'core', showPoints: true, showOrbits: true };
|
||||
state._params = {
|
||||
catalog: 'core',
|
||||
showPoints: true,
|
||||
showOrbits: true,
|
||||
// Which satellite classes show (src/layers/satellites/classes.js). Starlink
|
||||
// follows `catalog`: its points exist only in dense mode.
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES },
|
||||
};
|
||||
// 'core' | 'dense'
|
||||
|
||||
/** SATCAT records (object type, status, owner) by NORAD id, last update. */
|
||||
state._satcat = new Map();
|
||||
|
||||
/** 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
|
||||
|
||||
@@ -151,6 +177,25 @@ 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');
|
||||
|
||||
/** The catalog changed, so the time satellites can be shown at may have. */
|
||||
|
||||
state.coverageChanged = () => worldClock.coverageChanged();
|
||||
|
||||
// Scratch variables
|
||||
|
||||
state._scratchCartesian = new Cesium.Cartesian3();
|
||||
|
||||
@@ -26,10 +26,14 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
// Extra catalog/point rows so a test can exercise a docked cluster (and a
|
||||
// control satellite that must NOT be treated as part of it).
|
||||
neighbours = [],
|
||||
// Optional class of the tracked satellite and class visibility, e.g.
|
||||
// { telecom: false }.
|
||||
satelliteClass = undefined,
|
||||
classes = null,
|
||||
}) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._catalog = new Map([
|
||||
[noradId, { name, satrec, group: 'stations' }],
|
||||
[noradId, { name, satrec, group: 'stations', satelliteClass }],
|
||||
]);
|
||||
layerState._points = new Map([[noradId, point]]);
|
||||
for (const neighbour of neighbours) {
|
||||
@@ -37,6 +41,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
name: neighbour.name,
|
||||
satrec: neighbour.satrec || satrec,
|
||||
group: neighbour.group || 'stations',
|
||||
satelliteClass: neighbour.satelliteClass,
|
||||
});
|
||||
layerState._points.set(neighbour.noradId, neighbour.point);
|
||||
}
|
||||
@@ -51,6 +56,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
catalog: 'core',
|
||||
showPoints: false,
|
||||
showOrbits: false,
|
||||
...(classes ? { classes } : {}),
|
||||
};
|
||||
layerState._enabled = true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassLabel } from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { formatQuantity, unitLabel } from '../../ui/unitLabels.js';
|
||||
import {
|
||||
@@ -95,7 +95,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedNorad,
|
||||
layerState._catalog.get(layerState._trackedNorad)?.group,
|
||||
);
|
||||
lastPos.show = true;
|
||||
// Back to its class's visibility: a hidden class stays hidden.
|
||||
lastPos.show = parts.controls._classVisible(layerState._trackedNorad);
|
||||
lastPos.pixelSize = style.pixelSize;
|
||||
lastPos.color = style.color;
|
||||
lastPos.outlineColor = style.outlineColor;
|
||||
@@ -118,6 +119,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedEntity = null;
|
||||
}
|
||||
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;
|
||||
@@ -150,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(),
|
||||
);
|
||||
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,
|
||||
@@ -241,7 +246,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
name,
|
||||
operator: '',
|
||||
noradId: String(noradId),
|
||||
class: satelliteClassLabel(sat.group, {
|
||||
class: satelliteClassText(sat.satelliteClass, sat.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
localize: false,
|
||||
}),
|
||||
@@ -366,7 +371,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
// looking at, and it stays readable under the IR styles that flatten the
|
||||
// dot colors to a single channel (the card is painted above post-FX).
|
||||
const details = [
|
||||
satelliteClassLabel(sat?.group, {
|
||||
satelliteClassText(sat?.satelliteClass, sat?.group, {
|
||||
isIss: layerState._trackedNorad === ISS_NORAD,
|
||||
}),
|
||||
detail,
|
||||
@@ -420,6 +425,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
|
||||
// Show orbital path
|
||||
parts.rendering._showOrbitPath(noradId, Cesium.Color.YELLOW);
|
||||
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
|
||||
|
||||
// Tracked entity position propagates per evaluation through the per-frame
|
||||
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
|
||||
@@ -434,7 +440,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
// Comfortable tracking landing: ~726 km back for LEO (user-validated
|
||||
// "slightly zoomed out" framing — no stutter, label reads cleanly), scaled
|
||||
// up for MEO/GEO so the camera doesn't land on top of a high-orbit dot.
|
||||
const initialPos = parts.orbits.propagatePosition(sat.satrec, new Date());
|
||||
const initialPos = parts.orbits.propagatePosition(
|
||||
sat.satrec,
|
||||
new Date(layerState.now()),
|
||||
);
|
||||
const viewScale =
|
||||
initialPos && initialPos.altitude > HIGH_ORBIT_ALTITUDE_M
|
||||
? TRACK_VIEW_FROM_HIGH_SCALE
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createSelection } from './selection.js';
|
||||
import { createViewerHost } from './viewerHost.js';
|
||||
import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
|
||||
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
import { decodeParams, encodeParams } from './params.js';
|
||||
import {
|
||||
composeUIState,
|
||||
@@ -41,6 +42,9 @@ const GROUND_RETRY_MS = 1000;
|
||||
* a time.
|
||||
* @param {{providers: Array<import('./registry.js').StreetLevelProvider>, services?: object}} options
|
||||
*/
|
||||
// "Since N days" counts back from the world time.
|
||||
const streetLevelTime = worldTimeFor(STREET_LEVEL_LAYER_ID);
|
||||
|
||||
export function createStreetLevelLayer({
|
||||
providers: definitions,
|
||||
services = {},
|
||||
@@ -93,7 +97,7 @@ export function createStreetLevelLayer({
|
||||
return Object.freeze({
|
||||
services: state.services,
|
||||
/** Resolved against now, so "since N days" keeps up with the clock. */
|
||||
getFilter: () => resolveFilter(state.filter),
|
||||
getFilter: () => resolveFilter(state.filter, streetLevelTime()),
|
||||
/** The layer and this provider's switch are both on. */
|
||||
isActive: () => state.enabled && entry.on,
|
||||
notify,
|
||||
@@ -365,7 +369,7 @@ export function createStreetLevelLayer({
|
||||
const filter = normalizeFilter(next, state.filter);
|
||||
if (sameFilter(filter, state.filter)) return;
|
||||
state.filter = filter;
|
||||
const resolved = resolveFilter(filter);
|
||||
const resolved = resolveFilter(filter, streetLevelTime());
|
||||
for (const entry of state.providers.values())
|
||||
entry.instance.setFilter(resolved);
|
||||
notify();
|
||||
|
||||
@@ -3927,6 +3927,7 @@ test('parked transit reprojects held and reported courses at the bounded camera
|
||||
_rotationRevision: -1,
|
||||
_cameraRevision: 0,
|
||||
_rotationDirty: false,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
const noop = () => {};
|
||||
const rendering = createRendering({
|
||||
|
||||
@@ -108,7 +108,7 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
function sampleIdle(entry) {
|
||||
if (!state._moving.has(entry)) {
|
||||
updatePlayback(entry, Date.now(), performance.now());
|
||||
updatePlayback(entry, state.now(), performance.now());
|
||||
placeSample(entry);
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ export function createRendering({ state, services, parts }) {
|
||||
() => {
|
||||
entry.wakeTimer = null;
|
||||
if (!state._enabled || !state._vehicles.has(entry.key)) return;
|
||||
updatePlayback(entry, Date.now(), performance.now());
|
||||
updatePlayback(entry, state.now(), performance.now());
|
||||
placeSample(entry);
|
||||
schedulePlayback(entry);
|
||||
syncRenderHold();
|
||||
@@ -400,7 +400,7 @@ export function createRendering({ state, services, parts }) {
|
||||
)
|
||||
return;
|
||||
if (!state._enabled) return;
|
||||
const now = Date.now();
|
||||
const now = state.now();
|
||||
if (state._vehicles.size === 0) {
|
||||
state._moving.clear();
|
||||
syncRenderHold();
|
||||
@@ -436,7 +436,7 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
|
||||
parts.trails.update();
|
||||
refreshRotations(now);
|
||||
refreshRotations(Date.now());
|
||||
const selected = state._vehicles.get(state._selectedKey);
|
||||
if (selected && state._visible.has(selected)) {
|
||||
syncHeadingIcon(selected);
|
||||
@@ -502,7 +502,7 @@ export function createRendering({ state, services, parts }) {
|
||||
const noSample = !entry.sample || !Number.isFinite(entry.sample.lat);
|
||||
if (entry.track?.count && (!state._visible.has(entry) || noSample)) {
|
||||
entry.sample ||= {};
|
||||
updatePlayback(entry, now, performance.now());
|
||||
updatePlayback(entry, state.now(), performance.now());
|
||||
}
|
||||
sphere.center =
|
||||
state._visible.has(entry) || !entry.sample
|
||||
@@ -570,7 +570,7 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
function resumePlayback() {
|
||||
if (!state._enabled) return;
|
||||
const now = Date.now(),
|
||||
const now = state.now(),
|
||||
mono = performance.now();
|
||||
const entries = new Set(state._visible);
|
||||
const selected = state._vehicles.get(state._selectedKey);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createHistoryBudget } from '../../data/contactPlayback.js';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
/**
|
||||
* One Transit layer's mutable scene state. Every field lives on the instance,
|
||||
@@ -14,6 +15,8 @@ export function createState({ services }) {
|
||||
|
||||
const state = {};
|
||||
state._historyBudget = createHistoryBudget();
|
||||
/** The time vehicles play back behind by their display delay, in epoch ms. */
|
||||
state.now = worldTimeFor('transit');
|
||||
|
||||
state.DEFAULT_OVERLAY_HOST = Object.freeze({
|
||||
setEntries: setOverlayEntries,
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* The selected vessel as a Cockpit bridge subject: identity, motion, its
|
||||
* displayed type and a representative bridge eye height from the AIS type.
|
||||
* The Cockpit owns camera placement; this module owns what AIS says.
|
||||
*/
|
||||
import { normalizeVesselType } from '../../data/vesselTypes.js';
|
||||
import { displayVesselType } from '../../data/vesselLabels.js';
|
||||
|
||||
/** The layer id a vessel subject carries through Cockpit events and state. */
|
||||
export const VESSEL_COCKPIT_LAYER_ID = 'ais-live-vessels';
|
||||
|
||||
/** Knots to metres per second, as the AIS source uses. */
|
||||
const KNOTS_TO_MPS = 0.514444;
|
||||
|
||||
/**
|
||||
* Bridge eye height above the waterline by normalized AIS type family. AIS
|
||||
* reports no hull height, so these are representative values: deep-sea
|
||||
* cargo and tanker bridges, passenger and cruise ship bridges, harbour
|
||||
* craft, small craft. River and harbour ferries, matched by name in the
|
||||
* patterns below, sit low. Text types from non-numeric feeds fall through
|
||||
* to the patterns.
|
||||
*/
|
||||
const EYE_HEIGHT_BY_FAMILY = Object.freeze({
|
||||
CARGO: 30,
|
||||
TANKER: 30,
|
||||
PASSENGER: 25,
|
||||
MILITARY: 18,
|
||||
'HIGH-SPEED': 8,
|
||||
DREDGER: 10,
|
||||
TOWING: 7,
|
||||
TUG: 7,
|
||||
PILOT: 6,
|
||||
SAR: 6,
|
||||
'PORT TENDER': 6,
|
||||
'ANTI-POLLUTION': 7,
|
||||
'LAW ENFORCE': 7,
|
||||
MEDICAL: 7,
|
||||
'DIVE OPS': 5,
|
||||
FISHING: 6,
|
||||
SAILING: 3,
|
||||
PLEASURE: 3,
|
||||
// AIS "Other" (90-99) is mostly small craft such as river boats. Only
|
||||
// that type takes it (see isAisOther).
|
||||
OTHER: 4,
|
||||
});
|
||||
|
||||
const EYE_HEIGHT_PATTERNS = Object.freeze([
|
||||
{ pattern: /tanker|cargo|container|bulk|carrier/i, heightM: 30 },
|
||||
{ pattern: /passenger|cruise|ro-?ro/i, heightM: 25 },
|
||||
// River and harbour ferries: a low wheelhouse just above the water.
|
||||
{ pattern: /ferry/i, heightM: 4 },
|
||||
{ pattern: /tug|tow|pilot|supply|service/i, heightM: 7 },
|
||||
{ pattern: /fishing|trawler/i, heightM: 6 },
|
||||
{ pattern: /sail|pleasure|yacht/i, heightM: 3 },
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether a raw type is AIS "Other" proper: codes 90 to 99, or a feed's text
|
||||
* type. normalizeVesselType also files the reserved, wing-in-ground and
|
||||
* spare codes (1-29, 38-39, 56-57, 59) under OTHER, but they name no family.
|
||||
*/
|
||||
function isAisOther(type) {
|
||||
const text = String(type ?? '').trim();
|
||||
if (!/^\d+$/.test(text)) return true;
|
||||
const code = Number(text);
|
||||
return code >= 90 && code <= 99;
|
||||
}
|
||||
|
||||
/**
|
||||
* Representative bridge eye height for an AIS vessel type.
|
||||
* @param {string|number} type Raw AIS type: a numeric code or feed text.
|
||||
* @returns {number|null} Metres above the waterline, or null when the type
|
||||
* names no known family (the Cockpit then uses its default).
|
||||
*/
|
||||
export function vesselEyeHeightM(type) {
|
||||
const family = normalizeVesselType(type).toUpperCase();
|
||||
if (family === 'OTHER' && !isAisOther(type)) return null;
|
||||
if (Object.hasOwn(EYE_HEIGHT_BY_FAMILY, family))
|
||||
return EYE_HEIGHT_BY_FAMILY[family];
|
||||
const matched = EYE_HEIGHT_PATTERNS.find((entry) =>
|
||||
entry.pattern.test(family),
|
||||
);
|
||||
return matched ? matched.heightM : null;
|
||||
}
|
||||
|
||||
function finiteOrNull(value) {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a selected vessel record into Cockpit subject info.
|
||||
*
|
||||
* `track` is where the camera looks and `motionCourse` is where the hull
|
||||
* moves: a ship faces its true heading while current and wind set it along
|
||||
* its course over ground. Either falls back to the other when one is missing.
|
||||
* @param {object|null} record Vessel record from the vessel layer.
|
||||
* @returns {object|null} Subject info, or null without a usable fix.
|
||||
*/
|
||||
export function vesselCockpitInfo(record) {
|
||||
if (!record?.mmsi) return null;
|
||||
const latitude = Number(record.lat);
|
||||
const longitude = Number(record.lon);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
const heading = finiteOrNull(record.heading);
|
||||
const course = finiteOrNull(record.course);
|
||||
const speedKt = finiteOrNull(record.speed);
|
||||
const epochSec = finiteOrNull(record.lastPositionEpoch);
|
||||
const feedEpochSec = finiteOrNull(record.fixFeedEpoch);
|
||||
return {
|
||||
kind: 'vessel',
|
||||
layerId: VESSEL_COCKPIT_LAYER_ID,
|
||||
id: String(record.mmsi),
|
||||
mmsi: String(record.mmsi),
|
||||
name: String(record.name || record.mmsi),
|
||||
type: String(record.type || ''),
|
||||
typeLabel: displayVesselType(record.type),
|
||||
destination: String(record.destination || '').trim(),
|
||||
latitude,
|
||||
longitude,
|
||||
heading,
|
||||
course,
|
||||
speedKt,
|
||||
velocityMps: speedKt === null ? null : Math.max(0, speedKt) * KNOTS_TO_MPS,
|
||||
track: heading ?? course,
|
||||
// What `track` is: the true heading, or course over ground standing in
|
||||
// for a ship that reports none. The HUD says which.
|
||||
trackSource:
|
||||
heading !== null ? 'heading' : course !== null ? 'course' : null,
|
||||
motionCourse: course ?? heading,
|
||||
fixEpochMs: epochSec === null ? null : epochSec * 1000,
|
||||
// When this client first received the fix (its own clock) and the
|
||||
// newest fix in that refresh (the feed's clock): the fix's age without
|
||||
// clock skew, still ageing while the feed re-serves it.
|
||||
receivedAtMs: finiteOrNull(record.fixReceivedAtMs),
|
||||
feedEpochMs: feedEpochSec === null ? null : feedEpochSec * 1000,
|
||||
eyeHeightM: vesselEyeHeightM(record.type),
|
||||
stale: (record.missedRefreshes || 0) > 0,
|
||||
onGround: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// src/layers/vessels/cockpitSubject.test.mjs — bridge eye heights by AIS
|
||||
// type and the selected vessel as Cockpit subject info.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
VESSEL_COCKPIT_LAYER_ID,
|
||||
vesselCockpitInfo,
|
||||
vesselEyeHeightM,
|
||||
} from './cockpitSubject.js';
|
||||
|
||||
test('bridge eye height follows the AIS type family', () => {
|
||||
assert.equal(vesselEyeHeightM('71'), 30, 'cargo');
|
||||
assert.equal(vesselEyeHeightM('84'), 30, 'tanker');
|
||||
assert.equal(vesselEyeHeightM('60'), 25, 'passenger');
|
||||
assert.equal(vesselEyeHeightM('52'), 7, 'tug');
|
||||
assert.equal(vesselEyeHeightM('30'), 6, 'fishing');
|
||||
assert.equal(vesselEyeHeightM('37'), 3, 'pleasure');
|
||||
assert.equal(vesselEyeHeightM('36'), 3, 'sailing');
|
||||
});
|
||||
|
||||
test('text vessel types resolve through the same families', () => {
|
||||
assert.equal(vesselEyeHeightM('Container Ship'), 30);
|
||||
assert.equal(vesselEyeHeightM('Cruise ship'), 25);
|
||||
assert.equal(vesselEyeHeightM('Ferry'), 4);
|
||||
assert.equal(vesselEyeHeightM(99), 4, 'AIS Other');
|
||||
assert.equal(vesselEyeHeightM('90'), 4, 'AIS Other');
|
||||
assert.equal(vesselEyeHeightM('Other'), 4, 'a feed text type Other');
|
||||
assert.equal(vesselEyeHeightM('Yacht'), 3);
|
||||
});
|
||||
|
||||
test('codes filed under OTHER that are not AIS Other keep the default', () => {
|
||||
// Reserved (1-19), wing in ground (20-29), reserved (38-39), spare
|
||||
// (56-57) and local (59) codes name no family.
|
||||
for (const type of ['1', '19', '20', '29', '38', '39', '56', '57', '59'])
|
||||
assert.equal(vesselEyeHeightM(type), null, type);
|
||||
});
|
||||
|
||||
test('an unknown or missing type has no eye height of its own', () => {
|
||||
for (const type of ['', '0', '255', 'Research vessel', null]) {
|
||||
assert.equal(vesselEyeHeightM(type), null, String(type));
|
||||
}
|
||||
});
|
||||
|
||||
test('vessel info faces the true heading and moves along course over ground', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
mmsi: '211000000',
|
||||
name: 'NORDIC STAR',
|
||||
type: '70',
|
||||
destination: ' KIEL ',
|
||||
lat: 54.5,
|
||||
lon: 10.2,
|
||||
speed: 12,
|
||||
course: 95,
|
||||
heading: 90,
|
||||
lastPositionEpoch: 1_700_000_000,
|
||||
missedRefreshes: 0,
|
||||
});
|
||||
assert.equal(info.kind, 'vessel');
|
||||
assert.equal(info.layerId, VESSEL_COCKPIT_LAYER_ID);
|
||||
assert.equal(info.id, '211000000');
|
||||
assert.equal(info.typeLabel, 'CARGO');
|
||||
assert.equal(info.track, 90);
|
||||
assert.equal(info.motionCourse, 95);
|
||||
assert.equal(info.destination, 'KIEL');
|
||||
assert.equal(info.eyeHeightM, 30);
|
||||
assert.equal(info.fixEpochMs, 1_700_000_000_000);
|
||||
assert.ok(Math.abs(info.velocityMps - 12 * 0.514444) < 1e-9);
|
||||
assert.equal(info.stale, false);
|
||||
assert.equal(info.onGround, false);
|
||||
});
|
||||
|
||||
test('a missing heading or course falls back to the other', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(vesselCockpitInfo({ ...base, course: 40 }).track, 40);
|
||||
assert.equal(vesselCockpitInfo({ ...base, heading: 50 }).motionCourse, 50);
|
||||
const neither = vesselCockpitInfo(base);
|
||||
assert.equal(neither.track, null);
|
||||
assert.equal(neither.motionCourse, null);
|
||||
});
|
||||
|
||||
test('the subject says whether its track is the heading or the course', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, heading: 50, course: 40 }).trackSource,
|
||||
'heading',
|
||||
);
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, course: 40 }).trackSource,
|
||||
'course',
|
||||
);
|
||||
// A heading of 0 is due north, not a missing heading.
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, heading: 0 }).trackSource,
|
||||
'heading',
|
||||
);
|
||||
assert.equal(vesselCockpitInfo(base).trackSource, null);
|
||||
});
|
||||
|
||||
test('a vessel without identity or position is not a subject', () => {
|
||||
assert.equal(vesselCockpitInfo(null), null);
|
||||
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
|
||||
assert.equal(vesselCockpitInfo({ mmsi: '1', lat: 'x', lon: 1 }), null);
|
||||
});
|
||||
|
||||
test('a vessel missing from recent refreshes reads as stale', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
mmsi: '1',
|
||||
lat: 1,
|
||||
lon: 1,
|
||||
missedRefreshes: 2,
|
||||
});
|
||||
assert.equal(info.stale, true);
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { t, msg } from '../../i18n/index.js';
|
||||
import { vesselCockpitInfo } from './cockpitSubject.js';
|
||||
import { vesselTypeCss } from '../../data/vesselLabels.js';
|
||||
import { greatCircleMeters } from '../../geoDistance.js';
|
||||
|
||||
// ingestion.js is a portable export (package.json) and writes English labels
|
||||
// into state; translate the known ones here, pass anything else through.
|
||||
@@ -20,6 +23,7 @@ import {
|
||||
AIS_STATUS_REASON,
|
||||
REFRESH_MS,
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
VESSEL_LIFT_M,
|
||||
} from './policy.js';
|
||||
|
||||
export function createQueries({
|
||||
@@ -346,6 +350,59 @@ export function createQueries({
|
||||
return entries.slice(0, cap);
|
||||
},
|
||||
|
||||
/**
|
||||
* Vessels around a point for the Cockpit bridge radar, nearest first.
|
||||
* The ship whose bridge the Cockpit occupies is left out. Distances are
|
||||
* great-circle from the AIS positions, so no rendered visual is needed.
|
||||
* @param {number} lat Latitude of the centre, degrees.
|
||||
* @param {number} lon Longitude of the centre, degrees.
|
||||
* @param {number} rangeM Max distance in metres.
|
||||
* @param {number} [maxCount=60] Maximum entries to return.
|
||||
* @returns {Array<{ id: string, name: string, latitude: number,
|
||||
* longitude: number, course: number|null, heading: number|null,
|
||||
* type: string, color: string, stale: boolean }>} Empty while the
|
||||
* layer is off. A ship with no MMSI has an `unkeyed:` id.
|
||||
*/
|
||||
getRadarContacts(lat, lon, rangeM, maxCount = 60) {
|
||||
const records = state.records.all;
|
||||
if (!state.feed.enabled || !Array.isArray(records) || !records.length)
|
||||
return [];
|
||||
if (!Number.isFinite(rangeM) || rangeM <= 0) return [];
|
||||
const cap =
|
||||
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 60;
|
||||
const center = { lat, lon };
|
||||
const subject = state.cockpitSubjectMmsi;
|
||||
const finite = (value) => {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
};
|
||||
|
||||
const entries = [];
|
||||
records.forEach((record, index) => {
|
||||
if (subject && String(record.mmsi) === subject) return;
|
||||
const distanceM = greatCircleMeters(center, {
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
});
|
||||
if (!(distanceM <= rangeM)) return;
|
||||
entries.push({ record, index, distanceM });
|
||||
});
|
||||
entries.sort((a, b) => a.distanceM - b.distanceM);
|
||||
return entries.slice(0, cap).map(({ record, index }) => ({
|
||||
// A ship with no MMSI still needs a key of its own on the scope.
|
||||
id: record.mmsi ? String(record.mmsi) : `unkeyed:${index}`,
|
||||
name: String(record.name || record.mmsi || ''),
|
||||
latitude: record.lat,
|
||||
longitude: record.lon,
|
||||
course: finite(record.course),
|
||||
heading: finite(record.heading),
|
||||
type: String(record.type || ''),
|
||||
color: vesselTypeCss(record.type),
|
||||
stale: (record.missedRefreshes || 0) > 0,
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get positions of all currently loaded vessels.
|
||||
* @param {number} [maxCount=800] Maximum entries to return.
|
||||
@@ -462,6 +519,55 @@ export function createQueries({
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Describe the selected vessel for the Cockpit bridge view.
|
||||
* @returns {object|null} `vesselCockpitInfo` fields plus `seaSurfaceHeightM`
|
||||
* (the local geoid height the sprite datum uses) and `markHeightM` (the
|
||||
* height the sprite is drawn at), or null when the layer is off or
|
||||
* nothing is selected.
|
||||
*/
|
||||
getCockpitSubject() {
|
||||
if (!state.feed.enabled) return null;
|
||||
const info = vesselCockpitInfo(state.selectedRecord);
|
||||
if (!info) return null;
|
||||
const geoidN = components.tracking.currentGeoidN(
|
||||
info.latitude,
|
||||
info.longitude,
|
||||
);
|
||||
return {
|
||||
...info,
|
||||
seaSurfaceHeightM: vesselDatumHeightM(geoidN, 0),
|
||||
markHeightM: vesselDatumHeightM(geoidN, VESSEL_LIFT_M),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark the vessel whose bridge the Cockpit camera occupies, or release it.
|
||||
* Its sprite, card and detection bracket stay hidden while it is held.
|
||||
* @param {string|number|null} mmsi Subject MMSI, or null to release.
|
||||
* @returns {boolean} Always true.
|
||||
*/
|
||||
setCockpitSubject(mmsi) {
|
||||
const next = normalizeSelectionMmsi(mmsi);
|
||||
if (state.cockpitSubjectMmsi === next) return true;
|
||||
state.cockpitSubjectMmsi = next;
|
||||
// The ridden ship's trail runs from under the eye: hidden, its history
|
||||
// kept, while the bridge holds the ship it belongs to.
|
||||
state.trail?.setVisible?.(!next || next !== state.trailMmsi);
|
||||
components.rendering.updateVisibility(true);
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the camera to the selected vessel's map view, as a click on it does.
|
||||
* @returns {boolean} True when a selected vessel took the camera.
|
||||
*/
|
||||
focusSelectedVessel() {
|
||||
const record = state.selectedRecord;
|
||||
if (!record || !state.feed.enabled) return false;
|
||||
return components.selection.selectAndFocusVessel(record);
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a subset of vessels for the universal detection overlay.
|
||||
* Deterministic stride sampling distributes selections evenly across the
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// src/layers/vessels/radarContacts.test.mjs — the vessels the Cockpit bridge
|
||||
// radar draws: within range, nearest first, without the ship it rides; and
|
||||
// the ridden ship's own trail, hidden while the bridge holds it.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createVesselLayer } from './index.js';
|
||||
import { vesselTypeCss } from '../../data/vesselLabels.js';
|
||||
|
||||
const noop = () => {};
|
||||
function services() {
|
||||
return {
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
registerEntityContext: () => null,
|
||||
},
|
||||
trails: {
|
||||
createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }),
|
||||
},
|
||||
labels: {},
|
||||
picking: { unregisterPickOwner: noop },
|
||||
overlay: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
geoid: {},
|
||||
sprites: {},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
forgetSpriteFocus: noop,
|
||||
},
|
||||
worldFocus: {},
|
||||
render: {
|
||||
holdContinuousRender: noop,
|
||||
releaseContinuousRender: noop,
|
||||
governorRequestRender: noop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A vessel `northNm` nautical miles north of 54.5°N 10.2°E. */
|
||||
function record(mmsi, northNm, extra = {}) {
|
||||
return {
|
||||
mmsi,
|
||||
name: `SHIP ${mmsi}`,
|
||||
type: '70',
|
||||
lat: 54.5 + northNm / 60,
|
||||
lon: 10.2,
|
||||
speed: 10,
|
||||
course: 45,
|
||||
heading: 40,
|
||||
missedRefreshes: 0,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function layerWith(records, options = {}) {
|
||||
const layer = createVesselLayer({
|
||||
source: { getSnapshot: noop },
|
||||
services: services(),
|
||||
});
|
||||
layer.testing._setVesselStateForTest({
|
||||
viewer: {},
|
||||
records,
|
||||
billboardCollection: { add: (entry) => ({ ...entry }), remove: noop },
|
||||
...options,
|
||||
});
|
||||
return layer;
|
||||
}
|
||||
|
||||
test('radar contacts are within range, nearest first and capped', () => {
|
||||
const layer = layerWith([
|
||||
record('3', 5),
|
||||
record('1', 1),
|
||||
record('far', 20),
|
||||
record('2', 3, { course: null, heading: '', missedRefreshes: 2 }),
|
||||
]);
|
||||
const contacts = layer.getRadarContacts(54.5, 10.2, 6 * 1852, 60);
|
||||
assert.deepEqual(
|
||||
contacts.map((entry) => entry.id),
|
||||
['1', '2', '3'],
|
||||
);
|
||||
assert.deepEqual(contacts[0], {
|
||||
id: '1',
|
||||
name: 'SHIP 1',
|
||||
latitude: 54.5 + 1 / 60,
|
||||
longitude: 10.2,
|
||||
course: 45,
|
||||
heading: 40,
|
||||
type: '70',
|
||||
color: vesselTypeCss('70'),
|
||||
stale: false,
|
||||
});
|
||||
assert.equal(contacts[1].course, null);
|
||||
assert.equal(contacts[1].heading, null);
|
||||
assert.equal(contacts[1].stale, true);
|
||||
assert.deepEqual(
|
||||
layer.getRadarContacts(54.5, 10.2, 6 * 1852, 2).map((entry) => entry.id),
|
||||
['1', '2'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the ship whose bridge the Cockpit rides is not its own contact', () => {
|
||||
const layer = layerWith([record('own', 0), record('other', 2)]);
|
||||
layer.setCockpitSubject('own');
|
||||
assert.deepEqual(
|
||||
layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((entry) => entry.id),
|
||||
['other'],
|
||||
);
|
||||
layer.setCockpitSubject(null);
|
||||
assert.equal(layer.getRadarContacts(54.5, 10.2, 6 * 1852).length, 2);
|
||||
});
|
||||
|
||||
test('ships with no MMSI each keep a key of their own', () => {
|
||||
const layer = layerWith([
|
||||
record('', 1, { name: 'A' }),
|
||||
record('', 2, { name: 'B' }),
|
||||
]);
|
||||
const ids = layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((c) => c.id);
|
||||
assert.equal(ids.length, 2);
|
||||
assert.equal(new Set(ids).size, 2, ids.join(', '));
|
||||
assert.ok(ids.every((id) => id.startsWith('unkeyed:')));
|
||||
});
|
||||
|
||||
test("the ridden ship's trail is hidden while the bridge holds it", () => {
|
||||
const shown = [];
|
||||
const trail = {
|
||||
setPositions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
setVisible: (visible) => shown.push(visible),
|
||||
};
|
||||
const layer = layerWith([record('own', 0), record('other', 2)], {
|
||||
trail,
|
||||
trailMmsi: 'own',
|
||||
});
|
||||
layer.setCockpitSubject('own');
|
||||
assert.deepEqual(shown, [false]);
|
||||
layer.setCockpitSubject(null);
|
||||
assert.deepEqual(shown, [false, true]);
|
||||
});
|
||||
|
||||
test('a disabled layer has no radar contacts', () => {
|
||||
const layer = layerWith([record('1', 1)], { enabled: false });
|
||||
assert.deepEqual(layer.getRadarContacts(54.5, 10.2, 6 * 1852), []);
|
||||
});
|
||||
@@ -26,6 +26,18 @@ export function normalizeVessel(row) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Note when a fix was first received (`fixReceivedAtMs`, this client's
|
||||
* clock) and the newest fix in that refresh (`fixFeedEpoch`, the feed's
|
||||
* clock): its age is then read on each clock separately, so neither a
|
||||
* skewed client clock nor a re-served cached row hides how old it is.
|
||||
* `receivedAtMs` stays the time the row was last seen, for retention.
|
||||
*/
|
||||
function stampFix(record, receivedAtMs, feedLatestEpoch) {
|
||||
record.fixReceivedAtMs = receivedAtMs;
|
||||
record.fixFeedEpoch = feedLatestEpoch;
|
||||
}
|
||||
|
||||
function finiteNumber(value) {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
@@ -46,6 +58,18 @@ export class VesselRecords {
|
||||
effects,
|
||||
) {
|
||||
const receivedAtMs = this.now();
|
||||
// The newest fix in the batch: the feed's own "now", so a fix's age can
|
||||
// be read on the feed's clock rather than against this client's (see
|
||||
// stampFix).
|
||||
let feedLatestEpoch = null;
|
||||
for (const row of rows) {
|
||||
const epoch = finiteNumber(row?.last_position_epoch);
|
||||
if (
|
||||
epoch !== null &&
|
||||
(feedLatestEpoch === null || epoch > feedLatestEpoch)
|
||||
)
|
||||
feedLatestEpoch = epoch;
|
||||
}
|
||||
for (const record of this.unkeyed) effects.remove(record, false);
|
||||
this.unkeyed = [];
|
||||
const seen = new Set();
|
||||
@@ -53,6 +77,7 @@ export class VesselRecords {
|
||||
const next = normalizeVessel(row);
|
||||
if (!next) continue;
|
||||
next.receivedAtMs = receivedAtMs;
|
||||
stampFix(next, receivedAtMs, feedLatestEpoch);
|
||||
if (!next.mmsi) {
|
||||
effects.add(next);
|
||||
this.unkeyed.push(next);
|
||||
@@ -63,6 +88,12 @@ export class VesselRecords {
|
||||
const record = this.byMmsi.get(next.mmsi);
|
||||
if (record) {
|
||||
const before = effects.beforeUpdate(record);
|
||||
// A feed re-serving a cached row repeats its fix: the fix keeps the
|
||||
// time it was first received, so it goes on ageing.
|
||||
if (next.lastPositionEpoch !== record.lastPositionEpoch) {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
record.reference = next.reference;
|
||||
record.receivedAtMs = next.receivedAtMs;
|
||||
record.lat = next.lat;
|
||||
|
||||
@@ -111,3 +111,33 @@ test('unkeyed records rebuild on each refresh and numeric coercion keeps unknown
|
||||
assert.equal(probe.store.all.length, 1);
|
||||
assert.equal(normalizeVessel(row('bad', { lon: Infinity })), null);
|
||||
});
|
||||
|
||||
test("each fix keeps when it was first received and its refresh's newest fix", () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([
|
||||
row('111', { last_position_epoch: 1_800_000_000 }),
|
||||
row('222', { last_position_epoch: 1_800_000_030 }),
|
||||
row('333'),
|
||||
]);
|
||||
for (const mmsi of ['111', '222', '333']) {
|
||||
const record = probe.store.byMmsi.get(mmsi);
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_030, mmsi);
|
||||
assert.equal(record.fixReceivedAtMs, 1000, mmsi);
|
||||
}
|
||||
// A new fix is stamped afresh.
|
||||
probe.advance(60_000);
|
||||
probe.reconcile([row('111', { last_position_epoch: 1_800_000_050 })]);
|
||||
const record = probe.store.byMmsi.get('111');
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.fixReceivedAtMs, 61_000);
|
||||
// The same fix re-served by later polls keeps its first receipt, while
|
||||
// the row itself counts as seen for retention.
|
||||
probe.advance(30_000);
|
||||
probe.reconcile([
|
||||
row('111', { last_position_epoch: 1_800_000_050 }),
|
||||
row('222', { last_position_epoch: 1_800_000_090 }),
|
||||
]);
|
||||
assert.equal(record.fixReceivedAtMs, 61_000);
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.receivedAtMs, 91_000);
|
||||
});
|
||||
@@ -286,7 +286,9 @@ export function createRendering({
|
||||
const visual = getVisual(record);
|
||||
const visible = isVisible(visual.surfacePosition, occluder);
|
||||
if (visual.billboard) {
|
||||
visual.billboard.show = visible;
|
||||
// The bridge camera sits on this sprite; showing it would fill the view.
|
||||
visual.billboard.show =
|
||||
visible && record.mmsi !== state.cockpitSubjectMmsi;
|
||||
if (visible && doRotations && scene) {
|
||||
const rot = screenProjectedRotation(
|
||||
scene,
|
||||
@@ -422,7 +424,11 @@ export function createRendering({
|
||||
const viewer = state.viewer;
|
||||
const scene = viewer?.scene;
|
||||
const selected = state.selectedRecord;
|
||||
const entries = selected
|
||||
// From the bridge, the selected vessel is the viewer; its card would be
|
||||
// pinned to the camera position.
|
||||
const selectedCarded =
|
||||
selected && selected.mmsi !== state.cockpitSubjectMmsi;
|
||||
const entries = selectedCarded
|
||||
? [components.cards.buildSelectedVesselCard(selected)]
|
||||
: [];
|
||||
const maxLabels = labelRowLimit();
|
||||
@@ -458,7 +464,7 @@ export function createRendering({
|
||||
// Greedy min-separation pass over the priority-ranked cell winners: the
|
||||
// selected card's anchor seeds the accepted set so ambient cards keep clear.
|
||||
const accepted = [];
|
||||
if (selected) {
|
||||
if (selectedCarded) {
|
||||
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
getVisual(selected).billboard?.position || getVisual(selected).position,
|
||||
|
||||
@@ -37,6 +37,9 @@ export function createSelection({
|
||||
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
|
||||
if (!isPointerFree()) return;
|
||||
if (!state.feed.enabled) return;
|
||||
// The bridge view owns the selection: a click on open water must not
|
||||
// deselect the vessel the camera is riding.
|
||||
if (state.cockpitSubjectMmsi) return;
|
||||
const picked = pickContact
|
||||
? pickContact(viewer.scene, click.position)
|
||||
: viewer.scene.pick(click.position);
|
||||
|
||||
@@ -72,6 +72,8 @@ export function createVesselState({ source, services }) {
|
||||
activeFocusCount: 0,
|
||||
activeLabelCount: 0,
|
||||
selectedRecord: null,
|
||||
/** @type {string|null} MMSI whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
|
||||
cockpitSubjectMmsi: null,
|
||||
/** @type {{setPositions: Function, clear: Function, destroy: Function}|null} Selected-vessel fading trail */
|
||||
trail: null,
|
||||
/** @type {Cesium.Cartesian3[]} Chronological trail vertices (oldest first) */
|
||||
|
||||
+218
-17
@@ -1,22 +1,75 @@
|
||||
import { createWorldClock } from '../../time/worldClock.js';
|
||||
|
||||
export const RADAR_MAX_GAP_MS = 30 * 60_000;
|
||||
export const REGIONAL_INFRARED_MAX_GAP_MS = 30 * 60_000;
|
||||
export const GLOBAL_INFRARED_MAX_GAP_MS = 3 * 60 * 60_000;
|
||||
export const LIGHTNING_MAX_GAP_MS = 30 * 60_000;
|
||||
/** The longest play waits on a frame before it goes on without it. */
|
||||
export const PLAY_WAIT_MS = 8_000;
|
||||
// Playing on its own, the world does not wait on the frame it is at: that
|
||||
// frame loads as play goes on. Play holds only at the next frame while the
|
||||
// one before it still loads, then goes on to it once it shows, so every frame
|
||||
// shows, play stops only for a load that is slow, and a frame loaded ahead
|
||||
// costs play nothing.
|
||||
|
||||
/** Transient observed time. Products must honor the signal before installing a frame. */
|
||||
let clocks = 0;
|
||||
|
||||
/**
|
||||
* Transient observed time. Products must honor the signal before installing a
|
||||
* frame. Its time is the world clock's: latest while the world is live,
|
||||
* history at the world's time otherwise. Replay steps the observed frames and
|
||||
* moves the world clock as it goes, as the world clock's driver.
|
||||
*/
|
||||
export function createWeatherClock({
|
||||
now = Date.now,
|
||||
setTimeout = globalThis.setTimeout,
|
||||
clearTimeout = globalThis.clearTimeout,
|
||||
world = createWorldClock({ now }),
|
||||
} = {}) {
|
||||
const registry = new Map();
|
||||
const listeners = new Set();
|
||||
let mode = 'latest';
|
||||
let target = null;
|
||||
let playing = false;
|
||||
// The world time last applied; while this clock moves the world, the
|
||||
// transition its move started.
|
||||
let seen = 'latest';
|
||||
let moving = false;
|
||||
let moved = null;
|
||||
const releases = new Map();
|
||||
// Attached at the end, once the API exists.
|
||||
let driver = null;
|
||||
let generation = 0;
|
||||
let timer = null;
|
||||
let pending = null;
|
||||
// This clock's name on the world, for its holds and its gate.
|
||||
const holdId = `weather:${++clocks}`;
|
||||
// While the world plays, the hold on it at the next frame as the one before
|
||||
// it loads, and the timer that lets play go on should that frame never
|
||||
// come; and whether the move to the next frame waits on it.
|
||||
let waiting = null;
|
||||
let waitTimer = null;
|
||||
let deferred = false;
|
||||
const stopWaiting = () => {
|
||||
const release = waiting;
|
||||
waiting = null;
|
||||
if (waitTimer !== null) clearTimeout(waitTimer);
|
||||
waitTimer = null;
|
||||
release?.();
|
||||
};
|
||||
const startWaiting = () => {
|
||||
if (waiting || destroyed || !registry.size) return;
|
||||
waiting = world.wait(holdId);
|
||||
waitTimer = setTimeout(() => {
|
||||
waitTimer = null;
|
||||
stopWaiting();
|
||||
// The frame that never came gives way to the one play is at.
|
||||
if (deferred) void transition();
|
||||
}, PLAY_WAIT_MS);
|
||||
};
|
||||
// Playing on its own, the world waits for frames as they load.
|
||||
const worldPlaysOn = (state = world.getState()) =>
|
||||
state.playing && !state.live && !state.stepping;
|
||||
let destroyed = false;
|
||||
const timesFor = (product) =>
|
||||
[...new Set(product.getTimes())]
|
||||
@@ -49,6 +102,9 @@ export function createWeatherClock({
|
||||
mode,
|
||||
target,
|
||||
playing,
|
||||
// Frames come on one after another: this clock replays them, or the world
|
||||
// plays on through them, so the next is worth loading ahead.
|
||||
advancing: playing || worldPlaysOn(),
|
||||
timeline: getTimeline(),
|
||||
products: [...registry.values()].map(({ product }) => ({
|
||||
id: product.id,
|
||||
@@ -65,11 +121,32 @@ export function createWeatherClock({
|
||||
timer = null;
|
||||
};
|
||||
const canPlay = () => getTimeline().length >= 2;
|
||||
const stopPlaying = () => {
|
||||
if (!playing) return;
|
||||
playing = false;
|
||||
driver?.driven(false);
|
||||
};
|
||||
// Move the world clock; the change comes back through followWorld. Returns
|
||||
// the transition the move started, if it started one.
|
||||
const move = (fn) => {
|
||||
const outer = [moving, moved];
|
||||
moving = true;
|
||||
moved = null;
|
||||
try {
|
||||
fn();
|
||||
return moved;
|
||||
} finally {
|
||||
[moving, moved] = outer;
|
||||
}
|
||||
};
|
||||
const selections = () =>
|
||||
[...registry.values()].map(({ product }) => selectedFor(product)).join();
|
||||
let applied = null;
|
||||
function schedule() {
|
||||
cancelTimer();
|
||||
if (!playing || destroyed || pending) return;
|
||||
if (!canPlay()) {
|
||||
playing = false;
|
||||
stopPlaying();
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
@@ -92,7 +169,11 @@ export function createWeatherClock({
|
||||
if (destroyed) return Promise.resolve(false);
|
||||
cancelTimer();
|
||||
const owner = ++generation;
|
||||
if (!canPlay()) playing = false;
|
||||
if (!canPlay()) stopPlaying();
|
||||
// A scrub drops what loads and moves on; play goes on as this loads.
|
||||
applied = selections();
|
||||
deferred = false;
|
||||
stopWaiting();
|
||||
for (const entry of registry.values()) entry.controller?.abort();
|
||||
// Start all products together; a rejection must not skip the settle barrier.
|
||||
const tasks = [...registry.values()].map((entry) => {
|
||||
@@ -106,13 +187,17 @@ export function createWeatherClock({
|
||||
});
|
||||
const result = Promise.allSettled(tasks).then(() => {
|
||||
if (destroyed || owner !== generation) return false;
|
||||
stopWaiting();
|
||||
pending = null;
|
||||
if (!canPlay()) playing = false;
|
||||
if (!canPlay()) stopPlaying();
|
||||
notify();
|
||||
schedule();
|
||||
// Play held at the next frame for this one goes on to it.
|
||||
if (deferred) void transition();
|
||||
return true;
|
||||
});
|
||||
pending = result;
|
||||
if (moving) moved ??= result;
|
||||
notify();
|
||||
return result;
|
||||
}
|
||||
@@ -123,11 +208,41 @@ export function createWeatherClock({
|
||||
throw new Error(`Duplicate weather product: ${product.id}`);
|
||||
const entry = { product, controller: null };
|
||||
registry.set(product.id, entry);
|
||||
// The product moves with the world clock, and its frames are time the
|
||||
// world clock's timeline can show while it is on, suspended or not, so
|
||||
// the way back to live stays on screen. Both calls notify the world's
|
||||
// listeners, which may destroy this clock: the release is in place
|
||||
// first, and anything acquired after a destroy is let go at once.
|
||||
let unhold = null;
|
||||
let uncover = null;
|
||||
const release = () => {
|
||||
uncover?.();
|
||||
unhold?.();
|
||||
uncover = unhold = null;
|
||||
};
|
||||
releases.set(product.id, release);
|
||||
unhold = world.hold(product.id);
|
||||
if (!destroyed)
|
||||
uncover = world.register({
|
||||
id: product.id,
|
||||
coverage: () => {
|
||||
const marks = timesFor(product).map((time) => Date.parse(time));
|
||||
return marks.length
|
||||
? { start: marks[0], end: marks.at(-1), marks }
|
||||
: null;
|
||||
},
|
||||
});
|
||||
if (destroyed) {
|
||||
release();
|
||||
return () => {};
|
||||
}
|
||||
void api.refresh();
|
||||
return () => {
|
||||
if (registry.get(product.id) !== entry) return;
|
||||
entry.controller?.abort();
|
||||
registry.delete(product.id);
|
||||
releases.get(product.id)?.();
|
||||
releases.delete(product.id);
|
||||
void api.refresh();
|
||||
};
|
||||
},
|
||||
@@ -140,9 +255,11 @@ export function createWeatherClock({
|
||||
const normalized = new Date(time).toISOString();
|
||||
if (mode === 'history' && target === normalized)
|
||||
return pending ?? Promise.resolve(true);
|
||||
mode = 'history';
|
||||
target = normalized;
|
||||
return transition();
|
||||
return (
|
||||
move(() => world.seek(Date.parse(normalized))) ??
|
||||
pending ??
|
||||
Promise.resolve(true)
|
||||
);
|
||||
},
|
||||
step(direction) {
|
||||
if (destroyed || ![-1, 1].includes(direction))
|
||||
@@ -159,10 +276,9 @@ export function createWeatherClock({
|
||||
},
|
||||
latest() {
|
||||
if (destroyed) return Promise.resolve(false);
|
||||
mode = 'latest';
|
||||
target = null;
|
||||
playing = false;
|
||||
return transition();
|
||||
stopPlaying();
|
||||
if (mode === 'latest') return transition();
|
||||
return move(() => world.goLive()) ?? pending ?? Promise.resolve(true);
|
||||
},
|
||||
play() {
|
||||
if (destroyed || playing || !canPlay())
|
||||
@@ -170,18 +286,28 @@ export function createWeatherClock({
|
||||
playing = true;
|
||||
if (mode === 'latest') {
|
||||
const timeline = getTimeline();
|
||||
return api.setTarget(
|
||||
timeline.findLast((time) => Date.parse(time) <= now()) ?? timeline[0],
|
||||
const start =
|
||||
timeline.findLast((time) => Date.parse(time) <= now()) ?? timeline[0];
|
||||
// Playing and at the first frame in one move of the world.
|
||||
return (
|
||||
move(() => driver.driven(true, Date.parse(start))) ??
|
||||
pending ??
|
||||
Promise.resolve(true)
|
||||
);
|
||||
}
|
||||
driver.driven(true);
|
||||
notify();
|
||||
schedule();
|
||||
return pending ?? Promise.resolve(true);
|
||||
},
|
||||
pause() {
|
||||
cancelTimer();
|
||||
if (!playing) return;
|
||||
playing = false;
|
||||
if (!playing) {
|
||||
// The world may be playing on its own; a pause or step here holds it.
|
||||
if (world.isPlaying()) world.pause();
|
||||
return;
|
||||
}
|
||||
stopPlaying();
|
||||
notify();
|
||||
},
|
||||
togglePlay() {
|
||||
@@ -189,8 +315,12 @@ export function createWeatherClock({
|
||||
},
|
||||
refresh() {
|
||||
if (destroyed) return Promise.resolve(false);
|
||||
// New frames, or products added or dropped, and with them the next.
|
||||
world.coverageChanged();
|
||||
gated = undefined;
|
||||
gateNext(world.getState());
|
||||
if (!canPlay()) {
|
||||
playing = false;
|
||||
stopPlaying();
|
||||
cancelTimer();
|
||||
}
|
||||
if (mode === 'history') return transition();
|
||||
@@ -204,15 +334,86 @@ export function createWeatherClock({
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
stopPlaying();
|
||||
destroyed = true;
|
||||
++generation;
|
||||
playing = false;
|
||||
stopWaiting();
|
||||
world.gate(holdId, null);
|
||||
cancelTimer();
|
||||
unfollowWorld();
|
||||
// The last weather clock leaves the world live, as a new one expects.
|
||||
if (driver.detach() === 0) world.goLive();
|
||||
for (const release of releases.values()) release();
|
||||
releases.clear();
|
||||
for (const entry of registry.values()) entry.controller?.abort();
|
||||
registry.clear();
|
||||
listeners.clear();
|
||||
pending = null;
|
||||
},
|
||||
};
|
||||
// Follow the world clock. A move of this clock's own always applies; one
|
||||
// from elsewhere (a host's seek, continuous play) applies only when it
|
||||
// changes the mode or a product's frame.
|
||||
function followWorld(state) {
|
||||
if (destroyed) return;
|
||||
gateNext(state);
|
||||
// Play starting or stopping changes whether the next frame loads ahead.
|
||||
const playsOn = worldPlaysOn(state);
|
||||
const playChanged = playsOn !== playedOn;
|
||||
playedOn = playsOn;
|
||||
const nextMode = state.live ? 'latest' : 'history';
|
||||
const nextTarget = state.live
|
||||
? null
|
||||
: new Date(Math.floor(state.timeMs)).toISOString();
|
||||
const key = nextTarget ?? 'latest';
|
||||
if (key === seen) {
|
||||
if (playChanged) notify();
|
||||
return;
|
||||
}
|
||||
seen = key;
|
||||
const modeChanged = nextMode !== mode;
|
||||
mode = nextMode;
|
||||
target = nextTarget;
|
||||
if (!moving && !modeChanged && selections() === applied) {
|
||||
// Back at the frame that loads, play need not hold for it.
|
||||
if (deferred) {
|
||||
deferred = false;
|
||||
stopWaiting();
|
||||
}
|
||||
// Played through, the time moves each frame with nothing new to show:
|
||||
// listeners hear of the frames as they change.
|
||||
if (!playsOn || playChanged) notify();
|
||||
return;
|
||||
}
|
||||
// Playing on into the next frame while the one before it loads, the
|
||||
// world holds here until that one shows.
|
||||
if (!moving && !modeChanged && pending && playsOn) {
|
||||
deferred = true;
|
||||
startWaiting();
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
void transition();
|
||||
}
|
||||
// Playing on its own, the world stops at each next frame to load it rather
|
||||
// than run past frames between its ticks.
|
||||
let gated = null;
|
||||
let playedOn = false;
|
||||
function gateNext(state) {
|
||||
const next = worldPlaysOn(state)
|
||||
? (getTimeline()
|
||||
.map((time) => Date.parse(time))
|
||||
.find((time) => time > Math.floor(state.timeMs)) ?? null)
|
||||
: null;
|
||||
if (next === gated) return;
|
||||
gated = next;
|
||||
world.gate(holdId, next);
|
||||
}
|
||||
const unfollowWorld = world.subscribe(followWorld);
|
||||
driver = world.attachDriver({
|
||||
play: () => (canPlay() ? void api.play() : false),
|
||||
pause: () => api.pause(),
|
||||
});
|
||||
followWorld(world.getState());
|
||||
return api;
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
REGIONAL_INFRARED_MAX_GAP_MS,
|
||||
GLOBAL_INFRARED_MAX_GAP_MS,
|
||||
LIGHTNING_MAX_GAP_MS,
|
||||
PLAY_WAIT_MS,
|
||||
} from './clock.js';
|
||||
import { createWorldClock } from '../../time/worldClock.js';
|
||||
|
||||
const time = (minutes) =>
|
||||
new Date(Date.UTC(2026, 8, 21, 12, minutes)).toISOString();
|
||||
@@ -37,7 +39,15 @@ function harness(t) {
|
||||
let at = Date.parse(time(20));
|
||||
const timers = new Map();
|
||||
let id = 0;
|
||||
let mono = 0;
|
||||
const world = createWorldClock({
|
||||
now: () => at,
|
||||
monotonicNow: () => mono,
|
||||
setInterval: () => 0,
|
||||
clearInterval() {},
|
||||
});
|
||||
const clock = createWeatherClock({
|
||||
world,
|
||||
now: () => at,
|
||||
setTimeout(fn, delay) {
|
||||
timers.set(++id, { fn, due: at + delay });
|
||||
@@ -50,9 +60,11 @@ function harness(t) {
|
||||
t.after(() => clock.destroy());
|
||||
return {
|
||||
clock,
|
||||
world,
|
||||
timers,
|
||||
tick(ms) {
|
||||
at += ms;
|
||||
mono += ms;
|
||||
for (const [id, timer] of [...timers]) {
|
||||
if (timer.due > at) continue;
|
||||
timers.delete(id);
|
||||
@@ -275,3 +287,423 @@ test('registration joins history; unregister and destroy abort work and release
|
||||
assert.deepEqual(clock.getTimeline(), []);
|
||||
assert.equal(await clock.setTarget(time(5)), false);
|
||||
});
|
||||
|
||||
test('the weather time is the world time, both ways', async (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const radar = product('radar', [0, 10, 20]);
|
||||
clock.register(radar);
|
||||
assert.equal(world.follows('radar'), true);
|
||||
await clock.setTarget(time(10));
|
||||
assert.equal(world.isLive(), false);
|
||||
assert.equal(world.now(), Date.parse(time(10)));
|
||||
world.seek(Date.parse(time(3)));
|
||||
await flush();
|
||||
assert.equal(clock.getState().target, time(3));
|
||||
assert.equal(radar.shown, time(0));
|
||||
world.goLive();
|
||||
await flush();
|
||||
assert.equal(clock.getState().mode, 'latest');
|
||||
assert.equal(radar.shown, time(20));
|
||||
});
|
||||
|
||||
test('world play and pause drive the weather replay', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = product('radar', [0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(0)));
|
||||
await flush();
|
||||
world.play();
|
||||
assert.equal(clock.getState().playing, true);
|
||||
assert.equal(world.isPlaying(), true);
|
||||
tick(2000);
|
||||
await flush();
|
||||
assert.equal(radar.shown, time(10));
|
||||
assert.equal(world.now(), Date.parse(time(10)));
|
||||
world.pause();
|
||||
assert.equal(clock.getState().playing, false);
|
||||
clock.play();
|
||||
assert.equal(world.isPlaying(), true);
|
||||
clock.pause();
|
||||
assert.equal(world.isPlaying(), false);
|
||||
clock.play();
|
||||
world.goLive();
|
||||
await flush();
|
||||
assert.equal(clock.getState().playing, false);
|
||||
assert.equal(clock.getState().mode, 'latest');
|
||||
});
|
||||
|
||||
test('a moving world re-applies frames only when a product changes frame', async (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const radar = product('radar', [0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(0)));
|
||||
await flush();
|
||||
const applied = radar.calls.length;
|
||||
world.seek(Date.parse(time(0)) + 60_000);
|
||||
await flush();
|
||||
assert.equal(radar.calls.length, applied);
|
||||
assert.equal(
|
||||
clock.getState().target,
|
||||
new Date(Date.parse(time(1))).toISOString(),
|
||||
);
|
||||
world.seek(Date.parse(time(11)));
|
||||
await flush();
|
||||
assert.equal(radar.calls.length, applied + 1);
|
||||
assert.equal(radar.shown, time(10));
|
||||
});
|
||||
|
||||
test('a world without frames to step plays on its own', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
world.seek(Date.parse(time(0)));
|
||||
world.play();
|
||||
assert.equal(clock.getState().playing, false);
|
||||
tick(1000);
|
||||
assert.equal(world.now(), Date.parse(time(0)) + 1000);
|
||||
});
|
||||
|
||||
function worldAt(at) {
|
||||
return createWorldClock({
|
||||
now: () => at,
|
||||
monotonicNow: () => 0,
|
||||
setInterval: () => 0,
|
||||
clearInterval() {},
|
||||
});
|
||||
}
|
||||
|
||||
test('weather clocks sharing a world hand play over, and the last leaves it live', async () => {
|
||||
const world = worldAt(Date.parse(time(20)));
|
||||
const a = createWeatherClock({ world, now: () => Date.parse(time(20)) });
|
||||
const b = createWeatherClock({ world, now: () => Date.parse(time(20)) });
|
||||
const radarA = product('radar', [0, 10, 20]);
|
||||
const radarB = product('radar', [0, 10, 20]);
|
||||
a.register(radarA);
|
||||
b.register(radarB);
|
||||
await a.play();
|
||||
assert.equal(world.isPlaying(), true);
|
||||
world.pause();
|
||||
assert.equal(a.getState().playing, false);
|
||||
assert.equal(world.isPlaying(), false);
|
||||
await a.play();
|
||||
world.goLive();
|
||||
assert.equal(a.getState().playing, false);
|
||||
b.destroy();
|
||||
assert.equal(world.follows('radar'), true);
|
||||
world.seek(Date.parse(time(0)));
|
||||
world.play();
|
||||
assert.equal(a.getState().playing, true);
|
||||
a.destroy();
|
||||
assert.equal(world.follows('radar'), false);
|
||||
assert.equal(world.isLive(), true);
|
||||
assert.equal(world.isPlaying(), false);
|
||||
});
|
||||
|
||||
test('pausing from inside the first playing notice stops the world too', async (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
clock.register(product('radar', [0, 10, 20]));
|
||||
const off = clock.subscribe((state) => {
|
||||
if (state.playing) {
|
||||
off();
|
||||
clock.pause();
|
||||
}
|
||||
});
|
||||
await clock.play();
|
||||
assert.equal(clock.getState().playing, false);
|
||||
assert.equal(world.isPlaying(), false);
|
||||
});
|
||||
|
||||
test('a step holds a world that was playing on its own', async (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
world.seek(Date.parse(time(0)));
|
||||
world.play();
|
||||
clock.register(product('radar', [0, 10, 20]));
|
||||
await clock.step(1);
|
||||
assert.equal(world.isPlaying(), false);
|
||||
assert.equal(world.now(), Date.parse(time(10)));
|
||||
});
|
||||
|
||||
test('a target superseded from a listener resolves false', async (t) => {
|
||||
const { clock } = harness(t);
|
||||
const radar = product('radar', [0, 10, 20]);
|
||||
clock.register(radar);
|
||||
await flush();
|
||||
let redirected = false;
|
||||
clock.subscribe((state) => {
|
||||
if (state.target === time(0) && !redirected) {
|
||||
redirected = true;
|
||||
void clock.setTarget(time(10));
|
||||
}
|
||||
});
|
||||
assert.equal(await clock.setTarget(time(0)), false);
|
||||
assert.equal(radar.shown, time(10));
|
||||
});
|
||||
|
||||
test('each product’s frames are world clock coverage, and support the timeline while shown', (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
assert.equal(world.coverage(), null);
|
||||
assert.equal(world.getState().supported, false);
|
||||
const radar = product('radar', [0, 10]);
|
||||
const unregister = clock.register(radar);
|
||||
clock.register(product('lightning', [5]));
|
||||
assert.deepEqual(world.coverage(), {
|
||||
start: Date.parse(time(0)),
|
||||
end: Date.parse(time(10)),
|
||||
marks: [0, 5, 10].map((m) => Date.parse(time(m))),
|
||||
});
|
||||
assert.equal(world.getState().supported, true);
|
||||
unregister();
|
||||
assert.deepEqual(world.coverage().marks, [Date.parse(time(5))]);
|
||||
clock.destroy();
|
||||
assert.equal(world.coverage(), null);
|
||||
assert.equal(world.getState().supported, false);
|
||||
});
|
||||
|
||||
test('a suspended product keeps its coverage, so the way back to live stays', (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const radar = product('radar', [0, 10]);
|
||||
clock.register(radar);
|
||||
radar.suspended = true;
|
||||
void clock.refresh();
|
||||
assert.equal(world.getState().supported, true);
|
||||
assert.deepEqual(
|
||||
world.coverage().marks,
|
||||
[0, 10].map((m) => Date.parse(time(m))),
|
||||
);
|
||||
});
|
||||
|
||||
test('new frames reach the world clock through refresh', (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const radar = product('radar', []);
|
||||
clock.register(radar);
|
||||
const supported = [];
|
||||
world.subscribe((state) => supported.push(state.supported));
|
||||
assert.equal(world.getState().supported, false);
|
||||
radar.times = [time(0)];
|
||||
void clock.refresh();
|
||||
assert.equal(supported.at(-1), true);
|
||||
});
|
||||
|
||||
test('a clock destroyed while it registers a product lets go of it', (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const off = world.subscribe(() => {
|
||||
off();
|
||||
clock.destroy();
|
||||
});
|
||||
const unregister = clock.register(product('radar', [0, 10]));
|
||||
unregister();
|
||||
assert.equal(world.follows('radar'), false);
|
||||
assert.equal(world.coverage(), null);
|
||||
assert.equal(world.getState().supported, false);
|
||||
});
|
||||
|
||||
// A radar whose frames load only when the test says.
|
||||
function slowRadar(minutes) {
|
||||
const radar = product('radar', minutes);
|
||||
radar.loads = [];
|
||||
radar.apply = (selected, { signal }) =>
|
||||
new Promise((resolve) => {
|
||||
radar.loads.push({
|
||||
selected,
|
||||
signal,
|
||||
done() {
|
||||
radar.shown = selected;
|
||||
resolve(true);
|
||||
},
|
||||
});
|
||||
});
|
||||
return radar;
|
||||
}
|
||||
|
||||
test('play stops at the next frame, not past it, until it shows', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = slowRadar([0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(1)));
|
||||
await flush();
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
world.play({ rate: 3_600, continuous: true });
|
||||
world.coverageChanged();
|
||||
tick(1_000);
|
||||
assert.equal(
|
||||
world.now(),
|
||||
Date.parse(time(10)),
|
||||
'an hour on, but held at the frame',
|
||||
);
|
||||
});
|
||||
|
||||
test('playing, a frame loads as play goes on, and play holds at the next until it shows', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = slowRadar([0, 10, 20, 30]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(9)));
|
||||
await flush();
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
world.play({ rate: 60, continuous: true });
|
||||
// Into the next frame (the page's frames tell of it): it loads as play goes on.
|
||||
tick(2_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(radar.loads.at(-1).selected, time(10));
|
||||
assert.equal(
|
||||
world.getState().buffering,
|
||||
false,
|
||||
'no hold for the frame play is at',
|
||||
);
|
||||
// At the frame after while that one still loads, play holds there.
|
||||
tick(10_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(world.now(), Date.parse(time(20)));
|
||||
assert.equal(world.getState().buffering, true);
|
||||
assert.equal(
|
||||
radar.loads.at(-1).selected,
|
||||
time(10),
|
||||
'the frame before still loads',
|
||||
);
|
||||
tick(5_000);
|
||||
assert.equal(world.now(), Date.parse(time(20)), 'held while it loads');
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
assert.equal(
|
||||
radar.loads.at(-1).selected,
|
||||
time(20),
|
||||
'and on to the next once it shows',
|
||||
);
|
||||
assert.equal(world.getState().buffering, false);
|
||||
tick(1_000);
|
||||
assert.equal(world.now(), Date.parse(time(20)) + 60_000);
|
||||
|
||||
// A scrub aborts what loads and loads where the hand is, with no wait.
|
||||
world.pause();
|
||||
world.seek(Date.parse(time(30)));
|
||||
await flush();
|
||||
const scrubbed = radar.loads.at(-1);
|
||||
world.seek(Date.parse(time(0)));
|
||||
await flush();
|
||||
assert.equal(scrubbed.signal.aborted, true);
|
||||
assert.equal(radar.loads.at(-1).selected, time(0));
|
||||
assert.equal(world.getState().buffering, false);
|
||||
});
|
||||
|
||||
test('a frame that never comes holds play only so long', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = slowRadar([0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(9)));
|
||||
await flush();
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
world.play({ rate: 60, continuous: true });
|
||||
tick(2_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
tick(10_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(world.getState().buffering, true);
|
||||
const stuck = radar.loads.at(-1);
|
||||
tick(PLAY_WAIT_MS);
|
||||
await flush();
|
||||
assert.equal(world.getState().buffering, false, 'play goes on without it');
|
||||
assert.equal(stuck.signal.aborted, true);
|
||||
assert.equal(radar.loads.at(-1).selected, time(20), 'loading where play is');
|
||||
});
|
||||
|
||||
test('held at the next frame, a scrub back to the one loading lets play go', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = slowRadar([0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(9)));
|
||||
await flush();
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
world.play({ rate: 60, continuous: true });
|
||||
tick(2_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
tick(10_000);
|
||||
world.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(world.getState().buffering, true);
|
||||
world.pause();
|
||||
world.seek(Date.parse(time(11)));
|
||||
await flush();
|
||||
world.play({ rate: 60, continuous: true });
|
||||
assert.equal(
|
||||
world.getState().buffering,
|
||||
false,
|
||||
'no hold for the frame it is at',
|
||||
);
|
||||
const at = world.now();
|
||||
tick(1_000);
|
||||
assert.equal(world.now(), at + 60_000);
|
||||
});
|
||||
|
||||
test('a frame in flight as play starts loads as it goes on; a refresh does not hold', async (t) => {
|
||||
const { clock, world } = harness(t);
|
||||
const radar = slowRadar([0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(5)));
|
||||
await flush();
|
||||
world.play({ continuous: true });
|
||||
assert.equal(world.getState().buffering, false);
|
||||
radar.loads.at(-1).done();
|
||||
await flush();
|
||||
void clock.refresh();
|
||||
await flush();
|
||||
assert.equal(world.getState().buffering, false, 'the same frames, no hold');
|
||||
radar.loads.at(-1).done();
|
||||
});
|
||||
|
||||
test('weather clocks sharing a world gate it each on their own', async (t) => {
|
||||
let mono = 0;
|
||||
const world = createWorldClock({
|
||||
now: () => Date.parse(time(30)),
|
||||
monotonicNow: () => mono,
|
||||
setInterval: () => 0,
|
||||
clearInterval() {},
|
||||
});
|
||||
const a = createWeatherClock({ world, now: () => Date.parse(time(30)) });
|
||||
const b = createWeatherClock({ world, now: () => Date.parse(time(30)) });
|
||||
t.after(() => {
|
||||
a.destroy();
|
||||
b.destroy();
|
||||
});
|
||||
a.register(product('radar', [0, 10]));
|
||||
b.register(product('clouds', [0, 15]));
|
||||
world.seek(Date.parse(time(1)));
|
||||
await flush();
|
||||
world.play({ rate: 3_600, continuous: true });
|
||||
world.coverageChanged();
|
||||
b.destroy();
|
||||
world.coverageChanged();
|
||||
mono += 1_000;
|
||||
assert.equal(
|
||||
world.now(),
|
||||
Date.parse(time(10)),
|
||||
'the other clock’s gate stays',
|
||||
);
|
||||
});
|
||||
|
||||
test('played through, listeners hear of frames as they change, and of play stopping', async (t) => {
|
||||
const { clock, world, tick } = harness(t);
|
||||
const radar = product('radar', [0, 10, 20]);
|
||||
clock.register(radar);
|
||||
world.seek(Date.parse(time(1)));
|
||||
await flush();
|
||||
world.play({ rate: 60, continuous: true });
|
||||
await flush();
|
||||
const heard = [];
|
||||
clock.subscribe((state) => heard.push(state));
|
||||
// Seconds of world time within one frame: nothing new to show.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
tick(100);
|
||||
world.coverageChanged();
|
||||
}
|
||||
await flush();
|
||||
assert.equal(heard.length, 0);
|
||||
world.pause();
|
||||
await flush();
|
||||
assert.equal(heard.at(-1)?.advancing, false, 'heard play stop');
|
||||
});
|
||||
@@ -52,7 +52,8 @@ const utc = (value) =>
|
||||
: t('Unavailable');
|
||||
|
||||
/** A per-application observation layer, using the existing layer lifecycle and
|
||||
* row controls. History is transient: shared links always open latest imagery. */
|
||||
* row controls. Its time is the world clock's, so a link made away from live
|
||||
* opens its imagery at that time; one made live opens the latest. */
|
||||
export function createWeatherLayer({
|
||||
feed,
|
||||
clock,
|
||||
@@ -108,7 +109,8 @@ export function createWeatherLayer({
|
||||
const notify = () => listener?.();
|
||||
const shownTime = () => (noFrame ? null : rendering?.getDiagnostics().time);
|
||||
const unsubscribeClock = clock?.subscribe(() => {
|
||||
if (!clock.getState().playing || suspended()) rendering?.cancelPrefetch?.();
|
||||
if (!clock.getState().advancing || suspended())
|
||||
rendering?.cancelPrefetch?.();
|
||||
notify();
|
||||
});
|
||||
const observationDelayed = () =>
|
||||
@@ -210,7 +212,7 @@ export function createWeatherLayer({
|
||||
if (
|
||||
!enabled ||
|
||||
suspended() ||
|
||||
!(clock ? clock.getState().playing : playing)
|
||||
!(clock ? clock.getState().advancing : playing)
|
||||
)
|
||||
return;
|
||||
const times = manifest?.times ?? [];
|
||||
|
||||
Reference in new issue
Block a user