Draw the transit trail through the draw port and take it off the Cesium list

The selected vehicle's trail is now two draw-port line sets instead of
Cesium primitives. The body is each run of joined history subdivisions as
draped lines in two lanes, a dark 5 px backing under the 3 px mode colour.
A subdivision shows once the vehicle has passed it and fades with its age;
both are written in place as segment shows and colours, once a second or
at a crossing, and a new mode colour is written the same way. The head is
the subdivision the vehicle is on, in the same two lanes, revealed up to
the vehicle with revealFraction: it is drawn anew only at a crossing.
Shows are written only when they change.

The transit tests bind a fake draw port, and the transit QA script finds
the trail's primitives by their draw set.
This commit is contained in:
Sameh Khamis committed 2026-11-07 07:41:00 -08:00
1 parent e8872ab419
commit 87c80856c2
7 files changed
+495 -568

No files matched your search

+253 -317
View File
@@ -1,153 +1,289 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { readFileSync } from 'node:fs';
import { TRAIL_VERTEX_LIMIT } from '../layers/transit/trails.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
createContactTrailRenderer,
trailAlpha,
} from './contactTrailRenderer.js';
function fixture(t, ground = false) {
for (const key of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
]) {
const prior = globalThis[key];
globalThis[key] = class {};
t.after(() => {
if (prior === undefined) delete globalThis[key];
else globalThis[key] = prior;
});
}
const width = Cesium.ContextLimits._maximumAliasedLineWidth;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
t.after(() => {
Cesium.ContextLimits._maximumAliasedLineWidth = width;
});
const primitives = new Cesium.PrimitiveCollection();
t.after(() => primitives.destroy());
const groundPrimitives = new Cesium.PrimitiveCollection();
t.after(() => groundPrimitives.destroy());
return {
primitives,
groundPrimitives,
frameState: { context: { depthTexture: ground } },
globe: { show: false },
};
const GREEN = [0x5e / 255, 0xf0 / 255, 0x8a / 255];
const DARK = [0.02, 0.03, 0.05];
function viewerWithDraw(t) {
const viewer = { isDestroyed: () => false };
const { draw, unbind } = bindFakeDraw(viewer);
t.after(unbind);
return { viewer, draw };
}
test('body clips future subdivisions, head ends at exact marker, and frames retain geometry', (t) => {
const scene = fixture(t),
renderer = createContactTrailRenderer(scene);
const positions = [0, 1, 2].map((i) =>
Cesium.Cartesian3.fromDegrees(-71, 42 + i * 0.001, 11.5),
);
renderer.replaceHistory({
revision: 1,
const point = (i) => ({ x: 1000 * i, y: 2000, z: 3000 });
function history(revision = 1) {
return {
revision,
segments: [
{
fromSeq: 0,
toSeq: 1,
fromT: 0,
toT: 10000,
positions: positions.slice(0, 2),
positions: [point(0), point(1)],
},
{
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 20000,
positions: positions.slice(1, 3),
positions: [point(1), point(2)],
},
],
});
const { body } = renderer.diagnostics();
assert.equal(body.allowPicking, false);
// The constructor defers this check until shader preparation. Run the real
// Cesium validator without WebGL, including a missing-attribute control.
const source = body.depthFailAppearance.vertexShaderSource;
body._batchTableAttributeIndices = { color: 0 };
assert.throws(
() => Cesium.Primitive._updateColorAttribute(body, source, true),
/depthFailColor/,
);
for (const instance of body.geometryInstances) {
assert.deepEqual(
instance.attributes.depthFailColor.value,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
}
body._batchTableAttributeIndices = { color: 0, depthFailColor: 1 };
assert.doesNotThrow(() =>
Cesium.Primitive._updateColorAttribute(body, source, true),
);
const attributes = new Map(
body.geometryInstances.map((instance) => [
instance.id,
{
show: new Uint8Array([0]),
color: new Uint8Array(4),
depthFailColor: new Uint8Array(4),
},
]),
);
// Simulate Cesium's completed upload; exercise public attribute writes.
body._ready = true;
body.getGeometryInstanceAttributes = (id) => {
const stored = attributes.get(id),
accessor = {};
for (const name of ['show', 'color', 'depthFailColor'])
Object.defineProperty(accessor, name, {
get: () => stored[name].slice(),
set: (value) => {
stored[name] = value.slice();
},
});
return accessor;
};
const marker = Cesium.Cartesian3.lerp(
positions[1],
positions[2],
0.5,
new Cesium.Cartesian3(),
}
/** The trail's live set whose id ends with `suffix`. */
const setOf = (draw, suffix) =>
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(suffix),
);
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
const close = (actual, expected) =>
actual.every((value, i) => Math.abs(value - expected[i]) < 1e-9);
test('the body is two draped lanes whose passed segments show, faded by age', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const body = setOf(draw, ':body');
assert.equal(body.spec.pickable, false);
const lines = [...body.items.values()];
// One run (the segments join): a backing lane under the mode colour.
assert.deepEqual(
[...attributes.values()].map((a) => a.show[0]),
[1, 1, 0, 0],
lines.map((line) => [line.id, line.widthPx, line.mode, line.clampTo]),
[
['backing:0', 5, 'draped', 'both'],
['line:0', 3, 'draped', 'both'],
],
);
for (const a of attributes.values())
assert.deepEqual(
a.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
const result = renderer.diagnostics();
assert.equal(result.body, body);
assert.equal(result.rebuilds, 1);
assert.equal(result.headRebuilds, 1, '120 frames retain head geometry');
assert.equal(result.head.material.uniforms.fraction, 0.5);
assert.equal(result.head.width, 3);
assert.equal(result.backing.width, 5);
assert.ok(Cesium.Cartesian3.equals(result.head.positions.at(-1), marker));
assert.equal(result.head.positions.length, 2);
assert.deepEqual(lines[0].positions, [point(0), point(1), point(2)]);
assert.deepEqual(lines[0].segmentShow, [false, false], 'none passed yet');
const marker = { x: 1500, y: 2000, z: 3000 };
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample(sample, marker);
const [backing, line] = body.items.values();
assert.deepEqual(line.segmentShow, [true, false], 'the future is clipped');
assert.deepEqual(backing.segmentShow, [true, false]);
assert.ok(close(line.segmentColors[0], [...GREEN, trailAlpha(5000)]));
assert.ok(close(backing.segmentColors[0], [...DARK, trailAlpha(5000)]));
// Within the second, nothing is written again; a rewind hides again.
const writes = body.writes;
for (let i = 0; i < 60; i++) renderer.setDisplaySample(sample, marker);
assert.equal(body.writes, writes);
renderer.setDisplaySample(
{ ...sample, displayT: 5000, fraction: 0.25 },
positions[0],
point(0),
);
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
assert.deepEqual(
body.items.get('line:0').segmentShow,
[false, false],
'rewind hides future geometry again',
);
assert.equal(renderer.diagnostics().rebuilds, 1);
renderer.destroy();
assert.equal(scene.primitives.length, 0);
assert.equal(body.disposed, true);
});
test('the head is revealed to the vehicle and drawn anew only at a crossing', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const head = renderer.diagnostics().headLines;
const record = setOf(draw, ':head');
assert.equal(record.spec.pickable, false);
const marker = { x: 1500, y: 2000, z: 3000 };
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
assert.equal(head.show, true);
const lanes = [...record.items.values()];
assert.deepEqual(
lanes.map((lane) => [lane.id, lane.widthPx, lane.revealFraction]),
[
['backing', 5, 0.5],
['line', 3, 0.5],
],
);
assert.deepEqual(lanes[1].positions, [point(1), point(2)]);
assert.ok(close(lanes[1].style.color, [...GREEN, 0.8]));
assert.ok(close(lanes[0].style.color, [...DARK, 0.8]));
const result = renderer.diagnostics();
assert.equal(result.headRebuilds, 1, '120 frames retain head geometry');
assert.equal(result.entitiesAdded, 0);
assert.equal(result.ground, true);
assert.deepEqual(result.head.positions, [point(1), marker]);
assert.equal(result.head.width, 3);
assert.equal(result.backing.width, 5);
// A frame further along writes only how far it is revealed.
renderer.setDisplaySample({ ...sample, displayT: 17500 }, marker);
assert.equal(record.items.get('line').revealFraction, 0.75);
assert.equal(renderer.diagnostics().headRebuilds, 1);
// The next subdivision, or the end of the leg, hides it.
renderer.setDisplaySample({ ...sample, fraction: 1 }, marker);
assert.equal(head.show, false);
renderer.setVisible(false);
renderer.setDisplaySample(sample, marker);
assert.equal(head.show, false, 'hidden with the trail');
assert.equal(result.body.show, false);
});
test('a new mode colour is written into the segments, never rebuilding the body', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample(sample, point(1));
const body = setOf(draw, ':body');
const look = body.items.get('line:0').style;
renderer.setStyle('#FFFFFF');
renderer.setDisplaySample(sample, point(1));
const line = body.items.get('line:0');
assert.deepEqual(line.style, look, 'the line itself is unchanged');
assert.ok(close(line.segmentColors[0], [1, 1, 1, trailAlpha(5000)]));
assert.equal(renderer.diagnostics().rebuilds, 1);
assert.equal(renderer.diagnostics().headRebuilds, 1, 'no crossing');
const headLine = setOf(draw, ':head').items.get('line');
assert.ok(close(headLine.style.color, [1, 1, 1, 0.8]), 'and the head');
});
test('separate runs of the history are separate lines', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
const { segments } = history();
segments[1] = { ...segments[1], positions: [point(5), point(6)] };
renderer.replaceHistory({ revision: 2, segments });
assert.deepEqual(
[...setOf(draw, ':body').items.keys()],
['backing:0', 'backing:1', 'line:0', 'line:1'],
);
renderer.replaceHistory({ revision: 3, segments: [] });
assert.equal(setOf(draw, ':body').items.size, 0);
});
test('a viewer with nothing to draw with draws no trail', () => {
const renderer = createContactTrailRenderer({ isDestroyed: () => false });
assert.doesNotThrow(() => {
renderer.replaceHistory(history());
renderer.setDisplaySample(
{ displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 },
point(1),
);
});
assert.equal(renderer.diagnostics().ground, false);
renderer.destroy();
});
test('playback across a crossing redraws the head once and shows the passed segment', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory({
revision: 1,
segments: history().segments.map((segment) => ({ ...segment, toSeq: 2 })),
});
const body = setOf(draw, ':body'),
head = setOf(draw, ':head');
// 60 fps through both subdivisions of one leg.
for (let t = 0; t < 20000; t += 16)
renderer.setDisplaySample(
{ displayT: t, fromSeq: 0, toSeq: 2, fraction: t / 20000 },
point(t / 10000),
);
assert.equal(renderer.diagnostics().headRebuilds, 2, 'one per subdivision');
assert.deepEqual(body.items.get('line:0').segmentShow, [true, false]);
assert.deepEqual(head.items.get('line').positions, [point(1), point(2)]);
assert.ok(head.items.get('line').revealFraction > 0.99);
// Body writes: one a second, and one at the crossing at most.
assert.ok(body.writes <= 1 + 20 + 1, `${body.writes} body writes`);
});
test('the head hides off its leg and with no sample, and shows again', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const head = renderer.diagnostics().headLines;
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample({ ...sample, toSeq: 9 }, point(1));
assert.equal(head.show, false, 'another leg');
renderer.setDisplaySample(sample, point(1));
assert.equal(head.show, true);
renderer.setDisplaySample(null, null);
assert.equal(head.show, false, 'no sample');
renderer.setVisible(false);
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
assert.equal(head.show, true, 'shown again with the trail');
assert.equal(renderer.diagnostics().body.show, true);
const sets = [setOf(draw, ':body'), setOf(draw, ':head')];
renderer.destroy();
assert.ok(
sets.every((set) => set.disposed),
'both sets disposed',
);
});
test('a segment with no length ends a run and later ones keep their times', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
const { segments } = history();
segments.splice(1, 0, {
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 10000,
positions: [],
});
segments[2] = { ...segments[2], fromT: 10000, toT: 20000 };
renderer.replaceHistory({ revision: 1, segments });
renderer.setDisplaySample(
{ displayT: 25000, fromSeq: 0, toSeq: 1, fraction: 1 },
point(2),
);
const body = setOf(draw, ':body');
assert.deepEqual(
[...body.items.keys()],
['backing:0', 'backing:1', 'line:0', 'line:1'],
);
const later = body.items.get('line:1');
assert.deepEqual(later.positions, [point(1), point(2)]);
assert.deepEqual(later.segmentShow, [true]);
assert.ok(close(later.segmentColors[0], [...GREEN, trailAlpha(5000)]));
});
test('frames that change nothing write no show', (t) => {
const { viewer } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
const { body, headLines } = renderer.diagnostics();
let writes = 0;
for (const set of [body, headLines]) {
let show = set.show;
Object.defineProperty(set, 'show', {
get: () => show,
set(value) {
writes++;
show = value;
},
});
}
for (let i = 0; i < 30; i++) {
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
}
assert.equal(writes, 0, 'a renderer may redraw for each show written');
});
test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(0), 0.8);
assert.equal(trailAlpha(120000), 0.45);
@@ -155,203 +291,3 @@ test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(900000), 0.08);
assert.ok(Math.abs(trailAlpha(60000) - 0.625) < 1e-10);
});
test('ground body and clipped head stay inside rebuild and frame geometry budgets', async () => {
Cesium.ApproximateTerrainHeights._terrainHeights = JSON.parse(
readFileSync(
new URL(
import.meta
.resolve('@cesium/engine/Source/Assets/approximateTerrainHeights.json'),
),
),
);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
const start = performance.now();
const instances = async (count) =>
Promise.all(
Array.from(
{ length: count },
async (_, i) =>
new Cesium.GeometryInstance({
id: i,
geometry: await Cesium.GroundPolylineGeometry.createGeometry(
new Cesium.GroundPolylineGeometry({
positions,
width: i % 2 ? 3 : 5,
granularity: 0,
}),
),
}),
),
);
const pipelineBytes = async (count) => {
// Match GroundPolylinePrimitive's internal Primitive options and the
// application's morph-capable scene, including batch IDs and encoding.
const result = Cesium.PrimitivePipeline.combineGeometry({
instances: await instances(count),
projection: new Cesium.GeographicProjection(),
ellipsoid: Cesium.Ellipsoid.WGS84,
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
elementIndexUintSupported: true,
scene3DOnly: false,
vertexCacheOptimize: false,
compressVertices: false,
createPickOffsets: false,
});
return result.geometries.reduce(
(sum, geometry) =>
sum +
Object.values(geometry.attributes).reduce(
(n, a) => n + (a?.values?.byteLength || 0),
0,
) +
geometry.indices.byteLength,
0,
);
};
const bytes = await pipelineBytes(1);
const bodyInstances = 2 * (TRAIL_VERTEX_LIMIT - 1);
const bodyBytes = await pipelineBytes(bodyInstances);
assert.equal(bytes, 1576, 'measure final encoded and batched geometry');
assert.equal(bodyBytes, 2014128);
const instanceReserve = 64 * bodyInstances;
assert.ok(bodyBytes + instanceReserve <= 2 * 1024 * 1024);
assert.ok(
bytes <= 2048,
'subdivision crossings stay below 2 KiB of head geometry',
);
console.log(
`trail final pipeline: ${bytes} bytes/head crossing, 0 bytes/ordinary head frame, ${bodyBytes} bytes/body (${bodyInstances} instances), ${instanceReserve} bytes instance reserve; geometry CPU ${(performance.now() - start).toFixed(3)} ms`,
);
});
test('supported scenes drape body and clipped head on 3D tiles and retain head geometry', (t) => {
const scene = fixture(t, true),
renderer = createContactTrailRenderer(scene);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
renderer.replaceHistory({
revision: 1,
segments: [{ fromSeq: 0, toSeq: 1, fromT: 0, toT: 20000, positions }],
});
const first = renderer.diagnostics();
assert.ok(first.body instanceof Cesium.GroundPolylinePrimitive);
assert.equal(first.body.classificationType, Cesium.ClassificationType.BOTH);
assert.ok(scene.groundPrimitives.contains(first.body));
for (const instance of first.body.geometryInstances)
assert.ok(instance.geometry instanceof Cesium.GroundPolylineGeometry);
for (let i = 1; i <= 120; i++)
renderer.setDisplaySample(
{ displayT: i * 100, fromSeq: 0, toSeq: 1, fraction: i / 200 },
positions[1],
);
const result = renderer.diagnostics();
assert.equal(result.body, first.body);
assert.equal(result.headRebuilds, 1);
assert.ok(result.headPrimitive instanceof Cesium.GroundPolylinePrimitive);
assert.equal(result.head.material.uniforms.fraction, 0.6);
assert.match(result.head.material.shaderSource, /discard/);
for (const stack of ['Google', 'OSM', 'Bing', 'Google']) {
scene.globe.show = stack !== 'Google';
renderer.setDisplaySample(
{ displayT: 12000, fromSeq: 0, toSeq: 1, fraction: 0.6 },
positions[1],
);
const retained = renderer.diagnostics();
assert.equal(retained.body, result.body, `${stack}: retained history`);
assert.equal(retained.headPrimitive, result.headPrimitive);
for (const primitive of [retained.body, retained.headPrimitive]) {
assert.equal(
primitive.classificationType,
Cesium.ClassificationType.BOTH,
stack,
);
assert.equal(primitive.show, true, stack);
}
}
renderer.setVisible(false);
assert.equal(result.body.show, false);
assert.equal(result.headPrimitive.show, false);
renderer.destroy();
assert.equal(scene.groundPrimitives.length, 0);
assert.equal(scene.primitives.length, 0);
});
test('subdivision crossings only write the changed show range and age colors once per second', (t) => {
const renderer = createContactTrailRenderer(fixture(t));
const positions = [
Cesium.Cartesian3.fromDegrees(-71, 42),
Cesium.Cartesian3.fromDegrees(-71, 42.001),
];
renderer.replaceHistory({
revision: 1,
segments: Array.from({ length: 100 }, (_, i) => ({
fromSeq: 0,
toSeq: 1,
fromT: i * 500,
toT: (i + 1) * 500,
positions,
})),
});
const { body } = renderer.diagnostics();
const counts = { show: 0, color: 0, depthFailColor: 0 };
const attributes = new Map(
body.geometryInstances.map((instance) => {
const result = {};
for (const name of Object.keys(counts)) {
let value = instance.attributes[name].value;
Object.defineProperty(result, name, {
get: () => value,
set(next) {
value = next;
counts[name]++;
},
});
}
return [instance.id, result];
}),
);
body._ready = true;
body.getGeometryInstanceAttributes = (id) => attributes.get(id);
const display = (displayT) =>
renderer.setDisplaySample(
{ displayT, fromSeq: 0, toSeq: 1, fraction: 0.1 },
positions[0],
);
const reset = () => {
for (const name of Object.keys(counts)) counts[name] = 0;
};
display(100);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
reset();
display(600);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
reset();
display(100);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
'backward seek hides the completed range',
);
reset();
display(1100);
assert.deepEqual(counts, { show: 4, color: 200, depthFailColor: 200 });
reset();
display(1200);
assert.deepEqual(counts, { show: 0, color: 0, depthFailColor: 0 });
renderer.setStyle('#FF4538');
display(1200);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
for (const a of attributes.values())
assert.deepEqual(
a.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#FF4538').withAlpha(0.55),
),
);
});