Contacts move back as smoothly as they move on

A snapshot timeline may declare spanMs: each record of a snapshot at a
time then carries its own fixes from spanMs before the time to spanMs
after it. Flights, military flights and vessels following the clock are
placed on those fixes, so a seek or a move back within the fixes loaded
is no jump: nothing is cleared and play does not wait. The step there is
asked for once and stands in for every contact; those it has keep their
place. Fixes are merged across snapshots at least 20 s apart, at most
240 a contact, and a contact is not drawn more than a minute before its
first fix.
This commit is contained in:
Sameh Khamis committed 2026-11-15 09:27:31 -08:00
1 parent b8a320edce
commit 2b5fb51684
27 files changed
+1377 -182

No files matched your search

+25 -5
View File
@@ -1,4 +1,9 @@
import * as Cesium from 'cesium';
import {
historyBracketIndex,
historyUnseenAt,
liftGroundedHistory,
} from '../../data/timelineHistory.js';
import { julianAt } from '../../time/julian.js';
import {
COURSE_HOLD_SPEED_MPS,
@@ -120,6 +125,7 @@ export function createMotion({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
flightState._cullPositions.delete(icao24); // above the ellipsoid now (or floors say otherwise next poll)
const position = Cesium.Cartesian3.fromDegrees(
@@ -127,10 +133,12 @@ export function createMotion({
info.rawLat,
lifted,
);
const history = flightState._positionHistory.get(icao24);
const newest = history?.[history.length - 1];
if (newest)
newest.position = Cesium.Cartesian3.clone(position, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
position,
drawnM,
lifted,
);
const bb = flightState._billboards.get(icao24);
if (bb) bb.position = position;
}
@@ -153,6 +161,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 = flightState._billboards.get(icao24)?.position;
flightState._drCourseDeg = info?.true_track || 0;
@@ -198,7 +207,15 @@ export function createMotion({
);
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
for (let i = history.length - 1; i >= 1; i--) {
// The pair around the render time (and the one before it, for a fix at
// exactly that time), found by halving: a contact following the clock
// keeps a long history.
for (
let i = historyBracketIndex(history, renderTime),
stop = Math.max(1, i - 1);
i >= stop;
i--
) {
const a = history[i - 1];
const b = history[i];
if (
@@ -254,6 +271,9 @@ export function createMotion({
// the oldest fix froze the icon; extrapolating the NEWEST fix to wall-clock now made
// the icon jump back ~one poll interval the instant interpolation took over.)
const oldest = history[0];
// Following the clock, a time well before its first fix is before it
// was there: the fleet pass hides it.
flightState._drUnseen = historyUnseenAt(history, renderTime);
const lookbackSec = Cesium.JulianDate.secondsDifference(
oldest.time,
renderTime,
+7 -3
View File
@@ -1032,6 +1032,7 @@ export function createRendering({
flightState._scratchFleetPos,
renderTime,
);
const unseen = flightState._drUnseen;
// The dead-reckoned point drifts away from the fix whose cell supplied the
// height, so a grounded contact's sprite ends up under the mesh it taxied
// (or coasted) over. Re-floor at the DISPLAYED coordinate — read-only, and
@@ -1057,9 +1058,12 @@ export function createRendering({
// sub-ellipsoid point near the limb "beyond the horizon" and the fleet
// pass would hide a plane that is really just low over high-N terrain
// waiting for its floor to warm (ATL grounded contacts at geoid −31 m).
const beyondHorizon = !occluder.isPointVisible(
flightState._cullPositions.get(icao24) || bb.position,
);
// A contact not there yet at the time drawn is hidden as one beyond it.
const beyondHorizon =
unseen ||
!occluder.isPointVisible(
flightState._cullPositions.get(icao24) || bb.position,
);
// A billboard flipping INTO view (horizon reveal while the camera idles)
// gets its rotation refreshed THIS tick even without a pose change —
// otherwise it reappears wearing its stale (often creation-north) nose for
+101 -68
View File
@@ -10,6 +10,10 @@ import { aircraftIcon } from '../../data/aircraftIcons.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { observeLiveAircraft } from './placed.js';
import {
historyAfterTrail,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
/** Apply reconciled aircraft records to Cesium resources and follow state. */
export function createFlightSnapshotRenderer({
@@ -101,6 +105,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,
@@ -111,80 +127,94 @@ 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.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// 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.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.velocity,
track: meta.true_track,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// 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);
// 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(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(entry.position.clone(), entry.epochMs, {
nullAltitude: entry.inventedHeight,
});
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.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
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(),
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// 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.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// 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);
// 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(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
} 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);
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);
}
}
}
}
@@ -228,6 +258,7 @@ export function createFlightSnapshotRenderer({
// the raw fix drew it ahead until the next fleet tick snapped it back;
// skipping the floor started a taxiing contact low and then raised it.
const delayed = motion._deadReckon(icao24, new Cesium.Cartesian3());
const unseenAtStart = flightState._drUnseen;
const displayed =
(delayed &&
motion._floorGroundedDisplayPosition(
@@ -256,7 +287,9 @@ export function createFlightSnapshotRenderer({
// close (_groundDepthDistance).
disableDepthTestDistance: rendering._groundDepthDistance(),
id: icao24,
show: !isTracked, // hidden if currently tracked (entity replaces it)
// Hidden if currently tracked (entity replaces it), or not there yet
// at the time drawn (see historyUnseenAt).
show: !isTracked && !unseenAtStart,
});
flightState._billboards.set(icao24, bb);
rendering._applyFleetBillboardPresentation(icao24, bb);
+5
View File
@@ -321,6 +321,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;
+17 -1
View File
@@ -1,4 +1,8 @@
import * as Cesium from 'cesium';
import {
historyBracketIndex,
historyUnseenAt,
} from '../../data/timelineHistory.js';
import { julianAt } from '../../time/julian.js';
import {
lerpAngleDeg,
@@ -61,6 +65,7 @@ export function createMotion({
*/
function _deadReckon(icao24, result) {
flightState._drUnseen = false;
const history = flightState._positionHistory.get(icao24);
const info = flightState.records.data.get(icao24);
if (!history || history.length === 0) {
@@ -93,7 +98,15 @@ export function createMotion({
);
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
for (let i = history.length - 1; i >= 1; i--) {
// The pair around the render time (and the one before it, for a fix at
// exactly that time), found by halving: a contact following the clock
// keeps a long history.
for (
let i = historyBracketIndex(history, renderTime),
stop = Math.max(1, i - 1);
i >= stop;
i--
) {
const a = history[i - 1];
const b = history[i];
if (
@@ -147,6 +160,9 @@ export function createMotion({
// the bracketing interpolation above with NO freeze and NO backward snap. (Holding
// the oldest fix froze the icon until enough history accrued, then jumped.)
const oldest = history[0];
// Following the clock, a time well before its first fix is before it
// was there: the fleet pass hides it.
flightState._drUnseen = historyUnseenAt(history, renderTime);
const lookbackSec = Cesium.JulianDate.secondsDifference(
oldest.time,
renderTime,
+7 -3
View File
@@ -917,6 +917,7 @@ export function createRendering({
if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion
const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos);
const unseen = flightState._drUnseen;
// Gate the write — assigning Billboard.position dirties the whole
// collection's vertex buffer, so skip sub-meter moves.
if (dr && Cesium.Cartesian3.distanceSquared(dr, bb.position) > 1.0) {
@@ -926,9 +927,12 @@ export function createRendering({
// Round 6: occlusion-test a LIFTED point for contacts at/below the
// ellipsoid (mirror of flights.js — sub-ellipsoid points near the limb
// read "beyond the horizon" and would hide low contacts awaiting floors).
const beyondHorizon = !occluder.isPointVisible(
flightState.records.data.get(icao24)?.cullPosition || bb.position,
);
// A contact not there yet at the time drawn is hidden as one beyond it.
const beyondHorizon =
unseen ||
!occluder.isPointVisible(
flightState.records.data.get(icao24)?.cullPosition || bb.position,
);
// A billboard flipping INTO view (horizon reveal while the camera idles)
// gets its rotation refreshed THIS tick even without a pose change —
// otherwise it reappears wearing its stale (often creation-north) nose for
+104 -68
View File
@@ -8,6 +8,11 @@ import {
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
historyAfterTrail,
liftGroundedHistory,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import {
BILLBOARD_SCALE,
@@ -75,6 +80,18 @@ export function createMilitarySnapshotRenderer({
);
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,
@@ -85,76 +102,89 @@ 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.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// 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.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.speedMps,
track: meta.track,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// 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);
// 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(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(entry.position.clone(), entry.epochMs, {
nullAltitude: entry.inventedHeight,
});
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.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
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(),
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// 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.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// 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);
// 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(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
} 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);
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);
}
}
}
}
@@ -195,6 +225,7 @@ export function createMilitarySnapshotRenderer({
// it ahead until the next fleet tick snapped it back.
const displayed =
motion._deadReckon(icao24, new Cesium.Cartesian3()) || position;
const unseenAtStart = flightState._drUnseen;
const bb = flightState._billboardCollection.add({
position: displayed,
image: aircraftIcon(rendering._iconKind(icao24, meta.klass)),
@@ -217,7 +248,9 @@ export function createMilitarySnapshotRenderer({
// close (_groundDepthDistance).
disableDepthTestDistance: rendering._groundDepthDistance(),
id: icao24,
show: !isTracked, // hidden if currently tracked (entity replaces it)
// Hidden if currently tracked (entity replaces it), or not there yet
// at the time drawn (see historyUnseenAt).
show: !isTracked && !unseenAtStart,
});
flightState._billboards.set(icao24, bb);
rendering._applyFleetBillboardPresentation(icao24, bb);
@@ -259,6 +292,7 @@ export function createMilitarySnapshotRenderer({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
flightState._cullPositions.delete(icao24);
const liftedPos = Cesium.Cartesian3.fromDegrees(
@@ -266,10 +300,12 @@ export function createMilitarySnapshotRenderer({
info.rawLat,
lifted,
);
const hist = flightState._positionHistory.get(icao24);
const newest = hist?.[hist.length - 1];
if (newest)
newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
liftedPos,
drawnM,
lifted,
);
const bbStale = flightState._billboards.get(icao24);
if (bbStale) bbStale.position = liftedPos;
}
+5
View File
@@ -282,6 +282,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;
+4 -1
View File
@@ -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', () => {
+4 -2
View File
@@ -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,
+53 -3
View File
@@ -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;
}
+33 -1
View File
@@ -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);
});
+23 -2
View File
@@ -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,
};
}
@@ -146,8 +153,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;
+12
View File
@@ -181,3 +181,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);
});
@@ -124,6 +124,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);
+32 -10
View File
@@ -22,7 +22,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,
@@ -190,7 +191,7 @@ export function createRendering({
function addRecordPrimitives(record, occluder) {
const visible =
state.feed.enabled &&
isVisible(getVisual(record).surfacePosition, occluder);
isVisible(getVisual(record).surfacePosition, occluder, record);
getVisual(record).billboard = state.billboardCollection.add({
position: getVisual(record).position,
show: visible,
@@ -319,7 +320,7 @@ export function createRendering({
function billboardShown(record, occluder) {
const visual = getVisual(record);
return (
isVisible(visual.surfacePosition, occluder) &&
isVisible(visual.surfacePosition, occluder, record) &&
record.id !== state.cockpitSubjectId &&
!visual.modelOwnsVisual
);
@@ -343,7 +344,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;
}
@@ -461,7 +462,7 @@ export function createRendering({
motion.wallMs - hiddenFollowedAtWallMs >= HIDDEN_FOLLOW_MS;
if (moveHidden) hiddenFollowedAtWallMs = motion.wallMs;
for (const record of state.records.all) {
if (!record.motion) continue;
if (!record.motion && !fixesMove(record.fixes)) continue;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
@@ -623,14 +624,23 @@ export function createRendering({
const focusPass =
focusPassIsNeeded(focusTarget, state.activeFocusCount) &&
(force || now - state.lastFocusUpdate >= FOCUS_UPDATE_MS);
// 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 &&
state.viewer?.camera &&
cameraPoseSignature(state.viewer.camera) !== vesselState._lastCamPoseSig
((state.viewer?.camera &&
cameraPoseSignature(state.viewer.camera) !==
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).
@@ -662,7 +672,7 @@ export function createRendering({
const labelCandidates = [];
for (const record of state.records.all) {
const visual = getVisual(record);
const visible = isVisible(visual.surfacePosition, occluder);
const visible = isVisible(visual.surfacePosition, occluder, record);
if (visual.billboard) {
// The bridge camera sits on this sprite; showing it would fill the view.
// The same rule as billboardShown, its horizon test already made.
@@ -786,11 +796,23 @@ export function createRendering({
);
}
function isVisible(surfacePosition, occluder) {
function isVisible(surfacePosition, occluder, record) {
if (record && !seenYet(record)) return false;
if (!surfacePosition || !occluder) return true;
return occluder.isPointVisible(surfacePosition);
}
/** 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
+2
View File
@@ -81,6 +81,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,
+8
View File
@@ -181,6 +181,13 @@ export function createTesting({
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() {
@@ -203,6 +210,7 @@ export function createTesting({
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
_followClockForTest,
_setVesselOverlayHostForTest,
_updateVesselCardsForTest,
_reconcileVesselsForTest,