Draw flow lines and depth-fail colours through the Cesium draw port

Lines take the flow style, draped or not: the route annotation's flowing
dashes as a material whose clock the port runs each frame, asking for
frames while a shown set shows flow lines. Undraped lines with a
depth-fail colour draw it where the surface hides them, and one that moves
is built anew in place under the same pick id, so a line updated every
frame neither rebuilds its set nor blinks. A draped style the port cannot
drape is refused before the set changes. The shared conformance suite
draws both kinds and moves a depth-fail line frame by frame.
This commit is contained in:
Sameh Khamis committed 2026-11-07 05:42:17 -08:00
1 parent adedd51551
commit d18fae43c2
4 files changed
+543 -36

No files matched your search

+237 -36
View File
@@ -134,6 +134,39 @@ const ANCHORS = {
top: Cesium.VerticalOrigin.TOP,
};
/** The `flow` line material's type. */
const FLOW_MATERIAL = 'DrawFlowLine';
/**
* Along the line (`st.s`, 0 at its start, 1 at its end) the pattern repeats
* `repeat` times, each cell lit for its first `duty`, scrolled toward the
* end by `time * speed` cells; between the dashes the line stays faintly
* drawn, and the lit cells glow.
*/
const FLOW_SOURCE = `
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material m = czm_getDefaultMaterial(materialInput);
float s = materialInput.st.s;
float flow = fract(s * repeat - time * speed);
float on = smoothstep(duty + 0.08, duty - 0.08, flow);
float a = max(on, 0.18);
m.diffuse = color.rgb;
m.emission = color.rgb * on * 0.9;
m.alpha = color.a * a;
return m;
}`;
/**
* The `flow` lines' clock, seconds, for a line flowing at `speed` cells a
* second: wrapped to one cell's time, which draws the same dashes, so the
* single-precision uniform never runs out of digits over a long session.
*/
function flowTime(speed) {
if (!speed) return 0;
const cells = (performance.now() / 1000) * speed;
return (cells - Math.floor(cells)) / speed;
}
/**
* The draw port over `scene`, and what the other ports read of it: the live
* sets by id, a version that changes with them, the scene's 3D tilesets and
@@ -224,6 +257,7 @@ export function createCesiumDraw({
// or where an undraped one runs, are changed where they are.
if (patchPoints(record, list) || patchLines(record, list)) {
for (const item of list) items.set(item.id, item);
if (kind === 'lines') noteFlows(record);
setsVersion += 1;
requestRender();
return;
@@ -444,6 +478,7 @@ export function createCesiumDraw({
if (record.retiring && !record.retiring.isDestroyed?.() && live())
scene.primitives.remove(record.retiring);
record.retiring = null;
record.retiringFlows = null;
}
/**
@@ -487,6 +522,33 @@ export function createCesiumDraw({
}
}
/** Each frame, before it draws: the flow lines' clock. */
function runFlows() {
for (const record of sets.values()) {
for (const material of record.flowMaterials ?? [])
material.uniforms.time = flowTime(material.uniforms.speed);
for (const material of record.retiringFlows ?? [])
material.uniforms.time = flowTime(material.uniforms.speed);
}
}
/** Whether a shown set shows flow lines, which draw on in later frames. */
const flowing = () =>
[...sets.values()].some(
(record) => record.spec.show !== false && record.flowShown,
);
/** Note whether a line set shows any flow line, once its lines change. */
function noteFlows(record) {
record.flowShown = false;
if (!record.flowMaterials?.length) return;
for (const item of record.items.values())
if (item.style?.kind === 'flow' && item.show !== false) {
record.flowShown = true;
return;
}
}
function uncull(record) {
for (const placed of record.placed) placed.primitive.show = placed.shown;
}
@@ -885,8 +947,32 @@ export function createCesiumDraw({
return billboard;
}
/**
* A `flow` line's material: dashes that run toward the line's end, over a
* faint line between them, at `speed` cells a second (`flowTime` keeps
* its clock). The dash pattern of the route annotations, which drew their
* routes before the draw port.
*/
function flowMaterial(style) {
return new Cesium.Material({
fabric: {
type: FLOW_MATERIAL,
uniforms: {
color: toColor(style.color),
time: flowTime(style.speed),
repeat: style.repeat,
duty: style.duty,
speed: style.speed,
},
source: FLOW_SOURCE,
},
});
}
function lineMaterial(style) {
switch (style.kind) {
case 'flow':
return flowMaterial(style);
case 'solid':
return Cesium.Material.fromType('Color', {
color: toColor(style.color),
@@ -951,56 +1037,141 @@ export function createCesiumDraw({
return dense;
}
/**
* Whether `positions` make a line: two or more of them, not all at one
* place.
*/
const drawable = (positions) =>
positions.length >= 2 &&
positions.some((p) => !Cesium.Cartesian3.equals(p, positions[0]));
/**
* A line not draped that has a `depthFailColor`: a primitive of its own,
* drawn in that colour where the surface hides it. Built at once, so one
* built anew where it moves draws in the frame it replaces the old one.
* Null when its positions make no line.
*/
function depthFailLine(record, item, id) {
const positions = linePositions(item);
if (!drawable(positions)) return null;
const material = lineMaterial(item.style);
if (item.style.kind === 'flow') record.flowMaterials.push(material);
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolylineGeometry({
positions,
width: item.widthPx,
vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
// Straight between the positions, as the collection's lines are
// (geodesic ones come densified).
arcType: Cesium.ArcType.NONE,
}),
id,
}),
appearance: new Cesium.PolylineMaterialAppearance({ material }),
depthFailAppearance: new Cesium.PolylineMaterialAppearance({
material: Cesium.Material.fromType('Color', {
color: toColor(item.depthFailColor),
}),
}),
show: item.show !== false,
asynchronous: false,
});
}
function buildLines(record) {
const host = new Cesium.PolylineCollection();
// Refused before anything changes, so the set keeps drawing as it was.
for (const item of record.items.values())
if (
item.mode === 'draped' &&
item.style.kind !== 'solid' &&
item.style.kind !== 'flow'
)
throw new Error('the Cesium renderer drapes solid and flow lines only');
const polylines = new Cesium.PolylineCollection();
const draped = new Map();
const flows = [];
// Each line as drawn, for upserts that change it in place.
const parts = new Map();
record.lineParts = parts;
// What the old host's flow lines run on, while it still draws; a host
// already retiring keeps drawing in its place, with its own.
if (!record.retiring) record.retiringFlows = record.flowMaterials ?? null;
record.flowMaterials = [];
// Lines with a depth-fail colour, beside the collection.
let deep = null;
for (const item of record.items.values()) {
if (item.mode === 'draped') {
if (item.style.kind !== 'solid')
throw new Error('the Cesium renderer drapes solid lines only');
const kind = item.style.kind;
const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both';
if (!draped.has(clampTo)) draped.set(clampTo, []);
const id = pickId(record, item);
parts.set(item.id, {
const part = {
look: lineLook(item),
positions: flatPositions(item.positions),
clampTo,
id,
ground: null,
});
draped.get(clampTo).push(
new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
positions: linePositions(item),
width: item.widthPx,
arcType: Cesium.ArcType.GEODESIC,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
toColor(item.style.color),
),
show: new Cesium.ShowGeometryInstanceAttribute(
item.show !== false,
),
},
id,
}),
};
parts.set(item.id, part);
const show = new Cesium.ShowGeometryInstanceAttribute(
item.show !== false,
);
const instance = new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
positions: linePositions(item),
width: item.widthPx,
arcType: Cesium.ArcType.GEODESIC,
}),
attributes:
kind === 'solid'
? {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
toColor(item.style.color),
),
show,
}
: { show },
id,
});
if (kind === 'flow') {
// A material for the whole primitive: one primitive each.
const material = flowMaterial(item.style);
record.flowMaterials.push(material);
flows.push({ clampTo, instance, material, part });
continue;
}
if (!draped.has(clampTo)) draped.set(clampTo, []);
draped.get(clampTo).push(instance);
continue;
}
const polyline = host.add({
if (item.depthFailColor) {
deep ??= new Cesium.PrimitiveCollection();
const id = pickId(record, item);
const primitive = depthFailLine(record, item, id);
if (primitive) deep.add(primitive);
parts.set(item.id, { look: lineLook(item), id, deep: primitive });
continue;
}
const material = lineMaterial(item.style);
if (item.style.kind === 'flow') record.flowMaterials.push(material);
const polyline = polylines.add({
positions: linePositions(item),
width: item.widthPx,
material: lineMaterial(item.style),
material,
show: item.show !== false,
id: pickId(record, item),
});
parts.set(item.id, { look: lineLook(item), polyline });
}
if (!draped.size) return replaceHost(record, host);
let own = polylines;
if (deep) {
own = new Cesium.PrimitiveCollection();
own.add(polylines);
own.add(deep);
}
record.deepLines = deep;
noteFlows(record);
if (!draped.size && !flows.length) return replaceHost(record, own);
// Draped lines drape as the entities' clamped polylines do.
const byClamp = new Map();
const ground = [...draped].map(([clampTo, geometryInstances]) => {
@@ -1014,8 +1185,17 @@ export function createCesiumDraw({
return primitive;
});
for (const part of parts.values())
if (part.clampTo) part.ground = byClamp.get(part.clampTo);
replaceHost(record, collect(host, ground), ground, host);
if (part.clampTo) part.ground = byClamp.get(part.clampTo) ?? null;
for (const { clampTo, instance, material, part } of flows) {
part.ground = new Cesium.GroundPolylinePrimitive({
geometryInstances: [instance],
appearance: new Cesium.PolylineMaterialAppearance({ material }),
classificationType: classificationOf(clampTo),
allowPicking: record.spec.pickable !== false,
});
ground.push(part.ground);
}
replaceHost(record, collect(own, ground), ground, own);
}
/**
@@ -1051,7 +1231,8 @@ export function createCesiumDraw({
/**
* Upsert lines in place, without a rebuild, when every item is drawn now
* and looks the same: then only whether it shows, its `meta`, and where
* a line not draped runs change. A draped line keeps its positions, and
* a line not draped runs change (one with a depth-fail colour is built
* anew, alone). A draped line keeps its positions, and
* its ground primitive must be ready. False, changing nothing, otherwise.
*/
function patchLines(record, list) {
@@ -1060,6 +1241,8 @@ export function createCesiumDraw({
for (const item of list) {
const was = parts.get(item.id);
if (!was || was.look !== lineLook(item)) return false;
if (was.deep !== undefined && record.deepLines?.isDestroyed())
return false;
if (
was.ground &&
(was.ground.isDestroyed() ||
@@ -1077,6 +1260,20 @@ export function createCesiumDraw({
was.polyline.id.meta = item.meta;
continue;
}
if (was.deep !== undefined) {
was.id.meta = item.meta;
// Built anew where it now runs, under the same pick id.
const deep = record.deepLines;
const old = was.deep;
if (old)
record.flowMaterials = record.flowMaterials.filter(
(material) => material !== old.appearance.material,
);
was.deep = depthFailLine(record, item, was.id);
if (was.deep) deep.add(was.deep);
if (old) deep.remove(old);
continue;
}
was.id.meta = item.meta;
// A ground primitive still building takes its show once it is ready
// (`swapReady`), so a show change never restarts the build.
@@ -1525,17 +1722,21 @@ export function createCesiumDraw({
/** Whether a set's ground primitives are still being built. */
building: () => [...sets.values()].some((record) => record.pending),
/** Each frame, before it draws: the horizon cull. */
beforeRender: cullHorizon,
beforeRender() {
cullHorizon();
runFlows();
},
/** Each frame, after it drew: clamp state, and ground swaps. */
afterRender() {
watchClamp();
swapReady();
// Rows moving on a live clock draw on in the frames that follow.
for (const record of sets.values())
if (record.gpu?.animating()) {
requestRender();
break;
}
// Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow.
if (
[...sets.values()].some((record) => record.gpu?.animating()) ||
flowing()
)
requestRender();
},
/**
* Let go of the sets; with `removeHosts`, take what they draw out of
+236
View File
@@ -2288,3 +2288,239 @@ test('scene data packs draw their geometry and media marker through the Cesium d
assert.equal(scene.added.length, 0);
assert.equal(targets.size, 0);
});
test('flow lines run their dashes toward the end, draped or not, on the frame clock', () =>
withImageClasses(() => {
const scene = fakeScene();
let asked = 0;
const request = scene.requestRender;
scene.requestRender = function () {
asked += 1;
return request.call(this);
};
const { draw, frame } = drawOver(scene);
const set = draw.lines({ id: 'flowing' });
const style = {
kind: 'flow',
color: [0.2, 0.8, 1, 0.95],
repeat: 64,
duty: 0.46,
speed: 0.55,
};
const positions = [
{ lon: 0, lat: 0 },
{ lon: 1, lat: 1 },
];
set.set([
{ id: 'route', positions, widthPx: 9, mode: 'draped', style },
{
id: 'edge',
positions,
widthPx: 2,
mode: 'draped',
clampTo: 'terrain',
style: { kind: 'solid', color: '#fff' },
},
{ id: 'air', positions, widthPx: 3, mode: '3d', style },
]);
const host = scene.added[0];
const polylines = host.get(0);
const solid = host.get(1);
const draped = host.get(2);
assert.ok(solid.appearance instanceof Cesium.PolylineColorAppearance);
assert.equal(solid.classificationType, Cesium.ClassificationType.TERRAIN);
assert.ok(draped instanceof Cesium.GroundPolylinePrimitive);
assert.ok(draped.appearance instanceof Cesium.PolylineMaterialAppearance);
assert.equal(draped.classificationType, Cesium.ClassificationType.BOTH);
assert.equal(draped.geometryInstances[0].geometry.width, 9);
assert.equal(draped.geometryInstances[0].id.id, 'route');
const material = draped.appearance.material;
assert.equal(material.type, 'DrawFlowLine');
assert.equal(material.uniforms.repeat, 64);
assert.equal(material.uniforms.duty, 0.46);
assert.equal(material.uniforms.speed, 0.55);
assert.ok(
Cesium.Color.equals(
material.uniforms.color,
new Cesium.Color(0.2, 0.8, 1, 0.95),
),
);
const air = polylines.get(0);
assert.equal(air.material.type, 'DrawFlowLine', 'an undraped one too');
// The dashes run on the frame clock.
material.uniforms.time = -1;
air.material.uniforms.time = -1;
asked = 0;
frame();
assert.ok(material.uniforms.time >= 0, 'draped: its clock moved');
assert.ok(
material.uniforms.time < 1 / 0.55,
'wrapped to one cell, so the uniform keeps its digits',
);
assert.ok(air.material.uniforms.time >= 0, 'undraped: its clock moved');
assert.ok(asked > 0, 'and it asks for the frames that follow');
// A shown flow line hides in place once its ground is ready.
Object.defineProperty(draped, 'ready', { value: true });
const shown = new Uint8Array([1]);
draped.getGeometryInstanceAttributes = () => ({ show: shown });
set.upsert([
{ id: 'route', positions, widthPx: 9, mode: 'draped', style, show: false },
]);
assert.equal(scene.added[0], host, 'changed in place');
assert.deepEqual([...shown], [0]);
// Hidden or gone, a set asks for no more frames.
set.upsert([
{ id: 'air', positions, widthPx: 3, mode: '3d', style, show: false },
]);
asked = 0;
frame();
assert.equal(asked, 0, 'its flow lines hidden, it asks for no frames');
set.upsert([{ id: 'air', positions, widthPx: 3, mode: '3d', style }]);
asked = 0;
frame();
assert.ok(asked > 0, 'shown again, it does');
set.show = false;
asked = 0;
frame();
assert.equal(asked, 0, 'a hidden set asks for no frames');
set.show = true;
set.clear();
asked = 0;
frame();
assert.equal(asked, 0, 'an emptied set asks for none');
// Other styles still drape only solid.
assert.throws(
() =>
set.set([
{
id: 'dash',
positions,
widthPx: 1,
mode: 'draped',
style: { kind: 'dash', color: '#fff', length: 8 },
},
]),
/drapes solid and flow lines only/,
);
set.dispose();
}));
test('a line with a depth-fail colour draws it behind the surface, and moves in place', () =>
withImageClasses(() => {
const { scene, draw } = drawOver();
const set = draw.lines({ id: 'head' });
const head = (height, extra = {}) => ({
id: 'gev-trail:head',
positions: [
Cesium.Cartesian3.fromDegrees(0, 0, 100),
Cesium.Cartesian3.fromDegrees(0.01, 0.01, height),
],
widthPx: 2.5,
mode: 'geodesic',
style: { kind: 'solid', color: [1, 0, 1, 0.9] },
depthFailColor: [1, 0, 1, 0.45],
meta: height,
...extra,
});
set.set([
head(200),
{
id: 'plain',
positions: [
Cesium.Cartesian3.fromDegrees(0, 0, 0),
Cesium.Cartesian3.fromDegrees(1, 0, 0),
],
widthPx: 1,
mode: '3d',
style: { kind: 'solid', color: '#fff' },
depthFailColor: null,
},
]);
const host = scene.added[0];
assert.ok(host instanceof Cesium.PrimitiveCollection);
const polylines = host.get(0);
const deep = host.get(1);
assert.equal(polylines.length, 1, 'null: drawn as the plain lines are');
assert.equal(polylines.get(0).id.id, 'plain');
const first = deep.get(0);
assert.ok(first instanceof Cesium.Primitive);
assert.equal(first.geometryInstances.geometry._width, 2.5);
const id = first.geometryInstances.id;
assert.equal(id.id, 'gev-trail:head');
assert.equal(id.set, 'head');
assert.ok(
Cesium.Color.equals(
first.depthFailAppearance.material.uniforms.color,
new Cesium.Color(1, 0, 1, 0.45),
),
);
assert.ok(
Cesium.Color.equals(
first.appearance.material.uniforms.color,
new Cesium.Color(1, 0, 1, 0.9),
),
);
// Moved: built anew where it now runs, under the same pick id.
set.upsert([head(300)]);
assert.equal(scene.added[0], host, 'the set is not rebuilt');
assert.equal(deep.length, 1, 'the old one goes');
const moved = deep.get(0);
assert.notEqual(moved, first);
assert.equal(moved.geometryInstances.id, id, 'the same pick id');
assert.equal(id.meta, 300, 'with its new meta');
const end = moved.geometryInstances.geometry._positions.at(-1);
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
end,
Cesium.Cartesian3.fromDegrees(0.01, 0.01, 300),
1e-6,
),
);
// Positions that make no line draw nothing, until they do again.
set.upsert([head(300, { positions: [] })]);
assert.equal(deep.length, 0);
set.upsert([head(400, { show: false })]);
assert.equal(deep.length, 1);
assert.equal(deep.get(0).show, false, 'hidden as asked');
// A new colour is a new look: rebuilt.
set.upsert([head(400, { depthFailColor: [1, 1, 1, 1] })]);
assert.notEqual(scene.added[0], host);
set.dispose();
assert.equal(scene.added.length, 0);
}));
test('a draped flow line still drawing while its rebuilds build keeps flowing', () =>
withImageClasses(() => {
const { scene, draw, frame } = drawOver();
const set = draw.lines({ id: 'reflowing' });
const route = (lon) => ({
id: 'route',
positions: [
{ lon: 0, lat: 0 },
{ lon, lat: 1 },
],
widthPx: 9,
mode: 'draped',
style: {
kind: 'flow',
color: '#39d0ff',
repeat: 64,
duty: 0.46,
speed: 1,
},
});
set.set([route(1)]);
const host = scene.added[0];
const first = host.get(1);
Object.defineProperty(first, 'ready', { value: true });
frame();
// Two rebuilds while the first still draws in their place.
set.set([route(2)]);
set.set([route(3)]);
assert.ok(scene.added.includes(host), 'the first still draws');
const material = first.appearance.material;
material.uniforms.time = -1;
frame();
assert.ok(material.uniforms.time >= 0, 'and keeps its clock');
set.dispose();
}));
+1
View File
@@ -40,6 +40,7 @@ export const CESIUM_CHECKS = new Set([
'draw.drillPick',
'draw.icons.distance',
'draw.icons.update',
'draw.lines.styles',
'draw.ids',
'draw.models',
'draw.motion',
+69
View File
@@ -1348,6 +1348,75 @@ export function portChecks() {
set.dispose();
},
),
check(
'draw.lines.styles',
'flow lines draw draped and in space, and a line with a depth-fail colour moves every frame, without stopping the frame or picks',
async (h, r) => {
await overAustin(h, r);
const lines = r.draw.lines({ id: 'conf:line-styles' });
const at = (dLon, height = 0) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat, height });
const flow = {
kind: 'flow',
color: [0.2, 0.8, 1, 0.95],
repeat: 8,
duty: 0.5,
speed: 1,
};
const head = (height) => ({
id: 'head',
positions: [at(-0.002, 50), at(0.002, height)],
widthPx: 3,
mode: '3d',
style: { kind: 'solid', color: '#ff00ff' },
depthFailColor: [1, 0, 1, 0.45],
});
lines.set([
{
id: 'route',
positions: [at(-0.003), at(0), at(0.003)],
widthPx: 9,
mode: 'draped',
clampTo: 'both',
style: flow,
},
{
id: 'air',
positions: [at(-0.003, 200), at(0.003, 200)],
widthPx: 4,
mode: '3d',
style: flow,
},
head(100),
]);
equal(lines.size(), 3, 'every line held');
for (let i = 0; i < 4; i++) {
lines.upsert([head(100 + 50 * i)]);
await drawn(h, r, 1);
}
equal(lines.size(), 3, 'moved in place, not added');
lines.upsert([{ ...head(300), show: false }]);
await drawn(h, r);
const points = r.draw.points({ id: 'conf:line-styles-points' });
const pos = at(0, 0);
points.set([{ id: 'p', pos, pixelSize: 16, color: '#ff0000' }]);
await drawn(h, r);
const s = r.query.project(pos);
ok(s, 'the point projects');
equal(
r.query
.drillPick(s.x, s.y)
.find((hit) => hit.set === 'conf:line-styles-points')?.id,
'p',
'picks still find what is drawn among the lines',
);
lines.clear();
await drawn(h, r);
equal(lines.size(), 0, 'cleared');
points.dispose();
lines.dispose();
},
),
check(
'draw.points.update',
'an upserted point is drawn where it now is once drawn again, and shows only within its display range',