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

+182 -214
View File
@@ -1,4 +1,19 @@
import * as Cesium from 'cesium';
/**
* @module contactTrailRenderer
* @description The selected transit vehicle's trail, drawn through the
* renderer's draw port as draped lines: a history body and a moving head.
*
* The body is every subdivision of the vehicle's history, each a segment of
* a draped line in two lanes (a dark 5 px backing under a 3 px line in the
* mode colour). A segment shows once the vehicle has passed it and fades
* with its age; both change in place (`segmentShow`, `segmentColors`), so
* the body is rebuilt only when the history changes. The head is the
* subdivision the vehicle is on, revealed up to the vehicle
* (`revealFraction`): it is drawn anew only where the vehicle crosses into
* the next subdivision, and a frame writes how far it is revealed.
*/
import { cssColor } from '../render/color.js';
import { findDraw } from '../render/rendererOf.js';
const ALPHA_STOPS = [
[0, 0.8],
@@ -19,95 +34,126 @@ export function trailAlpha(ageMs) {
return 0.08;
}
/** One static history batch and one frequently updated head. Never entities. */
export function createContactTrailRenderer(scene) {
const ground =
!!scene.frameState?.context &&
Cesium.GroundPolylinePrimitive.isSupported(scene);
const collection = ground ? scene.groundPrimitives : scene.primitives;
// One 25 m corridor is clipped in material coordinates. Only subdivision
// crossings build geometry; frame updates write a scalar, never vertex buffers.
const headMaterial = (alpha) =>
new Cesium.Material({
fabric: {
type: 'TransitTrailHead',
uniforms: {
color: new Cesium.Color(0.37, 0.94, 0.54, alpha),
fraction: 0,
backing: true,
},
source: `czm_material czm_getMaterial(czm_materialInput materialInput) {
if (materialInput.st.s > fraction) discard;
czm_material m = czm_getDefaultMaterial(materialInput);
bool edge = abs(materialInput.st.t - 0.5) > 0.3;
m.diffuse = czm_gammaCorrect(vec4(edge && backing ? vec3(0.02, 0.03, 0.05) : color.rgb, 1.0)).rgb;
m.alpha = color.a;
return m;
}`,
},
translucent: true,
});
const material = headMaterial(0.8),
depthMaterial = headMaterial(0.55);
depthMaterial.uniforms.backing = false;
const head = { positions: [], show: false, width: 3, material };
/** The backing lane's colour, under the mode colour. */
const BACKING = [0.02, 0.03, 0.05];
/** Alpha of the head, and of a body segment the vehicle has just passed. */
const HEAD_ALPHA = 0.8;
const WHITE = [1, 1, 1, 1];
/** The two lanes, drawn in this order: the backing, then the line. */
const LANES = [
{ name: 'backing', widthPx: 5, dark: true },
{ name: 'line', widthPx: 3, dark: false },
];
/** Uniquifier for each renderer's set ids. */
let trailSeq = 0;
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
/**
* The history as runs of joined segments (each segment starting where the
* one before it ends), so each lane is a few lines rather than one a
* segment. `first` is the index of the run's first segment; a segment with
* no length ends a run.
*/
function runsOf(segments) {
const runs = [];
let run = null;
for (let i = 0; i < segments.length; i++) {
const [from, to] = segments[i].positions;
if (!from || !to) run = null;
else if (run && samePoint(run.positions.at(-1), from))
run.positions.push(to);
else runs.push((run = { first: i, positions: [from, to] }));
}
return runs;
}
/**
* The trail renderer of one selection, over `viewer`'s draw port. Never
* entities; nothing it draws takes part in picks.
* @param {object} viewer
*/
export function createContactTrailRenderer(viewer) {
const draw = findDraw(viewer);
const prefix = `transit-trail:${++trailSeq}`;
const body = draw?.lines({ id: `${prefix}:body`, pickable: false }) ?? null;
const headLines =
draw?.lines({ id: `${prefix}:head`, pickable: false, show: false }) ?? null;
/** What the head draws now, for diagnostics: its start to the vehicle. */
const endpoint = { x: 0, y: 0, z: 0 };
const headPositions = [null, endpoint];
const head = { positions: [], show: false, width: 3 };
const backing = { positions: [], show: false, width: 5 };
let headPrimitive = null,
headRebuilds = 0;
function geometry(positions, width, material = false) {
return ground
? new Cesium.GroundPolylineGeometry({ positions, width, granularity: 0 })
: new Cesium.PolylineGeometry({
positions,
width,
arcType: Cesium.ArcType.NONE,
vertexFormat: material
? Cesium.PolylineMaterialAppearance.VERTEX_FORMAT
: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
});
}
function primitive(instances, appearance, depthFailAppearance) {
return ground
? new Cesium.GroundPolylinePrimitive({
geometryInstances: instances,
appearance,
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
asynchronous: true,
show: visible,
})
: new Cesium.Primitive({
geometryInstances: instances,
appearance,
depthFailAppearance,
allowPicking: false,
asynchronous: false,
show: visible,
});
}
let body = null,
segments = [],
let segments = [],
runs = [],
revision = -1,
visible = true,
style = '#5EF08A';
style = '#5EF08A',
styleColor = cssColor(style).slice(0, 3);
let lastSecond = -1,
completed = -1,
active = null;
const styleColor = Cesium.Color.fromCssColorString(style);
const attributeIds = [];
const color = new Cesium.Color(),
endpoint = new Cesium.Cartesian3();
const headPositions = [new Cesium.Cartesian3(), endpoint];
let rebuilds = 0;
function tint(alpha, dark = false) {
if (dark) {
color.red = 0.02;
color.green = 0.03;
color.blue = 0.05;
} else Cesium.Color.clone(styleColor, color);
color.alpha = alpha;
return color;
active = null,
revealed = -1,
restyled = false;
let rebuilds = 0,
headRebuilds = 0;
const tint = (alpha, dark) => [...(dark ? BACKING : styleColor), alpha];
/** The body's lines: each lane's runs, segments shown up to `done`. */
function bodyLines(displayT, done) {
const lines = [];
for (const lane of LANES)
for (let r = 0; r < runs.length; r++) {
const run = runs[r];
const count = run.positions.length - 1;
const segmentColors = new Array(count);
const segmentShow = new Array(count);
for (let k = 0; k < count; k++) {
const i = run.first + k;
const alpha =
displayT === null
? HEAD_ALPHA
: trailAlpha(displayT - segments[i].toT);
segmentColors[k] = tint(alpha, lane.dark);
segmentShow[k] = i <= done;
}
lines.push({
id: `${lane.name}:${r}`,
positions: run.positions,
widthPx: lane.widthPx,
mode: 'draped',
clampTo: 'both',
// Every segment has its own colour: the line's own never
// changes, so a new mode colour is written in place.
style: { kind: 'solid', color: lane.dark ? [...BACKING, 1] : WHITE },
segmentColors,
segmentShow,
});
}
return lines;
}
/** The head's lines over `segment`, revealed to `fraction`. */
function headItems(segment, fraction) {
return LANES.map((lane) => ({
id: lane.name,
positions: segment.positions,
widthPx: lane.widthPx,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color: tint(HEAD_ALPHA, lane.dark) },
revealFraction: fraction,
}));
}
// Written only when it changes: a renderer may redraw for each write.
function showHead(show) {
head.show = backing.show = show;
if (headLines && headLines.show !== show) headLines.show = show;
}
function replaceHistory(next) {
if (next.revision === revision) return;
revision = next.revision;
@@ -115,51 +161,22 @@ export function createContactTrailRenderer(scene) {
completed = -1;
lastSecond = -1;
active = null;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
head.show = backing.show = false;
if (body) collection.remove(body);
body = null;
const instances = [];
attributeIds.length = 0;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
attributeIds.push([`${i}:0`, `${i}:1`]);
if (segment.positions.length < 2) continue;
for (let lane = 0; lane < 2; lane++) {
instances.push(
new Cesium.GeometryInstance({
id: `${i}:${lane}`,
geometry: geometry(segment.positions, lane ? 3 : 5),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.55),
),
show: new Cesium.ShowGeometryInstanceAttribute(false),
},
}),
);
}
}
if (instances.length) {
body = collection.add(
primitive(
instances,
new Cesium.PolylineColorAppearance({ translucent: true }),
new Cesium.PolylineColorAppearance({ translucent: true }),
),
);
rebuilds++;
revealed = -1;
showHead(false);
headLines?.clear();
runs = runsOf(segments);
if (!body) return;
if (!runs.length) {
body.clear();
return;
}
body.set(bodyLines(null, -1));
rebuilds++;
}
function setDisplaySample(sample, renderedPosition) {
if (!sample || !renderedPosition) {
head.show = false;
backing.show = false;
if (headPrimitive) headPrimitive.show = false;
showHead(false);
return;
}
const second = Math.floor(sample.displayT / 1000);
@@ -179,114 +196,67 @@ export function createContactTrailRenderer(scene) {
candidate.toSeq === sample.toSeq
? candidate
: null;
if (body?.ready && done !== completed) {
for (
let i = Math.min(done, completed) + 1;
i <= Math.max(done, completed);
i++
) {
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
// Cesium getters return copies. Write back the array we changed.
const show = attributes.show;
show[0] = i <= done ? 1 : 0;
attributes.show = show;
}
}
// Passed segments show, and every segment fades with its age, once a
// second; the port writes only the segments that change.
if (body && runs.length && (done !== completed || second !== lastSecond)) {
body.upsert(bodyLines(sample.displayT, done));
completed = done;
}
if (body?.ready && second !== lastSecond) {
for (let i = 0; i < segments.length; i++) {
const alpha = trailAlpha(sample.displayT - segments[i].toT);
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
const rgba = attributes.color;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
rgba,
);
attributes.color = rgba;
if (!ground) {
const depthRgba = attributes.depthFailColor;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(0.55),
depthRgba,
);
attributes.depthFailColor = depthRgba;
}
}
}
lastSecond = second;
}
const show = visible && !!segment && sample.fraction < 1;
head.show = show;
backing.show = show;
if (headPrimitive) headPrimitive.show = show;
const show =
visible &&
!!segment?.positions[0] &&
!!segment.positions[1] &&
sample.fraction < 1;
showHead(show);
if (!show) return;
if (active !== segment) {
active = segment;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = collection.add(
primitive(
new Cesium.GeometryInstance({
geometry: geometry(segment.positions, 5, true),
}),
new Cesium.PolylineMaterialAppearance({
material,
translucent: true,
}),
new Cesium.PolylineMaterialAppearance({
material: depthMaterial,
translucent: true,
}),
),
);
headRebuilds++;
headPositions[0] = segment.positions[0];
headPositions[1] = endpoint;
}
Cesium.Cartesian3.clone(renderedPosition, endpoint);
head.positions = headPositions;
backing.positions = headPositions;
material.uniforms.fraction = Math.max(
const fraction = Math.max(
0,
Math.min(
1,
(sample.displayT - segment.fromT) / (segment.toT - segment.fromT),
),
);
depthMaterial.uniforms.fraction = material.uniforms.fraction;
Cesium.Color.clone(tint(0.8), material.uniforms.color);
Cesium.Color.clone(tint(0.55), depthMaterial.uniforms.color);
if (active !== segment || restyled) {
if (active !== segment) headRebuilds++;
active = segment;
restyled = false;
revealed = fraction;
headLines?.set(headItems(segment, fraction));
} else if (fraction !== revealed) {
revealed = fraction;
headLines?.upsert(headItems(segment, fraction));
}
headPositions[0] = segment.positions[0];
endpoint.x = renderedPosition.x;
endpoint.y = renderedPosition.y;
endpoint.z = renderedPosition.z;
head.positions = backing.positions = headPositions;
}
return {
replaceHistory,
setDisplaySample,
setStyle(next) {
if (next === style) return;
style = next;
Cesium.Color.fromCssColorString(style, styleColor);
styleColor = cssColor(style)?.slice(0, 3) ?? styleColor;
// Faded again in the new colour on the next sample, and the head
// drawn in it.
lastSecond = -1;
restyled = true;
},
setVisible(next) {
visible = next;
if (headPrimitive) headPrimitive.show = next && head.show;
if (body) body.show = next;
if (body && body.show !== next) body.show = next;
if (!next) showHead(false);
},
destroy() {
if (body) collection.remove(body);
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
material.destroy();
depthMaterial.destroy();
body = null;
body?.dispose();
headLines?.dispose();
segments = [];
runs = [];
active = null;
},
diagnostics() {
return {
@@ -294,13 +264,11 @@ export function createContactTrailRenderer(scene) {
rebuilds,
segments: segments.length,
body,
headLines,
head,
backing,
headPrimitive,
headStrategy: ground
? 'draped corridor with material clip'
: 'depth-fail corridor with material clip',
ground,
headStrategy: 'draped lines revealed to the vehicle',
ground: !!draw,
headRebuilds,
entitiesAdded: 0,
};
+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),
),
);
});
+13 -20
View File
@@ -44,6 +44,7 @@ import {
} from '../../renderGovernor.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs';
import { framePortFor } from '../../testSupport/fakeFramePort.mjs';
@@ -310,8 +311,11 @@ function harness(
// The layer reads the camera through its port; this one reads the fake
// camera above as the Cesium port reads a real one, so a test can still
// move it by changing the fake. Terrain heights come through the query
// port, which reads the fake globe the same way.
// port, which reads the fake globe the same way. The selected trail is
// drawn through the draw port.
const draw = fakeDrawPort();
const unbindCamera = bindRenderer(viewer, {
draw,
query: fakeSceneQuery(viewer),
camera: {
pose() {
@@ -360,6 +364,7 @@ function harness(
return {
layer,
viewer,
draw,
input,
primitives,
sprites,
@@ -3224,7 +3229,7 @@ for (const count of [800, 3000]) {
});
}
test('click handler selects a migrated scripted billboard and prepares a valid depth-fail trail', async (t) => {
test('click handler selects a migrated scripted billboard and prepares its draped trail', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.layer.enable(app.viewer);
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
@@ -3234,15 +3239,9 @@ test('click handler selects a migrated scripted billboard and prepares a valid d
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, entry.key);
const body = app.layer._transitPartsForTest().trails.diagnostics().body;
assert.ok(body.geometryInstances.length > 0);
body._batchTableAttributeIndices = { color: 0, depthFailColor: 1 };
assert.doesNotThrow(() =>
Cesium.Primitive._updateColorAttribute(
body,
body.depthFailAppearance.vertexShaderSource,
true,
),
);
const lines = [...app.draw.sets.get(body.id).items.values()];
assert.ok(lines.length > 0);
assert.ok(lines.every((line) => line.mode === 'draped'));
assert.ok(entry.trailSegments.length > 0);
app.run(1000, 16);
assert.equal(entry.marker.show, true);
@@ -3916,18 +3915,12 @@ test('selected draped history prepares geometry before surface heights resolve',
delete entry.qaFloorM;
entry.marker.show = false;
entry.heightPending = true;
// Exercise the real GroundPolylinePrimitive branch, without a WebGL context.
const width = Cesium.ContextLimits._maximumAliasedLineWidth;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
t.after(() => {
Cesium.ContextLimits._maximumAliasedLineWidth = width;
});
app.viewer.scene.frameState = { context: { depthTexture: true } };
app.viewer.scene.groundPrimitives = app.viewer.scene.primitives;
parts.selection.selectVehicle(entry.key);
const trail = parts.trails.diagnostics();
assert.equal(trail.ground, true);
assert.ok(trail.body instanceof Cesium.GroundPolylinePrimitive);
const lines = [...app.draw.sets.get(trail.body.id).items.values()];
assert.ok(lines.length > 0);
assert.ok(lines.every((line) => line.mode === 'draped'));
assert.ok(trail.segments > 0);
assert.equal(trail.body.show, true);
assert.equal(
+1 -1
View File
@@ -34,7 +34,7 @@ export function createTrails({ state, services, parts, source }) {
revision = 0;
function ensureRenderer() {
if (!renderer && state._viewer)
renderer = createContactTrailRenderer(state._viewer.scene);
renderer = createContactTrailRenderer(state._viewer);
return renderer;
}
function style() {
-1
View File
@@ -12,7 +12,6 @@
"src/data/aircraftModelLayer.js",
"src/data/aircraftMotionRegime.js",
"src/data/cctvGizmo.js",
"src/data/contactTrailRenderer.js",
"src/data/detection.js",
"src/data/focusDeemphasis.js",
"src/data/geoFileImport.js",