mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main through #1634 into the renderer seam
Brings in the CCTV opening camera, the Iceland, Giroc HLS, Taiwan, Quebec, Ottawa and world camera packs, the world clock and timeline, the zoom-out limit and registered-only layer state, ported onto the renderer contract: the sky follows the world time through the frame port's setTime in preUpdate, the Quebec overlay reads the eye, projects and redraws through the camera, query and frame ports, launches hide pending missions through their draw records, and mission orbit rings turn on the scene clock.
This commit is contained in:
commit
2b60531c3c
170 files changed
+44096
-319
No files matched your search
@@ -128,9 +128,11 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
record.camera.lon,
|
||||
),
|
||||
inView,
|
||||
isVideo: parts.model.isVideoFeedType(
|
||||
parts.model.normalizeFeedType(record.camera.feedType),
|
||||
),
|
||||
// Québec's browser-only sources have no registered frame endpoint;
|
||||
// keep them out of still-card fill just like video feeds.
|
||||
isVideo:
|
||||
parts.model.isVideoFeedCamera(record.camera) ||
|
||||
parts.model.isBrowserOverlayCamera(record.camera),
|
||||
sx,
|
||||
sy,
|
||||
});
|
||||
|
||||
@@ -237,9 +237,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
groundElevationM,
|
||||
absoluteHeightM: groundElevationM + mountHeightM,
|
||||
pitchDeg,
|
||||
frameRefreshMs: parts.model.safeNumber(source.frameRefreshMs, NaN),
|
||||
license: String(source.license || source.licenseNote || ''),
|
||||
credit: String(source.credit || ''),
|
||||
code: String(source.code || ''),
|
||||
sourceUrl: String(source.sourceUrl || ''),
|
||||
browserMediaUrl: String(source.browserMediaUrl || ''),
|
||||
accuracyM: parts.model.safeNumber(source.accuracyM, NaN),
|
||||
positionSource: String(source.positionSource || ''),
|
||||
// Shipped precompute (see server/providers/cctv/groundHeights.js).
|
||||
groundHeights:
|
||||
source.groundHeights && typeof source.groundHeights === 'object'
|
||||
|
||||
@@ -255,11 +255,20 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
// clears this latch so the next normal tick can refresh.
|
||||
if (runtime.imageLoading) return;
|
||||
const now = Date.now();
|
||||
const refreshMs =
|
||||
const defaultRefreshMs =
|
||||
record.camera.id === layerState._activeCameraId
|
||||
? PROJECTION_ACTIVE_REFRESH_MS
|
||||
: PROJECTION_IDLE_REFRESH_MS;
|
||||
if (!force && now - runtime.lastImageRefreshAt < refreshMs) return;
|
||||
const sourceRefreshMs = parts.model.safeNumber(
|
||||
record.camera.frameRefreshMs,
|
||||
0,
|
||||
);
|
||||
const refreshMs = Math.max(defaultRefreshMs, sourceRefreshMs);
|
||||
const sinceLastRefresh = now - runtime.lastImageRefreshAt;
|
||||
// Forced activation may skip the normal active interval, but it cannot
|
||||
// bypass a provider's explicit minimum between image requests.
|
||||
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
|
||||
if (!force && sinceLastRefresh < refreshMs) return;
|
||||
runtime.lastImageRefreshAt = now;
|
||||
|
||||
const frameUrl = frameUrlFor(record.camera, refreshMs);
|
||||
|
||||
@@ -43,9 +43,8 @@ export function createHover({ state: layerState, services, parts, source }) {
|
||||
!!record &&
|
||||
cameraId !== layerState._activeCameraId &&
|
||||
!layerState._cardIds.has(cameraId) &&
|
||||
!parts.model.isVideoFeedType(
|
||||
parts.model.normalizeFeedType(record.camera.feedType),
|
||||
);
|
||||
!parts.model.isBrowserOverlayCamera(record.camera) &&
|
||||
!parts.model.isVideoFeedCamera(record.camera);
|
||||
if (eligible) {
|
||||
cancelHoverRelease();
|
||||
layerState._hoverCardId = cameraId;
|
||||
|
||||
@@ -116,6 +116,8 @@ export function createCctvLayer({ services, source }) {
|
||||
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
|
||||
focusCctvRecord: parts.navigation.focusCctvRecord,
|
||||
maybeAutoHop: parts.navigation.maybeAutoHop,
|
||||
openingCameraId: parts.navigation.openingCameraId,
|
||||
reopenNearestCamera: parts.navigation.reopenNearestCamera,
|
||||
cctvCycleIndex: parts.navigation.cctvCycleIndex,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -122,6 +122,7 @@ export function createLifecycle({
|
||||
layerState._horizonCullListener = viewCamera.on('moveEnd', () => {
|
||||
layerState._cameraMoving = false;
|
||||
stopViewMotionTimer();
|
||||
parts.navigation.reopenNearestCamera();
|
||||
settleView();
|
||||
});
|
||||
}
|
||||
@@ -200,6 +201,7 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
layerState._lastHopAt = 0;
|
||||
layerState._lastViewContext = '';
|
||||
layerState._calibrationById = parts.calibration.loadCalibrationStore();
|
||||
@@ -322,11 +324,8 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
layerState._count = layerState._records.length;
|
||||
if (layerState._records.length > 0) {
|
||||
// Projection runtime + first frame fetch are deferred to enable() so
|
||||
// initializing the catalog stays render-cheap.
|
||||
layerState._activeCameraId = layerState._records[0].camera.id;
|
||||
}
|
||||
// No camera is picked here: enable() opens on the one nearest the
|
||||
// viewer, unless restored params selected one first.
|
||||
|
||||
// Task 5: if the prior batch lost init's bounded race, apply it post-hoc
|
||||
// when it lands (pure recomputes — applyLateGroundPriors guards against
|
||||
@@ -487,8 +486,9 @@ export function createLifecycle({
|
||||
return Boolean(coverage && layerState._recordById.has(coverage[1]));
|
||||
});
|
||||
if (!layerState._activeCameraId && layerState._records.length) {
|
||||
layerState._activeCameraId = layerState._records[0].camera.id;
|
||||
layerState._activeCameraId = parts.navigation.openingCameraId();
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = true;
|
||||
}
|
||||
const activeRecord = parts.selection.getActiveRecord();
|
||||
if (activeRecord) {
|
||||
@@ -584,6 +584,7 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
// Clear existing subscribers rather than replacing the Set —
|
||||
// replacing would silently orphan any unsubscribe() closures
|
||||
layerState._listeners.clear();
|
||||
|
||||
@@ -32,6 +32,7 @@ function lifecycleFor(state) {
|
||||
geometryQueue: { enqueueViewGeometry() {} },
|
||||
cards: { refreshAmbientCards() {} },
|
||||
presentation: { notifyListeners() {} },
|
||||
navigation: { reopenNearestCamera() {} },
|
||||
},
|
||||
});
|
||||
return { lifecycle, passes };
|
||||
|
||||
@@ -98,6 +98,19 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
return feedType === 'mp4' || feedType === 'hls' || feedType === 'webm';
|
||||
}
|
||||
|
||||
/** A browser-only source still counts as live-capable for map icon/LOD policy. */
|
||||
function isVideoFeedCamera(camera) {
|
||||
return (
|
||||
isVideoFeedType(normalizeFeedType(camera?.feedType)) ||
|
||||
Boolean(camera?.browserMediaUrl)
|
||||
);
|
||||
}
|
||||
|
||||
/** Québec source pages and browser-played MP4s use the DOM overlay path. */
|
||||
function isBrowserOverlayCamera(camera) {
|
||||
return String(camera?.sourceKind || '').startsWith('quebec-');
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerces a value to a finite number or returns the fallback.
|
||||
*
|
||||
@@ -416,7 +429,12 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
|
||||
function projectionLoopIsNeeded() {
|
||||
if (!layerState._enabled || !layerState._viewer) return false;
|
||||
if (layerState._showProjection && parts.selection.getActiveRecord())
|
||||
const active = parts.selection.getActiveRecord();
|
||||
if (
|
||||
layerState._showProjection &&
|
||||
active &&
|
||||
!isBrowserOverlayCamera(active.camera)
|
||||
)
|
||||
return true;
|
||||
return focusPassIsNeeded(
|
||||
getFocusTarget(),
|
||||
@@ -523,6 +541,8 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
angularDeltaAbs,
|
||||
normalizeFeedType,
|
||||
isVideoFeedType,
|
||||
isVideoFeedCamera,
|
||||
isBrowserOverlayCamera,
|
||||
safeNumber,
|
||||
headingFromId,
|
||||
quantize,
|
||||
|
||||
@@ -33,6 +33,36 @@ export function createNavigation({
|
||||
return best?.id || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera the layer opens on when none is selected: the one nearest the
|
||||
* viewer, or the first record when the viewer has no position yet.
|
||||
* @returns {string|null} Camera ID, or null when the catalog is empty.
|
||||
*/
|
||||
|
||||
function openingCameraId() {
|
||||
return (
|
||||
nearestCameraIdToViewer() || layerState._records[0]?.camera?.id || null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* After a settled move, moves the opening camera to the one nearest the
|
||||
* view, until someone chooses a camera. A shared view's flight lands after
|
||||
* enable() picked from the startup view.
|
||||
* @returns {boolean} True when the active camera changed.
|
||||
*/
|
||||
|
||||
function reopenNearestCamera() {
|
||||
if (!layerState._openingCameraProvisional || !layerState._enabled)
|
||||
return false;
|
||||
const nearest = nearestCameraIdToViewer();
|
||||
if (!nearest || nearest === layerState._activeCameraId) return false;
|
||||
parts.selection.setActiveCamera(nearest);
|
||||
// setActiveCamera ends the opening pick; this is still that pick.
|
||||
layerState._openingCameraProvisional = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flies the viewer's camera to frame the specified CCTV camera,
|
||||
* looking along its heading from above.
|
||||
@@ -146,6 +176,8 @@ export function createNavigation({
|
||||
}
|
||||
return {
|
||||
nearestCameraIdToViewer,
|
||||
openingCameraId,
|
||||
reopenNearestCamera,
|
||||
focusCctvRecord,
|
||||
focusCamera,
|
||||
maybeAutoHop,
|
||||
|
||||
@@ -160,9 +160,14 @@ export function createPresentation({
|
||||
const camera = record.camera;
|
||||
const health = layerState._healthById.get(camera.id) || null;
|
||||
const isActive = camera.id === resolvedActiveId;
|
||||
const refreshMs = isActive
|
||||
const defaultRefreshMs = isActive
|
||||
? ACTIVE_FRAME_REFRESH_MS
|
||||
: IDLE_FRAME_REFRESH_MS;
|
||||
const sourceRefreshMs = Number(camera.frameRefreshMs);
|
||||
const refreshMs =
|
||||
Number.isFinite(sourceRefreshMs) && sourceRefreshMs > 0
|
||||
? Math.max(defaultRefreshMs, sourceRefreshMs)
|
||||
: defaultRefreshMs;
|
||||
return {
|
||||
id: camera.id,
|
||||
name: camera.name,
|
||||
@@ -192,13 +197,18 @@ export function createPresentation({
|
||||
mountHeightM: camera.mountHeightM,
|
||||
active: isActive,
|
||||
feedType: camera.feedType,
|
||||
sourceUrl: camera.sourceUrl || '',
|
||||
browserMediaUrl: camera.browserMediaUrl || '',
|
||||
accuracyM: Number.isFinite(camera.accuracyM) ? camera.accuracyM : null,
|
||||
positionSource: camera.positionSource || '',
|
||||
isVideo:
|
||||
parts.model.isVideoFeedType(camera.feedType) &&
|
||||
parts.model.isVideoFeedCamera(camera) &&
|
||||
record.projection?.mode !== 'image',
|
||||
sourceKind:
|
||||
health?.sourceKind ||
|
||||
camera.sourceKind ||
|
||||
(camera.feedConfigured ? 'configured' : 'seed'),
|
||||
sourceKind: camera.sourceKind?.startsWith('quebec-')
|
||||
? camera.sourceKind
|
||||
: health?.sourceKind ||
|
||||
camera.sourceKind ||
|
||||
(camera.feedConfigured ? 'configured' : 'seed'),
|
||||
sourceStatus: health?.status || 'unknown',
|
||||
sourceMessage: health?.message || '',
|
||||
sourceLabel: health?.label || camera.provider || '',
|
||||
@@ -276,6 +286,7 @@ export function createPresentation({
|
||||
hoverId: layerState._hoverCardId,
|
||||
},
|
||||
activeCameraId: activeId,
|
||||
activeCameraReselection: layerState._activeCameraReselection,
|
||||
activeCamera: active ? getPublicCameraState(active, activeId) : null,
|
||||
cameraIndex: cameraIndex(),
|
||||
summary: buildSummaryText(),
|
||||
|
||||
@@ -201,6 +201,9 @@ export function createProjection({
|
||||
|
||||
function createProjectionRuntime(record) {
|
||||
if (!layerState._viewer) return null;
|
||||
// Québec 511 denies CORS pixel access; Québec map previews are native DOM
|
||||
// videos positioned over the globe, never Cesium video textures.
|
||||
if (parts.model.isBrowserOverlayCamera(record.camera)) return null;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = PROJECTION_CANVAS_WIDTH;
|
||||
canvas.height = PROJECTION_CANVAS_HEIGHT;
|
||||
|
||||
@@ -204,8 +204,7 @@ export function createRendering({
|
||||
function cameraColorFor(record) {
|
||||
if (record.camera.id === layerState._activeCameraId)
|
||||
return ACTIVE_CAMERA_COLOR;
|
||||
if (parts.model.isVideoFeedType(record.camera.feedType))
|
||||
return LIVE_CAMERA_COLOR;
|
||||
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR;
|
||||
return IDLE_CAMERA_COLOR;
|
||||
}
|
||||
|
||||
@@ -557,8 +556,9 @@ export function createRendering({
|
||||
if (
|
||||
layerState._enabled &&
|
||||
isActive &&
|
||||
!parts.model.isBrowserOverlayCamera(record.camera) &&
|
||||
(layerState._showProjection ||
|
||||
parts.model.isVideoFeedType(record.camera.feedType))
|
||||
parts.model.isVideoFeedCamera(record.camera))
|
||||
) {
|
||||
parts.projection.ensureProjectionRuntime(record);
|
||||
}
|
||||
@@ -568,7 +568,8 @@ export function createRendering({
|
||||
const planeShowing = !!(
|
||||
layerState._enabled &&
|
||||
layerState._showProjection &&
|
||||
isActive
|
||||
isActive &&
|
||||
!parts.model.isBrowserOverlayCamera(record.camera)
|
||||
);
|
||||
|
||||
const inVisibleSet = coverageVisible.has(record.camera.id);
|
||||
|
||||
@@ -69,7 +69,13 @@ test('focus de-emphasis fades each icon from its own color', () => {
|
||||
createRendering({
|
||||
state,
|
||||
services: { focus },
|
||||
parts: { model: { isVideoFeedType } },
|
||||
parts: {
|
||||
model: {
|
||||
isVideoFeedType,
|
||||
isVideoFeedCamera: (camera) =>
|
||||
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
|
||||
},
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
@@ -280,7 +286,7 @@ test('a view pass writes only the icons it changes, in one write', () => {
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: {
|
||||
model: { isVideoFeedType: () => false },
|
||||
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
|
||||
drawSets: { roleOfSet: () => null },
|
||||
},
|
||||
source: {},
|
||||
@@ -350,7 +356,9 @@ test('a pose with no perspective field of view is projected by the renderer', ()
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: { model: { isVideoFeedType: () => false } },
|
||||
parts: {
|
||||
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
|
||||
@@ -70,10 +70,17 @@ export function createSelection({
|
||||
record,
|
||||
)
|
||||
) {
|
||||
// Browser-only feeds have a separate player; a reselect retries it
|
||||
// without re-running activation or touching the projection geometry.
|
||||
if (parts.model.isBrowserOverlayCamera(record.camera)) {
|
||||
layerState._activeCameraReselection += 1;
|
||||
parts.presentation.notifyListeners();
|
||||
}
|
||||
return CCTV_ACTIVATION_RESULT.UNCHANGED;
|
||||
}
|
||||
layerState._activeCameraId = cameraId;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
// A real activation creates projection work — wake the self-stopping loop.
|
||||
parts.projection.startProjectionLoop();
|
||||
if (previousActiveRecord && previousActiveRecord !== record) {
|
||||
@@ -161,6 +168,7 @@ export function createSelection({
|
||||
if (!record) return false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = true;
|
||||
layerState._openingCameraProvisional = false;
|
||||
record.activationDone = false;
|
||||
parts.geometry.clearProbeClampOnDeactivation(record, (previous) => {
|
||||
parts.geometry.applyFrustumGeometry(
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
|
||||
import { createSelection } from './selection.js';
|
||||
|
||||
function makeSelection(sourceKind) {
|
||||
const camera = { id: 'same-camera', sourceKind };
|
||||
const record = { camera };
|
||||
const state = {
|
||||
_activeCameraId: camera.id,
|
||||
_activeCameraReselection: 0,
|
||||
_recordById: new Map([[camera.id, record]]),
|
||||
};
|
||||
let notifications = 0;
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {
|
||||
activation: { CCTV_ACTIVATION_RESULT },
|
||||
picking: { resolvePickId: () => null },
|
||||
},
|
||||
parts: {
|
||||
model: {
|
||||
cctvRecordNeedsActivation: () => false,
|
||||
isBrowserOverlayCamera: (value) =>
|
||||
String(value?.sourceKind || '').startsWith('quebec-'),
|
||||
},
|
||||
presentation: { notifyListeners: () => notifications++ },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
return { selection, state, notifications: () => notifications };
|
||||
}
|
||||
|
||||
test('same-camera selection does not notify or mutate snapshot-feed state', () => {
|
||||
const fixture = makeSelection('tripcheck-odot');
|
||||
|
||||
assert.equal(
|
||||
fixture.selection.setActiveCamera('same-camera'),
|
||||
CCTV_ACTIVATION_RESULT.UNCHANGED,
|
||||
);
|
||||
assert.equal(fixture.state._activeCameraReselection, 0);
|
||||
assert.equal(fixture.notifications(), 0);
|
||||
});
|
||||
|
||||
test('same-camera selection notifies browser-overlay feeds so playback can retry', () => {
|
||||
const fixture = makeSelection('quebec-511-browser');
|
||||
|
||||
assert.equal(
|
||||
fixture.selection.setActiveCamera('same-camera'),
|
||||
CCTV_ACTIVATION_RESULT.UNCHANGED,
|
||||
);
|
||||
assert.equal(fixture.state._activeCameraReselection, 1);
|
||||
assert.equal(fixture.notifications(), 1);
|
||||
});
|
||||
@@ -28,6 +28,10 @@ export function createState({ services }) {
|
||||
|
||||
layerState._activeCameraId = null;
|
||||
|
||||
// Advances when a user reselects the already-active camera. The geometry
|
||||
// activation remains a no-op, but browser-only camera UI can retry playback.
|
||||
layerState._activeCameraReselection = 0;
|
||||
|
||||
layerState._coverageMode = 'on';
|
||||
// 'off' | 'on' (wireframes) | 'viewshed' (color-coded volumes)
|
||||
|
||||
@@ -35,6 +39,12 @@ export function createState({ services }) {
|
||||
|
||||
layerState._autoHop = false;
|
||||
|
||||
// True while the active camera is the one enable() opened on and nobody has
|
||||
// chosen a camera since: each settled move then re-picks the one nearest
|
||||
// the view, so a share flight that lands after enable still opens nearby.
|
||||
|
||||
layerState._openingCameraProvisional = false;
|
||||
|
||||
// An explicit empty-space deselect keeps AUTO HOP configured but prevents its
|
||||
// timer from silently choosing a replacement. A later explicit activation or
|
||||
// AUTO HOP toggle-on releases the hold.
|
||||
|
||||
@@ -101,6 +101,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
coverageMode = 'on',
|
||||
showProjection = false,
|
||||
healthById = new Map(),
|
||||
openingCameraProvisional = false,
|
||||
} = {}) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._records = Array.isArray(records) ? records : [];
|
||||
@@ -113,6 +114,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
layerState._projectionEntities = [];
|
||||
layerState._activeCameraId = activeCameraId;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = !!openingCameraProvisional;
|
||||
layerState._enabled = !!enabled;
|
||||
layerState._coverageMode = parts.model.normalizeCoverageMode(
|
||||
coverageMode,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { eastNorthUp, framePoint } from '../../geo/frames.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThan,
|
||||
julianNow,
|
||||
julianFromEpochMs,
|
||||
secondsDifference,
|
||||
} from '../../geo/julian.js';
|
||||
import {
|
||||
@@ -209,7 +209,7 @@ export function createMotion({
|
||||
const renderTime =
|
||||
sampledRenderTime ??
|
||||
addSeconds(
|
||||
julianNow(flightState._scratchRenderTime),
|
||||
julianFromEpochMs(flightState.now(), flightState._scratchRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -306,7 +306,7 @@ export function createMotion({
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = addSeconds(
|
||||
julianNow(),
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -12,6 +12,7 @@ function fixture() {
|
||||
_scratchArc: {},
|
||||
_scratchOffset: { x: 0, y: 0, z: 0 },
|
||||
_scratchRenderTime: { dayNumber: 0, secondsOfDay: 0 },
|
||||
now: Date.now,
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
@@ -129,7 +130,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 = [
|
||||
@@ -147,8 +148,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 startMs = Cesium.JulianDate.toDate(start).getTime();
|
||||
const spy = t.mock.method(Date, 'now', () => startMs + elapsed * 1000);
|
||||
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),
|
||||
@@ -169,7 +173,7 @@ 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);
|
||||
// Sampled into the layer's scratch, not a new date.
|
||||
assert.ok(
|
||||
Cesium.JulianDate.equals(
|
||||
|
||||
@@ -187,6 +187,7 @@ test('the tracked trail head is drawn each frame while tracked and stops with th
|
||||
);
|
||||
let headLon = 0.03;
|
||||
const flightState = {
|
||||
now: Date.now,
|
||||
_viewer: viewer,
|
||||
_trackedIcao: 'abc123',
|
||||
_trail: null,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { FlightRecords } from './records.js';
|
||||
import { createFlightFeed } from './ingestion.js';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
@@ -10,6 +11,8 @@ export function createFlightState({ source, services }) {
|
||||
...services.geoid,
|
||||
...services.groundFloor,
|
||||
});
|
||||
/** 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
|
||||
|
||||
@@ -21,7 +21,7 @@ import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianNow,
|
||||
julianFromEpochMs,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
@@ -441,7 +441,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 = addSeconds(
|
||||
julianNow(),
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -81,6 +81,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,
|
||||
} = {}) {
|
||||
@@ -175,7 +177,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
+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 || []) {
|
||||
|
||||
@@ -225,6 +225,7 @@ export function createIngestion({
|
||||
}
|
||||
layerState._focusAfterActiveLookup = false;
|
||||
parts.panel.renderMissionPanel();
|
||||
layerState.coverageChanged();
|
||||
layerState._entryCameraView = null;
|
||||
} catch (error) {
|
||||
if (layerState._enabled && token === layerState._lifecycleToken) {
|
||||
|
||||
@@ -74,7 +74,9 @@ export function createLaunchPad({
|
||||
}
|
||||
const nowMs = Date.now();
|
||||
if (nowMs - layerState._lastMissionRingRotationMs >= 1000) {
|
||||
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(nowMs);
|
||||
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(
|
||||
layerState.orbitNow(),
|
||||
);
|
||||
layerState._lastMissionRingRotationMs = nowMs;
|
||||
}
|
||||
const launch = layerState._launches.find(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { followOnDoubleClick } from '../../data/stockFollow.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
|
||||
const HOVER_PICK_INTERVAL_MS = 120;
|
||||
|
||||
@@ -155,6 +156,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) {
|
||||
@@ -233,6 +249,7 @@ export function createLifecycle({
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
async _enableBody() {
|
||||
@@ -300,6 +317,7 @@ export function createLifecycle({
|
||||
parts.overlays.clearMissionOverlaySources();
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
parts.panel.renderMissionPanel();
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
async destroy(viewer) {
|
||||
|
||||
@@ -113,6 +113,9 @@ export function createOrbitRendering({
|
||||
return Boolean(
|
||||
layerState._enabled &&
|
||||
parts.rendering.missionsShown() &&
|
||||
!layerState.launchHidden(
|
||||
layerState._missionOverlayRecords.get(launchId)?.launch,
|
||||
) &&
|
||||
(!layerState._selectedLaunchId ||
|
||||
layerState._selectedLaunchId === launchId),
|
||||
);
|
||||
|
||||
@@ -404,8 +404,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,
|
||||
|
||||
@@ -142,7 +142,9 @@ export function createRendering({
|
||||
sites: draw.points({ id: setIds.sites, show: false }),
|
||||
markers: draw.points({ id: setIds.markers, show: false }),
|
||||
reticles: draw.icons({ id: setIds.reticles, show: false }),
|
||||
orbits: draw.lines({ id: setIds.orbits }),
|
||||
// Their inertial rings turn at the frame's time, the world time the
|
||||
// sky is drawn at, so away from live they sit under the payload.
|
||||
orbits: draw.lines({ id: setIds.orbits, motionClock: { kind: 'scene' } }),
|
||||
pad: draw.shapes({ id: setIds.pad }),
|
||||
};
|
||||
layerState._missionSets = sets;
|
||||
@@ -265,6 +267,25 @@ export function createRendering({
|
||||
return layerState._replayTracks.get(launchId)?.projectedOrbitPath ?? null;
|
||||
}
|
||||
|
||||
// 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 (followSampled) followSampled = false;
|
||||
else frameNumber += 1;
|
||||
@@ -272,25 +293,34 @@ export function createRendering({
|
||||
parts.overlays.hideReplayVehicleOverlay();
|
||||
return;
|
||||
}
|
||||
syncPendingLaunches();
|
||||
parts.panel.updateMissionTelemetry();
|
||||
const eye = findCamera(layerState._viewer)?.pose().position;
|
||||
const occluder = eye ? horizonFrom(eye) : null;
|
||||
parts.overlays.updateReplayVehicleOverlay(occluder);
|
||||
parts.overlays.refreshSelectedMissionOverlayText();
|
||||
for (const record of records.values()) {
|
||||
if (!record.isolated || !record.position) continue;
|
||||
if (!record.isolated) continue;
|
||||
// Away from live, a launch shows from its lift-off on.
|
||||
const pending = layerState._pendingLaunchIds.has(record.launchId);
|
||||
if (!record.position) {
|
||||
record.graphicShow = !pending;
|
||||
refresh(record);
|
||||
continue;
|
||||
}
|
||||
const live = typeof record.position === 'function';
|
||||
const position = live ? record.position() : record.position;
|
||||
let horizonVisible = Boolean(
|
||||
position && occluder?.isPointVisible(position),
|
||||
);
|
||||
let horizonVisible =
|
||||
!pending && Boolean(position && occluder?.isPointVisible(position));
|
||||
if (record.id.startsWith('rocket-launch:')) {
|
||||
horizonVisible = parts.overlays.missionAnchorVisible(
|
||||
eye,
|
||||
position,
|
||||
record.launchId,
|
||||
layerState._selectedLaunchId,
|
||||
);
|
||||
horizonVisible =
|
||||
!pending &&
|
||||
parts.overlays.missionAnchorVisible(
|
||||
eye,
|
||||
position,
|
||||
record.launchId,
|
||||
layerState._selectedLaunchId,
|
||||
);
|
||||
// The selection's isolation stays its own; horizon state is kept
|
||||
// apart, so a rear-side anchor is judged again as the camera moves.
|
||||
}
|
||||
@@ -643,7 +673,7 @@ export function createRendering({
|
||||
orbitCurrent.latitude,
|
||||
orbitCurrent.altitude,
|
||||
);
|
||||
const liveTime = new Date();
|
||||
const liveTime = new Date(layerState.orbitNow());
|
||||
const liveTelemetry = {
|
||||
speedMps: null,
|
||||
// Where the payload draws now, for the mission panel.
|
||||
@@ -661,7 +691,7 @@ export function createRendering({
|
||||
const updateLiveState = () => {
|
||||
if (frameNumber !== 0 && frameNumber === liveFrameNumber) return;
|
||||
liveFrameNumber = frameNumber;
|
||||
const nowMs = Date.now();
|
||||
const nowMs = layerState.orbitNow();
|
||||
liveTime.setTime(nowMs);
|
||||
if (satelliteTrack) {
|
||||
const propagated =
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
services.overlays;
|
||||
@@ -147,6 +149,38 @@ export function createState({ services }) {
|
||||
|
||||
state._missionOrbitPrimitives = new Map();
|
||||
|
||||
/** 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._pathDistanceCache = new WeakMap();
|
||||
state._sourceController = new AbortController();
|
||||
return state;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// 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 { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
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',
|
||||
name: 'Ceres-1',
|
||||
lon: 0,
|
||||
lat: 0,
|
||||
launchTime: new Date(LAUNCH_MS).toISOString(),
|
||||
status: 'Launch Successful',
|
||||
recoveryStages: [],
|
||||
trajectory: [
|
||||
{ latitude: 0, longitude: 0 },
|
||||
{ latitude: 1, longitude: 1 },
|
||||
],
|
||||
};
|
||||
const viewer = { scene: {} };
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera: {
|
||||
pose: () => ({ position: { x: 2e7, y: 0, z: 0 } }),
|
||||
on: () => () => {},
|
||||
},
|
||||
});
|
||||
t.after(unbind);
|
||||
state._enabled = true;
|
||||
state._viewer = viewer;
|
||||
const syncs = { labels: 0, orbits: 0 };
|
||||
const parts = {
|
||||
model: { missionMarkerColor: () => [1, 1, 1, 1] },
|
||||
policyHelpers: { launchStatusAllowsOrbit: () => false },
|
||||
paths: { surfaceSafePath: (positions) => positions },
|
||||
panel: { updateMissionTelemetry: noop },
|
||||
overlays: {
|
||||
missionHoverReticleImage: () => ({}),
|
||||
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 });
|
||||
rendering.attach(viewer);
|
||||
rendering.showMissions(true);
|
||||
rendering.addLaunchEntity(launch, null);
|
||||
rendering.flushLaunchEntities();
|
||||
// The drawn item by id, across the mission sets.
|
||||
const item = (id) => {
|
||||
for (const record of draw.sets.values())
|
||||
if (!record.disposed && record.items.has(id)) return record.items.get(id);
|
||||
return null;
|
||||
};
|
||||
assert.ok(item(`rocket-launch:${launch.id}`), 'the marker is drawn');
|
||||
assert.ok(item(`rocket-trajectory:${launch.id}:0`), 'the path is drawn');
|
||||
const shown = () => {
|
||||
rendering.updateMissionFrame();
|
||||
return {
|
||||
marker: item(`rocket-launch:${launch.id}`).show,
|
||||
path: item(`rocket-trajectory:${launch.id}:0`).show,
|
||||
};
|
||||
};
|
||||
return { state, rendering, launch, syncs, shown, draw };
|
||||
}
|
||||
|
||||
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, rendering, launch, shown } = scene(t);
|
||||
state._selectedLaunchId = launch.id;
|
||||
rendering.isolateMission(launch.id);
|
||||
worldClock.seek(LAUNCH_MS - 60_000);
|
||||
assert.deepEqual(shown(), { marker: true, path: true });
|
||||
});
|
||||
|
||||
test('the live orbit rings turn at the frame time, not the wall clock', (t) => {
|
||||
const { draw } = scene(t);
|
||||
const orbits = [...draw.sets.values()].find((record) =>
|
||||
record.spec.id.endsWith(':orbits'),
|
||||
);
|
||||
assert.deepEqual(orbits.spec.motionClock, { kind: 'scene' });
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { eastNorthUp, framePoint } from '../../geo/frames.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThan,
|
||||
julianNow,
|
||||
julianFromEpochMs,
|
||||
secondsDifference,
|
||||
} from '../../geo/julian.js';
|
||||
import {
|
||||
@@ -125,7 +125,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 = addSeconds(
|
||||
julianNow(),
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -219,7 +219,7 @@ export function createMotion({
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = addSeconds(
|
||||
julianNow(),
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createMilitaryFeed } from './ingestion.js';
|
||||
import { worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
const { createGroundSnap } = services.groundSnap;
|
||||
@@ -9,6 +10,8 @@ export function createFlightState({ source, services }) {
|
||||
...services.geoid,
|
||||
...services.groundFloor,
|
||||
});
|
||||
/** 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
|
||||
|
||||
@@ -21,7 +21,7 @@ import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianNow,
|
||||
julianFromEpochMs,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
@@ -561,7 +561,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 = addSeconds(
|
||||
julianNow(),
|
||||
julianFromEpochMs(flightState.now()),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
|
||||
@@ -34,7 +34,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) {
|
||||
@@ -156,6 +156,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)`,
|
||||
@@ -220,6 +221,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
layerState._denseCursor = 0;
|
||||
layerState._count = layerState._points.size;
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
}
|
||||
return {
|
||||
_abortActiveUpdates,
|
||||
|
||||
Vendored
+4
-1
@@ -190,7 +190,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 {
|
||||
|
||||
@@ -100,7 +100,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 = [];
|
||||
@@ -181,6 +181,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');
|
||||
|
||||
@@ -34,6 +34,8 @@ function ingestionFor(catalogText) {
|
||||
_denseLoadToken: 0,
|
||||
_catalogRevision: 0,
|
||||
_params: { catalog: 'core', showOrbits: false },
|
||||
now: Date.now,
|
||||
coverageChanged() {},
|
||||
};
|
||||
const parts = {
|
||||
orbits: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { frameOf } from '../../render/rendererOf.js';
|
||||
import { ISS_OVERLAY_SOURCE_ID } from './policy.js';
|
||||
import { ISS_OVERLAY_SOURCE_ID, SATELLITE_COVERAGE_MS } from './policy.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
@@ -8,6 +9,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;
|
||||
|
||||
@@ -53,6 +68,7 @@ export function createLifecycle({
|
||||
layerState._denseStatus = 'idle';
|
||||
layerState._denseError = null;
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
|
||||
// The sets the satellite dots, the tracked dot and the rings draw in
|
||||
parts.rendering._attach(viewer);
|
||||
@@ -95,6 +111,7 @@ export function createLifecycle({
|
||||
layerState._preRenderListener = onEachFrame(frameOf(viewer));
|
||||
}
|
||||
parts.tracking._applyPendingTrackingRestore();
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
disable(viewer) {
|
||||
@@ -119,6 +136,7 @@ export function createLifecycle({
|
||||
layerState._preRenderListener();
|
||||
layerState._preRenderListener = null;
|
||||
}
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
destroy(viewer) {
|
||||
@@ -168,6 +186,7 @@ export function createLifecycle({
|
||||
failedGroups: [],
|
||||
};
|
||||
layerState._viewer = null;
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -176,6 +176,7 @@ test('the rendering part draws the dots, the tracked dot and the rings through t
|
||||
const { draw, unbind } = bindFakeDraw(viewer);
|
||||
try {
|
||||
const state = {
|
||||
now: Date.now,
|
||||
_points: new Map(),
|
||||
_orbitPaths: new Map(),
|
||||
_catalog: new Map([[25544, { satrec: {} }]]),
|
||||
@@ -357,6 +358,7 @@ test('the focus pass projects every dot in one call and dims the dot under the f
|
||||
cameraDistance: 1,
|
||||
};
|
||||
const state = {
|
||||
now: Date.now,
|
||||
_points: new Map(),
|
||||
_orbitPaths: new Map(),
|
||||
_catalog: new Map(),
|
||||
|
||||
@@ -111,7 +111,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,
|
||||
@@ -141,7 +141,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
lonDeg,
|
||||
minElevDeg = 10,
|
||||
requireVisible = false,
|
||||
fromMs = Date.now(),
|
||||
fromMs = layerState.now(),
|
||||
},
|
||||
) {
|
||||
const id = Number(noradId);
|
||||
@@ -245,7 +245,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 {
|
||||
|
||||
@@ -28,6 +28,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;
|
||||
|
||||
@@ -79,7 +79,7 @@ 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;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
|
||||
import { fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
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';
|
||||
|
||||
/**
|
||||
* The satellites layer's drawing, through the renderer contract's draw port:
|
||||
@@ -407,12 +412,14 @@ 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 base = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
|
||||
if (base.length < 2) return;
|
||||
|
||||
const pathColor = color || DEFAULT_RING_COLOR;
|
||||
const path = {
|
||||
color: pathColor,
|
||||
bakeMs: bakeDate.getTime(),
|
||||
base,
|
||||
// Same Date object as computeOrbitPath's internal fixedGmst → identical
|
||||
// GMST value (gstime is pure), so the ring starts unturned.
|
||||
@@ -461,7 +468,14 @@ export function createRendering({
|
||||
if (layerState._orbitPaths.size === 0) return;
|
||||
const gmst = gstime(nowDate);
|
||||
const changed = [];
|
||||
for (const path of layerState._orbitPaths.values()) {
|
||||
for (const [noradId, path] of [...layerState._orbitPaths]) {
|
||||
// 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;
|
||||
}
|
||||
path.item.positions = _ringPositions(path, gmst);
|
||||
changed.push(path.item);
|
||||
}
|
||||
@@ -486,7 +500,7 @@ export function createRendering({
|
||||
*/
|
||||
|
||||
function _propagateAll() {
|
||||
const now = new Date();
|
||||
const now = new Date(layerState.now());
|
||||
let updated = 0;
|
||||
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
@@ -578,7 +592,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
services.overlays;
|
||||
@@ -150,6 +152,14 @@ export function createState({ services }) {
|
||||
|
||||
state._trackedFrameNowForTest = null;
|
||||
|
||||
/** 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();
|
||||
|
||||
/** Update the explicit model only when the rounded altitude line changes. */
|
||||
/** Epoch of the last shared-context refresh for the tracked satellite. */
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
sat.satrec,
|
||||
layerState._trackedFrameNowForTest
|
||||
? new Date(layerState._trackedFrameNowForTest())
|
||||
: new Date(),
|
||||
: new Date(layerState.now()),
|
||||
);
|
||||
if (!pos) return layerState._trackedFrameGeo; // propagation hiccup — keep last good sample
|
||||
layerState._trackedFrameGeo = pos;
|
||||
@@ -426,7 +426,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
|
||||
|
||||
@@ -7,6 +7,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,
|
||||
@@ -45,6 +46,9 @@ const GROUND_RETRY_MS = 1000;
|
||||
* the caller loads the package's `./render/cesium/unbound` export first.
|
||||
* @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 = {},
|
||||
@@ -97,7 +101,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,
|
||||
@@ -375,7 +379,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();
|
||||
|
||||
@@ -4206,6 +4206,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({
|
||||
|
||||
@@ -488,7 +488,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);
|
||||
}
|
||||
}
|
||||
@@ -535,7 +535,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);
|
||||
flushMarkers();
|
||||
@@ -775,7 +775,7 @@ export function createRendering({ state, services, parts }) {
|
||||
return;
|
||||
if (!state._enabled) return;
|
||||
forgetView();
|
||||
const now = Date.now();
|
||||
const now = state.now();
|
||||
if (state._vehicles.size === 0) {
|
||||
state._moving.clear();
|
||||
syncRenderHold();
|
||||
@@ -811,7 +811,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)) {
|
||||
const marker = selected.marker;
|
||||
@@ -891,7 +891,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());
|
||||
}
|
||||
const center =
|
||||
state._visible.has(entry) || !entry.sample
|
||||
@@ -964,7 +964,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,4 +1,5 @@
|
||||
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,
|
||||
@@ -13,6 +14,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,
|
||||
|
||||
+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');
|
||||
});
|
||||
@@ -59,7 +59,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,
|
||||
@@ -113,7 +114,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 = () =>
|
||||
@@ -215,7 +217,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