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

+149 -88
View File
@@ -1,29 +1,27 @@
/**
* @module trailRenderer
* @description Shared track-history renderer (PRD WS-F F4; rebuilt round 6,
* 2026-07-06).
* 2026-07-06; drawn through the renderer's draw port since 2026-11).
*
* One trail = one ENTITY polyline. Round 6 replaced the faded per-vertex
* Primitive for two owner directives from the field:
* - "the line must ALWAYS be visible": the Primitive's depthFailAppearance
* did not reliably render segments below the photoreal mesh — entity
* polylines with `depthFailMaterial` DO (in-repo proof: CCTV's frustum
* wireframes read through geometry with exactly this), so occluded
* segments now draw dimmed instead of vanishing.
* - "show actual tracks, don't style them too much": the tail-fade is gone;
* the whole history renders at one readable alpha (dimmer where it passes
* behind/below geometry).
* One trail = one line set on the viewer's draw port: the history line and,
* for layers that draw one, the live head from the last history point to
* the moving contact. Two owner directives from the field shape it:
* - "the line must ALWAYS be visible": where the trail passes behind or
* below scene geometry it draws dimmed (the line's depth-fail colour)
* instead of vanishing.
* - "show actual tracks, don't style them too much": the whole history
* renders at one readable alpha (dimmer where it is hidden).
*
* Trails update at poll cadence (~15-60 s) plus once on history backfill, so
* assigning a fresh positions array per update is cheap. `allowPicking` has
* no entity equivalent; the polyline entity is excluded from clicks by never
* carrying a pick id the layers' click handlers resolve.
* The history changes at poll cadence (~15-60 s) plus once on backfill; the
* head may change every frame. Either is rebuilt alone, under the same pick
* id, without rebuilding the other.
*/
import * as Cesium from 'cesium';
import { cssColor } from '../render/color.js';
import { findDraw } from '../render/rendererOf.js';
import { registerPickOwner } from './pickRegistry.js';
// Round 6: trail ENTITIES are pickable (the old Primitive had
// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would
// Trail lines are pickable (a click on one must not fall through to the
// ground under it). A trail hugs its aircraft, so an unclaimed pick would
// read as "empty space" in every layer's click handler and deselect the very
// plane being tracked. Claiming the 'gev-trail:' id namespace makes
// isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op
@@ -32,7 +30,7 @@ registerPickOwner('trails', (pickedId) =>
String(pickedId).startsWith('gev-trail:'),
);
/** @type {number} Uniquifier for trail entity ids (Cesium requires unique entity ids). */
/** @type {number} Uniquifier for trail set and line ids. */
let _trailSeq = 0;
/** @constant {number} Alpha where the trail passes the depth test. */
@@ -40,108 +38,171 @@ const TRAIL_ALPHA = 0.85;
/** @constant {number} Alpha where the trail is behind/below scene geometry —
* visible (owner: never vanish) but readable as occluded. */
const TRAIL_OCCLUDED_ALPHA = 0.4;
/** @constant {number} Alpha of the live head, and where it is hidden. */
const HEAD_ALPHA = 0.9;
const HEAD_OCCLUDED_ALPHA = 0.45;
/** @constant {number} Squared distance (m^2) below which consecutive points are merged. */
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
/** `css` (any CSS colour) at `alpha`, as a renderer colour. */
function colorAt(css, alpha) {
const [r, g, b] = cssColor(css) ?? [1, 1, 1];
return [r, g, b, alpha];
}
const distanceSq = (a, b) =>
(a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2;
/**
* Consecutive near-duplicates dropped (zero-length segments add nothing),
* as plain ECEF; empty when fewer than 2 distinct positions remain.
* @param {Array<{x: number, y: number, z: number}|null|undefined>} given
*/
function trailPositions(given) {
const positions = [];
for (const position of Array.isArray(given) ? given : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (last && distanceSq(last, position) < MIN_SEGMENT_DISTANCE_SQ) continue;
positions.push({ x: position.x, y: position.y, z: position.z });
}
return positions.length >= 2 ? positions : [];
}
/**
* Create an always-visible polyline trail bound to a viewer.
* @param {Cesium.Viewer} viewer - Viewer whose entity collection owns the trail.
* @param {object} viewer - Viewer whose renderer draws the trail.
* @param {object} options - Trail options.
* @param {string} options.color - CSS color string for the trail hue.
* @param {number} [options.width=2.5] - Polyline width in pixels.
* @returns {{setPositions: function(Array<Cesium.Cartesian3|{x: number, y: number, z: number}>): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
* Trail handle: setPositions replaces the geometry, setVisible temporarily
* hides it without discarding history, clear empties it, and destroy removes
* the entity permanently.
* @param {string} options.color - CSS colour of the trail.
* @param {number} [options.width=2.5] - Line width in pixels.
* @returns {{setPositions: function(Array<{x: number, y: number, z: number}>): void, setHead: function(Array<{x: number, y: number, z: number}>|null): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
* Trail handle: setPositions replaces the history, setHead the live head
* (null or fewer than 2 positions: none), setVisible temporarily hides
* both without discarding them, clear empties both, and destroy removes
* the trail permanently.
*/
export function createTrail(viewer, { color, width = 2.5 }) {
const baseColor = Cesium.Color.fromCssColorString(color);
/** @type {Cesium.Cartesian3[]} Current deduped positions (owned copy). */
let current = [];
const seq = ++_trailSeq;
const bodyId = `gev-trail:${seq}`;
const headId = `gev-trail:${seq}:head`;
let destroyed = false;
let visible = true;
/** @type {Cesium.Entity|null} */
let entity = null;
/** @type {import('../render/contract/draw').DrawSet<import('../render/contract/draw').LineItem>|null} */
let set = null;
/** Each line as last drawn and its positions' key, by id, to skip a redraw that changes nothing. */
const drawn = new Map();
/** The head given while the trail is hidden, drawn once it shows. */
let pendingHead = null;
function ensureEntity() {
if (entity || destroyed || !viewer || viewer.isDestroyed()) return;
entity = viewer.entities.add({
id: `gev-trail:${++_trailSeq}`,
show: visible,
polyline: {
// CallbackProperty so a positions swap never rebuilds the entity —
// Cesium re-reads on change; `false` marks it non-constant.
positions: new Cesium.CallbackProperty(() => current, false),
width,
material: baseColor.withAlpha(TRAIL_ALPHA),
// The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground.
depthFailMaterial: baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA),
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
// globe"): NONE draws straight 3D chords between waypoints — over a
// sparse trans-oceanic trace a single segment spans hundreds of km
// and tunnels through the planet. GEODESIC subdivides each segment
// along the curved surface (heights interpolated), so long legs hug
// the globe instead of chording through it.
arcType: Cesium.ArcType.GEODESIC,
},
});
function ensureSet() {
if (set || destroyed || !viewer || viewer.isDestroyed?.()) return set;
set =
findDraw(viewer)?.lines({ id: `trail:${seq}`, show: visible }) ?? null;
return set;
}
/**
* Draw one of the trail's lines, or with no positions hide it. A hidden
* line stays in the set, so the other is never rebuilt for it.
*/
function draw(id, positions, alpha, occludedAlpha, mode = 'geodesic') {
if (destroyed || !viewer || viewer.isDestroyed?.()) return;
const lines = ensureSet();
if (!lines) return;
const key = positions.map(({ x, y, z }) => `${x},${y},${z}`).join(';');
const was = drawn.get(id);
if ((was?.key ?? '') === key) return;
if (!positions.length) {
const hidden = { ...was.item, show: false };
drawn.set(id, { key, item: hidden });
lines.upsert([hidden]);
return;
}
const item = {
id,
positions,
widthPx: width,
mode,
style: { kind: 'solid', color: colorAt(color, alpha) },
// The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground.
depthFailColor: colorAt(color, occludedAlpha),
};
drawn.set(id, { key, item });
lines.upsert([item]);
}
/**
* Replace the live head: the segment from the last drawn history point
* to where the contact is drawn now. It may change every frame: while
* the trail is hidden it is only kept, and drawn once the trail shows.
* @param {Array<{x: number, y: number, z: number}>|null} cartesians
*/
function setHead(cartesians) {
if (!visible) {
pendingHead = cartesians ?? [];
return;
}
pendingHead = null;
// One poll interval long at most: straight is the geodesic to the
// pixel, and a frame's rebuild stays two positions.
draw(
headId,
trailPositions(cartesians),
HEAD_ALPHA,
HEAD_OCCLUDED_ALPHA,
'3d',
);
}
return {
/**
* Replace the trail geometry with a chronological position list
* (oldest first). Fewer than 2 distinct positions clears the trail.
* @param {Array<Cesium.Cartesian3|{x: number, y: number, z: number}>} cartesians
* @param {Array<{x: number, y: number, z: number}>} cartesians
* ECEF positions, oldest -> newest.
*/
setPositions(cartesians) {
if (destroyed || !viewer || viewer.isDestroyed()) return;
// Drop consecutive near-duplicates: zero-length segments add nothing.
const positions = [];
for (const position of Array.isArray(cartesians) ? cartesians : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (
last &&
Cesium.Cartesian3.distanceSquared(last, position) <
MIN_SEGMENT_DISTANCE_SQ
)
continue;
// Callers may hand plain ECEF {x, y, z}: the polyline gets Cartesian3s.
positions.push(
position instanceof Cesium.Cartesian3
? position
: new Cesium.Cartesian3(position.x, position.y, position.z),
);
}
current = positions.length >= 2 ? positions : [];
ensureEntity();
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
// globe"): straight 3D chords between sparse trans-oceanic
// waypoints tunnel through the planet; a geodesic line follows the
// curved surface (heights interpolated) instead.
draw(
bodyId,
trailPositions(cartesians),
TRAIL_ALPHA,
TRAIL_OCCLUDED_ALPHA,
);
},
setHead,
/** Temporarily hide/show the trail without discarding accumulated history. */
setVisible(nextVisible) {
visible = nextVisible !== false;
if (entity) entity.show = visible;
if (set) set.show = visible;
if (visible && pendingHead) setHead(pendingHead);
},
/** Empty the trail without removing the entity (cheap re-arm). */
/** Empty the trail, keeping its set (cheap re-arm). */
clear() {
current = [];
pendingHead = null;
if (!destroyed && set && !viewer?.isDestroyed?.() && drawn.size) {
drawn.clear();
set.clear();
}
},
/** Remove the trail entity permanently (layer disable/teardown). */
/** Remove the trail permanently (layer disable/teardown). */
destroy() {
destroyed = true;
current = [];
if (entity && viewer && !viewer.isDestroyed()) {
try {
viewer.entities.remove(entity);
} catch {
/* torn down */
}
try {
set?.dispose();
} catch {
/* torn down */
}
entity = null;
set = null;
drawn.clear();
},
};
}
+140 -51
View File
@@ -1,62 +1,151 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createTrail } from './trailRenderer.js';
import { findPickOwner } from './pickRegistry.js';
test('trail visibility can change without discarding its accumulated geometry', () => {
const added = [];
const removed = [];
const viewer = {
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove(entity) {
removed.push(entity);
},
},
};
function viewerWithDraw(t) {
const viewer = { isDestroyed: () => false };
const { draw, unbind } = bindFakeDraw(viewer);
t.after(unbind);
return { viewer, draw };
}
test('a trail draws its history as one dimmed-when-hidden geodesic line', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const trail = createTrail(viewer, { color: '#00d4ff', width: 2.5 });
trail.setPositions([
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 3.01 },
{ x: 4, y: 5, z: 6 },
]);
const set = draw.find('trail:');
assert.equal(set.kind, 'lines');
assert.equal(set.items.size, 1);
const [line] = set.items.values();
assert.match(line.id, /^gev-trail:/, 'claimed by the trail pick owner');
assert.equal(findPickOwner(line.id), 'trails');
// The near-duplicate merges.
assert.deepEqual(line.positions, [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
]);
assert.equal(line.widthPx, 2.5);
assert.equal(line.mode, 'geodesic');
assert.equal(line.style.kind, 'solid');
assert.deepEqual(line.style.color, [0, 212 / 255, 1, 0.85]);
assert.deepEqual(line.depthFailColor, [0, 212 / 255, 1, 0.4]);
// The same positions again change nothing; fewer than two distinct hide it.
const writes = set.writes;
trail.setPositions([
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
]);
assert.equal(set.writes, writes);
trail.setPositions([{ x: 1, y: 2, z: 3 }]);
assert.equal(set.items.get(line.id).show, false, 'hidden, kept in place');
});
test('a trail head is a line of its own beside the history, at the head alphas', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const trail = createTrail(viewer, { color: '#ffb800' });
trail.setPositions([
{ x: 0, y: 0, z: 0 },
{ x: 10, y: 0, z: 0 },
]);
trail.setHead([
{ x: 10, y: 0, z: 0 },
{ x: 20, y: 0, z: 0 },
]);
const set = draw.find('trail:');
assert.equal(set.items.size, 2);
const head = [...set.items.values()].find((line) =>
line.id.endsWith(':head'),
);
assert.equal(findPickOwner(head.id), 'trails');
assert.equal(head.style.color[3], 0.9);
assert.equal(head.depthFailColor[3], 0.45);
assert.equal(head.mode, '3d', 'short: straight, two positions a frame');
// No head: hidden once, then nothing more to write.
trail.setHead(null);
assert.equal(set.items.get(head.id).show, false);
const writes = set.writes;
trail.setHead([]);
assert.equal(set.writes, writes);
trail.clear();
assert.equal(set.items.size, 0);
});
test('trail visibility can change without discarding its accumulated geometry', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const trail = createTrail(viewer, { color: '#ffffff' });
const positions = [
new Cesium.Cartesian3(1, 2, 3),
new Cesium.Cartesian3(4, 5, 6),
];
trail.setVisible(false);
trail.setPositions(positions);
assert.equal(added.length, 1);
assert.equal(added[0].show, false);
assert.deepEqual(added[0].polyline.positions.getValue(), positions);
trail.setPositions([
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
]);
const set = draw.find('trail:');
assert.equal(set.show, false, 'made hidden');
trail.setVisible(true);
assert.equal(added[0].show, true);
assert.deepEqual(added[0].polyline.positions.getValue(), positions);
assert.equal(set.show, true);
assert.equal(set.items.size, 1, 'history kept');
trail.destroy();
assert.deepEqual(removed, [added[0]]);
assert.equal(set.disposed, true);
trail.setPositions([
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
]);
assert.equal(draw.find('trail:'), undefined, 'nothing after destroy');
});
test('trail positions may be plain ECEF: the polyline still draws Cartesian3s', () => {
const added = [];
const viewer = {
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove() {},
},
};
const trail = createTrail(viewer, { color: '#ffffff' });
const given = new Cesium.Cartesian3(1, 2, 3);
trail.setPositions([given, { x: 1, y: 2, z: 3.01 }, { x: 4, y: 5, z: 6 }]);
const drawn = added[0].polyline.positions.getValue();
// The near-duplicate merges; a Cartesian3 given passes through as it is.
assert.equal(drawn.length, 2);
assert.equal(drawn[0], given);
assert.ok(drawn[1] instanceof Cesium.Cartesian3);
assert.deepEqual([drawn[1].x, drawn[1].y, drawn[1].z], [4, 5, 6]);
test('a head given while the trail is hidden is drawn once it shows', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const trail = createTrail(viewer, { color: '#fff' });
trail.setPositions([
{ x: 0, y: 0, z: 0 },
{ x: 10, y: 0, z: 0 },
]);
const set = draw.find('trail:');
trail.setVisible(false);
const writes = set.writes;
for (let i = 1; i <= 3; i++)
trail.setHead([
{ x: 10, y: 0, z: 0 },
{ x: 10 + i, y: 0, z: 0 },
]);
assert.equal(set.writes, writes, 'nothing drawn while hidden');
trail.setVisible(true);
const head = [...set.items.values()].find((line) =>
line.id.endsWith(':head'),
);
assert.deepEqual(head.positions.at(-1), { x: 13, y: 0, z: 0 }, 'the last');
// Any CSS colour, at the trail's alphas.
assert.deepEqual(head.style.color, [1, 1, 1, 0.9]);
});
test('a hidden line shows again where it is next given', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const trail = createTrail(viewer, { color: '#39ffd5' });
const line = (x) => [
{ x: 0, y: 0, z: 0 },
{ x, y: 0, z: 0 },
];
trail.setPositions(line(10));
trail.setPositions([]);
trail.setPositions(line(20));
const [body] = draw.find('trail:').items.values();
assert.notEqual(body.show, false);
assert.deepEqual(body.positions, line(20));
});
test('a viewer with nothing to draw with draws no trail', () => {
const trail = createTrail({ isDestroyed: () => false }, { color: '#fff' });
assert.doesNotThrow(() =>
trail.setPositions([
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
]),
);
trail.destroy();
});