Draw contact trails through the draw port

The shared trail renderer draws a trail's history and its live head as
lines in a draw-port set, geodesic for the history and straight for the
head, each dimmed behind the surface in its depth-fail colour, and
leaves the Cesium allow-list. The flights and military trail heads are
drawn through the trail each frame from the frame port instead of
entity callbacks, and the local ADS-B head uses the same head line. A
head given while its trail is hidden waits until the trail shows.

Geodesic lines are cut a step a degree of arc, with at least 64 steps
over the line, so a long trail of short legs costs its positions rather
than 64 vertices a leg.
This commit is contained in:
Sameh Khamis committed 2026-11-07 07:39:58 -08:00
1 parent 6bbe35f232
commit 8cefc8cc4a
12 files changed
+631 -350

No files matched your search

+93
View File
@@ -161,3 +161,96 @@ test('a flight layer without an icon set declines contact refreshes', () => {
assert.equal(layer.refreshTr3b('abc123'), false);
assert.equal(layer.trackById('abc123'), false);
});
test('the tracked trail head is drawn each frame while tracked and stops with the trail', async () => {
const Cesium = await import('cesium');
const { bindFakeDraw } = await import('../../testSupport/fakeDrawPort.mjs');
const trails = await import('../../data/trailRenderer.js');
const listeners = new Set();
const frame = {
on(phase, cb) {
const entry = { phase, cb };
listeners.add(entry);
return () => listeners.delete(entry);
},
};
const tick = () => {
for (const { phase, cb } of [...listeners]) if (phase === 'preRender') cb();
};
const viewer = { isDestroyed: () => false };
const { draw, unbind } = bindFakeDraw(viewer, { frame });
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 1000);
const old = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
-600,
new Cesium.JulianDate(),
);
let headLon = 0.03;
const flightState = {
_viewer: viewer,
_trackedIcao: 'abc123',
_trail: null,
_trailPositions: [],
_trailBackfillToken: 0,
_trailHeadOff: null,
_cockpitContactMode: false,
_positionHistory: new Map([
[
'abc123',
[0, 0.01, 0.02].map((lon) => ({ time: old, position: at(lon) })),
],
]),
_scratchWarmupTime: new Cesium.JulianDate(),
_scratchTrailHead: new Cesium.Cartesian3(),
feed: { _source: {} },
records: { data: new Map() },
lifetime: new AbortController(),
};
const supplied = services();
supplied.trails = trails;
const tracking = createTracking({
flightState,
services: supplied,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_trackedTrailCached: () => at(headLon),
_trackedDisplayPosition: () => null,
_trackedModelCenterWorld: () => null,
_trackedModelEnvelopeM: () => 0,
},
},
layer: {},
});
try {
tracking._startTrail('abc123');
assert.equal(listeners.size, 1, 'one frame listener');
tick();
const set = draw.find('trail:');
const head = () => set.items.get(`${[...set.items.keys()][0]}:head`);
assert.ok(
Cesium.Cartesian3.equals(
new Cesium.Cartesian3(...Object.values(head().positions[1])),
at(0.03),
),
);
headLon = 0.04;
tick();
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
new Cesium.Cartesian3(...Object.values(head().positions[1])),
at(0.04),
1e-6,
),
);
// Tracked again: still one listener.
tracking._clearTrail();
assert.equal(listeners.size, 0, 'cleared with the trail');
tracking._startTrail('abc123');
assert.equal(listeners.size, 1);
tracking._destroyTrail();
assert.equal(listeners.size, 0, 'gone with the trail');
} finally {
unbind();
}
});
+4 -8
View File
@@ -189,15 +189,11 @@ export function createFlightState({ source, services }) {
flightState._trail = null;
/** @type {Cesium.Entity|null} Cheap 2-point head segment bridging the last fix to the LIVE
* dead-reckoned icon, updated per frame via a CallbackProperty — so the trail head stays
* glued to the 12 Hz icon without rebuilding the 400-point trail primitive every frame. */
/** @type {(() => void)|null} Stops the per-frame live head (last body point → live
* icon), drawn as the trail's head line so the head stays glued to the 12 Hz icon
* without rebuilding the 400-point trail body every frame. */
flightState._trailHeadEntity = null;
/** @type {number} Uniquifier for head-segment entity ids (Cesium requires unique ids). */
flightState._trailHeadSeq = 0;
flightState._trailHeadOff = null;
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
+59 -73
View File
@@ -1,4 +1,5 @@
import { cameraOf } from '../../render/cesium/camera.js';
import { findFrame } from '../../render/rendererOf.js';
import {
entityFollowTarget,
onFollowChanged,
@@ -224,7 +225,6 @@ export function createTracking({
// synchronously blocked Chrome's renderer into Page Unresponsive.
if (flightState._modelCollection) flightState._modelCollection.show = true;
flightState._trail?.setVisible(!next);
if (flightState._trailHeadEntity) flightState._trailHeadEntity.show = !next;
for (const icao24 of flightState._icons?.ids() ?? [])
parts.icons._applyIconPresentation(icao24);
flightState._lastFleetTickMs = 0;
@@ -382,7 +382,7 @@ export function createTracking({
// The trail BODY is the accumulated fixes EXCLUDING the newest raw one — that newest
// fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at
// now − RENDER_DELAY_SEC), so drawing it would push the trail in front of the plane.
// The cheap per-frame _trailHeadEntity segment bridges the last body point to the
// The cheap per-frame trail head segment bridges the last body point to the
// delayed dead-reckoned head, so the body primitive only rebuilds on a real fix
// (poll cadence), never at motion cadence.
if (!flightState._trail) return;
@@ -393,6 +393,54 @@ export function createTracking({
);
}
/**
* The live head: the last DISPLAYED body point to the delayed head, or no
* positions while there is none.
* @returns {Cesium.Cartesian3[]}
*/
function _trailHeadPositions() {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
// start at the last DISPLAYED body point (index n−2). With a single fix that
// point would be the sole raw fix — which is ~now, AHEAD of the delayed icon —
// so the segment would draw IN FRONT of the plane. Likewise during warm-up the
// icon predates all real history, so there is no valid body point behind it.
if (
!flightState._trackedIcao ||
flightState._trailPositions.length < 2 ||
parts.motion._isTrackWarmingUp()
)
return [];
const head =
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
// backward/reversing segment.
const start =
flightState._trailPositions[flightState._trailPositions.length - 2];
// On a contact that has not moved this segment runs from inside the
// model out to its own anchor — a line through the fuselage. The END
// never gives, so a moving trail still terminates on the tail; the
// START is what slides, from nothing on a parked contact out to the
// whole segment once it has cleared its own envelope.
// See trailHeadStart. Read `head` in place and clone only on the draw
// path — a suppressed parked contact runs this every frame.
const from = trailHeadStart(
start,
head,
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState._scratchTrailHead,
);
if (!from) return [];
return [from, Cesium.Cartesian3.clone(head)];
}
/** Each drawn frame, before it draws: the live head where the aircraft is now. */
function _drawTrailHead() {
flightState._trail?.setHead(_trailHeadPositions());
}
/**
* Start the trail for a newly tracked aircraft: seed it with the short
* dead-reckoning history (chronological), render immediately, then
@@ -425,65 +473,13 @@ export function createTracking({
});
}
flightState._trail?.setVisible(!flightState._cockpitContactMode);
// Live head segment: last fix → current dead-reckoned icon, updated every frame via
// a CallbackProperty (Cesium updates entity-polyline positions cheaply, unlike the
// trail primitive which fully rebuilds on setPositions). Keeps the head glued to the
// 12 Hz icon instead of lagging ~1 s behind it.
if (!flightState._trailHeadEntity && flightState._viewer) {
flightState._trailHeadEntity = flightState._viewer.entities.add({
// 'gev-trail' namespace (round 6): claimed by trailRenderer's pick
// owner so a click on the head segment never reads as empty space.
id: `gev-trail:fl-head-${++flightState._trailHeadSeq}`,
show: !flightState._cockpitContactMode,
polyline: {
positions: new Cesium.CallbackProperty(() => {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
// start at the last DISPLAYED body point (index n−2). With a single fix that
// point would be the sole raw fix — which is ~now, AHEAD of the delayed icon —
// so the segment would draw IN FRONT of the plane. Likewise during warm-up the
// icon predates all real history, so there is no valid body point behind it.
if (
!flightState._trackedIcao ||
flightState._trailPositions.length < 2 ||
parts.motion._isTrackWarmingUp()
)
return [];
const head =
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
// backward/reversing segment.
const start =
flightState._trailPositions[
flightState._trailPositions.length - 2
];
// On a contact that has not moved this segment runs from inside the
// model out to its own anchor — a line through the fuselage. The END
// never gives, so a moving trail still terminates on the tail; the
// START is what slides, from nothing on a parked contact out to the
// whole segment once it has cleared its own envelope.
// See trailHeadStart. Read `head` in place and clone only on the draw
// path — a suppressed parked contact runs this every frame.
const from = trailHeadStart(
start,
head,
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
flightState._scratchTrailHead,
);
if (!from) return [];
return [from, Cesium.Cartesian3.clone(head)];
}, false),
width: 2.5,
material: Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.9),
// Round 4: the head must never vanish into the mesh either (dimmed
// when occluded so depth still reads).
depthFailMaterial:
Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.45),
arcType: Cesium.ArcType.GEODESIC, // round 8: consistent with the trail body (no chords)
},
});
// Live head segment: last displayed body point → current dead-reckoned icon, drawn
// again each frame before it draws, so it stays glued to the 12 Hz icon instead of
// lagging ~1 s behind it. Only the head line is rebuilt; the body rebuilds on a real
// fix (poll cadence). Dimmed where occluded (round 4), geodesic as the body (round 8).
if (!flightState._trailHeadOff && flightState._viewer) {
flightState._trailHeadOff =
findFrame(flightState._viewer)?.on('preRender', _drawTrailHead) ?? null;
}
_refreshTrailDisplay();
@@ -600,18 +596,8 @@ export function createTracking({
flightState._trailBackfillToken += 1;
flightState._trailPositions = [];
if (flightState._trail) flightState._trail.clear();
if (
flightState._trailHeadEntity &&
flightState._viewer &&
!flightState._viewer.isDestroyed()
) {
try {
flightState._viewer.entities.remove(flightState._trailHeadEntity);
} catch {
/* already gone */
}
}
flightState._trailHeadEntity = null;
flightState._trailHeadOff?.();
flightState._trailHeadOff = null;
}
/**