diff --git a/src/layers/rail/routeDisplay.js b/src/layers/rail/routeDisplay.js index c2e94bb4c..31eeae4b8 100644 --- a/src/layers/rail/routeDisplay.js +++ b/src/layers/rail/routeDisplay.js @@ -32,6 +32,11 @@ import { const NETWORK_SLICE_MS = 6; /** The fade is applied in steps, so a slow zoom does not rewrite it per event. */ const FADE_STEP = 0.05; +/** A split that moved less than this share of the line is not redrawn. */ +const SPLIT_EPSILON = 1e-5; +/** The selected line's dark rim, which keeps it legible over bright + * imagery: the outer 28% of its width at 22% of its colour. */ +const ROUTE_RIM = Object.freeze({ shade: 0.22, widthFraction: 0.28 }); /** Arc a route-bound train must cover before its direction is trusted (m). */ const DIRECTION_EVIDENCE_M = 60; const STOP_DOT_PX = 5; @@ -315,58 +320,53 @@ export function createRouteDisplay({ dropRoute(); const { path } = shape; const positions = []; - // Arc length (m) of each drawn vertex, so each segment knows the arc - // it spans, and the cumulative drawn length per path vertex, which - // the split's fraction is measured on. - const drawnS = []; + // The cumulative drawn length per path vertex, which the split's + // fraction is measured on: metres on the ground, as a draped line's + // texture runs; one per vertex where the scene draws it over the + // surface instead, as a polyline's does. + const ground = port.clampState?.() !== 'overlay'; const chordAt = new Float64Array(path.n); for (let i = 0; i < path.n; i++) { const point = fromDegrees(path.lon[i], path.lat[i], 0); const last = positions[positions.length - 1]; const step = last ? distance(last, point) : 0; const repeat = last && step < REPEAT_M; - if (i > 0) chordAt[i] = chordAt[i - 1] + (repeat ? 0 : step); - if (!repeat) { - positions.push(point); - drawnS.push(path.s[i]); - } + if (i > 0) + chordAt[i] = chordAt[i - 1] + (repeat ? 0 : ground ? step : 1); + if (!repeat) positions.push(point); } if (positions.length < 2) return; routeSet ||= lineSet(`rail:${instance}:route:${++routeBuilds}`); if (!routeSet) return; routeSet.show = true; - const ahead = categoryColor(entry.category, 1); - const travelled = categoryColor(entry.category, ROUTE_TRAVELLED_ALPHA); - const midS = new Float64Array(positions.length - 1); - for (let j = 0; j < midS.length; j++) - midS[j] = (drawnS[j] + drawnS[j + 1]) / 2; + // Solid ahead of the train, dimmer behind, split where it is. const item = { id: 'route', positions, widthPx: ROUTE_AHEAD_WIDTH_PX, mode: 'draped', - style: { kind: 'solid', color: ahead }, - segmentColors: new Array(midS.length).fill(ahead), + style: { + kind: 'split', + color: categoryColor(entry.category, 1), + behind: categoryColor(entry.category, ROUTE_TRAVELLED_ALPHA), + at: -1, + rim: ROUTE_RIM, + }, pickable: false, }; routeSet.set([item]); state._route = { id, item, - ahead, - travelled, - midS, path, chordAt, + ground, binding: shape.binding, // A trip's own shape runs the way the trip does; a route's shape may // be drawn either way, so its direction is learnt from the train. direction: shape.binding?.via === 'trip' ? 1 : 0, firstS: shape.binding ? shape.binding.drawS : NaN, fraction: NaN, - /** Segments drawn travelled, and which way: `${direction}:${count}`. */ - split: '1:0', - ground: port.clampState?.() !== 'overlay', }; governorRequestRender('rail-route'); } else if (state._route.binding !== shape.binding) { @@ -378,10 +378,7 @@ export function createRouteDisplay({ updateSplit(); } - /** - * Colour the segments behind the train travelled and the rest ahead: a - * segment is behind it when the middle of its arc is. - */ + /** Move the travelled/ahead split to where the train is drawn now. */ function updateSplit() { const route = state._route; if (!route) return; @@ -396,24 +393,26 @@ export function createRouteDisplay({ route.direction !== 0 && Number.isFinite(s) ? splitFraction(route.path, route.chordAt, s) : NaN; - // No position on the line yet: draw it all as ahead. - route.fraction = Number.isFinite(fraction) ? fraction : NaN; - const mids = route.midS; - let behind = 0; - if (Number.isFinite(fraction)) - for (let j = 0; j < mids.length; j++) - if (route.direction > 0 ? mids[j] < s : mids[j] > s) behind += 1; - const direction = Number.isFinite(fraction) ? route.direction : 1; - const split = `${direction}:${behind}`; - if (split === route.split) return; - route.split = split; - const colors = route.item.segmentColors; - for (let j = 0; j < mids.length; j++) { - const travelled = - Number.isFinite(fraction) && - (route.direction > 0 ? mids[j] < s : mids[j] > s); - colors[j] = travelled ? route.travelled : route.ahead; + const style = route.item.style; + if (!Number.isFinite(fraction)) { + // No position on the line yet: draw it all as ahead. + route.fraction = NaN; + if (style.at === -1 && !style.reverse) return; + } else { + const reverse = route.direction < 0; + if ( + Number.isFinite(route.fraction) && + Math.abs(fraction - route.fraction) < SPLIT_EPSILON && + Boolean(style.reverse) === reverse + ) + return; + route.fraction = fraction; } + const at = Number.isFinite(fraction) ? fraction : -1; + route.item = { + ...route.item, + style: { ...style, at, reverse: at >= 0 && route.direction < 0 }, + }; routeSet?.upsert([route.item]); governorRequestRender('rail-route-split'); } diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 39a008369..7202f49b8 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -56,6 +56,20 @@ export function toColor(color, alpha = 1) { return c.withAlpha(c.alpha * alpha); } +/** + * A split line style's colours and split as its material's uniforms: `at` + * outside 0..1 draws it all in `color`, as a split before the start does. + */ +function splitUniforms(style) { + const at = Number.isFinite(style.at) && style.at >= 0 && style.at <= 1; + return { + color: toColor(style.color), + behind: toColor(style.behind), + splitAt: at ? style.at : -1, + direction: at && style.reverse ? -1 : 1, + }; +} + /** * An image reference as something a billboard or material takes: a URL, an * SVG as a data URL, a blob as its object URL, or the canvas itself. An @@ -238,6 +252,26 @@ czm_material czm_getMaterial(czm_materialInput materialInput) { return m; }`; +const SPLIT_MATERIAL = 'DrawSplitLine'; + +/** + * Along the line (`st.s`, 0 at its start, 1 at its end, by length on the + * ground) `color` from `splitAt` on and `behind` before it (`direction` + * -1: the other way); across it (`st.t`) the outer `rimFraction` in all is + * each colour's shade. + */ +const SPLIT_SOURCE = ` +czm_material czm_getMaterial(czm_materialInput materialInput) { + czm_material m = czm_getDefaultMaterial(materialInput); + float s = materialInput.st.s; + bool before = direction > 0.0 ? s < splitAt : s > splitAt; + vec4 c = before ? behind : color; + bool rim = abs(materialInput.st.t - 0.5) > 0.5 - rimFraction * 0.5; + m.diffuse = czm_gammaCorrect(rim ? c.rgb * rimShade : c.rgb); + m.alpha = c.a; + return m; +}`; + /** * How finely a clamped ellipse with an image fill is cut, radians, so an * image's round edge (a zone's rim) runs round. @@ -307,6 +341,7 @@ const DRAPED_STYLES = new Set([ 'flow', 'arrow', 'pattern', + 'split', ]); // Whether Cesium's approximate terrain heights have been asked for. @@ -501,6 +536,10 @@ export function createCesiumDraw({ // A shape's pulse the renderer cannot run is refused before anything // changes. const checkPulses = (list) => { + if (kind === 'lines') + for (const item of list) + if (item.style?.kind === 'split' && item.mode !== 'draped') + throw new TypeError('a split line is draped'); if (kind !== 'shapes') return; for (const item of list) pulseOf(item); if (list.some((item) => item.animate)) record.mayPulse = true; @@ -2136,9 +2175,12 @@ export function createCesiumDraw({ // values in the fabric would be merged into copies of the type's. const template = ({ type, source, uniforms }) => source ? { type, source, uniforms } : { type }; - // A pattern's image carries its own alpha: drawn in the translucent - // pass, whatever its colour. - const translucent = style.kind === 'pattern' ? { translucent: true } : {}; + // A pattern's image carries its own alpha, and a split line's colours + // may each have one: drawn in the translucent pass, whatever its colour. + const translucent = + style.kind === 'pattern' || style.kind === 'split' + ? { translucent: true } + : {}; const material = reveal === undefined ? new Cesium.Material({ fabric: template(fabric), ...translucent }) @@ -2195,6 +2237,16 @@ export function createCesiumDraw({ }, source: FLOW_SOURCE, }; + case 'split': + return { + type: SPLIT_MATERIAL, + uniforms: { + ...splitUniforms(style), + rimShade: style.rim?.shade ?? 1, + rimFraction: style.rim?.widthFraction ?? 0, + }, + source: SPLIT_SOURCE, + }; case 'solid': // An outlined line keeps its edge in one material: two lines // stacked would darken where their translucent passes overlap. @@ -2976,7 +3028,10 @@ export function createCesiumDraw({ replaceHost(record, collect(own, ground), ground, own); } - /** A line style but for its colours, which its material takes in place. */ + /** + * A line style but for its colours (and a split line's split), which its + * material takes in place. + */ const colourlessStyle = (style) => style.outline ? { @@ -2984,13 +3039,23 @@ export function createCesiumDraw({ color: undefined, outline: { ...style.outline, color: undefined }, } - : { ...style, color: undefined }; + : style.kind === 'split' + ? { + ...style, + color: undefined, + behind: undefined, + at: undefined, + reverse: undefined, + } + : { ...style, color: undefined }; /** Give a line's material its style's colours, its outline's too. */ function paintLine(material, style) { material.uniforms.color = toColor(style.color); if (style.outline && 'outlineColor' in material.uniforms) material.uniforms.outlineColor = toColor(style.outline.color); + if (style.kind === 'split' && 'splitAt' in material.uniforms) + Object.assign(material.uniforms, splitUniforms(style)); } /** diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index f7b44b67e..ab1a1af95 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -5497,6 +5497,60 @@ test('a draped arrow drapes its arrow material on a ground polyline of its own, set.dispose(); })); +test('a split line draws ahead and behind its split with a rim, the split moving in place', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'route', clampTo: 'tiles' }); + const positions = new Float64Array([ + ...Object.values(Cesium.Cartesian3.fromDegrees(0, 0)), + ...Object.values(Cesium.Cartesian3.fromDegrees(0.01, 0.01)), + ]); + const route = (at, reverse) => ({ + id: 'route', + positions, + widthPx: 5, + mode: 'draped', + style: { + kind: 'split', + color: [0.2, 0.6, 1, 1], + behind: [0.2, 0.6, 1, 0.3], + at, + reverse, + rim: { shade: 0.22, widthFraction: 0.28 }, + }, + }); + set.set([route(-1)]); + const host = scene.added[0]; + const line = [...Array(host.length).keys()] + .map((i) => host.get(i)) + .find((p) => p.appearance?.material?.type === 'DrawSplitLine'); + assert.ok(line, 'drawn by the split material'); + const uniforms = line.appearance.material.uniforms; + assert.deepEqual( + [uniforms.splitAt, uniforms.direction, uniforms.rimShade], + [-1, 1, 0.22], + ); + assert.equal(uniforms.rimFraction, 0.28); + assert.equal(uniforms.behind.alpha, 0.3); + assert.ok(line.appearance.material.isTranslucent()); + set.upsert([route(0.4)]); + assert.ok(!line.isDestroyed(), 'the same ground primitive'); + assert.deepEqual([uniforms.splitAt, uniforms.direction], [0.4, 1]); + set.upsert([route(0.6, true)]); + assert.deepEqual([uniforms.splitAt, uniforms.direction], [0.6, -1]); + set.upsert([route(Number.NaN, true)]); + assert.deepEqual( + [uniforms.splitAt, uniforms.direction], + [-1, 1], + 'no split: all ahead', + ); + assert.throws( + () => set.upsert([{ ...route(0.5), mode: 'geodesic' }]), + TypeError, + 'a split line is draped', + ); + })); + test('a draped line drawn by its own material changes colour in place; a batched one rebuilds', () => withImageClasses(() => { const { scene, draw } = drawOver(); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 30b3b7c89..58ffd121f 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -69,6 +69,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.lines.styles', 'draw.lines.outline', 'draw.lines.drape', + 'draw.lines.split', 'draw.lines.segments', 'draw.lines.segmentStyles', 'draw.sets.blend', diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 69ac29764..9c4919359 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -3032,6 +3032,96 @@ export function portChecks() { lines.dispose(); }, ), + check( + 'draw.lines.split', + 'a draped split line draws its behind colour before its split and its colour after it, each with a darker rim, the split and its direction moved in place', + async (h, r) => { + if (h.pixels === false) + return { skip: 'this harness reads no drawn pixels' }; + await overAustin(h, r); + // Off the row under the camera, where a ground line can leave a gap. + const at = (dLon) => + h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + 0.002 }); + const lines = r.draw.lines({ id: 'conf:line-split' }); + const item = (split, reverse = false) => ({ + id: 'route', + positions: [at(-0.004), at(0.004)], + widthPx: 24, + mode: 'draped', + style: { + kind: 'split', + color: '#ff0000', + behind: '#00ff00', + at: split, + reverse, + rim: { shade: 0.25, widthFraction: 0.3 }, + }, + }); + // The middle column across the line at `dLon`, top to bottom: + // R/G its core, r/g the rim (under 0.8 of the core’s brightness, as + // a renderer may light or fog the colours), - neither. + const column = (dLon) => { + r.frame.renderNow(); + const s = r.query.project(at(dLon)); + const half = 24; + const image = r.readPixels({ + crop: { + x: Math.round(s.x) - 2, + y: Math.round(s.y) - half, + width: 5, + height: 2 * half + 1, + }, + }); + const read = []; + for (let row = 0; row < image.height; row++) { + const i = (row * image.width + 2) * 4; + const [red, green, blue] = image.data.slice(i, i + 3); + const hue = + red > green + 20 && red > blue + 20 + ? 'r' + : green > red + 20 && green > blue + 20 + ? 'g' + : ''; + read.push([hue, hue === 'r' ? red : hue === 'g' ? green : 0]); + } + const core = Math.max(...read.map(([, v]) => v)); + return read + .map(([hue, v]) => + !hue ? '-' : v >= 0.8 * core ? hue.toUpperCase() : hue, + ) + .join(''); + }; + const reads = (col, hue) => { + const runs = col.match(/([rRgG])\1*/g) ?? []; + const core = runs.find((run) => run[0] === hue.toUpperCase()); + const rims = runs.filter((run) => run[0] === hue); + return Boolean(core) && rims.length >= 2; + }; + try { + lines.set([item(0.25)]); + await drawn(h, r); + await settled(r); + await drawn(h, r); + let a = column(-0.003); + let b = column(0.001); + ok(reads(a, 'g'), `behind its split: green, rimmed (${a})`); + ok(reads(b, 'r'), `ahead of its split: red, rimmed (${b})`); + lines.upsert([item(0.75)]); + await drawn(h, r); + b = column(0.001); + ok(reads(b, 'g'), `the split moved past it: green (${b})`); + lines.upsert([item(0.25, true)]); + await drawn(h, r); + a = column(-0.003); + b = column(0.001); + ok(reads(a, 'r'), `reversed: ahead before the split, red (${a})`); + ok(reads(b, 'g'), `reversed: behind after it, green (${b})`); + equal(lines.size(), 1, 'moved in place, not added'); + } finally { + lines.dispose(); + } + }, + ), check( 'draw.lines.segments', 'a draped line takes segment colours and shows, changed every frame in place, without stopping the frame or picks', diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 2c85d2fec..2d4528611 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -242,7 +242,23 @@ export type LineStyle = | { kind: 'dash'; color: Color; length: number; pattern16?: number } | { kind: 'arrow'; color: Color } | { kind: 'pattern'; image: ImageRef; repeat: number } - | { kind: 'flow'; color: Color; repeat: number; duty: number; speed: number }; + | { kind: 'flow'; color: Color; repeat: number; duty: number; speed: number } + | { + /** + * Draped lines only. `color` from fraction `at` of the line's length + * to its end, `behind` from its start to `at` (the other way round + * with `reverse`); `at` outside 0..1 draws it all in `color`. With a + * `rim`, the outer `widthFraction` of the width in all (half each + * side) draws each colour's red, green and blue times `shade`, its + * alpha kept. `at`, `reverse` and the colours change in place. + */ + kind: 'split'; + color: Color; + behind: Color; + at: number; + reverse?: boolean; + rim?: { shade: number; widthFraction: number }; + }; export interface LineItem { id: string; diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 5e1d19f1f..ff45bb895 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -19,14 +19,15 @@ test('the stub passes the conformance suite', async () => { const skipped = report.results .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 and - // the blends' (over a drawn shape), video tiles' and the weather's pixels (drawn, and by scene time) go unread; its camera takes no user gestures: the drag and wheel scripts are for a + // It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a + // split line's and the blends' (over a drawn shape), video tiles' and the weather's pixels (drawn, and by scene time) 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', 'draw.shapes.lit', 'draw.lines.outline', 'draw.sets.blend', + 'draw.lines.split', 'draw.models.blend', 'globe.imagery.video', 'globe.weather.drawn',