A line can be drawn as several runs (breaks) (#1895)

* A line can be drawn as several runs (`breaks`)

LineItem.breaks (capability lineBreaks) lists the positions that start a new
run of a line: the segment into each is not drawn nor picked, and the line
does not join across it, each run having ends of its own. Many lines in one
style, such as many moving objects' trails, can then be sent as one item.
Segment colours and shows stay one a pair of positions, age times one a
position, and the reveal runs along the runs in order. The Cesium port draws
a line in runs a piece a run, draped or not, and lists the capability; the
stub picks the runs only; the conformance check draw.lines.breaks pins it.

* A line in runs is cut by time run by run, whatever their order

The conformance check draw.lines.breaks.timeWindow draws a line in runs,
draped and not, whose first run is later than its second, and reads each
run drawn and cut by its own times as the scene clock moves.

It found that a plain line drawn in a polyline collection after an aged one
was the page's first of its style's type stopped the frame: Cesium keeps a
material type's uniform names from the first material of it, and a part of
a composite material has them renumbered. A part's type is now made on its
own first.

* Changelog for line breaks (#1895)
This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-11-21 13:04:19 -08:00
1 parent e4caf5d3af
commit d9d79ebc4d
15 files changed
+868 -29

No files matched your search

+167 -26
View File
@@ -603,6 +603,47 @@ function checkAgeFade(item) {
);
}
/**
* Make a material of `fabric`'s type on its own once, before one is a part
* of a composite material. Cesium keeps a type's uniform names, for all the
* page's materials of that type, from the first it makes, and a part has
* them numbered as the composite's: a plain material of that type made
* later then fails in a polyline collection (`material._uniforms[uniform]
* is not a function`), stopping the frame.
* @param {{type: string}} fabric
*/
function ownUniforms(fabric) {
if (!Cesium.Material._uniformList[fabric.type])
new Cesium.Material({ fabric }).destroy();
}
/**
* A line's `breaks`, checked: strictly increasing whole position indices,
* each past the first position and within the line (`0 < i < count`).
* Refused otherwise.
* @param {import('../contract/draw').LineItem} item
*/
function checkBreaks(item) {
const breaks = item.breaks;
if (breaks == null) return;
const count =
item.positions instanceof Float64Array
? item.positions.length / 3
: item.positions.length;
let previous = 0;
const fits =
(Array.isArray(breaks) || breaks instanceof Uint32Array) &&
Array.prototype.every.call(breaks, (at) => {
const ok = Number.isInteger(at) && at > previous && at < count;
previous = at;
return ok;
});
if (!fits)
throw new TypeError(
'a line breaks at whole, increasing position indices after its first position and before its end',
);
}
/**
* 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
@@ -683,6 +724,8 @@ export function createCesiumDraw({
const ageFades = capabilities.has('lineAgeFade');
// And draw only within a span of the scene clock (`LineAgeFade.showMs`).
const timeWindows = ageFades && capabilities.has('lineTimeWindow');
// And as several runs, not joined across their breaks (`LineItem.breaks`).
const lineBreaks = capabilities.has('lineBreaks');
// Fields share the sets' ids.
const fieldPart = createCesiumFields({
scene,
@@ -772,6 +815,7 @@ export function createCesiumDraw({
if (item.style?.kind === 'split' && item.mode !== 'draped')
throw new TypeError('a split line is draped');
if (ageFades) checkAgeFade(item);
if (lineBreaks) checkBreaks(item);
}
if (kind !== 'shapes') return;
for (const item of list) pulseOf(item);
@@ -2531,14 +2575,17 @@ export function createCesiumDraw({
? { translucent: true }
: {};
let built = template(fabric);
if (reveal !== undefined)
if (reveal !== undefined) {
ownUniforms(built);
built = {
type: `${REVEAL_MATERIAL}_${style.kind}`,
materials: { revealed: built },
uniforms: { reveal },
source: REVEAL_SOURCE,
};
if (age)
}
if (age) {
ownUniforms(built);
built = {
type: `${AGE_MATERIAL}_${reveal === undefined ? '' : 'revealed_'}${style.kind}`,
materials: { aged: built },
@@ -2549,6 +2596,7 @@ export function createCesiumDraw({
},
source: AGE_SOURCE,
};
}
const material = new Cesium.Material({ fabric: built, ...translucent });
const drawn = styleMaterial(material);
Object.assign(drawn.uniforms, fabric.uniforms);
@@ -3048,7 +3096,47 @@ export function createCesiumDraw({
!revealed(item) &&
!aged(item)
)) ||
(item.frame === 'inertial' && item.mode !== 'draped' && item.depthFail);
(item.frame === 'inertial' && item.mode !== 'draped' && item.depthFail) ||
// A line in runs with no segments of its own: a piece a run.
(broken(item) && !segmented(item));
/** Whether a line is drawn in runs, not joined across its breaks. */
const broken = (item) =>
lineBreaks && item.breaks != null && item.breaks.length > 0;
/** The positions that start a run of a line in runs, or null. */
const runStarts = (item) => (broken(item) ? new Set(item.breaks) : null);
/**
* Where a line drawn piece by piece is cut into pieces, by position
* index: `[a, b]` from position `a` to `b`, `j` its segment (its pair of
* positions, for its colour and show), `last` whether it ends its run (an
* arrow's head is drawn there). A segmented line has a piece a segment,
* but for those across a break; one in runs a piece a run; any other one
* piece. A run of one position draws nothing, and has no piece.
*/
function pieceSpans(item, count, bySegment) {
const starts = runStarts(item);
const spans = [];
if (bySegment) {
for (let j = 0; j + 1 < count; j++)
if (!starts?.has(j + 1))
spans.push({
a: j,
b: j + 1,
j,
last: j + 2 >= count || Boolean(starts?.has(j + 2)),
});
return spans;
}
if (!starts) return [{ a: 0, b: count - 1, j: 0, last: true }];
let a = 0;
for (const at of [...starts, count]) {
if (at - 1 > a) spans.push({ a, b: at - 1, j: -1, last: true });
a = at;
}
return spans;
}
/**
* The style a segment of a line draws in: the line's, in the segment's
@@ -3067,11 +3155,14 @@ export function createCesiumDraw({
* A line drawn piece by piece: a segment a piece for a segmented line
* (each its own primitive and material, under a pick id of its own that
* reads as the line's, so a segment's colour and show change in place),
* else one piece for the whole line. A revealed line reveals each piece
* by its share of the line's length. Draped pieces are ground polylines.
* Inertial pieces turn with the sky (`turnInertial`).
* a run a piece for a line in runs (`pieceSpans`), else one piece for
* the whole line. A revealed line reveals each piece by its share of the
* line's length. Draped pieces are ground polylines; the undraped pieces
* of a line in runs with no depth-fail style, in the Earth's frame, are
* polylines in the set's collection (`polylines`), the rest primitives
* in `host`. Inertial pieces turn with the sky (`turnInertial`).
*/
function linePieces(record, item, host, groundOut) {
function linePieces(record, item, host, groundOut, polylines) {
const id = pickId(record, item);
// Its own positions: a geodesic piece is cut along its arc as it is drawn.
const points = linePositions({ ...item, mode: '3d' });
@@ -3084,21 +3175,30 @@ export function createCesiumDraw({
pieces: [],
};
const bySegment = segmented(item);
const spans = bySegment
? points.slice(1).map((_, j) => [j, j + 1])
: [[0, points.length - 1]];
const lengths = spans.map(([a, b]) => {
const spans = pieceSpans(item, points.length, bySegment);
const lengths = spans.map(({ a, b }) => {
let length = 0;
for (let k = a; k < b; k++)
length += Cesium.Cartesian3.distance(points[k], points[k + 1]);
return length;
});
// The revealed length runs along the pieces, the gaps between runs
// having none.
const total = lengths.reduce((sum, length) => sum + length, 0);
// Several pieces of one line: each under a pick id of its own that
// reads as the line's.
const several = bySegment || spans.length > 1;
// Runs of a line drawn in the collection, as a line of one run is.
const inCollection =
broken(item) &&
item.mode !== 'draped' &&
!item.depthFail &&
item.frame !== 'inertial';
let start = 0;
spans.forEach(([a, b], j) => {
spans.forEach(({ a, b, j, last }, k) => {
const positions = points.slice(a, b + 1);
const begins = start;
start += lengths[j];
start += lengths[k];
if (!drawable(positions)) {
part.pieces.push(null);
return;
@@ -3109,16 +3209,16 @@ export function createCesiumDraw({
1,
Math.max(
0,
(item.revealFraction * total - begins) / (lengths[j] || 1),
(item.revealFraction * total - begins) / (lengths[k] || 1),
),
)
: 1;
const pieceId = bySegment ? Object.create(id) : id;
if (bySegment) record.pickIds.push(pieceId);
const pieceId = several ? Object.create(id) : id;
if (several) record.pickIds.push(pieceId);
const sub = {
...item,
positions,
style: pieceStyle(item, j, j === spans.length - 1),
style: pieceStyle(item, j, last),
...(revealed(item) && shown < 1 ? { revealFraction: shown } : {}),
// Its own points' times.
...(aged(item)
@@ -3130,6 +3230,7 @@ export function createCesiumDraw({
}
: {}),
};
delete sub.breaks;
if (!(revealed(item) && shown < 1)) delete sub.revealFraction;
const draped = item.mode === 'draped';
const showing = pieceShows(item, j, shown);
@@ -3138,17 +3239,33 @@ export function createCesiumDraw({
// would never show. Showing it later needs no build.
const primitive = draped
? groundPiece(record, sub, pieceId, true)
: depthFailLine(record, sub, pieceId);
: inCollection
? addPolyline(record, polylines, sub, pieceId).polyline
: depthFailLine(record, sub, pieceId);
if (!draped) primitive.show = showing;
// Ground pieces swap in with the set's other ground primitives.
if (draped) groundOut.push(primitive);
else host.add(primitive);
else if (!inCollection) host.add(primitive);
if (item.frame === 'inertial' && item.mode !== 'draped')
(record.inertialPieces ??= []).push(primitive);
// Drawn over the surface for a draped line: hidden past the horizon
// (`cullOverlayLines`), as a line of one run is.
const overlay =
item.overlaid && record.overlayLines
? {
part: { deep: primitive },
shown: showing,
ends: overlayEnds(positions),
}
: undefined;
if (overlay) record.overlayLines.push(overlay);
part.pieces.push({
primitive,
// The collection it is drawn in, for a polyline there.
home: inCollection ? polylines : null,
overlay,
j,
last: j === spans.length - 1,
last,
shown,
draped,
id: pieceId,
@@ -3158,6 +3275,9 @@ export function createCesiumDraw({
return part;
}
/** Whether a piece of a line is gone (with its viewer, say). */
const pieceGone = (piece) => (piece.home ?? piece.primitive).isDestroyed();
/** Whether a piece shows: its line, its segment and some of it revealed. */
const pieceShows = (item, j, shown = 1) =>
item.show !== false &&
@@ -3196,12 +3316,15 @@ export function createCesiumDraw({
/** A pieced line's colours and shows, written in place. */
function writePieces(part, item) {
for (const piece of part.pieces) {
if (!piece || piece.primitive.isDestroyed()) continue;
if (!piece || pieceGone(piece)) continue;
const style = pieceStyle(item, piece.j, piece.last);
const material = piece.primitive.appearance.material;
const material = piece.home
? piece.primitive.material
: piece.primitive.appearance.material;
if (style.kind !== 'pattern') paintLine(material, style);
const show = pieceShows(item, piece.j, piece.shown);
if (!piece.draped) piece.primitive.show = show;
if (piece.overlay) piece.overlay.shown = show;
else if (!piece.draped) piece.primitive.show = show;
else if (piece.primitive.ready) {
showOn(piece.primitive, piece.id, show);
piece.pendingShow = undefined;
@@ -3235,6 +3358,11 @@ export function createCesiumDraw({
if (first < 0) line.show = false;
else if (first > 0 || last < segmentShow.length - 1) {
line.positions = linePositions(item).slice(first, last + 2);
// Its runs' starts, among the positions it keeps.
if (broken(item))
line.breaks = Array.from(item.breaks)
.filter((at) => at > first && at < last + 2)
.map((at) => at - first);
if (item.ageFade)
line.ageFade = {
...item.ageFade,
@@ -3390,7 +3518,10 @@ export function createCesiumDraw({
for (const item of items) {
if (piecewise(item)) {
if (item.mode !== 'draped') pieces ??= new Cesium.PrimitiveCollection();
parts.set(item.id, linePieces(record, item, pieces, groundPieces));
parts.set(
item.id,
linePieces(record, item, pieces, groundPieces, polylines),
);
continue;
}
if (item.mode === 'draped') {
@@ -3626,6 +3757,8 @@ export function createCesiumDraw({
item.segmentShow != null,
revealed(item),
item.frame,
// Where its runs start.
broken(item) ? Array.from(item.breaks) : null,
// How it fades with age (its times change with its positions).
aged(item)
? [
@@ -3652,6 +3785,7 @@ export function createCesiumDraw({
(a.segmentShow != null) === (b.segmentShow != null) &&
revealed(a) === revealed(b) &&
a.frame === b.frame &&
(broken(a) ? a.breaks : null) === (broken(b) ? b.breaks : null) &&
sameAgeLook(a, b);
/** Whether two lines fade with age alike, but for their times. */
@@ -3864,7 +3998,7 @@ export function createCesiumDraw({
!flatEquals(item.positions, was.from) ||
!sameTimes(item, was.ageFrom) ||
item.revealFraction !== was.reveal ||
was.pieces.some((piece) => piece?.primitive.isDestroyed())
was.pieces.some((piece) => piece && pieceGone(piece))
)
return false;
looks.push(was.look);
@@ -4025,6 +4159,8 @@ export function createCesiumDraw({
item.mode !== 'draped' &&
item.frame !== 'inertial' &&
!item.depthFail &&
// A line in runs draws a piece a run.
!broken(item) &&
// A batch draws one colour per line, unfaded.
!aged(item) &&
item.style.kind === 'solid' &&
@@ -4475,10 +4611,15 @@ export function createCesiumDraw({
function segmentInstances(record, item, part) {
const points = linePositions(item);
const instances = [];
const starts = runStarts(item);
part.segments = [];
part.drawn = [];
for (let j = 0; j + 1 < points.length; j++) {
if (Cesium.Cartesian3.equals(points[j], points[j + 1])) {
// Nothing across a break, between two runs.
if (
starts?.has(j + 1) ||
Cesium.Cartesian3.equals(points[j], points[j + 1])
) {
part.segments.push(null);
part.drawn.push(null);
continue;
+23
View File
@@ -391,3 +391,26 @@ test('without the capability a line ignores its age fade; with it a bad fade is
);
assert.equal(set.size(), 0, 'nothing changed');
});
test('an aged line made first leaves its style’s type named as a plain material of it is', () => {
const lists = Cesium.Material._uniformList;
const was = lists.Color;
delete lists.Color;
try {
const { part, scene } = agedDraw();
const set = part.port.lines({ id: 'trails' });
set.set([trail(along(2), [T0, T0 + 1])]);
assert.deepEqual(lists.Color, ['color_0'], 'as a plain Color material');
// A plain line beside it then draws with it in its collection.
set.upsert([
{ ...trail(along(2), [T0, T0 + 1]), id: 'plain', ageFade: undefined },
]);
const plain = collectionOf(scene).get(1).material;
assert.equal(plain.type, 'Color');
assert.ok(
lists.Color.every((name) => typeof plain._uniforms[name] === 'function'),
);
} finally {
if (was) lists.Color = was;
}
});
+375
View File
@@ -0,0 +1,375 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test, { after } from 'node:test';
import { createCesiumDraw } from './draw.js';
// Node has no WebGL context to report line-width limits.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
// A material's texture uniform is told from the browser's image classes, which
// Node lacks.
const IMAGE_CLASSES = [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
];
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
after(() =>
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
);
/** A scene with what a line set touches: primitives, its events and its time. */
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
const added = [];
return {
added,
postRender: new Cesium.Event(),
preRender: new Cesium.Event(),
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
frameState: {
mode: Cesium.SceneMode.SCENE3D,
time: Cesium.JulianDate.fromDate(new Date(ms)),
},
updateHeight: () => () => {},
getHeight: () => undefined,
primitives: {
add: (primitive) => (added.push(primitive), primitive),
remove: (primitive) => {
const at = added.indexOf(primitive);
if (at >= 0) added.splice(at, 1);
return at >= 0;
},
length: 0,
},
requestRender() {},
isDestroyed: () => false,
};
}
const T0 = Date.UTC(2026, 0, 1);
/** A port over a fake scene that draws lines in runs (and with `more`). */
function brokenDraw(capabilities = ['lineBreaks'], scene = fakeScene()) {
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
capabilities: new Set(capabilities),
});
return { part, scene, set: part.port.lines({ id: 'trails' }) };
}
/** Six positions west to east, `height` up. */
const along = (n = 6, height = 100) =>
Array.from({ length: n }, (_, i) =>
Cesium.Cartesian3.fromDegrees(i * 0.01, 10, height),
);
/** Three runs: positions 0-1, 2-4 and 5 alone (which draws nothing). */
const trails = (extra = {}) => ({
id: 'trails',
positions: along(),
breaks: [2, 5],
widthPx: 3,
mode: '3d',
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
...extra,
});
/** Everything a set's host holds, collections opened. */
function everything(scene) {
const all = [];
const walk = (p) => {
all.push(p);
if (p instanceof Cesium.PrimitiveCollection)
for (let i = 0; i < p.length; i++) walk(p.get(i));
};
for (const p of scene.added) walk(p);
return all;
}
/** The polylines a set's collection draws. */
function polylinesOf(scene) {
const collection = everything(scene).find(
(p) => p instanceof Cesium.PolylineCollection,
);
const lines = [];
for (let i = 0; i < collection.length; i++) lines.push(collection.get(i));
return lines;
}
const lonOf = (p) =>
Number(
Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(p).longitude,
).toFixed(6),
);
test('an undraped line in runs is a polyline a run in its collection, each picked as the line', () => {
const { scene, set } = brokenDraw();
set.set([trails()]);
const lines = polylinesOf(scene);
assert.equal(lines.length, 2, 'a polyline a run with length');
assert.deepEqual(
lines.map((line) => line.positions.map(lonOf)),
[
[0, 0.01],
[0.02, 0.03, 0.04],
],
'nothing from position 1 to 2, nor 4 to 5',
);
assert.deepEqual(
lines.map((line) => line.id.id),
['trails', 'trails'],
'each run picks as its line',
);
assert.notEqual(lines[0].id, lines[1].id, 'under a pick id of its own');
assert.equal(set.size(), 1, 'one item');
});
test('a line in runs takes packed positions and breaks', () => {
const { scene, set } = brokenDraw();
const flat = new Float64Array(along().flatMap((p) => [p.x, p.y, p.z]));
set.set([trails({ positions: flat, breaks: new Uint32Array([3]) })]);
assert.deepEqual(
polylinesOf(scene).map((line) => line.positions.length),
[3, 3],
);
});
test('an arrow in runs has a head at the end of each run', () => {
const { scene, set } = brokenDraw();
set.set([trails({ style: { kind: 'arrow', color: '#ffffff' } })]);
assert.deepEqual(
polylinesOf(scene).map((line) => line.material.type),
['PolylineArrow', 'PolylineArrow'],
);
});
test('segment colours and shows stay a pair of positions; the pairs across a break draw nothing', () => {
const { scene, set } = brokenDraw();
const red = [1, 0, 0, 1];
const green = [0, 1, 0, 1];
const blue = [0, 0, 1, 1];
const line = (colors, shows) =>
trails({
style: { kind: 'glow', color: '#ffffff', power: 0.2 },
segmentColors: colors,
segmentShow: shows,
});
set.set([
line([red, blue, green, green, blue], [true, true, true, false, true]),
]);
const host = scene.added[0];
// In the set's collection, a polyline a segment.
const pieces = polylinesOf(scene);
assert.equal(pieces.length, 3, 'segments 0, 2 and 3; not 1 nor 4');
assert.equal(pieces[0].material.type, 'PolylineGlow');
const color = (p) => p.material.uniforms.color;
assert.deepEqual(
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
[
[1, 0, 0, true],
[0, 1, 0, true],
[0, 1, 0, false],
],
);
set.upsert([
line([green, red, red, blue, red], [true, false, true, true, true]),
]);
assert.equal(scene.added[0], host, 'recoloured and shown in place');
assert.deepEqual(
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
[
[0, 1, 0, true],
[1, 0, 0, true],
[0, 0, 1, true],
],
);
});
test('a run of a line that fades with age takes its own points’ times', () => {
const { scene, set } = brokenDraw(['lineAgeFade', 'lineBreaks']);
const times = along().map((_, i) => T0 + i * 1000);
set.set([trails({ ageFade: { times, windowMs: 60_000, alphaFloor: 0.1 } })]);
const lines = polylinesOf(scene);
assert.deepEqual(
lines.map((line) => [line.material.type, line.material.uniforms.ageCount]),
[
['DrawAgedLine_solid', 2],
['DrawAgedLine_solid', 3],
],
);
});
test('a revealed line in runs reveals them in order, along their own length', () => {
const { scene, set } = brokenDraw();
// Runs of one leg and of two, all of one length, the gap between them
// (positions 1 to 2) none: half their length is all of the first run
// and a quarter of the second.
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.5 })]);
let lines = polylinesOf(scene);
const revealOf = (line) => line.material.materials?.revealed;
assert.equal(revealOf(lines[0]), undefined, 'the first run all shown');
assert.equal(lines[0].show, true);
const second = lines[1];
assert.ok(revealOf(second), 'the second run revealed');
// Half its first leg, of two.
assert.ok(
Math.abs(second.material.uniforms.reveal - 0.25) < 1e-9,
`revealed a quarter along (${second.material.uniforms.reveal})`,
);
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.25 })]);
lines = polylinesOf(scene);
assert.equal(lines[1].show, false, 'a run not yet reached is hidden');
});
test('a draped line in runs drapes a ground piece a run; a solid segmented one a ground instance a segment, none across a break', () => {
const { scene, set } = brokenDraw();
set.set([trails({ mode: 'draped', positions: along(6, 0) })]);
const ground = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(ground.length, 2, 'a ground piece a run with length');
assert.deepEqual(
ground.map((p) => p.geometryInstances[0].geometry._positions.length),
[2, 3],
);
set.set([
trails({
mode: 'draped',
positions: along(6, 0),
segmentColors: along()
.slice(1)
.map(() => [0, 1, 0, 1]),
}),
]);
const batch = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(batch.length, 1, 'one batch');
assert.equal(
batch[0].geometryInstances.length,
3,
'segments 0, 2 and 3: not 1 nor 4',
);
});
test('changed breaks draw the line anew; the same ones change it in place', () => {
const { scene, set } = brokenDraw();
set.set([trails()]);
const host = scene.added[0];
set.upsert([trails({ show: false })]);
assert.equal(scene.added[0], host, 'shown in place');
assert.deepEqual(
polylinesOf(scene).map((line) => line.show),
[false, false],
);
set.upsert([trails({ breaks: [3] })]);
assert.notEqual(scene.added[0], host, 'built anew');
assert.deepEqual(
polylinesOf(scene).map((line) => line.positions.length),
[3, 3],
);
});
test('without the capability a line ignores its breaks; with it bad breaks are refused', () => {
const plain = brokenDraw([]);
plain.set.set([trails()]);
assert.equal(polylinesOf(plain.scene).length, 1, 'one line, joined');
const { set } = brokenDraw();
for (const breaks of [[0], [6], [3, 2], [2, 2], [1.5], ['2']])
assert.throws(
() => set.set([trails({ breaks })]),
TypeError,
`refused: ${JSON.stringify(breaks)}`,
);
assert.equal(set.size(), 0, 'nothing changed');
set.set([trails({ breaks: [] })]);
assert.equal(set.size(), 1, 'no breaks: one run');
});
test('where the scene cannot drape, a draped line in runs draws a run over the surface each, hidden past the horizon', () => {
const scene = fakeScene();
scene.frameState.context = { depthTexture: false };
const { part, set } = brokenDraw(['lineBreaks'], scene);
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0);
set.set([
trails({
mode: 'draped',
positions: [at(0), at(0.01), at(0.02), at(0.03)],
breaks: [2],
// The overlay draws its shown segments only, from first to last.
segmentShow: [false, true, true],
}),
trails({
id: 'two',
mode: 'draped',
positions: [at(0), at(0.01), at(0.02), at(0.03)],
breaks: [2],
}),
]);
const frame = () => {
part.beforeRender();
part.afterRender();
};
const runs = everything(scene).filter(
(p) => p instanceof Cesium.Primitive && p.depthFailAppearance,
);
// The first line kept positions 1 to 3, its break at 1 of them: a run of
// one position and one of two; the second two runs of two.
assert.equal(runs.length, 3, 'a primitive a run with length');
scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0);
frame();
assert.deepEqual(
runs.map((p) => p.show),
[true, true, true],
);
scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0);
frame();
assert.deepEqual(
runs.map((p) => p.show),
[false, false, false],
'past the horizon',
);
});
test('a draped line in runs whose first run is later than its second times each run by its own points', () => {
const { scene, set } = brokenDraw([
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
]);
set.set([
trails({
mode: 'draped',
positions: along(4, 0),
breaks: [2],
ageFade: {
times: [T0 + 110_000, T0 + 120_000, T0, T0 + 10_000],
windowMs: 60_000,
alphaFloor: 1,
showMs: 30_000,
},
}),
]);
const ground = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(ground.length, 2, 'a ground piece a run');
const ages = ground.map((p) => p.appearance.material.uniforms);
assert.deepEqual(
ages.map((u) => [u.ageCount, u.ageByLength, u.ageShow]),
[
[2, 1, 30],
[2, 1, 30],
],
'its own two points each, along its length, cut to the span',
);
// Each run's clock reads from its own newest point: the first's is
// 110 s later than the second's.
assert.equal(ages[1].ageNow - ages[0].ageNow, 110);
});
+2
View File
@@ -74,6 +74,8 @@ export const CESIUM_CHECKS = new Set([
'draw.lines.outlineDraped',
'draw.lines.ageFade',
'draw.lines.timeWindow',
'draw.lines.breaks',
'draw.lines.breaks.timeWindow',
'draw.lines.segments',
'draw.lines.segmentStyles',
'draw.sets.blend',
+2
View File
@@ -89,6 +89,8 @@ export function cesiumCapabilities(scene, only) {
...(scene?.context?.floatingPointTexture
? ['lineAgeFade', 'lineTimeWindow']
: []),
// Lines in runs, a piece a run (`draw.js`).
'lineBreaks',
'followFrame',
'pointVisibility',
// Cesium's AUTODETECT tracking frame (`follow.js`).
+1
View File
@@ -43,6 +43,7 @@ test('capabilities follow what the scene supports', () => {
'quads',
'meshes',
'fields',
'lineBreaks',
];
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
// A scene with a globe reads its visibility back.
+199
View File
@@ -3627,6 +3627,205 @@ export function portChecks() {
},
{ capability: 'lineTimeWindow' },
),
check(
'draw.lines.breaks',
'a line in runs, draped or not, draws and picks each run, in its segment colours, and nothing between them',
async (h, r) => {
await overAustin(h, r);
// Off the row under the camera, where a ground line can leave a gap.
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-breaks' });
// Two runs, west and east, the second starting at position 2: the
// pair from position 1 to 2, across the break, is not drawn.
const lons = [-0.004, -0.002, 0.001, 0.004];
const line = (id, dLat, mode, segmentColors) => ({
id,
positions: lons.map((dLon) =>
at(dLon, dLat, mode === 'draped' ? 0 : 20),
),
breaks: [2],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
...(segmentColors
? {
// The pair across the break has a colour, ignored.
segmentColors: [
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1],
],
}
: {}),
});
const kinds = [
['3d', 0.003, false],
['draped', 0.001, false],
['3d coloured', -0.001, true],
['draped coloured', -0.003, true],
];
const lat = new Map(kinds.map(([what, dLat]) => [what, dLat]));
lines.set(
kinds.map(([what, dLat, coloured]) =>
line(
what,
dLat,
what.startsWith('draped') ? 'draped' : '3d',
coloured,
),
),
);
const where = (what, dLon) =>
at(dLon, lat.get(what), what.startsWith('draped') ? 0 : 20);
// The colour drawn there, strongly: 'r', 'g', 'b', or null.
const colour = (what, dLon) => {
r.frame.renderNow();
const s = r.query.project(where(what, dLon));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y),
width: 1,
height: 1,
},
});
const [red, green, blue] = image.data;
if (red > green + 80 && red > blue + 80) return 'r';
if (green > red + 80 && green > blue + 80) return 'g';
if (blue > red + 80 && blue > green + 80) return 'b';
return null;
};
const picked = (what, dLon) => {
const s = r.query.project(where(what, dLon));
ok(s, `${what} projects`);
return r.query
.drillPick(s.x, s.y)
.filter((hit) => hit.set === 'conf:line-breaks')
.map((hit) => hit.id);
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, , coloured] of kinds) {
deepEqual(
picked(what, -0.003),
[what],
`${what}: its first run picks`,
);
deepEqual(
picked(what, -0.0005),
[],
`${what}: nothing between its runs`,
);
deepEqual(
picked(what, 0.0025),
[what],
`${what}: its second run picks`,
);
if (h.pixels === false) continue;
equal(
colour(what, -0.003),
coloured ? 'r' : 'g',
`${what}: its first run drawn`,
);
equal(
colour(what, -0.0005),
null,
`${what}: nothing drawn between its runs`,
);
equal(
colour(what, 0.0025),
coloured ? 'b' : 'g',
`${what}: its second run drawn`,
);
}
equal(lines.size(), kinds.length, 'one item a line');
} finally {
lines.dispose();
}
},
{ capability: 'lineBreaks' },
),
check(
'draw.lines.breaks.timeWindow',
'a line in runs, draped or not, whose first run is later than its second, cuts each run by its own times',
async (h, r) => {
if (!r.capabilities.has('lineBreaks'))
return { skip: 'the renderer draws no lines in runs' };
if (h.pixels === false)
return { skip: 'this harness reads no drawn pixels' };
await overAustin(h, r);
const t0 = Date.UTC(2026, 0, 1, 18);
r.frame.setTime(t0);
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-breaks-window' });
// Its first run, west, the last ten seconds to t0; its second, east,
// two minutes before.
const line = (id, dLat, mode) => ({
id,
positions: [-0.004, -0.001, 0.001, 0.004].map((dLon) =>
at(dLon, dLat, mode === 'draped' ? 0 : 20),
),
breaks: [2],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
ageFade: {
times: [t0 - 10_000, t0, t0 - 120_000, t0 - 110_000],
windowMs: 60_000,
alphaFloor: 1,
showMs: 30_000,
},
});
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
const green = (dLon, dLat) => {
r.frame.renderNow();
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y),
width: 1,
height: 1,
},
});
const [red, g, blue] = image.data;
return g > red + 80 && g > blue + 80;
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(-0.0025, dLat), `${what}: its later run drawn at t0`);
ok(!green(0.0025, dLat), `${what}: its earlier run too old at t0`);
ok(!green(0, dLat), `${what}: nothing between its runs`);
}
// 105 s before t0 the second run is within the span, the first
// not yet begun.
r.frame.setTime(t0 - 105_000);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(0.0025, dLat), `${what}: its earlier run drawn then`);
ok(!green(-0.0025, dLat), `${what}: its later run not yet drawn`);
ok(!green(0, dLat), `${what}: still nothing between its runs`);
}
equal(lines.size(), 2, 'never sent again');
} finally {
lines.dispose();
}
},
{ capability: 'lineTimeWindow' },
),
check(
'draw.lines.segments',
'a draped line takes segment colours and shows, changed every frame in place, without stopping the frame or picks',
+2
View File
@@ -211,6 +211,8 @@ export type Capability =
| 'lineAgeFade'
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
| 'lineTimeWindow'
/** Lines drawn as several runs, not joined across their breaks (`LineItem.breaks`). */
| 'lineBreaks'
/** Screen-space clustering of icons. */
| 'cluster'
/** Post-processing styles. */
+22
View File
@@ -337,10 +337,32 @@ export interface LineAgeFade {
showMs?: number;
}
/**
* `lineBreaks`: a line drawn as several runs, so many lines in one style can
* be one item (thousands of moving objects' trails sent as one line, say),
* and the renderer handles one item instead of thousands. Each break is the
* index `i` of a position that starts a new run (`0 < i < positions.length`,
* strictly increasing): the segment from position `i - 1` to `i` is not
* drawn (nor picked), and the line does not join across it, each run having
* two ends of its own, capped and joined as a line of its own would be.
* `segmentColors` and `segmentShow` stay one a pair of neighbouring
* positions (`j`: from position `j` to `j + 1`), so a pair across a break
* has an entry that is ignored; `ageFade.times` stays one a position; and
* `revealFraction` runs along the runs, in order, as one length (the gaps
* between them have none). A renderer without the capability is never sent
* `breaks`: its lines are sent one item a run instead.
*/
export type LineBreaks = number[] | Uint32Array;
export interface LineItem {
id: string;
/** ECEF positions, or packed `x, y, z` triples. */
positions: Ecef[] | Float64Array;
/**
* `lineBreaks`: the positions that start a new run of the line
* (`LineBreaks`). [absent or empty: one run]
*/
breaks?: LineBreaks;
widthPx: number;
/**
* `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on
+1
View File
@@ -43,6 +43,7 @@ export const CAPABILITIES = Object.freeze([
'courseGlide',
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
'cluster',
'styles',
'bloom',
+41 -2
View File
@@ -1330,9 +1330,19 @@ export function createStubRenderer(options = {}) {
return out;
}
/**
* The positions that start a run of a line in runs (`lineBreaks`), or
* null: nothing is drawn between two runs.
*/
const runStarts = (item) =>
capabilities.has('lineBreaks') && item.breaks?.length
? new Set(item.breaks)
: null;
/**
* A line's positions as ECEF, cut at its `revealFraction` of length (as
* drawn straight between its positions).
* drawn straight between its positions, along its runs, the gaps between
* them having none).
*/
function revealedLine(item) {
const flat = item.positions instanceof Float64Array;
@@ -1350,7 +1360,10 @@ export function createStubRenderer(options = {}) {
);
const fraction = item.revealFraction;
if (fraction === undefined || fraction >= 1) return points;
const at = alongLength(points, fraction);
const starts = runStarts(item);
const at = starts
? alongRuns(points, starts, fraction)
: alongLength(points, fraction);
if (!at) return [];
const { index, t } = at;
return [
@@ -1359,17 +1372,43 @@ export function createStubRenderer(options = {}) {
];
}
/**
* `alongLength` for a line in runs: the segment a fraction of its runs'
* length ends on, and how far along it, the segments between runs
* measuring nothing.
*/
function alongRuns(points, starts, fraction) {
if (!(fraction > 0) || points.length < 2) return null;
const lengths = [];
for (let i = 0; i + 1 < points.length; i++)
lengths.push(
starts.has(i + 1) ? 0 : magnitude(sub(points[i + 1], points[i])),
);
const total = lengths.reduce((sum, length) => sum + length, 0);
if (!(total > 0)) return null;
let left = fraction * total;
for (let i = 0; i < lengths.length; i++) {
if (lengths[i] > 0 && left <= lengths[i])
return { index: i, t: left / lengths[i] };
left -= lengths[i];
}
return { index: lengths.length - 1, t: 1 };
}
/**
* Where a line is under the pixel `(x, y)`: the nearest point of a
* drawn segment within half its width (and `slack`) of it, or null.
*/
function lineHit(item, x, y, slack) {
const points = revealedLine(item);
const starts = runStarts(item);
const reach = (item.widthPx ?? 1) / 2 + slack;
let best = null;
let bestDistance = Infinity;
for (let i = 0; i + 1 < points.length; i++) {
if (item.segmentShow?.[i] === false) continue;
// Nothing is drawn between two runs.
if (starts?.has(i + 1)) continue;
const a = points[i];
const b = points[i + 1];
if (isOccluded(a) && isOccluded(b)) continue;
+2 -1
View File
@@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => {
.filter((r) => r.status === 'skip')
.map((r) => r.id);
// It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a
// split line's, a draped outlined line's, an aged line's, a time-windowed line's and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// split line's, a draped outlined line's, an aged line's, a time-windowed line's (in runs too) and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// camera that does (a controller over it, say).
assert.deepEqual(skipped, [
'effects.screenModulation.pixels',
@@ -31,6 +31,7 @@ test('the stub passes the conformance suite', async () => {
'draw.lines.outlineDraped',
'draw.lines.ageFade',
'draw.lines.timeWindow',
'draw.lines.breaks.timeWindow',
'draw.models.blend',
'draw.models.paint',
'globe.imagery.video',