mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Main brings satellites and vessels moving every frame, smooth rewind for contacts, global clouds drawn to the level a feed names, and search for degrees-minutes-seconds, UTM, MGRS and plus codes. They keep this branch's renderer work: satellites write their reckoned positions into the points set once a frame; vessels move every frame and ask for frames from the camera pose and canvas, and a vessel not there yet is hidden through its icon; flights and military keep the branch's rendering, with main's timeline fixes, trail top-up and grounded lift; the cloud tiles keep their infrared transfer. The timeline history module uses the geo helpers instead of Cesium, and main's new tests use the draw port's items.
This commit is contained in:
commit
4b47d5e058
49 files changed
+3367
-348
No files matched your search
@@ -0,0 +1,180 @@
|
||||
import {
|
||||
fromDegrees,
|
||||
fromRadians,
|
||||
toCartographicRadians,
|
||||
} from '../geo/ellipsoid.js';
|
||||
import {
|
||||
julianFromEpochMs,
|
||||
julianLessThan,
|
||||
secondsDifference,
|
||||
} from '../geo/julian.js';
|
||||
import { clone, copyInto, toDegrees, toRadians } from '../geo/vector.js';
|
||||
import {
|
||||
mergeTimelineRuns,
|
||||
readTimelineFixes,
|
||||
TIMELINE_UNSEEN_MS,
|
||||
} from '../time/timelineFixes.js';
|
||||
|
||||
/** Fixes nearer than this are too close to read a course between. */
|
||||
const COURSE_MIN_M = 5;
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
|
||||
/** The initial great-circle course from one fix to another (degrees from
|
||||
* north), or null when they are too close to tell. */
|
||||
function courseBetween(from, to) {
|
||||
const lat1 = toRadians(from.lat);
|
||||
const lat2 = toRadians(to.lat);
|
||||
const dLon = toRadians(to.lon - from.lon);
|
||||
const dLat = lat2 - lat1;
|
||||
const a =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||||
if (2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(a))) < COURSE_MIN_M)
|
||||
return null;
|
||||
const y = Math.sin(dLon) * Math.cos(lat2);
|
||||
const x =
|
||||
Math.cos(lat1) * Math.sin(lat2) -
|
||||
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
|
||||
return (toDegrees(Math.atan2(y, x)) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's motion history with the fixes its record carries at a time
|
||||
* (`observation.fixes`, see src/time/timelineFixes.js) merged in, so the
|
||||
* layer places it on its own track at any time they span; null when the
|
||||
* record carries none. Each fix is drawn at the record's render height,
|
||||
* moved by the fix's own barometric change from the record's, and heads
|
||||
* where its track goes next (the last, where it came from). Entries are
|
||||
* marked `timeline`.
|
||||
* @param {object[]|undefined} history The contact's history entries.
|
||||
* @param {object} observation The record, with `fixes` and `baroAltitudeM`.
|
||||
* @param {{renderAltitudeM: number, renderAltitudeInvented?: boolean}} meta
|
||||
* @param {number|null} velocity The record's ground speed (m/s).
|
||||
* @param {number} centreMs The snapshot's time: the fixes kept are nearest it.
|
||||
* @returns {object[]|null}
|
||||
*/
|
||||
export function mergeAircraftTimelineFixes(
|
||||
history,
|
||||
observation,
|
||||
meta,
|
||||
velocity,
|
||||
centreMs,
|
||||
) {
|
||||
const fixes = readTimelineFixes(observation?.fixes);
|
||||
if (!fixes) return null;
|
||||
const baroM = Number.isFinite(observation.baroAltitudeM)
|
||||
? observation.baroAltitudeM
|
||||
: null;
|
||||
const entries = fixes.map((fix, index) => {
|
||||
const course =
|
||||
index + 1 < fixes.length
|
||||
? courseBetween(fix, fixes[index + 1])
|
||||
: courseBetween(fixes[index - 1], fix);
|
||||
return {
|
||||
time: julianFromEpochMs(fix.atMs),
|
||||
epochMs: fix.atMs,
|
||||
position: fromDegrees(
|
||||
fix.lon,
|
||||
fix.lat,
|
||||
baroM !== null && fix.altitudeM !== null
|
||||
? meta.renderAltitudeM + (fix.altitudeM - baroM)
|
||||
: meta.renderAltitudeM,
|
||||
),
|
||||
velocity,
|
||||
// No reported track per fix: the course is read from the fixes.
|
||||
track: course ?? undefined,
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
timeline: true,
|
||||
};
|
||||
});
|
||||
return mergeTimelineRuns(
|
||||
history ?? [],
|
||||
entries,
|
||||
(entry) => entry.epochMs,
|
||||
centreMs,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The index of the first history entry at or after `renderTime` (the last
|
||||
* entry when none is), by halving: a contact following the clock keeps up to
|
||||
* TIMELINE_FIXES_LIMIT entries, and it is placed on every fleet tick. The
|
||||
* bracketing pair is the entry before it and it.
|
||||
* @param {Array<{time: {dayNumber: number, secondsOfDay: number}}>} history
|
||||
* In time order (Julian dates, geo/julian).
|
||||
* @param {{dayNumber: number, secondsOfDay: number}} renderTime
|
||||
* @returns {number}
|
||||
*/
|
||||
export function historyBracketIndex(history, renderTime) {
|
||||
let low = 0;
|
||||
let high = history.length - 1;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (julianLessThan(history[mid].time, renderTime)) low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact following the clock is not to be drawn at `renderTime`:
|
||||
* its history is its own fixes around the time (`timeline` entries), and the
|
||||
* time is more than TIMELINE_UNSEEN_MS before the first, when it was not
|
||||
* there yet.
|
||||
* @param {Array<{time: {dayNumber: number, secondsOfDay: number},
|
||||
* timeline?: boolean}>|undefined} history
|
||||
* @param {{dayNumber: number, secondsOfDay: number}} renderTime
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function historyUnseenAt(history, renderTime) {
|
||||
const first = history?.[0];
|
||||
return (
|
||||
first?.timeline === true &&
|
||||
secondsDifference(first.time, renderTime) > TIMELINE_UNSEEN_MS / 1000
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift a grounded contact's history onto the floor: its newest fix to
|
||||
* `position`, or, when the history is its own fixes around the time
|
||||
* (`timeline` entries, the newest of them later than the time drawn), every
|
||||
* fix by the lift from `fromM` to `toM`, so it is not drawn rising to it.
|
||||
* @param {object[]|undefined} history
|
||||
* @param {{x: number, y: number, z: number}} position The newest fix lifted (ECEF).
|
||||
* @param {number|null} fromM The height it was drawn at.
|
||||
* @param {number} toM The height it is lifted to.
|
||||
*/
|
||||
export function liftGroundedHistory(history, position, fromM, toM) {
|
||||
const newest = history?.[history.length - 1];
|
||||
if (!newest) return;
|
||||
if (history[0].timeline !== true || !Number.isFinite(fromM)) {
|
||||
newest.position = newest.position
|
||||
? copyInto(position, newest.position)
|
||||
: clone(position);
|
||||
return;
|
||||
}
|
||||
for (const entry of history) {
|
||||
const carto = toCartographicRadians(entry.position);
|
||||
if (!carto) continue;
|
||||
copyInto(
|
||||
fromRadians(carto.lon, carto.lat, carto.height + (toM - fromM)),
|
||||
entry.position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The history entries a tracked contact's trail has yet to take: those after
|
||||
* its newest point (`trail` entries have `timeMs`) up to `untilMs`, the
|
||||
* snapshot's time, so the trail grows as the snapshots bring fixes.
|
||||
* @param {Array<{epochMs: number}>} history
|
||||
* @param {Array<{timeMs: number}>} trail
|
||||
* @param {number} untilMs
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function historyAfterTrail(history, trail, untilMs) {
|
||||
const lastMs = trail.length ? trail[trail.length - 1].timeMs : -Infinity;
|
||||
return history.filter(
|
||||
(entry) => entry.epochMs > lastMs && entry.epochMs <= untilMs,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
historyBracketIndex,
|
||||
historyUnseenAt,
|
||||
liftGroundedHistory,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from './timelineHistory.js';
|
||||
|
||||
const META = { renderAltitudeM: 3_000 };
|
||||
const fix = (atMs, lat, altitudeM = null, lon = 0) => ({
|
||||
atMs,
|
||||
lat,
|
||||
lon,
|
||||
altitudeM,
|
||||
});
|
||||
const julian = (ms) => Cesium.JulianDate.fromDate(new Date(ms));
|
||||
|
||||
test('an aircraft with no fixes merges nothing', () => {
|
||||
assert.equal(
|
||||
mergeAircraftTimelineFixes([], { fixes: null }, META, 100, 0),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("an aircraft's fixes join its history in order, each at the render height moved by its own climb", () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
baroAltitudeM: 1_000,
|
||||
fixes: [fix(120_000, 1, 1_200), fix(60_000, 0, 1_000), fix(180_000, 2)],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
history.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000],
|
||||
);
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
assert.ok(Math.abs(height(history[0]) - 3_000) < 1e-3);
|
||||
assert.ok(Math.abs(height(history[1]) - 3_200) < 1e-3);
|
||||
assert.ok(
|
||||
Math.abs(height(history[2]) - 3_000) < 1e-3,
|
||||
'no altitude: the render height',
|
||||
);
|
||||
// A later snapshot's fixes add to the earlier ones.
|
||||
const more = mergeAircraftTimelineFixes(
|
||||
history,
|
||||
{ baroAltitudeM: 1_000, fixes: [fix(180_000, 2), fix(240_000, 3)] },
|
||||
META,
|
||||
100,
|
||||
180_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
more.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000, 240_000],
|
||||
);
|
||||
});
|
||||
|
||||
test('the bracketing entry is the first at or after the time, else the last', () => {
|
||||
const history = [1_000, 2_000, 3_000].map((ms) => ({
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
}));
|
||||
const at = (ms) =>
|
||||
historyBracketIndex(history, Cesium.JulianDate.fromDate(new Date(ms)));
|
||||
assert.equal(at(500), 0);
|
||||
assert.equal(at(1_000), 0);
|
||||
assert.equal(at(1_500), 1);
|
||||
assert.equal(at(3_000), 2);
|
||||
assert.equal(at(9_000), 2);
|
||||
});
|
||||
|
||||
test('each fix heads where the track goes next, the last where it came from', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
fixes: [
|
||||
fix(0, 0, null, 0),
|
||||
fix(60_000, 0, null, 0.01),
|
||||
fix(120_000, 0.01, null, 0.01),
|
||||
fix(180_000, 0.01, null, 0.01),
|
||||
],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
0,
|
||||
);
|
||||
const tracks = history.map((entry) => entry.track);
|
||||
assert.ok(Math.abs(tracks[0] - 90) < 0.5, 'east');
|
||||
assert.ok(Math.abs(tracks[1]) < 0.5, 'north');
|
||||
assert.equal(tracks[2], undefined, 'no move to read');
|
||||
assert.equal(tracks[3], undefined);
|
||||
assert.ok(history.every((entry) => entry.timeline === true));
|
||||
});
|
||||
|
||||
test('a contact is unseen only well before the first of its own fixes', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(600_000, 0), fix(660_000, 1)] },
|
||||
META,
|
||||
100,
|
||||
600_000,
|
||||
);
|
||||
assert.equal(historyUnseenAt(history, julian(0)), true);
|
||||
assert.equal(historyUnseenAt(history, julian(560_000)), false);
|
||||
const live = [{ time: julian(600_000) }];
|
||||
assert.equal(historyUnseenAt(live, julian(0)), false, 'not on its fixes');
|
||||
assert.equal(historyUnseenAt(undefined, julian(0)), false);
|
||||
});
|
||||
|
||||
test('a grounded contact on its own fixes is lifted whole; else its newest fix', () => {
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 0.001)] },
|
||||
{ renderAltitudeM: 5 },
|
||||
0,
|
||||
0,
|
||||
);
|
||||
const lifted = Cesium.Cartesian3.fromDegrees(0, 0.001, 30);
|
||||
liftGroundedHistory(history, lifted, 5, 30);
|
||||
assert.ok(history.every((entry) => Math.abs(height(entry) - 30) < 1e-3));
|
||||
const live = [
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0, 5) },
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0.001, 5) },
|
||||
];
|
||||
liftGroundedHistory(live, lifted, 5, 30);
|
||||
assert.ok(Math.abs(height(live[0]) - 5) < 1e-3);
|
||||
assert.ok(Math.abs(height(live[1]) - 30) < 1e-3);
|
||||
});
|
||||
|
||||
test("a tracked trail takes the fixes after its newest point, up to the snapshot's time", () => {
|
||||
const history = [0, 60_000, 120_000, 180_000].map((epochMs) => ({ epochMs }));
|
||||
assert.deepEqual(
|
||||
historyAfterTrail(history, [{ timeMs: 60_000 }], 120_000).map(
|
||||
(entry) => entry.epochMs,
|
||||
),
|
||||
[120_000],
|
||||
);
|
||||
assert.equal(historyAfterTrail(history, [], 120_000).length, 3);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import { liftGroundedHistory } from '../../data/timelineHistory.js';
|
||||
import {
|
||||
motionCourse,
|
||||
motionPosition,
|
||||
@@ -185,11 +186,15 @@ export function createMotion({
|
||||
info.renderAltitudeM >= floor - 1
|
||||
)
|
||||
continue;
|
||||
const drawnM = info.renderAltitudeM;
|
||||
info.renderAltitudeM = lifted;
|
||||
const position = fromDegrees(info.rawLon, info.rawLat, lifted);
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history?.[history.length - 1];
|
||||
if (newest) newest.position = copyInto(position, newest.position);
|
||||
liftGroundedHistory(
|
||||
flightState._positionHistory.get(icao24),
|
||||
position,
|
||||
drawnM,
|
||||
lifted,
|
||||
);
|
||||
// Above the ellipsoid now (or floors say otherwise next poll).
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
parts.icons._planIcon(icao24);
|
||||
@@ -213,6 +218,7 @@ export function createMotion({
|
||||
|
||||
function _deadReckon(icao24, result, sampledRenderTime) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
flightState._drUnseen = false;
|
||||
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
|
||||
const position = parts.icons._iconPosition(icao24, vec());
|
||||
flightState._drCourseDeg = info?.true_track || 0;
|
||||
@@ -256,6 +262,9 @@ export function createMotion({
|
||||
);
|
||||
|
||||
const regime = _motionRegime(history, info, renderTime);
|
||||
// Following the clock, a time well before its first fix is before it
|
||||
// was there: it is not drawn.
|
||||
flightState._drUnseen = regime.unseen;
|
||||
if (regime.kind === 'between' && regime.piece) {
|
||||
// Along the curve between the two reports, as the icon and the trail.
|
||||
const ms = julianToEpochMs(renderTime);
|
||||
|
||||
@@ -9,6 +9,10 @@ import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
|
||||
import { observeLiveAircraft } from './placed.js';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from '../../data/timelineHistory.js';
|
||||
|
||||
/**
|
||||
* Note how late each report in a live snapshot is, and aim the display delay
|
||||
@@ -114,6 +118,18 @@ export function createFlightSnapshotRenderer({
|
||||
}
|
||||
const isTracked = icao24 === flightState._trackedIcao;
|
||||
|
||||
// Following the clock, a record may carry its own track around the
|
||||
// time: the contact is placed on it, so the clock can move within it,
|
||||
// back as well as on, without another snapshot.
|
||||
const timelineHistory = followsClock(flightState)
|
||||
? mergeAircraftTimelineFixes(
|
||||
flightState._positionHistory.get(icao24),
|
||||
observation,
|
||||
meta,
|
||||
meta.velocity,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
)
|
||||
: null;
|
||||
// A host-supplied placement, if any, is told every fix as taken.
|
||||
observeLiveAircraft(
|
||||
flightState,
|
||||
@@ -124,91 +140,111 @@ export function createFlightSnapshotRenderer({
|
||||
meta.velocity,
|
||||
meta.true_track,
|
||||
);
|
||||
|
||||
// Append to position history stamped with the FEED's fix epoch
|
||||
// (time_position), not client receipt time — OpenSky positions arrive
|
||||
// 5-15s stale and receipt-time stamping is what caused the
|
||||
// back/forward oscillation. Only append when the fix actually
|
||||
// advances, so stale repeats don't create zero-dt segments.
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
const report = newestReport(history);
|
||||
// Whole milliseconds, as the fix times are kept. A report newer than
|
||||
// the last report goes in, past any synthetic fix after it.
|
||||
if (
|
||||
!report ||
|
||||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
|
||||
) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
pushReport(
|
||||
history,
|
||||
{
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.velocity,
|
||||
meta.true_track,
|
||||
),
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
// Whether this report was on the ground: a trail backfill joins it
|
||||
// only across a landing or take-off it saw.
|
||||
onGround: meta.onGround === true,
|
||||
},
|
||||
POSITION_HISTORY_LIMIT,
|
||||
);
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
|
||||
// so the visible trail keeps growing while tracked. Ground traffic
|
||||
// appends nothing — a touchdown freezes the existing trail.
|
||||
// Round 2 (owner): ground traffic appends too — taxi history stays
|
||||
// live after touchdown (grounded flights positions are already
|
||||
// surface-clamped via the surfaceM chain, so the ground leg drapes).
|
||||
if (timelineHistory) {
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
track: meta.true_track,
|
||||
});
|
||||
for (const entry of historyAfterTrail(
|
||||
timelineHistory,
|
||||
flightState._trailFixes,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
))
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(entry.position),
|
||||
entry.epochMs,
|
||||
{ nullAltitude: entry.inventedHeight, track: entry.track },
|
||||
);
|
||||
flightState._positionHistory.set(icao24, timelineHistory);
|
||||
meta.turnRateDps = 0;
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
// Append to position history stamped with the FEED's fix epoch
|
||||
// (time_position), not client receipt time — OpenSky positions arrive
|
||||
// 5-15s stale and receipt-time stamping is what caused the
|
||||
// back/forward oscillation. Only append when the fix actually
|
||||
// advances, so stale repeats don't create zero-dt segments.
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
// Apply fresh kinematics only from a forward synthetic fix. Mutating
|
||||
// the historical fix reprojects the entire stale interval and snaps
|
||||
// the rendered aircraft when course or speed changes late. The stale
|
||||
// rules apply: none for a contact that holds at its report, a coast
|
||||
// capped from the real report, never below the ground. It is a motion
|
||||
// aid, not a report, so it never joins the trail.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.velocity || newest.track !== meta.true_track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
const report = newestReport(history);
|
||||
// Whole milliseconds, as the fix times are kept. A report newer than
|
||||
// the last report goes in, past any synthetic fix after it.
|
||||
if (
|
||||
!report ||
|
||||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
|
||||
) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
pushReport(
|
||||
history,
|
||||
{
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.velocity,
|
||||
meta.true_track,
|
||||
),
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
// Whether this report was on the ground: a trail backfill joins it
|
||||
// only across a landing or take-off it saw.
|
||||
onGround: meta.onGround === true,
|
||||
},
|
||||
POSITION_HISTORY_LIMIT,
|
||||
);
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
|
||||
// so the visible trail keeps growing while tracked. Ground traffic
|
||||
// appends nothing — a touchdown freezes the existing trail.
|
||||
// Round 2 (owner): ground traffic appends too — taxi history stays
|
||||
// live after touchdown (grounded flights positions are already
|
||||
// surface-clamped via the surfaceM chain, so the ground leg drapes).
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(position),
|
||||
fixEpochMs,
|
||||
{
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
track: meta.true_track,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
}
|
||||
// Apply fresh kinematics only from a forward synthetic fix. Mutating
|
||||
// the historical fix reprojects the entire stale interval and snaps
|
||||
// the rendered aircraft when course or speed changes late. The stale
|
||||
// rules apply: none for a contact that holds at its report, a coast
|
||||
// capped from the real report, never below the ground. It is a motion
|
||||
// aid, not a report, so it never joins the trail.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.velocity ||
|
||||
newest.track !== meta.true_track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,6 +277,11 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drExtrapolating = false;
|
||||
|
||||
/** Set by `_deadReckon`: following the clock, the time drawn is well
|
||||
* before the contact's first fix, so the fleet pass does not draw it. */
|
||||
|
||||
flightState._drUnseen = false;
|
||||
|
||||
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
|
||||
|
||||
flightState._cachedDRCourse = null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import { liftGroundedHistory } from '../../data/timelineHistory.js';
|
||||
import {
|
||||
motionCourse,
|
||||
motionPosition,
|
||||
@@ -124,6 +125,7 @@ export function createMotion({
|
||||
*/
|
||||
|
||||
function _deadReckon(icao24, result, sampledRenderTime) {
|
||||
flightState._drUnseen = false;
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (!history || history.length === 0) {
|
||||
@@ -158,6 +160,9 @@ export function createMotion({
|
||||
);
|
||||
|
||||
const regime = _motionRegime(history, info, renderTime);
|
||||
// Following the clock, a time well before its first fix is before it
|
||||
// was there: it is not drawn.
|
||||
flightState._drUnseen = regime.unseen;
|
||||
if (regime.kind === 'between' && regime.piece) {
|
||||
// Along the curve between the two reports, as the icon and the trail.
|
||||
const ms = julianToEpochMs(renderTime);
|
||||
@@ -654,11 +659,14 @@ export function createMotion({
|
||||
info.renderAltitudeM >= floor - 1
|
||||
)
|
||||
continue;
|
||||
const drawnM = info.renderAltitudeM;
|
||||
info.renderAltitudeM = lifted;
|
||||
const liftedPos = fromDegrees(info.rawLon, info.rawLat, lifted);
|
||||
const hist = flightState._positionHistory.get(icao24);
|
||||
const newest = hist?.[hist.length - 1];
|
||||
if (newest) newest.position = copyInto(liftedPos, newest.position);
|
||||
liftGroundedHistory(
|
||||
flightState._positionHistory.get(icao24),
|
||||
fromDegrees(info.rawLon, info.rawLat, lifted),
|
||||
drawnM,
|
||||
lifted,
|
||||
);
|
||||
if (flightState._icons.has(icao24)) {
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
parts.icons._planIcon(icao24);
|
||||
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
staleHoldsForFix,
|
||||
synthesizeForwardKinematicsFix,
|
||||
} from '../../data/motionModel.js';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from '../../data/timelineHistory.js';
|
||||
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
|
||||
@@ -88,6 +92,18 @@ export function createMilitarySnapshotRenderer({
|
||||
if (groundFlipped) flightState._groundSnap.forget(icao24);
|
||||
const isTracked = icao24 === flightState._trackedIcao;
|
||||
|
||||
// Following the clock, a record may carry its own track around the
|
||||
// time: the contact is placed on it, so the clock can move within it,
|
||||
// back as well as on, without another snapshot.
|
||||
const timelineHistory = followsClock(flightState)
|
||||
? mergeAircraftTimelineFixes(
|
||||
flightState._positionHistory.get(icao24),
|
||||
aircraft,
|
||||
meta,
|
||||
meta.speedMps,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
)
|
||||
: null;
|
||||
// A host-supplied placement, if any, is told every fix as taken.
|
||||
observeLiveAircraft(
|
||||
flightState,
|
||||
@@ -98,87 +114,106 @@ export function createMilitarySnapshotRenderer({
|
||||
meta.speedMps,
|
||||
meta.track,
|
||||
);
|
||||
|
||||
// Append to position history stamped with the FEED's fix epoch.
|
||||
// adsb.lol's seen_pos is the AGE in seconds of the last position
|
||||
// report, so the fix epoch is receipt time minus that age. Only
|
||||
// append when the fix actually advances, so stale repeats don't
|
||||
// create zero-dt segments.
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
const report = newestReport(history);
|
||||
// Whole milliseconds, as the fix times are kept. A report newer than
|
||||
// the last report goes in, past any synthetic fix after it.
|
||||
if (
|
||||
!report ||
|
||||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
|
||||
) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
pushReport(
|
||||
history,
|
||||
{
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.speedMps,
|
||||
meta.track,
|
||||
),
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
// Whether this report was on the ground: a trail backfill joins it
|
||||
// only across a landing or take-off it saw.
|
||||
onGround: meta.onGround === true,
|
||||
},
|
||||
POSITION_HISTORY_LIMIT,
|
||||
);
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F2)
|
||||
// so the visible trail keeps growing while tracked. Round 2
|
||||
// (owner): ground traffic appends too — taxi history stays live
|
||||
// after touchdown; _appendTrailFix floors grounded positions at
|
||||
// the surface so the ground leg drapes instead of diving.
|
||||
if (timelineHistory) {
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(motion._copyPosition(position), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
track: meta.track,
|
||||
});
|
||||
for (const entry of historyAfterTrail(
|
||||
timelineHistory,
|
||||
flightState._trailFixes,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
))
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(entry.position),
|
||||
entry.epochMs,
|
||||
{ nullAltitude: entry.inventedHeight, track: entry.track },
|
||||
);
|
||||
flightState._positionHistory.set(icao24, timelineHistory);
|
||||
meta.turnRateDps = 0;
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
// Append to position history stamped with the FEED's fix epoch.
|
||||
// adsb.lol's seen_pos is the AGE in seconds of the last position
|
||||
// report, so the fix epoch is receipt time minus that age. Only
|
||||
// append when the fix actually advances, so stale repeats don't
|
||||
// create zero-dt segments.
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
// A forward synthetic fix follows the stale rules (none while the
|
||||
// contact holds at its report, a coast capped from the real report,
|
||||
// never below the ground) and is a motion aid, never a trail report.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.speedMps || newest.track !== meta.track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.speedMps,
|
||||
track: meta.track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
const report = newestReport(history);
|
||||
// Whole milliseconds, as the fix times are kept. A report newer than
|
||||
// the last report goes in, past any synthetic fix after it.
|
||||
if (
|
||||
!report ||
|
||||
Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(report))
|
||||
) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
pushReport(
|
||||
history,
|
||||
{
|
||||
...motion._historyFix(
|
||||
fixEpochMs,
|
||||
position,
|
||||
meta.speedMps,
|
||||
meta.track,
|
||||
),
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
// Whether this report was on the ground: a trail backfill joins it
|
||||
// only across a landing or take-off it saw.
|
||||
onGround: meta.onGround === true,
|
||||
},
|
||||
POSITION_HISTORY_LIMIT,
|
||||
);
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F2)
|
||||
// so the visible trail keeps growing while tracked. Round 2
|
||||
// (owner): ground traffic appends too — taxi history stays live
|
||||
// after touchdown; _appendTrailFix floors grounded positions at
|
||||
// the surface so the ground leg drapes instead of diving.
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(
|
||||
motion._copyPosition(position),
|
||||
fixEpochMs,
|
||||
{
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
track: meta.track,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
}
|
||||
// A forward synthetic fix follows the stale rules (none while the
|
||||
// contact holds at its report, a coast capped from the real report,
|
||||
// never below the ground) and is a motion aid, never a trail report.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.speedMps || newest.track !== meta.track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.speedMps,
|
||||
track: meta.track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history.slice(-5));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +232,11 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drCourseHold = false;
|
||||
|
||||
/** Set by `_deadReckon`: following the clock, the time drawn is well
|
||||
* before the contact's first fix, so the fleet pass does not draw it. */
|
||||
|
||||
flightState._drUnseen = false;
|
||||
|
||||
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
|
||||
|
||||
flightState._cachedDRCourse = null;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { twoline2satrec } from 'satellite.js';
|
||||
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { gstime, twoline2satrec } from 'satellite.js';
|
||||
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
import {
|
||||
DENSE_REFRESH_FRAMES,
|
||||
DENSE_GROUP_PATH,
|
||||
DENSE_SAMPLES_PER_FRAME_MAX,
|
||||
POINT_STYLES,
|
||||
DENSE_CREATE_CHUNK,
|
||||
ORBIT_SAMPLE_HORIZON_MS,
|
||||
} from './policy.js';
|
||||
|
||||
export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
// _movePoint copies the position, so one scratch point serves every move.
|
||||
const scratch = { x: 0, y: 0, z: 0 };
|
||||
function _abortActiveUpdates() {
|
||||
for (const controller of layerState._activeUpdateControllers)
|
||||
controller.abort();
|
||||
@@ -20,35 +20,42 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-propagate a small per-frame slice of the dense extras (round-robin).
|
||||
* Budget: the full dense set completes one pass every ~DENSE_REFRESH_FRAMES
|
||||
* frames (~5s at 60fps ≈ 1/5 of the core cadence), so per-frame cost stays
|
||||
* ~35 propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the
|
||||
* work per frame avoids the once-per-second spike a tick-sized chunk
|
||||
* (~2K props ≈ 4ms) would cause.
|
||||
* Sample a small per-frame slice of the dense extras (round-robin); every
|
||||
* point is then reckoned from its sample each frame (rendering.js
|
||||
* _reckonPoints). At normal speed the full dense set is sampled once every
|
||||
* ~DENSE_REFRESH_FRAMES frames (~5s at 60fps), so per-frame cost stays ~35
|
||||
* propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the work
|
||||
* per frame avoids the once-per-second spike a tick-sized chunk (~2K props
|
||||
* ≈ 4ms) would cause. While time plays fast, or after a seek, the slice
|
||||
* grows so each sample stays within ORBIT_SAMPLE_HORIZON_MS of the world
|
||||
* time, up to DENSE_SAMPLES_PER_FRAME_MAX a frame.
|
||||
* @param {number} worldStepMs How far the world time moved since the last
|
||||
* frame (NaN on the first).
|
||||
*/
|
||||
|
||||
function _propagateDenseChunk() {
|
||||
if (layerState._denseIds.length === 0) return;
|
||||
const perFrame = Math.max(
|
||||
1,
|
||||
Math.ceil(layerState._denseIds.length / DENSE_REFRESH_FRAMES),
|
||||
function _propagateDenseChunk(worldStepMs) {
|
||||
const count = layerState._denseIds.length;
|
||||
if (count === 0) return;
|
||||
const share = Math.max(
|
||||
1 / DENSE_REFRESH_FRAMES,
|
||||
Number.isFinite(worldStepMs)
|
||||
? Math.abs(worldStepMs) / ORBIT_SAMPLE_HORIZON_MS
|
||||
: 1,
|
||||
);
|
||||
const now = new Date(layerState.now());
|
||||
const perFrame = Math.min(
|
||||
count,
|
||||
DENSE_SAMPLES_PER_FRAME_MAX,
|
||||
Math.max(1, Math.ceil(count * share)),
|
||||
);
|
||||
const nowMs = layerState.now();
|
||||
for (let i = 0; i < perFrame; i++) {
|
||||
if (layerState._denseCursor >= layerState._denseIds.length)
|
||||
layerState._denseCursor = 0;
|
||||
if (layerState._denseCursor >= count) layerState._denseCursor = 0;
|
||||
const noradId = layerState._denseIds[layerState._denseCursor++];
|
||||
if (noradId === layerState._trackedNorad) continue; // per-frame tracked path owns it
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
if (!sat || !layerState._points.has(noradId)) continue;
|
||||
const pos = parts.orbits.propagatePosition(sat.satrec, now);
|
||||
if (pos) {
|
||||
parts.rendering._movePoint(
|
||||
noradId,
|
||||
fromDegreesInto(pos.longitude, pos.latitude, pos.altitude, scratch),
|
||||
);
|
||||
}
|
||||
if (!sat) continue;
|
||||
const sample = sampleOrbit(sat.satrec, nowMs, sat.orbitSample);
|
||||
if (sample) sat.orbitSample = sample;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +104,8 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
|
||||
const entries = parts.orbits.parseTLE(text);
|
||||
const style = POINT_STYLES.dense;
|
||||
const now = new Date(layerState.now());
|
||||
const nowMs = layerState.now();
|
||||
const gmst = gstime(new Date(nowMs));
|
||||
let added = 0;
|
||||
|
||||
for (let start = 0; start < entries.length; start += DENSE_CREATE_CHUNK) {
|
||||
@@ -116,8 +124,9 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
if (!satrec || satrec.error !== 0) continue;
|
||||
const noradId = noradIdFromSatnum(satrec.satnum);
|
||||
if (layerState._catalog.has(noradId)) continue; // core catalog keeps priority
|
||||
const pos = parts.orbits.propagatePosition(satrec, now);
|
||||
if (!pos) continue;
|
||||
// Its first sample places it now and moves it from then on.
|
||||
const orbitSample = sampleOrbit(satrec, nowMs);
|
||||
if (!orbitSample) continue;
|
||||
|
||||
layerState._catalog.set(noradId, {
|
||||
name: entry.name,
|
||||
@@ -131,10 +140,11 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
ucs: null,
|
||||
satcat: null,
|
||||
sensor: null,
|
||||
orbitSample,
|
||||
});
|
||||
parts.rendering._addPoint(
|
||||
noradId,
|
||||
fromDegrees(pos.longitude, pos.latitude, pos.altitude),
|
||||
reckonEarthFixed(orbitSample, nowMs, gmst, { x: 0, y: 0, z: 0 }),
|
||||
style,
|
||||
);
|
||||
layerState._denseIds.push(noradId);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { propagate } from 'satellite.js';
|
||||
|
||||
/** The Earth's gravitational parameter, km³/s², as SGP4's WGS72 constants. */
|
||||
const MU_KM3_S2 = 398600.8;
|
||||
|
||||
/** Floats in one orbit sample: its time, then position, velocity,
|
||||
* acceleration and jerk. */
|
||||
export const ORBIT_SAMPLE_LENGTH = 13;
|
||||
|
||||
/**
|
||||
* One SGP4 state of a satellite for dead reckoning: its inertial (TEME)
|
||||
* position and velocity at `atMs`, with the two-body acceleration and its
|
||||
* rate of change (jerk) there.
|
||||
* Layout: [atMs, rx, ry, rz (km), vx, vy, vz (km/s), ax, ay, az (km/s²),
|
||||
* jx, jy, jz (km/s³)].
|
||||
* @param {object} satrec
|
||||
* @param {number} atMs Epoch milliseconds.
|
||||
* @param {Float64Array} [out]
|
||||
* @returns {Float64Array|null} Null when SGP4 has no state for that time.
|
||||
*/
|
||||
export function sampleOrbit(
|
||||
satrec,
|
||||
atMs,
|
||||
out = new Float64Array(ORBIT_SAMPLE_LENGTH),
|
||||
) {
|
||||
let state;
|
||||
try {
|
||||
state = propagate(satrec, new Date(atMs));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const p = state?.position;
|
||||
const v = state?.velocity;
|
||||
if (!p || typeof p === 'boolean' || !v || typeof v === 'boolean') return null;
|
||||
const r = Math.hypot(p.x, p.y, p.z);
|
||||
if (!(r > 0) || !Number.isFinite(v.x + v.y + v.z)) return null;
|
||||
const k = -MU_KM3_S2 / (r * r * r);
|
||||
// d/dt of -μ r/|r|³: -μ (v/|r|³ - 3 (r·v) r/|r|⁵).
|
||||
const radial = (3 * (p.x * v.x + p.y * v.y + p.z * v.z)) / (r * r);
|
||||
out[0] = atMs;
|
||||
out[1] = p.x;
|
||||
out[2] = p.y;
|
||||
out[3] = p.z;
|
||||
out[4] = v.x;
|
||||
out[5] = v.y;
|
||||
out[6] = v.z;
|
||||
out[7] = k * p.x;
|
||||
out[8] = k * p.y;
|
||||
out[9] = k * p.z;
|
||||
out[10] = k * (v.x - radial * p.x);
|
||||
out[11] = k * (v.y - radial * p.y);
|
||||
out[12] = k * (v.z - radial * p.z);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a satellite is at `atMs`, reckoned from its sample along the inertial
|
||||
* path (position, velocity, gravity and its change) and turned into the
|
||||
* Earth-fixed frame by the Greenwich sidereal angle at that time. Over half a
|
||||
* minute of world time the reckoned point stays within metres of SGP4.
|
||||
* @param {Float64Array} sample From sampleOrbit.
|
||||
* @param {number} atMs Epoch milliseconds.
|
||||
* @param {number} gmst Greenwich mean sidereal angle at `atMs`, radians.
|
||||
* @param {{x: number, y: number, z: number}} out Receives Earth-fixed metres.
|
||||
* @returns {{x: number, y: number, z: number}} `out`.
|
||||
*/
|
||||
export function reckonEarthFixed(sample, atMs, gmst, out) {
|
||||
const dt = (atMs - sample[0]) / 1000;
|
||||
const half = 0.5 * dt * dt;
|
||||
const sixth = (half * dt) / 3;
|
||||
const x = sample[1] + sample[4] * dt + sample[7] * half + sample[10] * sixth;
|
||||
const y = sample[2] + sample[5] * dt + sample[8] * half + sample[11] * sixth;
|
||||
const z = sample[3] + sample[6] * dt + sample[9] * half + sample[12] * sixth;
|
||||
const cos = Math.cos(gmst);
|
||||
const sin = Math.sin(gmst);
|
||||
out.x = (x * cos + y * sin) * 1000;
|
||||
out.y = (-x * sin + y * cos) * 1000;
|
||||
out.z = z * 1000;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// src/layers/satellites/motion.test.mjs — a satellite's point reckoned from
|
||||
// one SGP4 sample stays on SGP4's track between samples.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { gstime, twoline2satrec } from 'satellite.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
|
||||
const ISS = twoline2satrec(
|
||||
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
|
||||
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
|
||||
);
|
||||
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
|
||||
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
|
||||
|
||||
/** Where the layer has always drawn a satellite: SGP4, through geodetic. */
|
||||
function drawnBySgp4(atMs) {
|
||||
const pos = orbits.propagatePosition(ISS, new Date(atMs));
|
||||
return Cesium.Cartesian3.fromDegrees(
|
||||
pos.longitude,
|
||||
pos.latitude,
|
||||
pos.altitude,
|
||||
);
|
||||
}
|
||||
|
||||
function reckoned(sample, atMs) {
|
||||
return reckonEarthFixed(
|
||||
sample,
|
||||
atMs,
|
||||
gstime(new Date(atMs)),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
}
|
||||
|
||||
test('at its own time the reckoned point is where SGP4 draws it', () => {
|
||||
const sample = sampleOrbit(ISS, AT_MS);
|
||||
const gap = Cesium.Cartesian3.distance(
|
||||
reckoned(sample, AT_MS),
|
||||
drawnBySgp4(AT_MS),
|
||||
);
|
||||
assert.ok(gap < 1, `${gap} m`);
|
||||
});
|
||||
|
||||
test('between samples the point keeps to the SGP4 track', () => {
|
||||
const sample = sampleOrbit(ISS, AT_MS);
|
||||
for (const [seconds, withinM] of [
|
||||
[0.016, 1],
|
||||
[1, 2],
|
||||
[10, 2],
|
||||
[30, 10],
|
||||
[60, 50],
|
||||
]) {
|
||||
const atMs = AT_MS + seconds * 1000;
|
||||
const gap = Cesium.Cartesian3.distance(
|
||||
reckoned(sample, atMs),
|
||||
drawnBySgp4(atMs),
|
||||
);
|
||||
assert.ok(gap < withinM, `${seconds} s: ${gap} m`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the point moves every frame, at orbital speed', () => {
|
||||
const sample = sampleOrbit(ISS, AT_MS);
|
||||
const a = reckoned(sample, AT_MS + 500);
|
||||
const b = reckoned(sample, AT_MS + 516);
|
||||
const speed = Cesium.Cartesian3.distance(a, b) / 0.016;
|
||||
// ISS ground-relative speed: about 7.2–7.7 km/s.
|
||||
assert.ok(speed > 7000 && speed < 8000, `${speed} m/s`);
|
||||
});
|
||||
|
||||
test('reckoning backwards in time works as forwards', () => {
|
||||
const sample = sampleOrbit(ISS, AT_MS);
|
||||
const atMs = AT_MS - 30_000;
|
||||
const gap = Cesium.Cartesian3.distance(
|
||||
reckoned(sample, atMs),
|
||||
drawnBySgp4(atMs),
|
||||
);
|
||||
assert.ok(gap < 10, `${gap} m`);
|
||||
});
|
||||
|
||||
test('an element set SGP4 cannot propagate has no sample', () => {
|
||||
const decayed = { ...ISS, error: 0 };
|
||||
decayed.ecco = 2; // not an orbit
|
||||
assert.equal(sampleOrbit(decayed, AT_MS), null);
|
||||
});
|
||||
@@ -31,7 +31,16 @@ export const ISS_OVERLAY_SOURCE_OPTIONS = Object.freeze({
|
||||
export const ORBIT_PATH_STEPS = 180;
|
||||
// points per orbital path
|
||||
|
||||
/** How often every core satellite takes a fresh SGP4 sample (wall ms). */
|
||||
export const POSITION_UPDATE_MS = 1000;
|
||||
/**
|
||||
* Between SGP4 samples every point is reckoned each frame from its last one
|
||||
* (motion.js). A sample this far from the world time is taken again, so a
|
||||
* point is never more than about 10 m off SGP4 however fast time plays.
|
||||
*/
|
||||
export const ORBIT_SAMPLE_HORIZON_MS = 30_000;
|
||||
/** Beyond this from its sample a point is left where it is until sampled again. */
|
||||
export const ORBIT_RECKON_LIMIT_MS = 120_000;
|
||||
/** How far either side of now SGP4 on current element sets stays meaningful. */
|
||||
export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
|
||||
|
||||
@@ -41,7 +50,6 @@ export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
|
||||
* 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;
|
||||
// re-align baked orbit rings to current GMST every 1s
|
||||
@@ -80,6 +88,14 @@ export const DENSE_GROUP_PATH = 'starlink';
|
||||
export const DENSE_REFRESH_FRAMES = 300;
|
||||
// full dense pass spread over ~300 frames (~5s @ 60fps)
|
||||
|
||||
/**
|
||||
* The most dense extras sampled in one frame while time plays fast (~4 ms).
|
||||
* Past about 10 minutes of world time a second the full dense set no longer
|
||||
* fits within ORBIT_RECKON_LIMIT_MS, and its points move only as they are
|
||||
* sampled.
|
||||
*/
|
||||
export const DENSE_SAMPLES_PER_FRAME_MAX = 2000;
|
||||
|
||||
export const DENSE_CREATE_CHUNK = 1500;
|
||||
// satrec builds per macro-task while loading
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
// src/layers/satellites/reckon.test.mjs — every frame each shown point moves
|
||||
// to where its satellite is at the world time; samples are taken again when
|
||||
// time has moved far from them, and dense extras are sampled faster the
|
||||
// faster time plays.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { twoline2satrec } from 'satellite.js';
|
||||
import { createCatalog } from './catalog.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { sampleOrbit } from './motion.js';
|
||||
import {
|
||||
DENSE_REFRESH_FRAMES,
|
||||
DENSE_SAMPLES_PER_FRAME_MAX,
|
||||
ORBIT_RECKON_LIMIT_MS,
|
||||
ORBIT_SAMPLE_HORIZON_MS,
|
||||
} from './policy.js';
|
||||
|
||||
const ISS = twoline2satrec(
|
||||
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
|
||||
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
|
||||
);
|
||||
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
|
||||
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
|
||||
|
||||
/** A dot's point item that counts moves (a write of its `pos`). */
|
||||
function point(show = true) {
|
||||
let x = 0;
|
||||
const item = {
|
||||
show,
|
||||
writes: 0,
|
||||
pos: { y: 0, z: 0 },
|
||||
get position() {
|
||||
return item.pos;
|
||||
},
|
||||
};
|
||||
Object.defineProperty(item.pos, 'x', {
|
||||
enumerable: true,
|
||||
get: () => x,
|
||||
set(value) {
|
||||
item.writes++;
|
||||
x = value;
|
||||
},
|
||||
});
|
||||
return item;
|
||||
}
|
||||
|
||||
function scene(entries, { tracked = null } = {}) {
|
||||
const state = {
|
||||
_points: new Map(),
|
||||
_catalog: new Map(),
|
||||
_trackedNorad: tracked,
|
||||
_denseIds: [],
|
||||
_denseCursor: 0,
|
||||
};
|
||||
for (const [id, entry] of Object.entries(entries)) {
|
||||
state._points.set(id, entry.point);
|
||||
state._catalog.set(id, { satrec: ISS, group: 'core', ...entry.sat });
|
||||
}
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
return { state, rendering };
|
||||
}
|
||||
|
||||
function sgp4At(atMs) {
|
||||
const pos = orbits.propagatePosition(ISS, new Date(atMs));
|
||||
return Cesium.Cartesian3.fromDegrees(
|
||||
pos.longitude,
|
||||
pos.latitude,
|
||||
pos.altitude,
|
||||
);
|
||||
}
|
||||
|
||||
test('a shown point moves to its satellite at the world time; hidden and tracked ones do not', () => {
|
||||
const shown = point();
|
||||
const hidden = point(false);
|
||||
const tracked = point();
|
||||
const { rendering } = scene(
|
||||
{
|
||||
shown: { point: shown },
|
||||
hidden: { point: hidden },
|
||||
tracked: { point: tracked },
|
||||
},
|
||||
{ tracked: 'tracked' },
|
||||
);
|
||||
rendering._reckonPoints(AT_MS);
|
||||
assert.ok(Cesium.Cartesian3.distance(shown.position, sgp4At(AT_MS)) < 1);
|
||||
assert.equal(hidden.writes, 0);
|
||||
assert.equal(tracked.writes, 0);
|
||||
// The same time again (the clock paused): nothing is written.
|
||||
rendering._reckonPoints(AT_MS);
|
||||
assert.equal(shown.writes, 1);
|
||||
// Shown while paused, a hidden point moves at once.
|
||||
hidden.show = true;
|
||||
rendering._reckonPoints(AT_MS);
|
||||
assert.equal(hidden.writes, 1);
|
||||
});
|
||||
|
||||
test('between samples the point keeps to the track; far from its sample, a core satellite is sampled again', () => {
|
||||
const p = point();
|
||||
const { state, rendering } = scene({ iss: { point: p } });
|
||||
rendering._reckonPoints(AT_MS);
|
||||
const sample = state._catalog.get('iss').orbitSample;
|
||||
assert.equal(sample[0], AT_MS);
|
||||
// Within the horizon the same sample moves it on.
|
||||
const soon = AT_MS + ORBIT_SAMPLE_HORIZON_MS / 2;
|
||||
rendering._reckonPoints(soon);
|
||||
assert.equal(state._catalog.get('iss').orbitSample[0], AT_MS);
|
||||
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(soon)) < 5);
|
||||
// A seek an hour back samples it again there.
|
||||
const back = AT_MS - 3_600_000;
|
||||
rendering._reckonPoints(back);
|
||||
assert.equal(state._catalog.get('iss').orbitSample[0], back);
|
||||
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(back)) < 1);
|
||||
});
|
||||
|
||||
test('a dense extra is left for its round-robin, and stays put once too far from its sample', () => {
|
||||
const p = point();
|
||||
const { rendering } = scene({
|
||||
starlink: {
|
||||
point: p,
|
||||
sat: { group: 'dense', orbitSample: sampleOrbit(ISS, AT_MS) },
|
||||
},
|
||||
});
|
||||
rendering._reckonPoints(AT_MS + ORBIT_SAMPLE_HORIZON_MS * 2);
|
||||
assert.equal(p.writes, 1, 'reckoned from its own sample');
|
||||
rendering._reckonPoints(AT_MS + ORBIT_RECKON_LIMIT_MS + 1);
|
||||
assert.equal(p.writes, 1, 'too far: left where it is');
|
||||
});
|
||||
|
||||
test('the dense slice grows with how fast the world time moves, up to its cap', () => {
|
||||
const sampled = (count, worldStepMs) => {
|
||||
const state = {
|
||||
_denseIds: [],
|
||||
_denseCursor: 0,
|
||||
_catalog: new Map(),
|
||||
_trackedNorad: null,
|
||||
now: () => AT_MS,
|
||||
};
|
||||
for (let i = 0; i < count; i++) {
|
||||
state._denseIds.push(String(i));
|
||||
state._catalog.set(String(i), { satrec: ISS, group: 'dense' });
|
||||
}
|
||||
createCatalog({
|
||||
state,
|
||||
services: {},
|
||||
parts: {},
|
||||
source: {},
|
||||
})._propagateDenseChunk(worldStepMs);
|
||||
return [...state._catalog.values()].filter((sat) => sat.orbitSample).length;
|
||||
};
|
||||
// Real time: the set over DENSE_REFRESH_FRAMES frames.
|
||||
assert.equal(sampled(3000, 16), Math.ceil(3000 / DENSE_REFRESH_FRAMES));
|
||||
// A tenth of the horizon a frame: a tenth of the set.
|
||||
assert.equal(sampled(3000, ORBIT_SAMPLE_HORIZON_MS / 10), 300);
|
||||
// A seek, or the first frame: as many as the cap allows.
|
||||
assert.equal(sampled(3000, Number.NaN), DENSE_SAMPLES_PER_FRAME_MAX);
|
||||
assert.equal(sampled(1000, -ORBIT_SAMPLE_HORIZON_MS * 5), 1000);
|
||||
});
|
||||
@@ -1,10 +1,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 { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ORBIT_REBAKE_MS,
|
||||
ORBIT_RECKON_LIMIT_MS,
|
||||
ORBIT_SAMPLE_HORIZON_MS,
|
||||
POSITION_UPDATE_MS,
|
||||
RING_ROTATION_MS,
|
||||
} from './policy.js';
|
||||
@@ -558,37 +560,76 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagate all CORE satellite positions and update their dots.
|
||||
* (About 1,300 core satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms,
|
||||
* fine at the 1s/200ms cadence.) Dense extras are
|
||||
* excluded: they refresh on the round-robin budget in _propagateDenseChunk.
|
||||
* Take a fresh SGP4 sample of every CORE satellite (motion.js); the points
|
||||
* move from these each frame in _reckonPoints. (About 1,300 core
|
||||
* satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms, fine at the
|
||||
* 1s/200ms cadence.) Dense extras are excluded: they are sampled on the
|
||||
* round-robin budget in _propagateDenseChunk.
|
||||
* @returns {number} How many satellites were sampled.
|
||||
*/
|
||||
|
||||
function _propagateAll() {
|
||||
const now = new Date(layerState.now());
|
||||
const nowMs = layerState.now();
|
||||
let updated = 0;
|
||||
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
for (const sat of layerState._catalog.values()) {
|
||||
if (sat.group === 'dense') continue;
|
||||
const pos = parts.orbits.propagatePosition(sat.satrec, now);
|
||||
if (!pos) continue;
|
||||
|
||||
const point = layerState._points.get(noradId);
|
||||
if (point) {
|
||||
fromDegreesInto(pos.longitude, pos.latitude, pos.altitude, point.pos);
|
||||
_markDirty(noradId);
|
||||
updated++;
|
||||
}
|
||||
if (_sample(sat, nowMs)) updated++;
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample one satellite's orbit at `atMs` into its reused sample.
|
||||
* @returns {boolean} Whether SGP4 had a state for that time.
|
||||
*/
|
||||
|
||||
function _sample(sat, atMs) {
|
||||
const sample = sampleOrbit(sat.satrec, atMs, sat.orbitSample);
|
||||
if (!sample) return false;
|
||||
sat.orbitSample = sample;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move every shown dot to where its satellite is at the world time,
|
||||
* reckoned from its last sample, so dots glide every frame between
|
||||
* samples instead of stepping once a second; the moved dots go to the
|
||||
* points set with the frame's other dot changes. A core sample more than
|
||||
* ORBIT_SAMPLE_HORIZON_MS from the world time (time playing fast, or a
|
||||
* seek) is taken again first; dense extras are resampled by their own
|
||||
* round-robin. A hidden dot is moved when it is shown again, and the
|
||||
* tracked satellite is placed by its per-frame path.
|
||||
* @param {number} nowMs World time, epoch ms.
|
||||
*/
|
||||
|
||||
function _reckonPoints(nowMs) {
|
||||
const gmst = gstime(new Date(nowMs));
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (!point.show || noradId === layerState._trackedNorad) continue;
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
if (!sat || sat.reckonedAtMs === nowMs) continue;
|
||||
let sample = sat.orbitSample;
|
||||
if (
|
||||
sat.group !== 'dense' &&
|
||||
(!sample || Math.abs(nowMs - sample[0]) > ORBIT_SAMPLE_HORIZON_MS)
|
||||
)
|
||||
sample = _sample(sat, nowMs) ? sat.orbitSample : null;
|
||||
if (!sample || Math.abs(nowMs - sample[0]) > ORBIT_RECKON_LIMIT_MS)
|
||||
continue;
|
||||
reckonEarthFixed(sample, nowMs, gmst, point.pos);
|
||||
_markDirty(noradId);
|
||||
sat.reckonedAtMs = nowMs;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared preRender tick (single definition for init + enable):
|
||||
* - the tracked dot where the follow camera put it this frame,
|
||||
* - core fleet propagation at 200ms-tracked / 1s-idle cadence,
|
||||
* - dense extras on a per-frame round-robin budget,
|
||||
* - core fleet SGP4 samples at 200ms-tracked / 1s-idle cadence,
|
||||
* - dense extras sampled on a per-frame round-robin budget,
|
||||
* - every dot reckoned from its sample each frame (motion.js),
|
||||
* - tracked satellite's dot sample per frame (WS-D2),
|
||||
* - orbit ring GMST re-alignment every ~1s (WS-D1),
|
||||
* - the frame's dot changes sent to the points set.
|
||||
@@ -637,7 +678,12 @@ export function createRendering({
|
||||
layerState._lastPropagation = now;
|
||||
}
|
||||
|
||||
if (layerState._params.showPoints) parts.catalog._propagateDenseChunk();
|
||||
if (layerState._params.showPoints) {
|
||||
const worldMs = layerState.now();
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
}
|
||||
|
||||
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
|
||||
// with label + camera — runs after _propagateAll so the per-frame sample
|
||||
@@ -831,6 +877,7 @@ export function createRendering({
|
||||
_updateOrbitPathRotations,
|
||||
_hideOrbitPath,
|
||||
_propagateAll,
|
||||
_reckonPoints,
|
||||
_preRenderTick,
|
||||
_updatePointFocus,
|
||||
applySatellitePointFocusDeemphasis,
|
||||
|
||||
@@ -63,6 +63,10 @@ export function createState({ services }) {
|
||||
|
||||
state._lastPropagation = 0;
|
||||
|
||||
// The world time of the last frame that reckoned the points (motion.js),
|
||||
// NaN before the first.
|
||||
state._lastReckonMs = NaN;
|
||||
|
||||
state._lastRingRotation = 0;
|
||||
|
||||
state._lastFocusUpdate = 0;
|
||||
|
||||
@@ -420,7 +420,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
|
||||
// The tracked position propagates per evaluation through the per-frame
|
||||
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
|
||||
// Falls back to the dot's 1s-throttled position if SGP4 fails.
|
||||
// Falls back to the dot's reckoned position if SGP4 fails.
|
||||
const trackedPosition = () => {
|
||||
const pos = _getTrackedFramePosition();
|
||||
return pos
|
||||
|
||||
@@ -101,7 +101,10 @@ test('the subject says whether its track is the heading or the course', () => {
|
||||
test('a vessel without identity or position is not a subject', () => {
|
||||
assert.equal(vesselCockpitInfo(null), null);
|
||||
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
|
||||
assert.equal(vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }), null);
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('a vessel missing from recent refreshes reads as stale', () => {
|
||||
|
||||
@@ -39,8 +39,9 @@ export function createIngestion({
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function loadAt(atMs, { signal = null, replace = false } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
if (replace && feed.loading) {
|
||||
// Whatever polls or loads for another time no longer applies: the
|
||||
// timeline asks for one time at a time.
|
||||
if (feed.loading) {
|
||||
feed.abort?.abort();
|
||||
feed.loading = false;
|
||||
feed.abort = null;
|
||||
@@ -209,6 +210,7 @@ export function createIngestion({
|
||||
reference: record.reference,
|
||||
lat: record.latitude,
|
||||
lon: record.longitude,
|
||||
fixes: record.fixes,
|
||||
name: record.name,
|
||||
imo: record.imo,
|
||||
type: record.type,
|
||||
|
||||
@@ -1,14 +1,39 @@
|
||||
/**
|
||||
* Where a vessel is at world time `tMs` while the layer follows the world
|
||||
* clock: between the fix it moved from and the fix it moved to, along the
|
||||
* great circle; at the earlier fix before it, at the newer fix after it. A
|
||||
* vessel is never projected past its newest fix.
|
||||
* clock: on its own fixes around the time when its record carries them
|
||||
* (`fixes`, see src/time/timelineFixes.js), else between the fix it moved
|
||||
* from and the fix it moved to; along the great circle between two fixes, at
|
||||
* the first before them and at the last after them. A vessel is never
|
||||
* projected past its newest fix.
|
||||
* @param {{lat: number, lon: number, motion?: {fromLat: number, fromLon: number,
|
||||
* fromMs: number, toLat: number, toLon: number, toMs: number}|null}} record
|
||||
* @param {number} tMs
|
||||
* @returns {{lat: number, lon: number}}
|
||||
*/
|
||||
export function vesselPositionAt(record, tMs) {
|
||||
const fixes = record?.fixes;
|
||||
if (fixes?.length >= 2 && Number.isFinite(tMs)) {
|
||||
const first = fixes[0];
|
||||
const last = fixes[fixes.length - 1];
|
||||
if (tMs <= first.atMs) return { lat: first.lat, lon: first.lon };
|
||||
if (tMs >= last.atMs) return { lat: last.lat, lon: last.lon };
|
||||
let low = 1;
|
||||
let high = fixes.length - 1;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (fixes[mid].atMs < tMs) low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
const a = fixes[low - 1];
|
||||
const b = fixes[low];
|
||||
return greatCircleAt(
|
||||
a.lat,
|
||||
a.lon,
|
||||
b.lat,
|
||||
b.lon,
|
||||
b.atMs > a.atMs ? (tMs - a.atMs) / (b.atMs - a.atMs) : 1,
|
||||
);
|
||||
}
|
||||
const motion = record?.motion;
|
||||
if (
|
||||
!motion ||
|
||||
@@ -60,3 +85,28 @@ function unit(lat, lon) {
|
||||
Math.sin(phi),
|
||||
];
|
||||
}
|
||||
|
||||
// Whether each fixes array moves, read once per array: records keep theirs
|
||||
// until a snapshot brings new ones.
|
||||
const moving = new WeakMap();
|
||||
|
||||
/**
|
||||
* Whether a vessel's fixes (`record.fixes`) put it in more than one place,
|
||||
* so following the clock moves it; a moored vessel's do not.
|
||||
* @param {Array<{lat: number, lon: number}>|null|undefined} fixes
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function fixesMove(fixes) {
|
||||
if (!fixes?.length) return false;
|
||||
let moves = moving.get(fixes);
|
||||
if (moves === undefined) {
|
||||
const [first] = fixes;
|
||||
moves = fixes.some(
|
||||
(fix) =>
|
||||
Math.abs(fix.lat - first.lat) > 1e-6 ||
|
||||
Math.abs(fix.lon - first.lon) > 1e-6,
|
||||
);
|
||||
moving.set(fixes, moves);
|
||||
}
|
||||
return moves;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { vesselPositionAt } from './motion.js';
|
||||
import { fixesMove, vesselPositionAt } from './motion.js';
|
||||
|
||||
const record = {
|
||||
lat: 1,
|
||||
@@ -29,3 +29,35 @@ test('a vessel with no move is at its record', () => {
|
||||
assert.equal(vesselPositionAt(still, 2_000), still);
|
||||
assert.equal(vesselPositionAt({ ...still, motion: null }, 2_000).lat, 4);
|
||||
});
|
||||
|
||||
test('a vessel with fixes around the time is placed on them, held at either end', () => {
|
||||
const tracked = {
|
||||
lat: 9,
|
||||
lon: 9,
|
||||
motion: record.motion,
|
||||
fixes: [
|
||||
{ atMs: 1_000, lat: 0, lon: 0, altitudeM: null },
|
||||
{ atMs: 2_000, lat: 1, lon: 0, altitudeM: null },
|
||||
{ atMs: 4_000, lat: 1, lon: 2, altitudeM: null },
|
||||
],
|
||||
};
|
||||
assert.deepEqual(vesselPositionAt(tracked, 0), { lat: 0, lon: 0 });
|
||||
assert.deepEqual(vesselPositionAt(tracked, 9_000), { lat: 1, lon: 2 });
|
||||
const back = vesselPositionAt(tracked, 1_500);
|
||||
assert.ok(Math.abs(back.lat - 0.5) < 1e-3 && Math.abs(back.lon) < 1e-6);
|
||||
const on = vesselPositionAt(tracked, 3_000);
|
||||
assert.ok(Math.abs(on.lat - 1) < 1e-3 && Math.abs(on.lon - 1) < 1e-3);
|
||||
});
|
||||
|
||||
test('fixes that stay in one place do not move a vessel', () => {
|
||||
const still = [
|
||||
{ atMs: 0, lat: 1, lon: 2 },
|
||||
{ atMs: 60_000, lat: 1, lon: 2 },
|
||||
];
|
||||
assert.equal(fixesMove(still), false);
|
||||
assert.equal(
|
||||
fixesMove([...still, { atMs: 90_000, lat: 1.001, lon: 2 }]),
|
||||
true,
|
||||
);
|
||||
assert.equal(fixesMove(null), false);
|
||||
});
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
mergeTimelineRuns,
|
||||
readTimelineFixes,
|
||||
} from '../../time/timelineFixes.js';
|
||||
import {
|
||||
PARTIAL_RETENTION_MS,
|
||||
SELECTED_PIN_REFRESHES,
|
||||
@@ -35,6 +39,9 @@ export function normalizeVessel(row) {
|
||||
virtual: row.virtual === true,
|
||||
lastPositionUtc: String(row.last_position_UTC || ''),
|
||||
lastPositionEpoch: finiteNumber(row.last_position_epoch),
|
||||
// Its own track around the time, from a snapshot at a time (see
|
||||
// src/time/timelineFixes.js); null when the row carries none.
|
||||
fixes: readTimelineFixes(row.fixes),
|
||||
missedRefreshes: 0,
|
||||
};
|
||||
}
|
||||
@@ -145,8 +152,22 @@ export class VesselRecords {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
if (replace) record.motion = null;
|
||||
else if (follow) record.motion = motionBetween(record, next);
|
||||
if (replace) {
|
||||
record.motion = null;
|
||||
record.fixes = next.fixes;
|
||||
} else if (follow) {
|
||||
record.motion = motionBetween(record, next);
|
||||
// Without fixes now, it is placed by its record, not by fixes
|
||||
// that end before it.
|
||||
record.fixes = next.fixes
|
||||
? mergeTimelineRuns(
|
||||
record.fixes ?? [],
|
||||
next.fixes,
|
||||
(fix) => fix.atMs,
|
||||
(next.lastPositionEpoch ?? 0) * 1000,
|
||||
)
|
||||
: null;
|
||||
} else record.fixes = null;
|
||||
record.reference = next.reference;
|
||||
record.mmsi = next.mmsi;
|
||||
record.receivedAtMs = next.receivedAtMs;
|
||||
|
||||
@@ -187,3 +187,15 @@ test('an AIS row with no id is keyed by its MMSI; one with neither is unkeyed',
|
||||
assert.equal(probe.store.byId.size, 0);
|
||||
assert.equal(probe.store.unkeyed.length, 2);
|
||||
});
|
||||
|
||||
const fixes = (...pairs) =>
|
||||
pairs.map(([atMs, lat]) => ({ atMs, lat, lon: 4.05, altitudeM: null }));
|
||||
|
||||
test('following the clock, a vessel whose next record carries no fixes is placed by the record', () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([row('111', { fixes: fixes([0, 1], [60_000, 2]) })], {
|
||||
replace: true,
|
||||
});
|
||||
probe.reconcile([row('111', { lat: 3 })], { follow: true });
|
||||
assert.equal(probe.store.byId.get('111').fixes, null);
|
||||
});
|
||||
@@ -4,10 +4,11 @@ import { createVesselLayer } from './index.js';
|
||||
import { VISIBILITY_UPDATE_MS } from './policy.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
// Vessels move only when a poll lands, so the layer must let the scene idle:
|
||||
// it asks for frames for forced passes and one trailing frame after the camera
|
||||
// stops, and never schedules a frame from a pass the camera did not cause.
|
||||
// The layer must let the scene idle: it asks for frames for forced passes,
|
||||
// for vessels that move, and one trailing frame after the camera stops, and
|
||||
// never schedules a frame from a pass nothing caused.
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
@@ -78,7 +79,16 @@ function setup({ focusPassIsNeeded = () => false, placement = null } = {}) {
|
||||
}
|
||||
};
|
||||
const frame = () => layer.testing._runVisibilityPassForTest();
|
||||
return { layer, camera, requests, holds, timers, advance, frame };
|
||||
return {
|
||||
layer,
|
||||
camera,
|
||||
requests,
|
||||
holds,
|
||||
timers,
|
||||
advance,
|
||||
frame,
|
||||
now: () => clock,
|
||||
};
|
||||
}
|
||||
|
||||
test('a parked camera schedules no frames after the cadence pass', () => {
|
||||
@@ -117,6 +127,26 @@ test('a camera that stops inside the cadence gets exactly one trailing frame', (
|
||||
assert.equal(timers.size, 0);
|
||||
});
|
||||
|
||||
test('following the clock, a time moved inside the cadence gets one trailing frame', () => {
|
||||
const { layer, requests, timers, advance, frame } = setup();
|
||||
layer.testing._followClockForTest(1_000_000);
|
||||
frame();
|
||||
advance(100);
|
||||
// A seek while paused: the camera is still, the time drawn is not.
|
||||
layer.testing._followClockForTest(940_000);
|
||||
frame();
|
||||
assert.equal(timers.size, 1);
|
||||
advance(VISIBILITY_UPDATE_MS);
|
||||
assert.deepEqual(requests, ['ais-vessels-visibility']);
|
||||
frame();
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
advance(100);
|
||||
frame();
|
||||
}
|
||||
assert.deepEqual(requests, ['ais-vessels-visibility']);
|
||||
assert.equal(timers.size, 0);
|
||||
});
|
||||
|
||||
test('a forced pass requests its own frame', () => {
|
||||
const { layer, requests } = setup();
|
||||
layer.testing._runVisibilityPassForTest(true);
|
||||
@@ -239,3 +269,200 @@ test('a placement that places nothing asks for no frames; one that places a draw
|
||||
advance(1_000);
|
||||
assert.deepEqual(requests, ['ais-vessels-placement']);
|
||||
});
|
||||
|
||||
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
t.after(() => {
|
||||
if (originalDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = originalDocument;
|
||||
});
|
||||
let spot = { lat: 51.93, lon: 4.05 };
|
||||
const { layer, camera, timers, advance, now } = setup({
|
||||
placement: { layer: () => ({ place: () => spot }) },
|
||||
});
|
||||
// 20 km above the vessel, in a 1,000 px tall view about 57° tall.
|
||||
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
|
||||
camera.frustum = { fovy: 1 };
|
||||
const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
|
||||
// Drawn: on the camera's side of the horizon.
|
||||
const drawnVisual = (viewer) => {
|
||||
bindFakeCesiumScene(viewer);
|
||||
layer.testing._setVesselStateForTest({ viewer, records: [record] });
|
||||
layer.testing._prepareVesselVisualForTest(record).visible = true;
|
||||
};
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientHeight: 1000 } });
|
||||
// How long after a pass the next frame is asked for, once the vessel moved
|
||||
// `dLat` in the 16 ms since the pass before.
|
||||
const waitAfterStep = (dLat) => {
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000); // whatever frame that asked for comes and goes
|
||||
assert.equal(timers.size, 0);
|
||||
mono += 16;
|
||||
spot = { lat: spot.lat + dLat, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.equal(timers.size, 1);
|
||||
const [timer] = [...timers.values()];
|
||||
return timer.at - now();
|
||||
};
|
||||
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
|
||||
// is asked for within the frame.
|
||||
assert.ok(waitAfterStep(0.0001) <= 16);
|
||||
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
|
||||
assert.equal(waitAfterStep(0.0000001), 1000);
|
||||
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
|
||||
// next frame comes within two frames.
|
||||
camera.frustum = new Cesium.OrthographicOffCenterFrustum({
|
||||
left: -20_000,
|
||||
right: 20_000,
|
||||
bottom: -20_000,
|
||||
top: 20_000,
|
||||
near: 1,
|
||||
far: 1e8,
|
||||
});
|
||||
camera.viewMatrix = Cesium.Matrix4.IDENTITY;
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientWidth: 1000 } });
|
||||
assert.ok(waitAfterStep(0.0001) <= 32);
|
||||
});
|
||||
|
||||
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
t.after(() => {
|
||||
if (originalDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = originalDocument;
|
||||
});
|
||||
const { layer, camera, timers, advance } = setup();
|
||||
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
|
||||
camera.frustum = { fovy: 1 };
|
||||
const motion = {
|
||||
fromLat: 51.93,
|
||||
fromLon: 4.05,
|
||||
fromMs: 0,
|
||||
toLat: 51.94,
|
||||
toLon: 4.05,
|
||||
toMs: 60_000,
|
||||
};
|
||||
const vessel = (mmsi) => ({
|
||||
mmsi,
|
||||
lat: 51.94,
|
||||
lon: 4.05,
|
||||
motion: { ...motion },
|
||||
});
|
||||
const drawn = vessel('111');
|
||||
const hidden = vessel('222');
|
||||
const owned = vessel('333');
|
||||
const missing = vessel('444');
|
||||
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
|
||||
bindFakeCesiumScene(viewer);
|
||||
layer.testing._setVesselStateForTest({
|
||||
viewer,
|
||||
records: [drawn, hidden, owned, missing],
|
||||
});
|
||||
const visuals = [drawn, hidden, owned].map((record) =>
|
||||
layer.testing._prepareVesselVisualForTest(record),
|
||||
);
|
||||
// Drawn as an icon (on the camera's side of the horizon), hidden, and
|
||||
// drawn by its model.
|
||||
visuals[0].visible = true;
|
||||
visuals[1].visible = false;
|
||||
visuals[2].visible = false;
|
||||
visuals[2].modelOwnsVisual = true;
|
||||
const before = visuals.map((visual) => ({ ...visual.position }));
|
||||
const positions = visuals.map((visual) => visual.position);
|
||||
|
||||
// The first pass also moves hidden vessels, so the next stays within
|
||||
// HIDDEN_FOLLOW_MS of it.
|
||||
layer.testing._runClockPassForTest(10_000);
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(20_000);
|
||||
assert.equal(visuals[0].position, positions[0], 'written in place');
|
||||
assert.notDeepEqual({ ...visuals[0].position }, before[0]);
|
||||
assert.notDeepEqual({ ...visuals[2].position }, before[2], 'model moves');
|
||||
const hiddenAt = { ...visuals[1].position };
|
||||
assert.ok(
|
||||
layer.testing._vesselVisualForTest(missing).position,
|
||||
'a missing visual is prepared',
|
||||
);
|
||||
assert.equal(timers.size, 1, 'moving vessels ask for a frame');
|
||||
|
||||
// The hidden vessel waits for HIDDEN_FOLLOW_MS.
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(30_000);
|
||||
assert.deepEqual({ ...visuals[1].position }, hiddenAt);
|
||||
mono += 250;
|
||||
layer.testing._runClockPassForTest(40_000);
|
||||
assert.notDeepEqual({ ...visuals[1].position }, hiddenAt);
|
||||
|
||||
// The same world time again moves nothing and asks for no frame.
|
||||
advance(1_000);
|
||||
assert.equal(timers.size, 0);
|
||||
const still = { ...visuals[0].position };
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(40_000);
|
||||
assert.deepEqual({ ...visuals[0].position }, still);
|
||||
assert.equal(timers.size, 0);
|
||||
|
||||
// Scrubbed back, a vessel moves back.
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(20_000);
|
||||
assert.notDeepEqual({ ...visuals[0].position }, still);
|
||||
|
||||
// Each vessel moves once per world time: new fixes at the same world time
|
||||
// are drawn when the snapshot that brings them prepares the visual.
|
||||
const backAt = { ...visuals[0].position };
|
||||
drawn.motion = { ...motion, toLat: 52 };
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(20_000);
|
||||
assert.deepEqual({ ...visuals[0].position }, backAt);
|
||||
|
||||
// Past the newest fix, vessels hold still and ask for nothing.
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(70_000);
|
||||
advance(1_000);
|
||||
mono += 16;
|
||||
layer.testing._runClockPassForTest(80_000);
|
||||
assert.equal(timers.size, 0);
|
||||
});
|
||||
|
||||
test('following the clock, a vessel draws no icon before it was there, and draws it once the time comes', (t) => {
|
||||
const originalDocument = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
t.after(() => {
|
||||
if (originalDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = originalDocument;
|
||||
});
|
||||
const { layer, camera } = setup();
|
||||
const viewer = { camera, scene: {} };
|
||||
const { draw } = bindFakeCesiumScene(viewer);
|
||||
layer.testing._setVesselStateForTest({ viewer, icons: null });
|
||||
const first = 1_000_000;
|
||||
layer.testing._followClockForTest(first - 10 * 60_000);
|
||||
layer.testing._reconcileVesselsForTest(viewer, [
|
||||
{
|
||||
mmsi: '111',
|
||||
lat: 51.93,
|
||||
lon: 4.05,
|
||||
last_position_epoch: first / 1000,
|
||||
fixes: [
|
||||
{ atMs: first, lat: 51.93, lon: 4.05 },
|
||||
{ atMs: first + 60_000, lat: 51.94, lon: 4.05 },
|
||||
],
|
||||
},
|
||||
]);
|
||||
const shown = () => {
|
||||
const [set] = [...draw.sets.values()].filter(
|
||||
(record) => record.kind === 'icons',
|
||||
);
|
||||
return set.items.get('111').show;
|
||||
};
|
||||
layer.testing._runVisibilityPassForTest(true);
|
||||
assert.equal(shown(), false, 'ten minutes before its first fix');
|
||||
layer.testing._followClockForTest(first - 30_000);
|
||||
layer.testing._runVisibilityPassForTest(true);
|
||||
assert.equal(shown(), true, 'half a minute before it: reaching it');
|
||||
});
|
||||
+212
-70
@@ -9,7 +9,7 @@ import {
|
||||
} from '../../data/vesselLabels.js';
|
||||
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
|
||||
import { distance, distanceSquared } from '../../geo/vector.js';
|
||||
import { copyInto, distance, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import {
|
||||
canvasOf,
|
||||
drawOf,
|
||||
@@ -29,7 +29,8 @@ import {
|
||||
CARD_MIN_SEP_PX,
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { vesselPositionAt } from './motion.js';
|
||||
import { fixesMove, vesselPositionAt } from './motion.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js';
|
||||
import {
|
||||
fleetModelSet,
|
||||
loadFleetModelSet,
|
||||
@@ -38,10 +39,15 @@ import {
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { isAidToNavigation } from '../../data/vesselTypes.js';
|
||||
|
||||
/** How often vessels move on as the world clock plays (wall ms). */
|
||||
const FOLLOW_POSITION_MS = 250;
|
||||
/** A frame is asked for this often while a placement moves live vessels. */
|
||||
/** A moving vessel's next frame is asked for once it would move this far on
|
||||
* screen (pixels), so it glides when it moves visibly and the scene idles
|
||||
* when it does not. */
|
||||
const VESSEL_STEP_PX = 0.5;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves. */
|
||||
const PLACEMENT_FRAME_MS = 1000;
|
||||
/** How often vessels not drawn move on as the world clock plays (wall ms),
|
||||
* so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
|
||||
/** The ship artwork's own raster size (px). */
|
||||
const SHIP_ICON_PX = 32;
|
||||
@@ -51,6 +57,9 @@ let instances = 0;
|
||||
/** How often the vessels near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
|
||||
/** Scratch for where a moved vessel was drawn. */
|
||||
const _movedFrom = vec();
|
||||
|
||||
export function createRendering({
|
||||
vesselState,
|
||||
services,
|
||||
@@ -87,10 +96,8 @@ export function createRendering({
|
||||
visual.position = anchorAt(lat, lon);
|
||||
// A ship model's origin is its waterline: the sea surface, unlifted.
|
||||
visual.waterline = anchorAt(lat, lon, 0);
|
||||
if (services.placement) {
|
||||
visual.drawnLat = lat;
|
||||
visual.drawnLon = lon;
|
||||
}
|
||||
visual.drawnLat = lat;
|
||||
visual.drawnLon = lon;
|
||||
return visual;
|
||||
}
|
||||
|
||||
@@ -255,10 +262,13 @@ export function createRendering({
|
||||
function iconItem(record, visual) {
|
||||
const selected = record === state.selectedRecord;
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
// Following the clock, not there yet at the time drawn.
|
||||
visual.seen = seenYet(record);
|
||||
return {
|
||||
id: visual.iconId,
|
||||
// Hidden while the bridge camera rides it, or its model draws it.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual,
|
||||
// Hidden while the bridge camera rides it, its model draws it, or it
|
||||
// is not there yet.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
|
||||
pos: visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
@@ -289,7 +299,7 @@ export function createRendering({
|
||||
state.icons.put({ ...iconItem(record, visual), focus: 1 });
|
||||
if (visual.position)
|
||||
visual.cullPosition = liftedForHorizon(visual.position);
|
||||
visual.visible = isVisible(visual.cullPosition, occluder);
|
||||
visual.visible = isVisible(visual.cullPosition, occluder, record);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -429,7 +439,7 @@ export function createRendering({
|
||||
item.position = getVisual(record).waterline;
|
||||
// An aid to navigation is a fixed mark: it does not turn to a heading.
|
||||
item.headingDeg = item.spec?.fixed ? 0 : vesselCourseDeg(record);
|
||||
item.show = record.id !== state.cockpitSubjectId;
|
||||
item.show = record.id !== state.cockpitSubjectId && seenYet(record);
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -511,11 +521,11 @@ export function createRendering({
|
||||
modelCandidatesAtMs = -Infinity;
|
||||
}
|
||||
|
||||
// Vessels move only when a poll lands, so the layer does not hold the
|
||||
// continuous render loop. Its passes run in preRender, which idle mode fires
|
||||
// only for rendered frames: a forced pass (new data, selection) requests its
|
||||
// frame, a frame that moved the camera but fell inside the 800 ms cadence
|
||||
// leaves a trailing frame so the view the camera stopped on is always
|
||||
// The layer does not hold the continuous render loop. Its passes run in
|
||||
// preRender, which idle mode fires only for rendered frames: moving vessels
|
||||
// ask for the frame that next moves them visibly (askMotionFrame), a forced
|
||||
// pass (new data, selection) requests its frame, a frame that moved the
|
||||
// camera but fell inside the 800 ms cadence leaves a trailing frame so the view the camera stopped on is always
|
||||
// evaluated, and the continuous hold is kept only while focus emphasis is
|
||||
// animating. The trailing frame is keyed to camera motion alone: the pass's
|
||||
// own label publication requests a frame, and scheduling on that would loop.
|
||||
@@ -523,71 +533,181 @@ export function createRendering({
|
||||
if (state.preRenderRemover || !viewer) return;
|
||||
state.preRenderRemover =
|
||||
findFrame(viewer)?.on('preRender', () => {
|
||||
if (followsClock(vesselState)) followClockPositions();
|
||||
else if (services.placement && state.feed.enabled) followPlacements();
|
||||
if (state.feed.enabled) {
|
||||
if (followsClock(vesselState)) followClockPositions();
|
||||
else if (services.placement) followPlacements();
|
||||
}
|
||||
updateVisibility();
|
||||
if (state.feed.enabled) updateModels();
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
// As the world clock plays, vessels between two fixes move on along them.
|
||||
let followedAtWallMs = -Infinity;
|
||||
let followedAtMs = null;
|
||||
// As the world clock plays, vessels between two fixes move on along them:
|
||||
// drawn ones every frame, each once per world time, hidden ones (which may
|
||||
// come into view) every HIDDEN_FOLLOW_MS.
|
||||
let hiddenFollowedAtWallMs = -Infinity;
|
||||
function followClockPositions() {
|
||||
const wallMs = performance.now();
|
||||
if (wallMs - followedAtWallMs < FOLLOW_POSITION_MS) return;
|
||||
followedAtWallMs = wallMs;
|
||||
const atMs = vesselState.worldNow();
|
||||
if (atMs === followedAtMs) return;
|
||||
followedAtMs = atMs;
|
||||
const motion = startMotionPass();
|
||||
const moveHidden =
|
||||
motion.wallMs - hiddenFollowedAtWallMs >= HIDDEN_FOLLOW_MS;
|
||||
if (moveHidden) hiddenFollowedAtWallMs = motion.wallMs;
|
||||
for (const record of state.records.all) {
|
||||
if (!record.motion) continue;
|
||||
prepareRecordVisual(record);
|
||||
syncRecordIcon(record);
|
||||
if (!record.motion && !fixesMove(record.fixes)) continue;
|
||||
let visual = visualRecords.get(record);
|
||||
if (!visual?.position) {
|
||||
visual = prepareRecordVisual(record);
|
||||
visual.followedAtMs = atMs;
|
||||
syncRecordIcon(record);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
visual.followedAtMs === atMs ||
|
||||
(!drawnNow(record, visual) && !moveHidden)
|
||||
)
|
||||
continue;
|
||||
visual.followedAtMs = atMs;
|
||||
const { lat, lon } = vesselPositionAt(record, atMs);
|
||||
// At either end of its fixes a vessel holds still.
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(record, visual, lat, lon, motion);
|
||||
}
|
||||
askMotionFrame(motion);
|
||||
}
|
||||
|
||||
// Live with a host-supplied placement, vessels move on between refreshes:
|
||||
// drawn where it places them at most every FOLLOW_POSITION_MS, with a frame
|
||||
// asked for every PLACEMENT_FRAME_MS while it places any drawn vessel, so
|
||||
// they move while the scene idles.
|
||||
let placedAtWallMs = -Infinity;
|
||||
let placing = false;
|
||||
let placementFrameTimer = null;
|
||||
// drawn where it places them every frame, with the next frame asked for
|
||||
// as soon as a drawn vessel would move visibly, so they move while the
|
||||
// scene idles.
|
||||
function followPlacements() {
|
||||
const wallMs = performance.now();
|
||||
if (wallMs - placedAtWallMs >= FOLLOW_POSITION_MS) {
|
||||
placedAtWallMs = wallMs;
|
||||
placing = false;
|
||||
const nowMs = vesselState._aisRuntime.now();
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
const drawn =
|
||||
(visual.visible && !isCockpitSubject(record)) ||
|
||||
visual.modelOwnsVisual;
|
||||
if (!drawn) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) placing = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveRecordVisual(record, visual, lat, lon);
|
||||
}
|
||||
const nowMs = vesselState._aisRuntime.now();
|
||||
const motion = startMotionPass();
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
if (!drawnNow(record, visual)) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) motion.moving = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(record, visual, lat, lon, motion);
|
||||
}
|
||||
if (placing && placementFrameTimer === null)
|
||||
placementFrameTimer = vesselState._aisRuntime.setTimeout(() => {
|
||||
placementFrameTimer = null;
|
||||
if (state.feed.enabled && !followsClock(vesselState))
|
||||
governorRequestRender('ais-vessels-placement');
|
||||
}, PLACEMENT_FRAME_MS);
|
||||
askMotionFrame(motion);
|
||||
}
|
||||
|
||||
// One pass of moving vessels: whether any drawn vessel is moving, how far
|
||||
// the fastest moved (as an angle seen from the camera, radians, and in
|
||||
// metres), the pass's wall time and the wall time since the pass before.
|
||||
let motionPassWallMs = null;
|
||||
const motionPass = {
|
||||
pose: undefined,
|
||||
wallMs: 0,
|
||||
sinceMs: 0,
|
||||
moving: false,
|
||||
angle: 0,
|
||||
metres: 0,
|
||||
};
|
||||
function startMotionPass() {
|
||||
const wallMs = performance.now();
|
||||
// Read once, when a drawn vessel first moves in the pass.
|
||||
motionPass.pose = undefined;
|
||||
motionPass.wallMs = wallMs;
|
||||
motionPass.sinceMs =
|
||||
motionPassWallMs === null ? 0 : wallMs - motionPassWallMs;
|
||||
motionPass.moving = false;
|
||||
motionPass.angle = 0;
|
||||
motionPass.metres = 0;
|
||||
motionPassWallMs = wallMs;
|
||||
return motionPass;
|
||||
}
|
||||
|
||||
/** The camera's pose for a motion pass, read once in it (null without one). */
|
||||
function motionPose(motion) {
|
||||
if (motion.pose === undefined)
|
||||
motion.pose = state.viewer
|
||||
? (findCamera(state.viewer)?.pose() ?? null)
|
||||
: null;
|
||||
return motion.pose;
|
||||
}
|
||||
|
||||
/** Whether a vessel is drawn now: its icon on the camera's side of the
|
||||
* horizon and not the bridge camera's own vessel, or its model. */
|
||||
function drawnNow(record, visual) {
|
||||
return (
|
||||
(visual.visible && !isCockpitSubject(record)) ||
|
||||
Boolean(visual.modelOwnsVisual)
|
||||
);
|
||||
}
|
||||
|
||||
/** Move a drawn visual, noting how far it moved as seen from the camera. */
|
||||
function moveDrawnVisual(record, visual, lat, lon, motion) {
|
||||
const from = copyInto(visual.position, _movedFrom);
|
||||
moveRecordVisual(record, visual, lat, lon);
|
||||
if (!drawnNow(record, visual)) return;
|
||||
motion.moving = true;
|
||||
const metres = distance(from, visual.position);
|
||||
motion.metres = Math.max(motion.metres, metres);
|
||||
const eye = motionPose(motion)?.position;
|
||||
if (!eye) return;
|
||||
const range = distance(eye, from);
|
||||
if (range > 0) motion.angle = Math.max(motion.angle, metres / range);
|
||||
}
|
||||
|
||||
/** How far the fastest drawn vessel moved on screen in a pass (pixels):
|
||||
* through the perspective view's angle, or across the 2D view's width
|
||||
* (an orthographic projection's, `2 / m00` metres). */
|
||||
function movedPixels(motion) {
|
||||
const canvas = state.viewer ? canvasOf(state.viewer) : null;
|
||||
const pose = motion.pose;
|
||||
if (!canvas || !pose) return 0;
|
||||
if (pose.fovy > 0 && canvas.clientHeight > 0)
|
||||
return (
|
||||
(motion.angle * canvas.clientHeight) / (2 * Math.tan(pose.fovy / 2))
|
||||
);
|
||||
if (pose.fovy > 0 || !(canvas.clientWidth > 0)) return 0;
|
||||
let width = NaN;
|
||||
try {
|
||||
width = 2 / findCamera(state.viewer).matrices().projection[0];
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
return width > 0 ? (motion.metres * canvas.clientWidth) / width : 0;
|
||||
}
|
||||
|
||||
// The timer for the next vessel frame while one is asked for, and when it
|
||||
// is due (the AIS runtime's clock).
|
||||
let placementFrameTimer = null;
|
||||
let placementFrameDueMs = 0;
|
||||
/**
|
||||
* While a drawn vessel moves, ask for the next frame when the fastest one
|
||||
* will have moved VESSEL_STEP_PX on screen at the speed this pass saw, and
|
||||
* at most PLACEMENT_FRAME_MS away.
|
||||
*/
|
||||
function askMotionFrame(motion) {
|
||||
if (!motion.moving) return;
|
||||
let waitMs = PLACEMENT_FRAME_MS;
|
||||
const movedPx = movedPixels(motion);
|
||||
if (movedPx > 0 && motion.sinceMs > 0)
|
||||
waitMs = Math.min(waitMs, (VESSEL_STEP_PX * motion.sinceMs) / movedPx);
|
||||
// A frame already asked for no later than this one stands.
|
||||
const runtime = vesselState._aisRuntime;
|
||||
const dueMs = runtime.now() + waitMs;
|
||||
if (placementFrameTimer !== null) {
|
||||
if (placementFrameDueMs <= dueMs) return;
|
||||
runtime.clearTimeout(placementFrameTimer);
|
||||
}
|
||||
placementFrameDueMs = dueMs;
|
||||
placementFrameTimer = runtime.setTimeout(() => {
|
||||
placementFrameTimer = null;
|
||||
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
|
||||
}, waitMs);
|
||||
}
|
||||
|
||||
/** Stop asking for placement frames (the layer turned off or went away). */
|
||||
function cancelPlacementFrame() {
|
||||
placedAtWallMs = -Infinity;
|
||||
placing = false;
|
||||
motionPassWallMs = null;
|
||||
if (placementFrameTimer === null) return;
|
||||
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
|
||||
placementFrameTimer = null;
|
||||
@@ -629,14 +749,21 @@ export function createRendering({
|
||||
(regularPass || focusPass || !state.trailingVisibilityTimer)
|
||||
? findCamera(state.viewer)?.pose()
|
||||
: null;
|
||||
// Following the clock, the time drawn decides which vessels are there
|
||||
// yet: a time that moved since the last pass (a seek while paused) gets
|
||||
// its pass too.
|
||||
const worldMs = followsClock(vesselState) ? vesselState.worldNow() : null;
|
||||
if (
|
||||
!regularPass &&
|
||||
pose &&
|
||||
poseSignature(pose) !== vesselState._lastCamPoseSig
|
||||
((pose && poseSignature(pose) !== vesselState._lastCamPoseSig) ||
|
||||
worldMs !== state.visibilityWorldMs)
|
||||
)
|
||||
scheduleTrailingVisibilityPass(now);
|
||||
if (!regularPass && !focusPass) return;
|
||||
if (regularPass) state.lastVisibilityUpdate = now;
|
||||
if (regularPass) {
|
||||
state.lastVisibilityUpdate = now;
|
||||
state.visibilityWorldMs = worldMs;
|
||||
}
|
||||
if (focusPass) state.lastFocusUpdate = now;
|
||||
if (!state.records.all.length) {
|
||||
// No records — flush any lingering card entries (vanished-feed case).
|
||||
@@ -665,7 +792,9 @@ export function createRendering({
|
||||
const labelCandidates = [];
|
||||
for (const record of state.records.all) {
|
||||
const visual = getVisual(record);
|
||||
visual.visible = isVisible(visual.cullPosition, occluder);
|
||||
visual.visible = isVisible(visual.cullPosition, occluder, record);
|
||||
// A vessel the time drawn reaches (or leaves) shows (or hides) its icon.
|
||||
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
|
||||
if (visual.visible) labelCandidates.push(record);
|
||||
}
|
||||
updateClusteredLabels(labelCandidates);
|
||||
@@ -760,11 +889,23 @@ export function createRendering({
|
||||
return pose?.position ? horizonFrom(pose.position) : null;
|
||||
}
|
||||
|
||||
function isVisible(cullPosition, occluder) {
|
||||
function isVisible(cullPosition, occluder, record) {
|
||||
if (record && !seenYet(record)) return false;
|
||||
if (!cullPosition || !occluder) return true;
|
||||
return occluder.isPointVisible(cullPosition);
|
||||
}
|
||||
|
||||
/** Whether a vessel is there at the time drawn: following the clock, not
|
||||
* more than TIMELINE_UNSEEN_MS before its first fix. */
|
||||
function seenYet(record) {
|
||||
const first = record.fixes?.[0];
|
||||
return (
|
||||
!first ||
|
||||
!followsClock(vesselState) ||
|
||||
vesselState.worldNow() >= first.atMs - TIMELINE_UNSEEN_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Source selector for the shared world-overlay pipeline: the
|
||||
* grid declutter picks which vessels get cards — one winner per screen-space
|
||||
@@ -957,6 +1098,7 @@ export function createRendering({
|
||||
cancelTrailingVisibilityPass,
|
||||
cancelPlacementFrame,
|
||||
followPlacements,
|
||||
followClockPositions,
|
||||
applyVesselFocusDeemphasis,
|
||||
makeOccluder,
|
||||
isVisible,
|
||||
|
||||
@@ -84,6 +84,8 @@ export function createVesselState({ source, services }) {
|
||||
/** Pending timer that renders one frame after a cadence-skipped pass. */
|
||||
trailingVisibilityTimer: null,
|
||||
lastVisibilityUpdate: 0,
|
||||
/** Following the clock, the world time the last visibility pass drew. */
|
||||
visibilityWorldMs: null,
|
||||
lastFocusUpdate: 0,
|
||||
/** Sprites whose animated emphasis remains outside the 1.0 deadband. */
|
||||
activeFocusCount: 0,
|
||||
|
||||
@@ -170,12 +170,32 @@ export function createTesting({
|
||||
return components.rendering.prepareRecordVisual(record);
|
||||
}
|
||||
|
||||
/** A record's visual (the record itself before it has one). Test-only seam. */
|
||||
|
||||
function _vesselVisualForTest(record) {
|
||||
return components.rendering.getVisual(record);
|
||||
}
|
||||
|
||||
/** Run one live placement pass (a host-supplied placement). Test-only seam. */
|
||||
|
||||
function _runPlacementPassForTest() {
|
||||
components.rendering.followPlacements();
|
||||
}
|
||||
|
||||
/** Run one world-clock pass at world time `atMs`. Test-only seam. */
|
||||
|
||||
function _runClockPassForTest(atMs) {
|
||||
vesselState.worldNow = () => atMs;
|
||||
components.rendering.followClockPositions();
|
||||
}
|
||||
|
||||
/** Follow the world clock, standing at world time `atMs`. Test-only seam. */
|
||||
|
||||
function _followClockForTest(atMs) {
|
||||
vesselState.timeline = { active: () => true };
|
||||
vesselState.worldNow = () => atMs;
|
||||
}
|
||||
|
||||
/** True while a trailing visibility frame is scheduled. Test-only seam. */
|
||||
|
||||
function _hasTrailingVisibilityPassForTest() {
|
||||
@@ -204,6 +224,7 @@ export function createTesting({
|
||||
return {
|
||||
_bindVesselInteractionForTest,
|
||||
_setVesselStateForTest,
|
||||
_followClockForTest,
|
||||
_setVesselOverlayHostForTest,
|
||||
_updateVesselCardsForTest,
|
||||
_reconcileVesselsForTest,
|
||||
@@ -216,7 +237,9 @@ export function createTesting({
|
||||
_vesselRecordForTest,
|
||||
_runVisibilityPassForTest,
|
||||
_prepareVesselVisualForTest,
|
||||
_vesselVisualForTest,
|
||||
_runPlacementPassForTest,
|
||||
_runClockPassForTest,
|
||||
_hasTrailingVisibilityPassForTest,
|
||||
};
|
||||
}
|
||||
@@ -66,11 +66,10 @@ export function createTracking({
|
||||
continue;
|
||||
visual.position = components.rendering.anchorPosition(record);
|
||||
components.rendering.syncRecordIcon(record);
|
||||
// A placed vessel is drawn again at its placement on the next pass.
|
||||
if (services.placement) {
|
||||
visual.drawnLat = NaN;
|
||||
visual.drawnLon = NaN;
|
||||
}
|
||||
// A moving vessel is drawn again where it is on the next pass.
|
||||
visual.drawnLat = NaN;
|
||||
visual.drawnLon = NaN;
|
||||
visual.followedAtMs = undefined;
|
||||
}
|
||||
// The rows moved with no poll behind them: draw the frame that shows it.
|
||||
governorRequestRender('ais-vessels-refloor');
|
||||
|
||||
@@ -16,8 +16,13 @@ import {
|
||||
acquireInfraredMosaic,
|
||||
processInfraredImage,
|
||||
} from './infraredImage.js';
|
||||
// Bounded display detail for the hourly, approximately 3 km global product.
|
||||
// Bounded display detail for the hourly, approximately 3 km global product
|
||||
// when it is drawn from one 2048 × 1024 mosaic.
|
||||
const GLOBAL_TILE_MAXIMUM_LEVEL = 3;
|
||||
// Detail of the tiled products when the feed does not name its own.
|
||||
const TILE_MAXIMUM_LEVEL = 6;
|
||||
// The deepest level a feed may name: about 150 m a pixel.
|
||||
const SUPPLIED_MAXIMUM_LEVEL_LIMIT = 12;
|
||||
// Six decoded 2048×1024 canvases (8 MiB each) bound the cache below 50 MiB.
|
||||
const MAX_MOSAICS = 6;
|
||||
const MAX_PREFETCH_TILES = 8;
|
||||
@@ -89,10 +94,33 @@ function createGlobeRendering({
|
||||
let prefetchJob = null;
|
||||
let prefetchedKey = null;
|
||||
|
||||
/** The deepest level the feed's own tiles of `product` go to, or null. */
|
||||
function suppliedLevel(product) {
|
||||
if (!frameSource?.getTile) return null;
|
||||
let level = null;
|
||||
try {
|
||||
level = frameSource.maximumLevel?.(product) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return Number.isInteger(level) &&
|
||||
level >= 0 &&
|
||||
level <= SUPPLIED_MAXIMUM_LEVEL_LIMIT
|
||||
? level
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Global clouds come from one mosaic unless the feed tiles them itself. */
|
||||
function fromMosaic(product) {
|
||||
return product === 'clouds' && suppliedLevel(product) === null;
|
||||
}
|
||||
|
||||
function profile(product) {
|
||||
return {
|
||||
tileSize: 256,
|
||||
maximumLevel: product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : 6,
|
||||
maximumLevel:
|
||||
suppliedLevel(product) ??
|
||||
(product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : TILE_MAXIMUM_LEVEL),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -287,7 +315,7 @@ function createGlobeRendering({
|
||||
!snapshot.times.includes(time)
|
||||
)
|
||||
return false;
|
||||
const global = snapshot.product === 'clouds';
|
||||
const global = fromMosaic(snapshot.product);
|
||||
const tiles = global ? [] : prefetchTiles(snapshot);
|
||||
const supplied = !global && Boolean(frameSource?.getTile);
|
||||
const urls = global || supplied ? [] : tileUrls(snapshot, time, tiles);
|
||||
@@ -352,7 +380,7 @@ function createGlobeRendering({
|
||||
lastError = null;
|
||||
const { west, south, east, north } = snapshot.bounds;
|
||||
const rectangle = { west, south, east, north };
|
||||
const global = snapshot.product === 'clouds';
|
||||
const global = fromMosaic(snapshot.product);
|
||||
const frame = {
|
||||
snapshot,
|
||||
creditSnapshot,
|
||||
@@ -500,7 +528,10 @@ function createGlobeRendering({
|
||||
maxConcurrentRequests: 6,
|
||||
}
|
||||
: {}),
|
||||
...(snapshot.product === 'clouds-regional'
|
||||
// Infrared tiles get the display transfer the mosaic already
|
||||
// carries.
|
||||
...(snapshot.product === 'clouds-regional' ||
|
||||
snapshot.product === 'clouds'
|
||||
? {
|
||||
// The transfer runs on the upright tile the renderer
|
||||
// decoded.
|
||||
|
||||
@@ -121,6 +121,10 @@ export function weatherTileUrl(product, time, { size } = {}) {
|
||||
* degrees) a detail window of it. `getFrameTile` returns one `size`-pixel tile
|
||||
* of the geographic tiling scheme, or null for a transparent tile. Rows run
|
||||
* top-down (north first), as an image does. Both honour `signal`.
|
||||
* `frameMaximumLevel` names the deepest level of that scheme the feed's tiles
|
||||
* of a product hold detail at (0–12), or null for the layer's own: with it,
|
||||
* global clouds are drawn from the feed's tiles to that level instead of from
|
||||
* one 2048 × 1024 image.
|
||||
* @typedef {object} WeatherFrameFeed
|
||||
* @property {(request: { product: string, time: string,
|
||||
* size: { width: number, height: number },
|
||||
@@ -129,19 +133,25 @@ export function weatherTileUrl(product, time, { size } = {}) {
|
||||
* @property {(request: { product: string, time: string, z: number, x: number,
|
||||
* y: number, size: number, signal: AbortSignal })
|
||||
* => Promise<WeatherPixels | null>} [getFrameTile]
|
||||
* @property {(product: string) => number | null} [frameMaximumLevel]
|
||||
*/
|
||||
|
||||
/**
|
||||
* The frame source a feed provides, or null when it has neither method. A
|
||||
* missing method is left undefined, so that path keeps the routes.
|
||||
* @param {WeatherFrameFeed | undefined} feed
|
||||
* @returns {{ getImage?: Function, getTile?: Function } | null}
|
||||
* @returns {{ getImage?: Function, getTile?: Function,
|
||||
* maximumLevel?: Function } | null}
|
||||
*/
|
||||
export function weatherFrameSource(feed) {
|
||||
const image = typeof feed?.getFrameImage === 'function';
|
||||
const tile = typeof feed?.getFrameTile === 'function';
|
||||
if (!image && !tile) return null;
|
||||
const level = typeof feed?.frameMaximumLevel === 'function';
|
||||
return {
|
||||
maximumLevel: level
|
||||
? (product) => feed.frameMaximumLevel(product)
|
||||
: undefined,
|
||||
getImage: image
|
||||
? ({ product, time, size, bbox = null, signal }) =>
|
||||
feed.getFrameImage({ product, time, size, bbox, signal })
|
||||
|
||||
@@ -257,6 +257,13 @@ test('a frame source forwards exactly the documented requests to its feed', asyn
|
||||
assert.equal(imagesOnly.getTile, undefined, 'tiles keep the tile route');
|
||||
const tilesOnly = weatherFrameSource({ getFrameTile: feed.getFrameTile });
|
||||
assert.equal(tilesOnly.getImage, undefined, 'images keep the image route');
|
||||
assert.equal(tilesOnly.maximumLevel, undefined);
|
||||
const leveled = weatherFrameSource({
|
||||
getFrameTile: feed.getFrameTile,
|
||||
frameMaximumLevel: (product) => (product === 'clouds' ? 6 : null),
|
||||
});
|
||||
assert.equal(leveled.maximumLevel('clouds'), 6);
|
||||
assert.equal(leveled.maximumLevel('radar'), null);
|
||||
});
|
||||
|
||||
test('supplied pixels report their drawn size, draw at the origin and close once', (t) => {
|
||||
|
||||
@@ -2739,6 +2739,99 @@ test('a frame source supplies regional tiles in place of the tile route, through
|
||||
h.rendering.clear();
|
||||
});
|
||||
|
||||
test('a frame source that names its tile detail draws global clouds from its tiles to that level', async () => {
|
||||
let now = 0;
|
||||
const requests = [];
|
||||
const h = renderingHarness({
|
||||
now: () => now,
|
||||
fetchImpl: () => assert.fail('supplied clouds are not fetched'),
|
||||
frameSource: {
|
||||
getImage: () => assert.fail('no mosaic when the feed tiles clouds'),
|
||||
getTile: async (request) => {
|
||||
requests.push(request);
|
||||
return suppliedTile();
|
||||
},
|
||||
maximumLevel: (product) => (product === 'clouds' ? 6 : 8),
|
||||
},
|
||||
});
|
||||
h.viewer.scene.globe.tilesLoaded = false;
|
||||
const loaded = h.rendering.setFrame(globalSnapshot, times[0]);
|
||||
assert.equal(h.providers.length, 1);
|
||||
const [provider] = h.providers;
|
||||
assert.equal(typeof provider.spec.fetchTile, 'function', 'not the route');
|
||||
assert.equal(provider.spec.maxLevel, 6);
|
||||
await provider.requestImage(5, 3, 4, {});
|
||||
assert.deepEqual(
|
||||
[requests[0].product, requests[0].z, requests[0].x, requests[0].y],
|
||||
['clouds', 4, 5, 3],
|
||||
);
|
||||
now = 500;
|
||||
h.settle();
|
||||
assert.equal(await loaded, true);
|
||||
h.rendering.clear();
|
||||
|
||||
// Radar takes the level the feed names for it.
|
||||
const radar = renderingHarness({
|
||||
frameSource: {
|
||||
getTile: async () => suppliedTile(),
|
||||
maximumLevel: () => 8,
|
||||
},
|
||||
});
|
||||
radar.rendering.setFrame(snapshot, times[0]);
|
||||
assert.equal(radar.providers[0].spec.maxLevel, 8);
|
||||
radar.rendering.clear();
|
||||
});
|
||||
|
||||
test("a frame source naming no usable level keeps the layer's own detail", async () => {
|
||||
for (const maximumLevel of [
|
||||
() => null,
|
||||
() => 13,
|
||||
() => 2.5,
|
||||
() => 'deep',
|
||||
() => {
|
||||
throw new Error('no level');
|
||||
},
|
||||
]) {
|
||||
const h = renderingHarness({
|
||||
frameSource: { getTile: async () => suppliedTile(), maximumLevel },
|
||||
});
|
||||
h.rendering.setFrame(snapshot, times[0]);
|
||||
assert.equal(h.providers[0].spec.maxLevel, 6);
|
||||
h.rendering.clear();
|
||||
// Global clouds stay on the one image, cut to level 3.
|
||||
let mosaics = 0;
|
||||
const clouds = renderingHarness({
|
||||
frameSource: {
|
||||
getImage: async () => {
|
||||
mosaics++;
|
||||
return { width: 2048, height: 1024, close() {} };
|
||||
},
|
||||
getTile: () => assert.fail('clouds are not tiled without a level'),
|
||||
maximumLevel,
|
||||
},
|
||||
});
|
||||
await showMosaic(clouds, times[0]);
|
||||
assert.equal(mosaics, 1);
|
||||
assert.equal(clouds.providers[0].spec.maxLevel, 3);
|
||||
clouds.rendering.clear();
|
||||
}
|
||||
// A level without tiles leaves global clouds on the mosaic.
|
||||
let images = 0;
|
||||
const h = renderingHarness({
|
||||
frameSource: {
|
||||
getImage: async () => {
|
||||
images++;
|
||||
return suppliedTile();
|
||||
},
|
||||
maximumLevel: () => 6,
|
||||
},
|
||||
});
|
||||
h.rendering.setFrame(globalSnapshot, times[0]);
|
||||
await flush();
|
||||
assert.equal(images, 1);
|
||||
h.rendering.clear();
|
||||
});
|
||||
|
||||
test('a failed supplied tile fails the staged frame through the tile error', async () => {
|
||||
const h = renderingHarness({
|
||||
frameSource: {
|
||||
@@ -2798,6 +2891,57 @@ test("supplied regional infrared tiles get the transfer upright, as the route's
|
||||
}
|
||||
});
|
||||
|
||||
test('global clouds tiles get the infrared transfer, and prefetch asks for tiles, not the image', async () => {
|
||||
const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap');
|
||||
const previous = globalThis.ImageBitmap;
|
||||
globalThis.ImageBitmap = class ImageBitmap {
|
||||
width = 256;
|
||||
height = 256;
|
||||
close() {}
|
||||
};
|
||||
try {
|
||||
const requests = [];
|
||||
const h = renderingHarness({
|
||||
frameSource: {
|
||||
getImage: () => assert.fail('no image when the feed tiles clouds'),
|
||||
getTile: async (request) => {
|
||||
requests.push(request);
|
||||
return new globalThis.ImageBitmap();
|
||||
},
|
||||
maximumLevel: () => 6,
|
||||
},
|
||||
});
|
||||
void h.rendering.setFrame(globalSnapshot, times[0]);
|
||||
const [provider] = h.providers;
|
||||
const decoded = await provider.requestImage(5, 3, 4, {});
|
||||
const tile = await provider.spec.tileTransform(
|
||||
{ x: 5, y: 3, level: 4 },
|
||||
decoded,
|
||||
);
|
||||
assert.equal(tile.drawnWith, null, 'drawn upright, not flipped');
|
||||
assert.ok(tile.pixels, 'the infrared transfer ran');
|
||||
h.rendering.clear();
|
||||
requests.length = 0;
|
||||
const warm = renderingHarness({
|
||||
frameSource: {
|
||||
getImage: () => assert.fail('no image when the feed tiles clouds'),
|
||||
getTile: async (request) => {
|
||||
requests.push(request);
|
||||
return new globalThis.ImageBitmap();
|
||||
},
|
||||
maximumLevel: () => 6,
|
||||
},
|
||||
});
|
||||
assert.equal(await warm.rendering.prefetch(globalSnapshot, times[1]), true);
|
||||
assert.ok(requests.length > 0, 'prefetch asked for tiles');
|
||||
assert.ok(requests.every((request) => request.product === 'clouds'));
|
||||
warm.rendering.clear();
|
||||
} finally {
|
||||
if (hadBitmap) globalThis.ImageBitmap = previous;
|
||||
else delete globalThis.ImageBitmap;
|
||||
}
|
||||
});
|
||||
|
||||
test('tiled prefetch asks the frame source for the same level 0/1 tiles and releases them', async (t) => {
|
||||
const requests = [];
|
||||
const supplied = [];
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
/**
|
||||
* Strict decimal-degree coordinate parsing for the search box.
|
||||
* Strict coordinate parsing for the search box.
|
||||
*
|
||||
* A search that guesses is worse than one that declines: reading `12junk, 34oops`
|
||||
* as 12, 34 flies the operator somewhere they did not ask for and looks like a
|
||||
* successful search. So every rule here is exact — a component is a decimal
|
||||
* number, optionally signed, optionally marked with one hemisphere letter, and
|
||||
* nothing else. Two-dimensional WGS84 geo URIs use their own strict grammar.
|
||||
* Degrees/minutes/seconds and grid references are not handled;
|
||||
* they fall through to the geocoders, which is what happens today.
|
||||
* number, or degrees with minutes and seconds marked by their symbols
|
||||
* (`40°26'46"`), optionally signed, optionally marked with one hemisphere
|
||||
* letter, and nothing else. Two-dimensional WGS84 geo URIs use their own
|
||||
* strict grammar, as do UTM and MGRS grid references (`gridReference.js`) and
|
||||
* full plus codes (`plusCode.js`). Unmarked runs such as `40 26 46 N` and
|
||||
* short plus codes are not handled; they fall through to the geocoders.
|
||||
*/
|
||||
import { parseGridReference } from './gridReference.js';
|
||||
import { parsePlusCode } from './plusCode.js';
|
||||
|
||||
/** One decimal-degree component: an optional hemisphere letter on either side. */
|
||||
const COMPONENT =
|
||||
@@ -18,6 +22,14 @@ const COMPONENT =
|
||||
const GEO_URI =
|
||||
/^geo:(-?\d{1,2}(?:\.\d+)?),(-?\d{1,3}(?:\.\d+)?)(?:;crs=wgs84)?$/i;
|
||||
|
||||
/**
|
||||
* Degrees, minutes and optional seconds, each marked by its symbol, with an
|
||||
* optional sign and one optional hemisphere letter on either side. Only the
|
||||
* last number may have a decimal part.
|
||||
*/
|
||||
const DMS_COMPONENT =
|
||||
/^([NSEW])?\s*([+-])?(\d{1,3})\s*[°º]\s*(\d{1,2}(?:\.\d+)?)\s*['′’]\s*(?:(\d{1,2}(?:\.\d+)?)\s*(?:"|″|”|''|′′))?\s*([NSEW])?$/i;
|
||||
|
||||
/** Hemisphere letters, by the axis each one can name. */
|
||||
const LATITUDE_LETTERS = new Set(['N', 'S']);
|
||||
|
||||
@@ -29,7 +41,7 @@ const LATITUDE_LETTERS = new Set(['N', 'S']);
|
||||
*/
|
||||
function readComponent(text) {
|
||||
const match = COMPONENT.exec(String(text).trim());
|
||||
if (!match) return null;
|
||||
if (!match) return readDmsComponent(text);
|
||||
const [, before, digits, after] = match;
|
||||
// Two letters on one component is a contradiction, not a coordinate.
|
||||
if (before && after) return null;
|
||||
@@ -47,6 +59,34 @@ function readComponent(text) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one degrees-minutes-seconds component, by the same rules as a decimal
|
||||
* one: a sign and a letter never both, minutes and seconds below 60, and a
|
||||
* decimal part only on the last number given.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {{ value: number, axis: 'lat'|'lon'|null } | null}
|
||||
*/
|
||||
function readDmsComponent(text) {
|
||||
const match = DMS_COMPONENT.exec(String(text).trim());
|
||||
if (!match) return null;
|
||||
const [, before, sign, degrees, minutes, seconds, after] = match;
|
||||
if (before && after) return null;
|
||||
const letter = (before || after || '').toUpperCase();
|
||||
if (letter && sign) return null;
|
||||
if (seconds !== undefined && minutes.includes('.')) return null;
|
||||
if (Number(minutes) >= 60 || (seconds !== undefined && Number(seconds) >= 60))
|
||||
return null;
|
||||
const magnitude =
|
||||
Number(degrees) + Number(minutes) / 60 + Number(seconds ?? 0) / 3600;
|
||||
if (!letter)
|
||||
return { value: sign === '-' ? -magnitude : magnitude, axis: null };
|
||||
return {
|
||||
value: letter === 'S' || letter === 'W' ? -magnitude : magnitude,
|
||||
axis: LATITUDE_LETTERS.has(letter) ? 'lat' : 'lon',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Split on a comma, a semicolon, or whitespace — never on anything else.
|
||||
* A hemisphere letter stays with the number it names, so `40.7 N 74.0 W`
|
||||
@@ -61,8 +101,9 @@ function splitComponents(query) {
|
||||
return trimmed.length === 2 && trimmed.every(Boolean) ? trimmed : null;
|
||||
}
|
||||
const words = text.split(/\s+/);
|
||||
// Each component has at most a number, a degree sign and one hemisphere.
|
||||
if (words.length > 6) return null;
|
||||
// Each component has at most degrees, minutes and seconds with their
|
||||
// symbols and one hemisphere letter.
|
||||
if (words.length > 14) return null;
|
||||
// Keep every character: extracting tokens would turn `1e3` or `1.2.3`
|
||||
// into invented coordinates. A lone letter between numbers can name either
|
||||
// component; require an unambiguous split rather than guessing its owner.
|
||||
@@ -88,7 +129,9 @@ export function formatCoordinateLabel(lat, lon) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a decimal-degree pair or a two-dimensional WGS84 geo URI, or return null.
|
||||
* Parse a decimal-degree or degrees-minutes-seconds pair, a two-dimensional
|
||||
* WGS84 geo URI, a UTM or MGRS grid reference or a full plus code, or return
|
||||
* null.
|
||||
*
|
||||
* Both orders are accepted when the hemisphere letters say which is which
|
||||
* (`W 40, N 74` is longitude then latitude); with no letters the conventional
|
||||
@@ -107,7 +150,12 @@ export function parseCoordinateQuery(query) {
|
||||
const parts = /^geo:/i.test(text)
|
||||
? GEO_URI.exec(text)?.slice(1, 3)
|
||||
: splitComponents(text);
|
||||
if (!parts) return null;
|
||||
if (!parts) {
|
||||
const point = parseGridReference(text) ?? parsePlusCode(text);
|
||||
return (
|
||||
point && { ...point, label: formatCoordinateLabel(point.lat, point.lon) }
|
||||
);
|
||||
}
|
||||
|
||||
const first = readComponent(parts[0]);
|
||||
const second = readComponent(parts[1]);
|
||||
|
||||
@@ -124,12 +124,9 @@ test('malformed and ambiguous coordinates are refused, never guessed', () => {
|
||||
'0, 181',
|
||||
'0, -180.5',
|
||||
'N 100, W 74',
|
||||
// Degrees/minutes/seconds is out of scope and must fall through, not
|
||||
// be read as a decimal pair.
|
||||
'40°26\'46"N, 79°58\'56"W',
|
||||
// Degrees/minutes/seconds without their symbols must fall through, not
|
||||
// be read as a decimal pair (marked ones are in gridReference.test.mjs).
|
||||
'40 26 46, 79 58 56',
|
||||
// A grid reference is out of scope too.
|
||||
'33UXP0500444998',
|
||||
]) {
|
||||
assert.equal(
|
||||
parseCoordinateQuery(query),
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* UTM and MGRS grid references to latitude and longitude, for the search box.
|
||||
*
|
||||
* Strict, like the decimal parser: a reference either reads exactly or is
|
||||
* declined. UTM is `18T 585628 4511322` (zone, latitude band, easting,
|
||||
* northing); MGRS is `18T WL 85650 11369`, spaced or not, with 3 to 5 digits
|
||||
* each for easting and northing (100 m to 1 m). Coarser MGRS (`18T WL 8511`)
|
||||
* declines: written that way, `1 JAN 2023`, `3 USA 12` or `20 KPH 1000` would
|
||||
* read as grid squares. MGRS letters are capitals, as references are printed,
|
||||
* unless written unspaced (`18twl856113`), and the square must lie in its
|
||||
* zone. Letters that spell a month (`1 JAN 2023 1200`) decline: a date is far
|
||||
* likelier than one of those few squares. The polar UPS bands (A, B, Y, Z) and the zones Svalbard does not use
|
||||
* (32X, 34X, 36X) decline. A UTM `N` or `S` is the latitude band when its
|
||||
* northing falls in that band, and otherwise the hemisphere, as UTM is also
|
||||
* written (`33N 500000 4500000`); a southern reference between about 50°S and
|
||||
* 58°S written with `S` reads as band S.
|
||||
*/
|
||||
|
||||
/** WGS84. */
|
||||
const A = 6378137;
|
||||
const F = 1 / 298.257223563;
|
||||
const K0 = 0.9996;
|
||||
const FALSE_EASTING = 500000;
|
||||
const FALSE_NORTHING_SOUTH = 10000000;
|
||||
|
||||
/** Latitude bands C to X (no I or O), 8° each from 80°S; X is 12°. */
|
||||
const BANDS = 'CDEFGHJKLMNPQRSTUVWX';
|
||||
|
||||
/** MGRS 100 km column letters by zone set, and the row letters. */
|
||||
const COLUMN_SETS = ['ABCDEFGH', 'JKLMNPQR', 'STUVWXYZ'];
|
||||
const ROW_LETTERS = 'ABCDEFGHJKLMNPQRSTUV';
|
||||
|
||||
/** The latitude range of a band letter, or null. */
|
||||
function bandRange(letter) {
|
||||
const index = BANDS.indexOf(letter);
|
||||
if (index < 0) return null;
|
||||
const south = -80 + index * 8;
|
||||
return { south, north: letter === 'X' ? 84 : south + 8 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverse transverse Mercator (Krüger's series to the sixth order, as in
|
||||
* Karney 2011): UTM easting and northing in a zone to latitude and longitude.
|
||||
*/
|
||||
function utmToLatLon(zone, easting, northing, southern) {
|
||||
const n = F / (2 - F);
|
||||
const n2 = n * n;
|
||||
const n3 = n2 * n;
|
||||
const n4 = n3 * n;
|
||||
const n5 = n4 * n;
|
||||
const n6 = n5 * n;
|
||||
const rectifying = (A / (1 + n)) * (1 + n2 / 4 + n4 / 64 + n6 / 256);
|
||||
const beta = [
|
||||
n / 2 -
|
||||
(2 / 3) * n2 +
|
||||
(37 / 96) * n3 -
|
||||
n4 / 360 -
|
||||
(81 / 512) * n5 +
|
||||
(96199 / 604800) * n6,
|
||||
n2 / 48 +
|
||||
n3 / 15 -
|
||||
(437 / 1440) * n4 +
|
||||
(46 / 105) * n5 -
|
||||
(1118711 / 3870720) * n6,
|
||||
(17 / 480) * n3 - (37 / 840) * n4 - (209 / 4480) * n5 + (5569 / 90720) * n6,
|
||||
(4397 / 161280) * n4 - (11 / 504) * n5 - (830251 / 7257600) * n6,
|
||||
(4583 / 161280) * n5 - (108847 / 3991680) * n6,
|
||||
(20648693 / 638668800) * n6,
|
||||
];
|
||||
const xi =
|
||||
(southern ? northing - FALSE_NORTHING_SOUTH : northing) / (K0 * rectifying);
|
||||
const eta = (easting - FALSE_EASTING) / (K0 * rectifying);
|
||||
let xiPrime = xi;
|
||||
let etaPrime = eta;
|
||||
for (let j = 1; j <= 6; j += 1) {
|
||||
xiPrime -= beta[j - 1] * Math.sin(2 * j * xi) * Math.cosh(2 * j * eta);
|
||||
etaPrime -= beta[j - 1] * Math.cos(2 * j * xi) * Math.sinh(2 * j * eta);
|
||||
}
|
||||
const conformal = Math.asin(Math.sin(xiPrime) / Math.cosh(etaPrime));
|
||||
const longitudeOffset = Math.atan2(Math.sinh(etaPrime), Math.cos(xiPrime));
|
||||
// Conformal to geodetic latitude, by Newton's method on tan φ.
|
||||
const e = Math.sqrt(F * (2 - F));
|
||||
const tauPrime = Math.tan(conformal);
|
||||
let tau = tauPrime;
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
const sigma = Math.sinh(
|
||||
e * Math.atanh((e * tau) / Math.sqrt(1 + tau * tau)),
|
||||
);
|
||||
const tauIPrime =
|
||||
tau * Math.sqrt(1 + sigma * sigma) - sigma * Math.sqrt(1 + tau * tau);
|
||||
const delta =
|
||||
((tauPrime - tauIPrime) / Math.sqrt(1 + tauIPrime * tauIPrime)) *
|
||||
((1 + (1 - e * e) * tau * tau) /
|
||||
((1 - e * e) * Math.sqrt(1 + tau * tau)));
|
||||
tau += delta;
|
||||
if (Math.abs(delta) < 1e-12) break;
|
||||
}
|
||||
const lat = (Math.atan(tau) * 180) / Math.PI;
|
||||
let lon = (zone - 1) * 6 - 180 + 3 + (longitudeOffset * 180) / Math.PI;
|
||||
if (lon > 180) lon -= 360;
|
||||
if (lon < -180) lon += 360;
|
||||
return { lat, lon };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a latitude sits in a band, allowing `slack` degrees past its edges
|
||||
* (an MGRS square's centre can lie across the band edge the square touches).
|
||||
*/
|
||||
function inBand(lat, range, slack = 0) {
|
||||
return lat >= range.south - slack && lat <= range.north + slack;
|
||||
}
|
||||
|
||||
/** Zones 32, 34 and 36 do not exist in band X (Svalbard's widened zones). */
|
||||
function zoneExists(zone, band) {
|
||||
return !(band === 'X' && (zone === 32 || zone === 34 || zone === 36));
|
||||
}
|
||||
|
||||
/** Svalbard's widened zones in band X, as [west, east] longitudes. */
|
||||
const SVALBARD_ZONES = { 31: [0, 9], 33: [9, 21], 35: [21, 33], 37: [33, 42] };
|
||||
|
||||
/**
|
||||
* The longitudes a zone covers in a band: 6° each, except southwest Norway
|
||||
* (31V is 0°–3°E, 32V is 3°E–12°E) and Svalbard (band X).
|
||||
*/
|
||||
function zoneLongitudes(zone, band) {
|
||||
if (band === 'V' && zone === 31) return [0, 3];
|
||||
if (band === 'V' && zone === 32) return [3, 12];
|
||||
if (band === 'X' && SVALBARD_ZONES[zone]) return SVALBARD_ZONES[zone];
|
||||
const west = (zone - 1) * 6 - 180;
|
||||
return [west, west + 6];
|
||||
}
|
||||
|
||||
/** UTM `18T 585628 4511322` (or `18 T 585628 4511322`), or null. */
|
||||
function parseUtm(text) {
|
||||
const match =
|
||||
/^(\d{1,2})\s*([C-HJ-NP-X])\s+(\d{6}(?:\.\d+)?)\s*m?\s+(\d{1,7}(?:\.\d+)?)\s*m?$/i.exec(
|
||||
text,
|
||||
);
|
||||
if (!match) return null;
|
||||
const zone = Number(match[1]);
|
||||
const letter = match[2].toUpperCase();
|
||||
const easting = Number(match[3]);
|
||||
const northing = Number(match[4]);
|
||||
if (
|
||||
zone < 1 ||
|
||||
zone > 60 ||
|
||||
easting < 100000 ||
|
||||
easting > 900000 ||
|
||||
northing > 10000000 ||
|
||||
!zoneExists(zone, letter)
|
||||
)
|
||||
return null;
|
||||
const range = bandRange(letter);
|
||||
const asBand = utmToLatLon(zone, easting, northing, range.south < 0);
|
||||
const bandFits = inBand(asBand.lat, range);
|
||||
if (bandFits) return asBand;
|
||||
// `N` and `S` are also how UTM is written for the hemispheres. Where both
|
||||
// fit, the 32°N–40°N band (Tokyo, Los Angeles, the Mediterranean) is far
|
||||
// likelier than 50°S–58°S, so the band wins above.
|
||||
if (letter === 'N') {
|
||||
const north = utmToLatLon(zone, easting, northing, false);
|
||||
if (north.lat >= 0 && north.lat <= 84) return north;
|
||||
}
|
||||
if (letter === 'S') {
|
||||
const south = utmToLatLon(zone, easting, northing, true);
|
||||
if (south.lat < 0 && south.lat >= -80) return south;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lowest northing of each band, in metres, that MGRS's 2,000 km row
|
||||
* cycle is lifted past (the NGA table, as used by proj4's mgrs module).
|
||||
*/
|
||||
const BAND_MIN_NORTHING = {
|
||||
C: 1100000,
|
||||
D: 2000000,
|
||||
E: 2800000,
|
||||
F: 3700000,
|
||||
G: 4600000,
|
||||
H: 5500000,
|
||||
J: 6400000,
|
||||
K: 7300000,
|
||||
L: 8200000,
|
||||
M: 9100000,
|
||||
N: 0,
|
||||
P: 800000,
|
||||
Q: 1700000,
|
||||
R: 2600000,
|
||||
S: 3500000,
|
||||
T: 4400000,
|
||||
U: 5300000,
|
||||
V: 6200000,
|
||||
W: 7000000,
|
||||
X: 7900000,
|
||||
};
|
||||
|
||||
/** Month abbreviations a band and square could spell (`JAN`, `SEP`, …). */
|
||||
const MONTHS = new Set([
|
||||
'JAN',
|
||||
'FEB',
|
||||
'MAR',
|
||||
'MAY',
|
||||
'JUN',
|
||||
'JUL',
|
||||
'SEP',
|
||||
'NOV',
|
||||
'DEC',
|
||||
]);
|
||||
|
||||
/**
|
||||
* MGRS as `18TWL8565011369`, `18T WL 8565011369` or `18T WL 85650 11369`
|
||||
* (easting and northing the same length), or null.
|
||||
*/
|
||||
function parseMgrs(text) {
|
||||
const match =
|
||||
/^(\d{1,2})\s*([C-HJ-NP-X])\s*([A-HJ-NP-Z])([A-HJ-NP-V])(?:\s*(\d{6,10})|\s*(\d{3,5})\s+(\d{3,5}))$/i.exec(
|
||||
text,
|
||||
);
|
||||
if (!match) return null;
|
||||
const zone = Number(match[1]);
|
||||
const band = match[2].toUpperCase();
|
||||
const column = match[3].toUpperCase();
|
||||
const row = match[4].toUpperCase();
|
||||
let east;
|
||||
let north;
|
||||
if (match[5]) {
|
||||
if (match[5].length % 2) return null;
|
||||
east = match[5].slice(0, match[5].length / 2);
|
||||
north = match[5].slice(match[5].length / 2);
|
||||
} else if (match[6]) {
|
||||
if (match[6].length !== match[7].length) return null;
|
||||
[east, north] = [match[6], match[7]];
|
||||
}
|
||||
if (zone < 1 || zone > 60 || !zoneExists(zone, band)) return null;
|
||||
const precision = east.length;
|
||||
const letters = text.replace(/[\d\s]/g, '');
|
||||
if (MONTHS.has(letters.toUpperCase())) return null;
|
||||
if (letters !== letters.toUpperCase() && /\s/.test(text)) return null;
|
||||
const columnIndex = COLUMN_SETS[(zone - 1) % 3].indexOf(column);
|
||||
if (columnIndex < 0) return null;
|
||||
// Rows start at A in odd zones and at F in even ones.
|
||||
const rowIndex =
|
||||
(ROW_LETTERS.indexOf(row) - (zone % 2 === 0 ? 5 : 0) + 20) % 20;
|
||||
const scale = 10 ** (5 - precision);
|
||||
// The centre of the square the digits name; a 1 m reference is its corner.
|
||||
const half = precision < 5 ? scale / 2 : 0;
|
||||
const easting = (columnIndex + 1) * 100000 + Number(east) * scale + half;
|
||||
let northing = rowIndex * 100000 + Number(north) * scale + half;
|
||||
while (northing < BAND_MIN_NORTHING[band]) northing += 2000000;
|
||||
const range = bandRange(band);
|
||||
const point = utmToLatLon(zone, easting, northing, range.south < 0);
|
||||
// Slack of the square's size in degrees of latitude, and in longitude at
|
||||
// that latitude.
|
||||
const slack = scale / 111000;
|
||||
if (!inBand(point.lat, range, slack)) return null;
|
||||
const [zoneWest, zoneEast] = zoneLongitudes(zone, band);
|
||||
const lonSlack =
|
||||
slack / Math.max(Math.cos((point.lat * Math.PI) / 180), 0.01);
|
||||
// Compare across the antimeridian unwrapped: zone 1 starts at 180°W.
|
||||
let lon = point.lon;
|
||||
if (lon - zoneWest > 180) lon -= 360;
|
||||
if (zoneEast - lon > 180) lon += 360;
|
||||
return lon >= zoneWest - lonSlack && lon <= zoneEast + lonSlack
|
||||
? point
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A UTM or MGRS reference as `{ lat, lon }`, or null when the text is not
|
||||
* exactly one.
|
||||
* @param {string} text
|
||||
*/
|
||||
export function parseGridReference(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed || trimmed.length > 40) return null;
|
||||
return parseUtm(trimmed) ?? parseMgrs(trimmed);
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// GRID REFERENCES AND PLUS CODES — UTM, MGRS and full Open Location Codes read
|
||||
// as coordinates. Each is exact or refused, like a decimal pair: a misread
|
||||
// reference flies the operator somewhere else and looks like success.
|
||||
//
|
||||
// The UTM and MGRS points are one per latitude band (and the zone edges) from
|
||||
// pyproj and the mgrs package; the plus codes are from the Open Location Code
|
||||
// project's test data (decoding.csv, validityTests.csv).
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseGridReference } from './gridReference.js';
|
||||
import { parsePlusCode } from './plusCode.js';
|
||||
import { parseCoordinateQuery } from './coordinateParser.js';
|
||||
|
||||
/** Metres between two points, near enough for sub-metre checks. */
|
||||
function metres(a, b) {
|
||||
const r = Math.PI / 180;
|
||||
const h =
|
||||
Math.sin(((b.lat - a.lat) * r) / 2) ** 2 +
|
||||
Math.cos(a.lat * r) *
|
||||
Math.cos(b.lat * r) *
|
||||
Math.sin(((b.lon - a.lon) * r) / 2) ** 2;
|
||||
return 12742000 * Math.asin(Math.sqrt(h));
|
||||
}
|
||||
|
||||
// [MGRS, its latitude, its longitude, UTM, its latitude, its longitude]
|
||||
const GRID = [
|
||||
[
|
||||
'18TWL8565011369',
|
||||
40.7488215,
|
||||
-73.9854319,
|
||||
'18T 585651 4511369',
|
||||
40.748817,
|
||||
-73.985428,
|
||||
],
|
||||
[
|
||||
'56HLH3490052290',
|
||||
-33.8567842,
|
||||
151.2152996,
|
||||
'56H 334900 6252291',
|
||||
-33.856784,
|
||||
151.215297,
|
||||
],
|
||||
[
|
||||
'33XWG1427883355',
|
||||
78.2232003,
|
||||
15.6266906,
|
||||
'33X 514279 8683355',
|
||||
78.2232,
|
||||
15.6267,
|
||||
],
|
||||
[
|
||||
'32VKN9747700830',
|
||||
60.392994,
|
||||
5.3241531,
|
||||
'32V 297477 6700830',
|
||||
60.39299,
|
||||
5.32415,
|
||||
],
|
||||
[
|
||||
'17MQV8185780012',
|
||||
-0.1806554,
|
||||
-78.4678355,
|
||||
'17M 781858 9980013',
|
||||
-0.180653,
|
||||
-78.467834,
|
||||
],
|
||||
[
|
||||
'60KXF1292941202',
|
||||
-17.713404,
|
||||
178.0649977,
|
||||
'60K 612930 8041203',
|
||||
-17.7134,
|
||||
178.065,
|
||||
],
|
||||
[
|
||||
'03WVM8047852917',
|
||||
64.5010996,
|
||||
-165.4064093,
|
||||
'3W 480479 7152918',
|
||||
64.5011,
|
||||
-165.4064,
|
||||
],
|
||||
['31NAA6603200011', 0.0001039, 9.92e-5, '31N 166033 11', 0.0001, 0.0001],
|
||||
[
|
||||
'01CDM4324728161',
|
||||
-79.8999987,
|
||||
-179.9000186,
|
||||
'1C 443248 1128161',
|
||||
-79.9,
|
||||
-179.9,
|
||||
],
|
||||
[
|
||||
'19FEV4500027239',
|
||||
-54.7999989,
|
||||
-68.2999931,
|
||||
'19F 545000 3927239',
|
||||
-54.8,
|
||||
-68.3,
|
||||
],
|
||||
[
|
||||
'54SUD1748374870',
|
||||
34.9999987,
|
||||
138.9999956,
|
||||
'54S 317484 3874871',
|
||||
35.0,
|
||||
139.0,
|
||||
],
|
||||
['30UXC9988909362', 51.500002, -0.1200043, '30U 699890 5709362', 51.5, -0.12],
|
||||
[
|
||||
'10JBR3890542412',
|
||||
-26.7152573,
|
||||
-125.6244681,
|
||||
'10J 238906 7042412',
|
||||
-26.7152593,
|
||||
-125.6244672,
|
||||
],
|
||||
[
|
||||
'05RMK1662242662',
|
||||
26.6023189,
|
||||
-153.8374266,
|
||||
'5R 416623 2942663',
|
||||
26.6023191,
|
||||
-153.8374241,
|
||||
],
|
||||
[
|
||||
'31DDC8763628944',
|
||||
-70.046176,
|
||||
2.6753849,
|
||||
'31D 487636 2228945',
|
||||
-70.0461753,
|
||||
2.6753768,
|
||||
],
|
||||
[
|
||||
'50LNP6584960983',
|
||||
-10.3033721,
|
||||
117.601397,
|
||||
'50L 565849 8860983',
|
||||
-10.3033722,
|
||||
117.6013945,
|
||||
],
|
||||
[
|
||||
'14EMV6706624140',
|
||||
-59.3202819,
|
||||
-99.5786192,
|
||||
'14E 467066 3424141',
|
||||
-59.3202803,
|
||||
-99.5786205,
|
||||
],
|
||||
[
|
||||
'57QYF1413419747',
|
||||
22.7716198,
|
||||
161.0856759,
|
||||
'57Q 714135 2519747',
|
||||
22.7716153,
|
||||
161.0856775,
|
||||
],
|
||||
[
|
||||
'24PXB9668711309',
|
||||
14.5677772,
|
||||
-37.1743636,
|
||||
'24P 696687 1611310',
|
||||
14.5677806,
|
||||
-37.1743652,
|
||||
],
|
||||
[
|
||||
'30GTV9870806681',
|
||||
-41.4662188,
|
||||
-5.4104109,
|
||||
'30G 298709 5406682',
|
||||
-41.4662184,
|
||||
-5.4104096,
|
||||
],
|
||||
[
|
||||
'60XWU3439017795',
|
||||
83.8999979,
|
||||
179.899971,
|
||||
'60X 534391 9317796',
|
||||
83.9,
|
||||
179.9,
|
||||
],
|
||||
['32VJH3227421798', 55.9999999, 3.1000066, '32V 132274 6221799', 56.0, 3.1],
|
||||
[
|
||||
'60RWP4163073757',
|
||||
25.9820077,
|
||||
177.4159163,
|
||||
'60R 541631 2873757',
|
||||
25.9820033,
|
||||
177.415919,
|
||||
],
|
||||
[
|
||||
'60VWL2412126400',
|
||||
58.8767223,
|
||||
177.4183599,
|
||||
'60V 524121 6526400',
|
||||
58.876719,
|
||||
177.4183593,
|
||||
],
|
||||
[
|
||||
'60UUD2978050375',
|
||||
52.7763309,
|
||||
174.4763915,
|
||||
'60U 329781 5850376',
|
||||
52.7763332,
|
||||
174.476393,
|
||||
],
|
||||
[
|
||||
'32GKT8210286690',
|
||||
-42.5414587,
|
||||
6.3464153,
|
||||
'32G 282102 5286690',
|
||||
-42.5414631,
|
||||
6.346413,
|
||||
],
|
||||
];
|
||||
|
||||
test('MGRS and UTM references read to within a metre in every latitude band', () => {
|
||||
for (const [mgrs, mgrsLat, mgrsLon, utm, utmLat, utmLon] of GRID) {
|
||||
const fromMgrs = parseGridReference(mgrs);
|
||||
assert.ok(fromMgrs, mgrs);
|
||||
assert.ok(metres(fromMgrs, { lat: mgrsLat, lon: mgrsLon }) < 1, mgrs);
|
||||
const fromUtm = parseGridReference(utm);
|
||||
assert.ok(fromUtm, utm);
|
||||
assert.ok(metres(fromUtm, { lat: utmLat, lon: utmLon }) < 1, utm);
|
||||
}
|
||||
});
|
||||
|
||||
test('MGRS reads spaced and unspaced, to 100 m or finer', () => {
|
||||
const times = { lat: 40.74882, lon: -73.98543 };
|
||||
for (const text of [
|
||||
'18TWL8565011369',
|
||||
'18T WL 8565011369',
|
||||
'18T WL 85650 11369',
|
||||
'18twl8565011369',
|
||||
])
|
||||
assert.ok(metres(parseGridReference(text), times) < 1, text);
|
||||
// Coarser references name the centre of their square.
|
||||
assert.ok(metres(parseGridReference('18TWL856113'), times) < 71, '100 m');
|
||||
assert.ok(metres(parseGridReference('18T WL 856 113'), times) < 71, '100 m');
|
||||
assert.ok(metres(parseGridReference('18TWL85651136'), times) < 8, '10 m');
|
||||
// 1 km and 10 km squares, and a square alone, read too much ordinary text.
|
||||
for (const text of ['18TWL8511', '18T WL 85 11', '18TWL81', '18TWL'])
|
||||
assert.equal(parseGridReference(text), null, text);
|
||||
});
|
||||
|
||||
test('MGRS squares across a zone edge, Norway and Svalbard', () => {
|
||||
// Paris, the Eiffel Tower.
|
||||
assert.ok(
|
||||
metres(parseGridReference('31U DQ 48251 11932'), {
|
||||
lat: 48.85819,
|
||||
lon: 2.29449,
|
||||
}) < 1,
|
||||
);
|
||||
// 32V is widened to 3°E–12°E, 33X to 9°E–21°E.
|
||||
assert.ok(parseGridReference('32V NM 12345 54321'));
|
||||
assert.ok(parseGridReference('33X VG 12345 67890'));
|
||||
// A square that lands outside its zone's longitudes.
|
||||
assert.equal(parseGridReference('18T SL 50000 50000'), null);
|
||||
// Squares touching the antimeridian, from either side.
|
||||
for (const text of ['1HBD1970044714', '60TYQ364873', '1QAC860142'])
|
||||
assert.ok(parseGridReference(text), text);
|
||||
});
|
||||
|
||||
test('a UTM N is the northern hemisphere where band N does not fit', () => {
|
||||
const point = parseGridReference('33N 500000 4500000');
|
||||
assert.ok(
|
||||
Math.abs(point.lon - 15) < 1e-9 && point.lat > 40 && point.lat < 41,
|
||||
);
|
||||
// Within 0°–8°N it is band N, the same projection.
|
||||
assert.ok(parseGridReference('33N 500000 500000').lat < 5);
|
||||
});
|
||||
|
||||
test('a UTM S is the 32°N–40°N band where it fits, else the southern hemisphere', () => {
|
||||
const tokyo = parseGridReference('54S 383000 3950000');
|
||||
assert.ok(
|
||||
tokyo.lat > 35 && tokyo.lat < 36 && tokyo.lon > 139 && tokyo.lon < 140,
|
||||
);
|
||||
const sydney = parseGridReference('56S 334900 6252291');
|
||||
assert.ok(metres(sydney, { lat: -33.856784, lon: 151.215297 }) < 1);
|
||||
});
|
||||
|
||||
test('malformed grid references are refused', () => {
|
||||
for (const text of [
|
||||
'18TWL856501136', // odd digit count
|
||||
'18T WL 8565 11369', // easting and northing of different lengths
|
||||
'18IWL8565011369', // no band I
|
||||
'18TIL8565011369', // no column I
|
||||
'18TAL8565011369', // column A is not in zone 18's set
|
||||
'61T WL 85650 11369', // no zone 61
|
||||
'0T WL 85650 11369',
|
||||
'18Z WL 85650 11369', // polar bands are UPS, not UTM
|
||||
'18A 585651 4511369',
|
||||
'18T 58565 4511369', // a five-digit easting
|
||||
'18T 585651 4511369 extra',
|
||||
'18T WL 85650 11369 N',
|
||||
'WL 85650 11369',
|
||||
'18T',
|
||||
'ATL',
|
||||
// Ordinary text that spells a square in lower case.
|
||||
'1 jan',
|
||||
'7 feb',
|
||||
'3 usa',
|
||||
'1 jan 2023',
|
||||
'4 cat 12',
|
||||
'1the12',
|
||||
'60 jun 202311',
|
||||
'18t wl 85650 11369',
|
||||
// The same text in capitals, as dates and units are often written.
|
||||
'1 JAN 2023',
|
||||
'01 JAN 2023',
|
||||
'1JAN2023',
|
||||
'31 DEC 1999',
|
||||
'25 DEC 2025',
|
||||
'1 JAN 2023 1200',
|
||||
'15 SEP 2024 0630',
|
||||
'3 USA 12',
|
||||
'4 GAS 12',
|
||||
'33 UTC 12',
|
||||
'20 KPH 1000',
|
||||
// Zones Svalbard does not use.
|
||||
'32X 500000 8700000',
|
||||
'34X NG 12 34',
|
||||
'36XNG1234',
|
||||
])
|
||||
assert.equal(parseGridReference(text), null, text);
|
||||
});
|
||||
|
||||
// [code, latitude, longitude] of each code's centre.
|
||||
const PLUS_CODES = [
|
||||
['7FG49Q00+', 20.375, 2.775],
|
||||
['7FG49QCJ+2V', 20.370062500000003, 2.7821875],
|
||||
['7FG49QCJ+2VX', 20.3701125, 2.782234375],
|
||||
['7FG49QCJ+2VXGJ', 20.370113500000002, 2.7822353515650002],
|
||||
['CR4389W6+MV36X2V', 72.34663418, 141.3621622924805],
|
||||
['4V44CC8J+XR', -47.5825625, 162.4320625],
|
||||
['7G2394VR+3RXCXV', 10.392739899999999, 21.1421003417965],
|
||||
['94GG6QPW+', 60.23625, -129.20375],
|
||||
['CP9C0000+', 77.5, 108.5],
|
||||
['549QX497+9X', -22.0315625, -124.8850625],
|
||||
['979V23X2+V97C6Q', 57.0496617, -62.949092041015504],
|
||||
['7G6MCJCM+58', 14.4204375, 33.6333125],
|
||||
['7VHJGH8G+', 21.51625, 172.57625],
|
||||
['423726P5+P72', -48.963237500000005, -174.791859375],
|
||||
['2JH70000+', -78.5, 65.5],
|
||||
['58P6PP00+', -15.275, -55.275],
|
||||
['2Q3P6CPJ+Q3H7HQ7', -88.76306733999999, 134.430234069824],
|
||||
['9R000000+', 60.0, 150.0],
|
||||
['6FPW3600+', 4.074999999999999, 18.225],
|
||||
['C55GR473+C5732', 73.8135255, -109.89708496093749],
|
||||
['CV25MQ00+', 70.67500000000001, 163.775],
|
||||
['4J86FVGW+9449', -43.5241175, 64.89533984375],
|
||||
['8V2H837Q+44', 30.3128125, 171.08781249999998],
|
||||
['C8C35800+', 78.17500000000001, -58.675],
|
||||
['62M5653J+Q3', 3.2044375, -176.8198125],
|
||||
['8H8VW72V+9GXV5', 36.9009955, 57.2938583984375],
|
||||
];
|
||||
|
||||
test('full plus codes read to the centre of their area', () => {
|
||||
for (const [code, lat, lon] of PLUS_CODES) {
|
||||
const point = parsePlusCode(code);
|
||||
assert.ok(point, code);
|
||||
assert.ok(
|
||||
Math.abs(point.lat - lat) < 1e-9 && Math.abs(point.lon - lon) < 1e-9,
|
||||
code,
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
parsePlusCode(' 849vcwc8+r9 '),
|
||||
parsePlusCode('849VCWC8+R9'),
|
||||
);
|
||||
});
|
||||
|
||||
// [code, isValid, isShort, isFull]
|
||||
const VALIDITY = [
|
||||
['8FWC2345+G6', 'true', 'false', 'true'],
|
||||
['8FWC2345+G6G', 'true', 'false', 'true'],
|
||||
['8fwc2345+', 'true', 'false', 'true'],
|
||||
['8FWCX400+', 'true', 'false', 'true'],
|
||||
['84000000+', 'true', 'false', 'true'],
|
||||
['WC2345+G6g', 'true', 'true', 'false'],
|
||||
['2345+G6', 'true', 'true', 'false'],
|
||||
['45+G6', 'true', 'true', 'false'],
|
||||
['+G6', 'true', 'true', 'false'],
|
||||
['G+', 'false', 'false', 'false'],
|
||||
['+', 'false', 'false', 'false'],
|
||||
['8FWC2345+G', 'false', 'false', 'false'],
|
||||
['8FWC2_45+G6', 'false', 'false', 'false'],
|
||||
['8FWC2\u03b745+G6', 'false', 'false', 'false'],
|
||||
['8FWC2345+G6+', 'false', 'false', 'false'],
|
||||
['8FWC2345G6+', 'false', 'false', 'false'],
|
||||
['8FWC2300+G6', 'false', 'false', 'false'],
|
||||
['WC2300+G6g', 'false', 'false', 'false'],
|
||||
['WC2345+G', 'false', 'false', 'false'],
|
||||
['WC2300+', 'false', 'false', 'false'],
|
||||
['84900000+', 'false', 'false', 'false'],
|
||||
['849VGJQF+VX7QR3J', 'true', 'false', 'true'],
|
||||
['849VGJQF+VX7QR3U', 'false', 'false', 'false'],
|
||||
['849VGJQF+VX7QR3JW', 'true', 'false', 'true'],
|
||||
['849VGJQF+VX7QR3JU', 'false', 'false', 'false'],
|
||||
];
|
||||
|
||||
test('only valid full plus codes are read; short and invalid ones are refused', () => {
|
||||
for (const [code, , , isFull] of VALIDITY)
|
||||
assert.equal(parsePlusCode(code) !== null, isFull === 'true', code);
|
||||
});
|
||||
|
||||
test('the search box reads degrees-minutes-seconds, grid references and plus codes', () => {
|
||||
const near = (query, lat, lon, within) => {
|
||||
const point = parseCoordinateQuery(query);
|
||||
assert.ok(point, query);
|
||||
assert.ok(metres(point, { lat, lon }) < within, query);
|
||||
assert.match(point.label, /° [NS], .*° [EW]$/, query);
|
||||
};
|
||||
near('40°26\'46"N, 79°58\'56"W', 40.446111, -79.982222, 1);
|
||||
near('40° 26′ 46″ N 79° 58′ 56″ W', 40.446111, -79.982222, 1);
|
||||
near("N 40°26.767' W 79°58.933'", 40.446117, -79.982217, 1);
|
||||
near('-33°51\'24", 151°12\'55"', -33.856667, 151.215278, 1);
|
||||
near('33UXP0500444998', 48.249493, 16.414495, 1);
|
||||
near('18T 585651 4511369', 40.748817, -73.985428, 1);
|
||||
near('849VCWC8+R9', 37.4220625, -122.0840625, 1);
|
||||
for (const query of [
|
||||
'40°26\'46"N', // one component
|
||||
'40°60\'0"N, 79°0\'0"W', // 60 minutes
|
||||
'40°26\'60"N, 79°0\'0"W', // 60 seconds
|
||||
'40°26.5\'46"N, 79°0\'0"W', // a decimal before the last number
|
||||
'-40°26\'46"N, 79°0\'0"W', // a sign and a letter
|
||||
'N 40°26\'46"N, 79°0\'0"W', // two letters
|
||||
'91°0\'0"N, 79°0\'0"W', // out of range
|
||||
'40°26\'46"N, 40°26\'46"S', // both latitude
|
||||
'CWC8+R9', // a short plus code needs a place
|
||||
'CWC8+R9 Mountain View',
|
||||
])
|
||||
assert.equal(parseCoordinateQuery(query), null, query);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Full Open Location Codes ("plus codes", `849VCWC8+R9`) to the centre of
|
||||
* their area, for the search box. Implements the decoding half of the Open
|
||||
* Location Code specification (github.com/google/open-location-code). Short
|
||||
* codes (`CWC8+R9 Mountain View`) need a reference place and decline, as does
|
||||
* anything that is not exactly one valid full code.
|
||||
*/
|
||||
|
||||
const ALPHABET = '23456789CFGHJMPQRVWX';
|
||||
const SEPARATOR = '+';
|
||||
const SEPARATOR_POSITION = 8;
|
||||
const PADDING = '0';
|
||||
const PAIR_LENGTH = 10;
|
||||
const GRID_COLUMNS = 4;
|
||||
const GRID_ROWS = 5;
|
||||
const MAX_LENGTH = 15;
|
||||
|
||||
/** Whether `code` is a valid full code (the specification's isFull). */
|
||||
function isFullCode(code) {
|
||||
const separator = code.indexOf(SEPARATOR);
|
||||
if (separator < 0 || separator !== code.lastIndexOf(SEPARATOR)) return false;
|
||||
if (
|
||||
separator !== SEPARATOR_POSITION ||
|
||||
code.length === SEPARATOR_POSITION + 2
|
||||
)
|
||||
return false;
|
||||
const padding = code.indexOf(PADDING);
|
||||
if (padding >= 0) {
|
||||
// Padding only before the separator, in an even count from an even place,
|
||||
// and nothing after the separator.
|
||||
if (padding === 0 || padding % 2) return false;
|
||||
const run = /0+/.exec(code)[0];
|
||||
if (
|
||||
run.length % 2 ||
|
||||
run.length !== code.split('').filter((c) => c === PADDING).length
|
||||
)
|
||||
return false;
|
||||
if (padding + run.length !== separator) return false;
|
||||
if (code.length > separator + 1) return false;
|
||||
}
|
||||
for (const character of code)
|
||||
if (
|
||||
character !== SEPARATOR &&
|
||||
character !== PADDING &&
|
||||
!ALPHABET.includes(character)
|
||||
)
|
||||
return false;
|
||||
// The first two characters keep latitude below 90 and longitude below 180.
|
||||
if (ALPHABET.indexOf(code[0]) * 20 >= 180) return false;
|
||||
if (ALPHABET.indexOf(code[1]) * 20 >= 360) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The centre of a full plus code as `{ lat, lon }`, or null.
|
||||
* @param {string} text
|
||||
*/
|
||||
export function parsePlusCode(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const code = text.trim().toUpperCase();
|
||||
if (!code || code.length > 32 || !isFullCode(code)) return null;
|
||||
const digits = code
|
||||
.replace(SEPARATOR, '')
|
||||
.replace(/0+$/, '')
|
||||
.slice(0, MAX_LENGTH);
|
||||
let south = -90;
|
||||
let west = -180;
|
||||
let latStep = 400;
|
||||
let lonStep = 400;
|
||||
// Pairs: alternating latitude and longitude digits in base 20.
|
||||
for (let i = 0; i < Math.min(digits.length, PAIR_LENGTH); i += 2) {
|
||||
latStep /= 20;
|
||||
lonStep /= 20;
|
||||
south += ALPHABET.indexOf(digits[i]) * latStep;
|
||||
if (i + 1 < digits.length)
|
||||
west += ALPHABET.indexOf(digits[i + 1]) * lonStep;
|
||||
}
|
||||
// Beyond ten digits, each one picks a cell of a 4 × 5 grid.
|
||||
for (let i = PAIR_LENGTH; i < digits.length; i += 1) {
|
||||
latStep /= GRID_ROWS;
|
||||
lonStep /= GRID_COLUMNS;
|
||||
const index = ALPHABET.indexOf(digits[i]);
|
||||
south += Math.floor(index / GRID_COLUMNS) * latStep;
|
||||
west += (index % GRID_COLUMNS) * lonStep;
|
||||
}
|
||||
const lat = Math.min(90, south + latStep / 2);
|
||||
let lon = west + lonStep / 2;
|
||||
if (lon >= 180) lon -= 360;
|
||||
return { lat, lon };
|
||||
}
|
||||
@@ -24,6 +24,13 @@
|
||||
* freshness and staleness judged against `atMs`, and `atMs` echoed back. A
|
||||
* vessel snapshot at a time reports `transportStatus: 'live'`. getTrack then
|
||||
* receives `{ signal, atMs }` and returns only points at or before `atMs`.
|
||||
*
|
||||
* A timeline that declares `spanMs` lets each record of a snapshot at a time
|
||||
* carry `fixes`: `{atMs, lat, lon, altitudeM?}` in time order, its own track
|
||||
* from `spanMs` before the time to `spanMs` after it (see
|
||||
* src/time/timelineFixes.js). The layer places the contact on them at any
|
||||
* time they span, earlier ones too, so the clock can move within them,
|
||||
* forwards or back, without a new snapshot.
|
||||
*/
|
||||
// Messages are English data (AI tools read them too); the Layers panel shows
|
||||
// them translated by their shape (translateFeedError in src/ui/statusText.js),
|
||||
@@ -164,10 +171,13 @@ export function httpError(response, source) {
|
||||
* null while it does not know yet; `stepMs` is the spacing of its snapshots;
|
||||
* the optional `subscribe(listener)` tells of a change in coverage, or of a
|
||||
* better answer for a time already answered (a paused layer then loads the
|
||||
* time shown again), and returns the unsubscribe.
|
||||
* time shown again), and returns the unsubscribe. The optional `spanMs` is
|
||||
* how far either side of its time a snapshot's records carry their `fixes`
|
||||
* (0 when they carry none).
|
||||
* @param {object|null|undefined} source
|
||||
* @returns {{coverage: () => ({start: number, end: number}|null),
|
||||
* stepMs: number, subscribe: ((listener: () => void) => () => void)|null}|null}
|
||||
* stepMs: number, spanMs: number,
|
||||
* subscribe: ((listener: () => void) => () => void)|null}|null}
|
||||
*/
|
||||
export function readSnapshotTimeline(source) {
|
||||
const timeline = source?.timeline;
|
||||
@@ -177,9 +187,14 @@ export function readSnapshotTimeline(source) {
|
||||
if (!Number.isFinite(stepMs) || stepMs <= 0) return null;
|
||||
if (timeline.subscribe != null && typeof timeline.subscribe !== 'function')
|
||||
return null;
|
||||
const spanMs =
|
||||
Number.isFinite(timeline.spanMs) && timeline.spanMs > 0
|
||||
? timeline.spanMs
|
||||
: 0;
|
||||
return {
|
||||
coverage: () => timeline.coverage(),
|
||||
stepMs,
|
||||
spanMs,
|
||||
subscribe: timeline.subscribe
|
||||
? (listener) => timeline.subscribe(listener)
|
||||
: null,
|
||||
|
||||
+117
-10
@@ -1,4 +1,5 @@
|
||||
import { readSnapshotTimeline } from '../sources/live/contract.js';
|
||||
import { TIMELINE_HELD_MS } from './timelineFixes.js';
|
||||
|
||||
/** The longest play waits on a snapshot before it goes on without it. */
|
||||
export const SNAPSHOT_WAIT_MS = 8_000;
|
||||
@@ -23,6 +24,16 @@ export const SNAPSHOT_RETRY_MS = 5_000;
|
||||
* step as the clock nears the newest it has, and play does not pass a
|
||||
* snapshot still loading (for at most SNAPSHOT_WAIT_MS). Those snapshots
|
||||
* are applied as polls are (`replace: false`), so contacts move on smoothly.
|
||||
* - When the source's timeline declares `spanMs`, its records carry their
|
||||
* fixes from `spanMs` before a snapshot's time to `spanMs` after it, and
|
||||
* the layer places each contact on them by the clock. A seek or a move
|
||||
* back that stays within the fixes the loaded snapshots carry is then no
|
||||
* jump: nothing is cleared, play does not wait, and contacts move to the
|
||||
* time smoothly. A move to a step before the newest loaded asks for that
|
||||
* step once (`replace: true`): it brings back the contacts that left
|
||||
* after it and drops those not there yet, while those it has keep their
|
||||
* place, as their fixes put them. Paused, a time nearing the end of the
|
||||
* fixes after the newest asks for the snapshot there (`replace: false`).
|
||||
* - Outside the source's coverage the layer is `clear()`ed and nothing loads;
|
||||
* while the coverage is not known yet nothing loads and nothing is cleared.
|
||||
* - Back at live, the layer is `clear()`ed and `resumeLive()` polls at once.
|
||||
@@ -61,8 +72,11 @@ export function createSnapshotTimeline({
|
||||
// Each request's number; an answer to an older one is dropped.
|
||||
let sequence = 0;
|
||||
let inflight = null;
|
||||
// The time of the newest snapshot applied since the last jump.
|
||||
// The times of the newest and oldest snapshots applied since the last jump.
|
||||
let lead = null;
|
||||
let base = null;
|
||||
// The step a move back last asked for, until a newer snapshot applies.
|
||||
let scrubbed = null;
|
||||
// Cleared for a time outside coverage, so it is not cleared again.
|
||||
let empty = false;
|
||||
let waiting = null;
|
||||
@@ -135,23 +149,27 @@ export function createSnapshotTimeline({
|
||||
clear();
|
||||
};
|
||||
|
||||
function request(atMs, replace) {
|
||||
// `quiet`: a move within the loaded fixes, which shows the contacts
|
||||
// already: play does not wait for it, and its failure clears nothing.
|
||||
function request(atMs, replace, quiet = false) {
|
||||
// One load at a time: an older one is dropped before a newer starts.
|
||||
inflight?.controller.abort();
|
||||
const mine = ++sequence;
|
||||
const controller = new AbortController();
|
||||
inflight = { atMs, controller };
|
||||
inflight = { atMs, controller, quiet };
|
||||
const failed = () => {
|
||||
inflight = null;
|
||||
// A time that could not be shown shows nothing, not another time.
|
||||
if (replace) clearOnce();
|
||||
if (replace && !quiet) clearOnce();
|
||||
// Asked again once the retry is due.
|
||||
if (quiet) scrubbed = null;
|
||||
capped = false;
|
||||
stopWaiting();
|
||||
failedUntil = now() + SNAPSHOT_RETRY_MS;
|
||||
stopRetry();
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
if (started) follow(clock.getState());
|
||||
resume();
|
||||
}, SNAPSHOT_RETRY_MS);
|
||||
};
|
||||
// The source dropped this request for a newer one of its own: nothing
|
||||
@@ -159,10 +177,11 @@ export function createSnapshotTimeline({
|
||||
// as the clock next moves, or shortly.
|
||||
const superseded = () => {
|
||||
inflight = null;
|
||||
if (quiet) scrubbed = null;
|
||||
stopRetry();
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
if (started) follow(clock.getState());
|
||||
resume();
|
||||
}, SNAPSHOT_RETRY_MS);
|
||||
};
|
||||
Promise.resolve()
|
||||
@@ -175,7 +194,7 @@ export function createSnapshotTimeline({
|
||||
return;
|
||||
}
|
||||
inflight = null;
|
||||
lead = atMs;
|
||||
held(atMs, replace);
|
||||
empty = false;
|
||||
capped = false;
|
||||
stopWaiting();
|
||||
@@ -193,10 +212,87 @@ export function createSnapshotTimeline({
|
||||
);
|
||||
}
|
||||
|
||||
// The snapshot at `atMs` is applied: the stretch of snapshot times loaded
|
||||
// (`base` to `lead`) takes it in. One the stretch does not reach with its
|
||||
// fixes (play went on without waiting, far past the newest) starts it
|
||||
// afresh: the contacts have no fixes for the time between. The stretch is
|
||||
// kept to TIMELINE_HELD_MS, from the end just loaded, which every
|
||||
// contact's fixes still cover.
|
||||
function held(atMs, replace) {
|
||||
const reach = 2 * (timeline.spanMs || 0);
|
||||
scrubbed = null;
|
||||
if (
|
||||
replace ||
|
||||
lead === null ||
|
||||
atMs > lead + reach ||
|
||||
atMs < base - reach
|
||||
) {
|
||||
lead = atMs;
|
||||
base = atMs;
|
||||
return;
|
||||
}
|
||||
lead = Math.max(lead, atMs);
|
||||
base = Math.min(base, atMs);
|
||||
if (lead - base <= TIMELINE_HELD_MS) return;
|
||||
if (atMs === lead) base = lead - TIMELINE_HELD_MS;
|
||||
else lead = base + TIMELINE_HELD_MS;
|
||||
}
|
||||
|
||||
// Ask again for what the time needs, after a failure or a dropped load:
|
||||
// a time within the loaded fixes may still need a snapshot near their end.
|
||||
function resume() {
|
||||
if (!started) return;
|
||||
const state = clock.getState();
|
||||
if (!state.live && wasActive && heldAt(state.timeMs))
|
||||
scrubTo(state.timeMs, state);
|
||||
else follow(state);
|
||||
}
|
||||
|
||||
// Whether the fixes of the snapshots loaded since the last jump span the
|
||||
// time, so contacts can be placed there without a jump.
|
||||
const heldAt = (timeMs) =>
|
||||
timeline.spanMs > 0 &&
|
||||
lead !== null &&
|
||||
base !== null &&
|
||||
timeMs >= base - timeline.spanMs &&
|
||||
timeMs <= lead + timeline.spanMs;
|
||||
|
||||
// The clock moved to a time the loaded fixes span: contacts move there as
|
||||
// they are. A step before the newest loaded is asked for once, in place
|
||||
// of every contact; paused, a time in the outer half of the fixes after
|
||||
// the newest asks for the snapshot at its step, which brings those beyond.
|
||||
function scrubTo(timeMs, state) {
|
||||
const covered = span();
|
||||
if (!covered) return;
|
||||
if (!within(timeMs, covered)) {
|
||||
cancel();
|
||||
lead = null;
|
||||
base = null;
|
||||
setGate(null);
|
||||
clearOnce();
|
||||
return;
|
||||
}
|
||||
const half = timeline.spanMs / 2;
|
||||
const step = Math.max(covered.start, stepAtOrBefore(timeMs));
|
||||
if (step < lead) {
|
||||
if (step !== scrubbed && now() >= failedUntil) {
|
||||
scrubbed = step;
|
||||
if (inflight?.atMs !== step) request(step, true, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!playsOn(state) && timeMs > lead + half && step > lead) {
|
||||
if (inflight?.atMs !== step && now() >= failedUntil) request(step, false);
|
||||
return;
|
||||
}
|
||||
keepUp(timeMs, state);
|
||||
}
|
||||
|
||||
// Show the time afresh: the snapshot at its step replaces every contact.
|
||||
function jumpTo(timeMs) {
|
||||
cancel();
|
||||
lead = null;
|
||||
base = null;
|
||||
setGate(null);
|
||||
const covered = span();
|
||||
if (!covered) return;
|
||||
@@ -215,12 +311,14 @@ export function createSnapshotTimeline({
|
||||
if (!within(timeMs, covered)) {
|
||||
cancel();
|
||||
lead = null;
|
||||
base = null;
|
||||
setGate(null);
|
||||
clearOnce();
|
||||
return;
|
||||
}
|
||||
if (inflight) {
|
||||
if (playsOn(state) && timeMs >= inflight.atMs) startWaiting();
|
||||
if (playsOn(state) && timeMs >= inflight.atMs && !inflight.quiet)
|
||||
startWaiting();
|
||||
return;
|
||||
}
|
||||
if (now() < failedUntil) return;
|
||||
@@ -246,7 +344,10 @@ export function createSnapshotTimeline({
|
||||
return;
|
||||
}
|
||||
setGate(capped ? null : next);
|
||||
request(next, false);
|
||||
// Past what the loaded fixes reach (play went on without waiting), the
|
||||
// contacts have no fixes for the time between: the step stands in for
|
||||
// them all.
|
||||
request(next, timeline.spanMs > 0 && next > lead + 2 * timeline.spanMs);
|
||||
}
|
||||
|
||||
function follow(state) {
|
||||
@@ -259,6 +360,7 @@ export function createSnapshotTimeline({
|
||||
cancel();
|
||||
setGate(null);
|
||||
lead = null;
|
||||
base = null;
|
||||
empty = false;
|
||||
failedUntil = -Infinity;
|
||||
clear();
|
||||
@@ -266,6 +368,8 @@ export function createSnapshotTimeline({
|
||||
return;
|
||||
}
|
||||
const timeMs = state.timeMs;
|
||||
// Away from live already: a move may stay within the loaded fixes.
|
||||
const wasFollowing = wasActive;
|
||||
const jumped =
|
||||
!wasActive ||
|
||||
state.jumps !== lastJumps ||
|
||||
@@ -273,7 +377,8 @@ export function createSnapshotTimeline({
|
||||
wasActive = true;
|
||||
lastJumps = state.jumps;
|
||||
lastTimeMs = timeMs;
|
||||
if (jumped) {
|
||||
if (jumped && wasFollowing && heldAt(timeMs)) scrubTo(timeMs, state);
|
||||
else if (jumped) {
|
||||
failedUntil = -Infinity;
|
||||
jumpTo(timeMs);
|
||||
} else keepUp(timeMs, state);
|
||||
@@ -303,6 +408,7 @@ export function createSnapshotTimeline({
|
||||
lastJumps = null;
|
||||
lastTimeMs = null;
|
||||
lead = null;
|
||||
base = null;
|
||||
empty = false;
|
||||
failedUntil = -Infinity;
|
||||
gated = undefined;
|
||||
@@ -330,6 +436,7 @@ export function createSnapshotTimeline({
|
||||
setGate(null);
|
||||
wasActive = false;
|
||||
lead = null;
|
||||
base = null;
|
||||
for (const release of releases.splice(0).reverse()) release();
|
||||
timeline = null;
|
||||
},
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
const STEP = 10_000;
|
||||
const WALL = Date.UTC(2026, 10, 1, 12);
|
||||
|
||||
function harness({ timeline = true, coverage } = {}) {
|
||||
function harness({ timeline = true, coverage, spanMs } = {}) {
|
||||
const t = {
|
||||
wall: WALL,
|
||||
mono: 1_000,
|
||||
@@ -34,6 +34,7 @@ function harness({ timeline = true, coverage } = {}) {
|
||||
timeline: {
|
||||
coverage: () => span,
|
||||
stepMs: STEP,
|
||||
...(spanMs && { spanMs }),
|
||||
subscribe(listener) {
|
||||
coverageListeners.add(listener);
|
||||
return () => coverageListeners.delete(listener);
|
||||
@@ -335,3 +336,215 @@ test('a source that tells of a better answer has the paused time loaded again, n
|
||||
assert.equal(loads(h.calls).length, live, 'live, nothing is loaded');
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('with fixes either side, a move back within them asks for its step once, clearing nothing and holding nothing', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
assert.equal(loads(h.calls).length, 1);
|
||||
// Within the step loaded: the contacts move along their fixes.
|
||||
h.clock.seek(at + STEP / 2);
|
||||
h.clock.seek(at + 1_000);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).length, 1);
|
||||
// Back two steps: the contacts move along their fixes, and the step there
|
||||
// stands in for every contact once it loads, bringing back any that left
|
||||
// after it. Nothing is cleared and play does not wait.
|
||||
const before = h.calls.length;
|
||||
h.clock.seek(at - 2 * STEP);
|
||||
await flush();
|
||||
assert.deepEqual(h.calls.slice(before), [
|
||||
{ type: 'load', atMs: at - 2 * STEP, replace: true },
|
||||
]);
|
||||
assert.equal(h.clock.getState().buffering, false);
|
||||
// Moving within that step while it loads asks for nothing more.
|
||||
h.clock.seek(at - 2 * STEP + 1_000);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).length, 2);
|
||||
await h.answer();
|
||||
h.clock.seek(at - 2 * STEP + 2_000);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).length, 2);
|
||||
// Playing on from there asks for the next step, as play does.
|
||||
h.clock.play();
|
||||
h.advance(STEP - 2_000);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: at - STEP,
|
||||
replace: false,
|
||||
});
|
||||
await h.answer();
|
||||
h.clock.pause();
|
||||
// Paused past the outer half after the newest: the step there.
|
||||
const newest = loads(h.calls).at(-1).atMs;
|
||||
h.clock.seek(newest + 3 * STEP + 1_000);
|
||||
await flush();
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: newest + 3 * STEP,
|
||||
replace: false,
|
||||
});
|
||||
await h.answer();
|
||||
// Beyond the fixes is a jump: the time is shown afresh, play held.
|
||||
h.clock.seek(at - 60 * STEP);
|
||||
await flush();
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: at - 60 * STEP,
|
||||
replace: true,
|
||||
});
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('playing, a seek back within the fixes does not hold play on its step', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.play();
|
||||
h.clock.seek(at - 2 * STEP + 1_000);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).at(-1).atMs, at - 2 * STEP);
|
||||
h.advance(STEP / 4);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(h.clock.getState().buffering, false);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('without a span every move back is a jump', async () => {
|
||||
const h = harness();
|
||||
h.follower.start();
|
||||
const at = WALL - 600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.seek(at - STEP);
|
||||
await flush();
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: at - STEP,
|
||||
replace: true,
|
||||
});
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('a snapshot the loaded fixes do not reach starts the held stretch afresh', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 1_200_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.play();
|
||||
h.advance(100);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
// The next step is slow: play goes on without it, far past the fixes.
|
||||
h.advance(2 * STEP);
|
||||
h.clock.coverageChanged();
|
||||
h.advance(SNAPSHOT_WAIT_MS);
|
||||
h.advance(30 * STEP);
|
||||
h.clock.coverageChanged();
|
||||
await h.answer();
|
||||
const far = loads(h.calls).at(-1).atMs;
|
||||
assert.ok(far > at + STEP + 2 * SPAN, 'asked for a step past the fixes');
|
||||
assert.equal(
|
||||
loads(h.calls).at(-1).replace,
|
||||
true,
|
||||
'in place of every contact',
|
||||
);
|
||||
await h.answer();
|
||||
h.clock.pause();
|
||||
// Back between the two: no snapshot's fixes cover it, so it is a jump.
|
||||
h.clock.seek(at + SPAN + 2 * STEP);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).at(-1).replace, true);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('the held stretch is kept to the newest stretch every contact covers', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({
|
||||
spanMs: SPAN,
|
||||
coverage: { start: WALL - 6 * 3_600_000, end: WALL },
|
||||
});
|
||||
h.follower.start();
|
||||
const at = WALL - 3 * 3_600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.play();
|
||||
// Playing on for well over TIMELINE_HELD_MS, a step at a time.
|
||||
for (let k = 0; k < 160; k++) {
|
||||
h.advance(STEP);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
while (h.pending.length) await h.answer(h.pending.length - 1);
|
||||
}
|
||||
h.clock.pause();
|
||||
// Back to the first snapshot's time: past what is held, so a jump.
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).at(-1).replace, true);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('a step a move back asked for that the source drops is asked again', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.seek(at - 2 * STEP);
|
||||
await flush();
|
||||
const asked = loads(h.calls).length;
|
||||
h.pending
|
||||
.shift()
|
||||
.reject(Object.assign(new Error('dropped'), { name: 'AbortError' }));
|
||||
await flush();
|
||||
h.advance(SNAPSHOT_RETRY_MS);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).length, asked + 1);
|
||||
assert.equal(loads(h.calls).at(-1).atMs, at - 2 * STEP);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('a step a move back asked for that fails clears nothing and is asked again while paused', async () => {
|
||||
const SPAN = 5 * STEP;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 600_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.seek(at - 3 * STEP - 1_000);
|
||||
await flush();
|
||||
const asked = loads(h.calls).length;
|
||||
await h.answer(0, false);
|
||||
assert.equal(
|
||||
h.calls.some((call) => call.type === 'clear'),
|
||||
false,
|
||||
);
|
||||
h.advance(SNAPSHOT_RETRY_MS);
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).length, asked + 1);
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: at - 4 * STEP,
|
||||
replace: true,
|
||||
});
|
||||
h.follower.stop();
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* The fixes a snapshot at a time may carry for each contact (a record's
|
||||
* `fixes`, see readSnapshotTimeline in src/sources/live/contract.js): where
|
||||
* it was in the minutes around the time, so a layer following the world
|
||||
* clock places it at nearby times, earlier ones too, without asking again.
|
||||
*/
|
||||
|
||||
/** Most fixes a contact keeps across the snapshots that brought them. */
|
||||
export const TIMELINE_FIXES_LIMIT = 240;
|
||||
/** Kept fixes are at least this far apart, so the limit spans well over an
|
||||
* hour around the newest snapshot's time however dense the fixes come. */
|
||||
export const TIMELINE_FIX_SPACING_MS = 20_000;
|
||||
/**
|
||||
* The longest stretch of snapshot times a layer treats as loaded at once
|
||||
* (see src/time/snapshotTimeline.js). With each snapshot's fixes reaching a
|
||||
* span either side, it stays within what every contact keeps around the
|
||||
* newest snapshot's time.
|
||||
*/
|
||||
export const TIMELINE_HELD_MS = 20 * 60_000;
|
||||
/**
|
||||
* A contact following the clock is not drawn at a time more than this
|
||||
* before its first fix: it was not there yet. Within it, it is drawn
|
||||
* reaching its first fix, as a contact first seen is.
|
||||
*/
|
||||
export const TIMELINE_UNSEEN_MS = 60_000;
|
||||
|
||||
/**
|
||||
* A record's fixes in time order, those with a time and a position only,
|
||||
* or null when it carries fewer than two.
|
||||
* @param {unknown} value
|
||||
* @returns {Array<{atMs: number, lat: number, lon: number,
|
||||
* altitudeM: number|null}>|null}
|
||||
*/
|
||||
export function readTimelineFixes(value) {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const fixes = [];
|
||||
for (const fix of value) {
|
||||
const atMs = Number(fix?.atMs);
|
||||
const lat = Number(fix?.lat);
|
||||
const lon = Number(fix?.lon);
|
||||
if (
|
||||
!Number.isFinite(atMs) ||
|
||||
!Number.isFinite(lat) ||
|
||||
!Number.isFinite(lon) ||
|
||||
Math.abs(lat) > 90
|
||||
)
|
||||
continue;
|
||||
const altitudeM = Number(fix?.altitudeM);
|
||||
fixes.push({
|
||||
atMs,
|
||||
lat,
|
||||
lon,
|
||||
altitudeM:
|
||||
fix?.altitudeM != null && Number.isFinite(altitudeM) ? altitudeM : null,
|
||||
});
|
||||
}
|
||||
if (fixes.length < 2) return null;
|
||||
fixes.sort((a, b) => a.atMs - b.atMs);
|
||||
return fixes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two runs of entries in time order (`timeOf` reads an entry's epoch ms) as
|
||||
* one: `newer` stands in for the entries of `older` within the time it
|
||||
* spans, the rest of `older` is kept, and an entry closer than
|
||||
* TIMELINE_FIX_SPACING_MS to the one kept before it is left out, but for
|
||||
* the newest of `newer`, which is always kept. Only the `limit` entries nearest
|
||||
* `centreMs` are kept, so the fixes kept span at least `limit` times that
|
||||
* spacing.
|
||||
* @template T
|
||||
* @param {T[]} older
|
||||
* @param {T[]} newer
|
||||
* @param {(entry: T) => number} timeOf
|
||||
* @param {number} centreMs
|
||||
* @param {number} [limit]
|
||||
* @returns {T[]}
|
||||
*/
|
||||
export function mergeTimelineRuns(
|
||||
older,
|
||||
newer,
|
||||
timeOf,
|
||||
centreMs,
|
||||
limit = TIMELINE_FIXES_LIMIT,
|
||||
) {
|
||||
const first = newer.length ? timeOf(newer[0]) : Infinity;
|
||||
const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity;
|
||||
const newest = newer[newer.length - 1];
|
||||
// Both runs in order, the older entries within the newer run's time left
|
||||
// out, thinned to the spacing.
|
||||
const merged = [];
|
||||
const take = (entry) => {
|
||||
const k = merged.length - 1;
|
||||
if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= TIMELINE_FIX_SPACING_MS) {
|
||||
merged.push(entry);
|
||||
} else if (entry === newest) {
|
||||
merged[k] = entry;
|
||||
}
|
||||
};
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < older.length || j < newer.length) {
|
||||
if (i < older.length) {
|
||||
const t = timeOf(older[i]);
|
||||
if (t >= first && t <= last) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (j >= newer.length || t < timeOf(newer[j])) {
|
||||
take(older[i++]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
take(newer[j++]);
|
||||
}
|
||||
if (merged.length <= limit) return merged;
|
||||
// The window of `limit` entries nearest the centre.
|
||||
let start = 0;
|
||||
while (
|
||||
start + limit < merged.length &&
|
||||
Math.abs(timeOf(merged[start + limit]) - centreMs) <
|
||||
Math.abs(timeOf(merged[start]) - centreMs)
|
||||
)
|
||||
start++;
|
||||
return merged.slice(start, start + limit);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mergeTimelineRuns, readTimelineFixes } from './timelineFixes.js';
|
||||
|
||||
test('fixes are read in time order, the malformed left out, and fewer than two are none', () => {
|
||||
assert.equal(readTimelineFixes(undefined), null);
|
||||
assert.equal(readTimelineFixes([{ atMs: 1, lat: 1, lon: 1 }]), null);
|
||||
assert.deepEqual(
|
||||
readTimelineFixes([
|
||||
{ atMs: 3_000, lat: 3, lon: 3, altitudeM: 30 },
|
||||
{ atMs: 'x', lat: 0, lon: 0 },
|
||||
{ atMs: 2_000, lat: 95, lon: 2 },
|
||||
{ atMs: 1_000, lat: 1, lon: 1, altitudeM: null },
|
||||
]),
|
||||
[
|
||||
{ atMs: 1_000, lat: 1, lon: 1, altitudeM: null },
|
||||
{ atMs: 3_000, lat: 3, lon: 3, altitudeM: 30 },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('two runs merge in order, the newer standing in for the older within its time, thinned to the spacing', () => {
|
||||
const at = (atMs, from) => ({ atMs, from });
|
||||
const merged = mergeTimelineRuns(
|
||||
[at(0, 'old'), at(30_000, 'old'), at(105_000, 'old'), at(160_000, 'old')],
|
||||
[
|
||||
at(40_000, 'new'),
|
||||
at(80_000, 'new'),
|
||||
at(90_000, 'new'),
|
||||
at(150_000, 'new'),
|
||||
],
|
||||
(fix) => fix.atMs,
|
||||
60_000,
|
||||
);
|
||||
// 40 s is too near 30 s; 90 s too near 80 s; 105 s is within the newer
|
||||
// run; 160 s too near 150 s, the newest of the newer run, kept.
|
||||
assert.deepEqual(merged, [
|
||||
at(0, 'old'),
|
||||
at(30_000, 'old'),
|
||||
at(80_000, 'new'),
|
||||
at(150_000, 'new'),
|
||||
]);
|
||||
const ends = mergeTimelineRuns(
|
||||
[at(0, 'old')],
|
||||
[at(5_000, 'new'), at(10_000, 'new')],
|
||||
(fix) => fix.atMs,
|
||||
0,
|
||||
);
|
||||
assert.deepEqual(ends, [at(10_000, 'new')]);
|
||||
});
|
||||
|
||||
test("runs a step apart, however dense, keep a contact's fixes back over every step", () => {
|
||||
const spanMs = 5 * 60_000;
|
||||
for (const [stepMs, spacingMs] of [
|
||||
[10_000, 5_000],
|
||||
[60_000, 5_000],
|
||||
[60_000, 30_000],
|
||||
]) {
|
||||
let fixes = [];
|
||||
for (let t = 0; t <= 20 * 60_000; t += stepMs) {
|
||||
const run = [];
|
||||
for (
|
||||
let f = Math.ceil((t - spanMs) / spacingMs) * spacingMs;
|
||||
f <= t + spanMs;
|
||||
f += spacingMs
|
||||
)
|
||||
run.push({ atMs: f });
|
||||
fixes = mergeTimelineRuns(fixes, run, (fix) => fix.atMs, t);
|
||||
}
|
||||
assert.equal(fixes[0].atMs, -spanMs, `${stepMs}/${spacingMs}`);
|
||||
assert.equal(fixes.at(-1).atMs, 25 * 60_000);
|
||||
for (let k = 1; k < fixes.length - 1; k++)
|
||||
assert.ok(fixes[k].atMs - fixes[k - 1].atMs >= 20_000);
|
||||
}
|
||||
});
|
||||
|
||||
test('past the limit only the fixes nearest the centre are kept', () => {
|
||||
const run = (from, to) =>
|
||||
Array.from({ length: to - from }, (_, k) => ({
|
||||
atMs: (from + k) * 60_000,
|
||||
}));
|
||||
const kept = mergeTimelineRuns(
|
||||
run(0, 10),
|
||||
run(10, 20),
|
||||
(f) => f.atMs,
|
||||
15 * 60_000,
|
||||
6,
|
||||
);
|
||||
assert.deepEqual(
|
||||
kept.map((f) => f.atMs / 60_000),
|
||||
[12, 13, 14, 15, 16, 17],
|
||||
);
|
||||
const early = mergeTimelineRuns(run(0, 10), run(10, 20), (f) => f.atMs, 0, 4);
|
||||
assert.deepEqual(
|
||||
early.map((f) => f.atMs / 60_000),
|
||||
[0, 1, 2, 3],
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user