From 26633106fc732d5f29d3edd4bb9375157506268c Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 9 Nov 2026 03:10:29 -0800 Subject: [PATCH] Traffic surface keys and readiness through the globe port; draped lines fall back to overlay where the scene cannot drape The traffic layer keys its cached road heights by the globe port's surfaceVersion() and waits on isSettled('surface') instead of reading the scene through render/cesium/surfaceState.js, which is gone. Heat-lines are always asked for draped; the layer no longer checks whether the scene can drape and drops them. The traffic layer and application/sources no longer reach Cesium, and src/layers/traffic/rendering.js leaves the Cesium list. Where the Cesium renderer cannot drape (no depth textures), its draw port now draws every draped line over the surface, as the contract asks: along the surface's curve between its positions, in its colour where the surface hides it, hidden past the horizon (tested along its arc, shown in 2D). A segmented line runs from its first shown segment to its last, in its style colour. A line whose positions hold what they held takes a new colour in place, so pulsing jam lines build nothing per frame; one that moves is built anew alone. --- CHANGELOG.md | 13 ++ docs/CURRENT-STATE.md | 2 +- scripts/package-boundaries.json | 3 - src/layers/traffic/heatLines.test.mjs | 21 +-- src/layers/traffic/motion.test.mjs | 2 +- src/layers/traffic/rendering.js | 29 +--- src/layers/traffic/state.js | 4 - src/layers/traffic/surface.js | 22 ++- src/layers/traffic/surface.test.mjs | 2 +- src/render/cesium/draw.js | 208 +++++++++++++++++++++-- src/render/cesium/draw.test.mjs | 232 +++++++++++++++++++++++++- src/render/cesium/surfaceState.js | 98 ----------- src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 7 + src/testSupport/fakeSceneSurface.mjs | 68 +++++++- 15 files changed, 543 insertions(+), 169 deletions(-) delete mode 100644 src/render/cesium/surfaceState.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d27f317a..5f1d1211e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,19 @@ own with no renderer bound needs `gods-eye-view/render/cesium/unbound` loaded once first, or location framing throws and snaps answer nothing (samehkhamis). +- `gods-eye-view/layers/traffic` (and `gods-eye-view/application/sources`, + which reaches it) no longer reaches Cesium: the layer keys cached road + heights by the globe port's `surfaceVersion()` and waits on + `isSettled('surface')`. Heat-lines are always asked for draped; a renderer + that cannot drape draws them over the surface instead of the layer + dropping them. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- Where the Cesium renderer cannot drape (a WebGL context without depth + textures), every draped line now draws over the surface, as the renderer + contract asks: along the surface's curve between its positions, in its + colour where the surface hides it, hidden past the horizon. Segment colours + are dropped (it draws in its style colour) and it runs from its first shown + segment to its last (samehkhamis). ## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 2737c0d71..c4476d2bd 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1041,7 +1041,7 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. -Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger; only the surface identity, tile readiness and draped-line support are still read off the Cesium scene. +Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. Traffic and bikeshare expose factories through `./layers/traffic` and `./layers/bikeshare`. Traffic separates road requests, ingestion, animation, diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index f9f04b147..eb808bebd 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2397,7 +2397,6 @@ "src/layers/traffic/policy.js", "src/render/color.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", @@ -3680,7 +3679,6 @@ "src/layers/traffic/model.js", "src/layers/traffic/policy.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", @@ -4646,7 +4644,6 @@ "src/layers/traffic/model.js", "src/layers/traffic/policy.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", diff --git a/src/layers/traffic/heatLines.test.mjs b/src/layers/traffic/heatLines.test.mjs index 39ba6b5cf..87eccda57 100644 --- a/src/layers/traffic/heatLines.test.mjs +++ b/src/layers/traffic/heatLines.test.mjs @@ -22,12 +22,7 @@ const road = (level, length = 100, x = 0) => ({ ], }); -function setup({ - live = true, - heatline = true, - preset = 'normal', - supported = true, -} = {}) { +function setup({ live = true, heatline = true, preset = 'normal' } = {}) { const draw = fakeDrawPort(); const demand = []; const state = { @@ -37,7 +32,6 @@ function setup({ _stylePreset: preset, _heatJam: [], _heatLineCount: 0, - _heatSupported: supported, _heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }), }; const rendering = createRendering({ @@ -144,14 +138,9 @@ test('no heat-lines in simulation or with the mode off, and removal empties the assert.equal(items().length, 0, 'nothing to pulse'); }); -test('where lines cannot drape, no heat-lines are drawn and that is said once', (t) => { - const warn = t.mock.method(console, 'warn', () => {}); - const { state, rendering, items } = setup({ supported: null }); - state._viewer = { scene: {} }; +test('heat-lines are asked for draped whatever the renderer, with no check of their own', () => { + const { rendering, items } = setup(); rendering.rebuildHeatLines([road(0.2)]); - rendering.rebuildHeatLines([road(0.2)]); - assert.equal(items().length, 0); - assert.equal(state._heatSupported, false); - assert.equal(warn.mock.callCount(), 1); - assert.equal(rendering.heatPulsing(), false); + assert.equal(items().length, 1); + assert.equal(items()[0].mode, 'draped'); }); diff --git a/src/layers/traffic/motion.test.mjs b/src/layers/traffic/motion.test.mjs index c0e3e48b5..04f14db20 100644 --- a/src/layers/traffic/motion.test.mjs +++ b/src/layers/traffic/motion.test.mjs @@ -759,7 +759,7 @@ test('selection asks the query port for depth and screen positions, and the came camera: { pose: () => (poses++, { position: { x: eye.x, y: eye.y, z: eye.z } }), }, - globe: { isGlobeVisible: () => true }, + globe: { isGlobeVisible: () => true, isSettled: () => true }, query: { sampleHeightNow: () => 0, pickPosition(x, y) { diff --git a/src/layers/traffic/rendering.js b/src/layers/traffic/rendering.js index 54cb696cd..ce8046203 100644 --- a/src/layers/traffic/rendering.js +++ b/src/layers/traffic/rendering.js @@ -12,20 +12,6 @@ import { } from './policy.js'; import { distance } from '../../geo/vector.js'; import { findCamera } from '../../render/rendererOf.js'; -// The layer's other parts reach the renderer through the unbound camera -// factory (with its query port) and globe factory, loaded here with the -// adapter this file needs. -import '../../render/cesium/camera.js'; -import '../../render/cesium/globe.js'; -// What the dots' surface is, and whether it has loaded, the renderer -// contract cannot say: the Cesium adapter reads it off the scene. -import { - drapesLines, - surfaceTilesReady, - surfaceKey as trafficSurfaceKey, -} from '../../render/cesium/surfaceState.js'; - -export { surfaceTilesReady, trafficSurfaceKey }; export function createRendering({ state: layerState, @@ -66,7 +52,8 @@ export function createRendering({ * on top. Lines of the layer's heat-line draw set, draped on the tiles; * the jam lines pulse together (`pulseHeatLines`). Capped at * HEAT_LINE_CAP (jam first, longest first); overflow is logged. No-op in - * sim mode, when the heatline mode is off, or where lines cannot drape. + * sim mode or when the heatline mode is off. A renderer that cannot drape + * draws them over the surface instead (the draw port's `overlay`). * * @param {Array} roads - Road objects visible in the current render. */ @@ -81,18 +68,6 @@ export function createRendering({ removeHeatLines(); return; } - if (layerState._heatSupported === null) { - layerState._heatSupported = drapesLines(layerState._viewer); - if (!layerState._heatSupported) - console.warn( - '[Data:Traffic] Draped lines unsupported — heat-lines disabled', - ); - } - if (!layerState._heatSupported) { - removeHeatLines(); - return; - } - const candidates = []; for (const road of roads) { const flow = road.flow; diff --git a/src/layers/traffic/state.js b/src/layers/traffic/state.js index ecd643fbc..2554edb3b 100644 --- a/src/layers/traffic/state.js +++ b/src/layers/traffic/state.js @@ -182,10 +182,6 @@ export function createState({ services }) { layerState._heatLineCount = 0; - /** @type {boolean|null} Whether lines can drape here, checked once. */ - - layerState._heatSupported = null; - /** @type {number} Altitude of the last render, for late-flow heat rebuilds. */ layerState._lastRenderAltitude = 0; diff --git a/src/layers/traffic/surface.js b/src/layers/traffic/surface.js index 8541a7c2c..5d8e33053 100644 --- a/src/layers/traffic/surface.js +++ b/src/layers/traffic/surface.js @@ -10,9 +10,27 @@ import { findGlobe, findQuery, } from '../../render/rendererOf.js'; -import { surfaceTilesReady, trafficSurfaceKey } from './rendering.js'; +/** + * What heights are sampled against now: the globe port's surface identity, + * which changes when the base, terrain or photoreal route is swapped or the + * globe is shown or hidden, and never on camera moves or tile loads. A + * renderer without one (`surfaceIdentity`) names a single surface (0), so + * cached heights live as long as the layer's cache. + * @param {object|undefined} viewer + * @returns {number} + */ +export function trafficSurfaceKey(viewer) { + return findGlobe(viewer)?.surfaceVersion?.() ?? 0; +} -export { trafficSurfaceKey }; +/** + * Whether the drawn surface has loaded what is in view: the globe's terrain + * while it is shown, otherwise the shown 3D tiles (false with neither). + * @param {object|undefined} viewer + */ +function surfaceTilesReady(viewer) { + return findGlobe(viewer)?.isSettled('surface') === true; +} /** Whether the globe surface is drawn (else tiles alone are). */ const globeShown = (viewer) => findGlobe(viewer)?.isGlobeVisible?.() === true; diff --git a/src/layers/traffic/surface.test.mjs b/src/layers/traffic/surface.test.mjs index 9b92315b5..a430547d5 100644 --- a/src/layers/traffic/surface.test.mjs +++ b/src/layers/traffic/surface.test.mjs @@ -346,7 +346,7 @@ test('rendered road depth is geographically checked, bounded, and avoids mesh re ); }); -test('surface keys reuse identity without building arrays or strings on unchanged frames', (t) => { +test('surface keys follow the globe port’s surface identity, building nothing on unchanged frames', (t) => { const tiles = [ { show: true, tilesLoaded: true }, { show: true, tilesLoaded: false }, diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 7ef6edb7d..43b008259 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -790,6 +790,7 @@ export function createCesiumDraw({ // eye is hidden, as layers drawn without depth test used to do themselves. let occluder = null; function cullHorizon() { + cullOverlayLines(); for (const record of sets.values()) { if (!record.spec.horizonCull || !record.placed.length) continue; const horizon = horizonNow(); @@ -801,6 +802,26 @@ export function createCesiumDraw({ } } + /** + * Draped lines drawn over the surface (where the scene cannot drape) show + * while any of their ends or middle is this side of the horizon. + */ + function cullOverlayLines() { + let horizon; + for (const record of sets.values()) { + if (!record.overlayLines?.length) continue; + horizon ??= horizonNow(); + for (const line of record.overlayLines) { + // With no horizon (2D) every line shows as it was asked to. + const show = + line.shown && + (!horizon || line.ends.some((p) => horizon.isPointVisible(p))); + if (line.part.deep && line.part.deep.show !== show) + line.part.deep.show = show; + } + } + } + /** The horizon from the eye as it is now; null where there is none (2D). */ function horizonNow() { const eye = scene.camera?.positionWC; @@ -1849,8 +1870,11 @@ export function createCesiumDraw({ 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, + // (geodesic ones come densified); one drawn for a draped line + // follows the surface's curve between them, as draping does. + arcType: item.overlaid + ? Cesium.ArcType.GEODESIC + : Cesium.ArcType.NONE, }), id, }), @@ -1958,6 +1982,125 @@ export function createCesiumDraw({ ); } + /** Whether the scene can drape lines (Cesium's ground polylines need + * depth textures, which every WebGL 2 context has). */ + const drapes = () => scene.frameState?.context?.depthTexture !== false; + + /** + * A draped line as drawn where the scene cannot drape: undraped along its + * positions, in its colour where the surface hides it (so it draws over + * the surface), as one colour where it had segments of its own. One with + * segments runs from its first shown segment to its last, and is hidden + * with none shown. + */ + function overlayLine(item) { + if (item.mode !== 'draped') return item; + const { segmentColors, segmentShow, clampTo, ...rest } = item; + const line = { + ...rest, + mode: '3d', + depthFailColor: item.style.color, + overlaid: true, + }; + if (segmentShow?.length) { + const first = segmentShow.indexOf(true); + const last = segmentShow.lastIndexOf(true); + if (first < 0) line.show = false; + else if (first > 0 || last < segmentShow.length - 1) + line.positions = linePositions(item).slice(first, last + 2); + } + return line; + } + + /** + * Recolour, in place, a line drawn over the surface for a draped one whose + * positions are the ones it was built from. False, changing nothing, for + * one that moved or is revealed. + */ + function overlayRecoloured(record, part, item) { + const deep = part.deep; + if (!item.overlaid || !deep || revealed(item)) return false; + if (!flatEquals(item.positions, part.overlayFrom)) return false; + // Only its colour may have changed (`patchLines` checked its look). + deep.appearance.material.uniforms.color = toColor(item.style.color); + deep.depthFailAppearance.material.uniforms.color = toColor( + item.style.color, + ); + const line = record.overlayLines.find((entry) => entry.part === part); + if (line) line.shown = item.show !== false; + else deep.show = item.show !== false; + return true; + } + + /** An overlay line's look but its colours (its depth-fail colour is its + * colour too). */ + const overlayShape = (item) => + lineLook({ ...item, depthFailColor: null }, true); + + /** Stop tracking a line no longer drawn over the surface for a draped + * one. */ + function overlayLeft(record, part) { + const lines = record.overlayLines; + const at = lines ? lines.findIndex((line) => line.part === part) : -1; + if (at >= 0) lines.splice(at, 1); + part.overlayFrom = undefined; + part.overlayShape = undefined; + } + + /** Track a patched overlay line for the horizon cull, as built now. */ + function overlayMoved(record, part, item) { + part.overlayFrom = flatPositions(item.positions); + part.overlayShape = overlayShape(item); + const lines = record.overlayLines; + const at = lines.findIndex((line) => line.part === part); + if (at >= 0) lines.splice(at, 1); + if (!part.deep) return; + lines.push({ + part, + shown: item.show !== false, + ends: overlayEnds(item.positions), + }); + } + + /** + * Points along a line for the horizon test: up to 16 of its positions, + * evenly spread, and between each two the point on the surface's curve + * halfway (so a long arc under the eye is not taken as past the horizon). + */ + function overlayEnds(positions) { + const all = linePositions({ positions }); + if (!all.length) return []; + const picks = Math.min(all.length, 16); + const probes = []; + let previous = null; + for (let k = 0; k < picks; k++) { + const at = + all[Math.round((k * (all.length - 1)) / Math.max(1, picks - 1))]; + if (previous) { + const mid = Cesium.Cartesian3.midpoint( + previous, + at, + new Cesium.Cartesian3(), + ); + const radius = + (Cesium.Cartesian3.magnitude(previous) + + Cesium.Cartesian3.magnitude(at)) / + 2; + if (Cesium.Cartesian3.magnitude(mid) > 0) + probes.push( + Cesium.Cartesian3.multiplyByScalar( + Cesium.Cartesian3.normalize(mid, mid), + radius, + mid, + ), + ); + } + probes.push(at); + previous = at; + } + return probes; + } + function buildLines(record) { // Refused before anything changes, so the set keeps drawing as it was. for (const item of record.items.values()) @@ -1981,6 +2124,14 @@ export function createCesiumDraw({ throw new Error( 'the Cesium renderer colours and shows segments of draped solid lines only', ); + // Where the scene cannot drape at all, draped lines draw over the + // surface instead (`overlay`): undraped, in their own colour where the + // surface hides them, and hidden past the horizon (`cullOverlayLines`). + const overlay = !drapes(); + const items = overlay + ? [...record.items.values()].map(overlayLine) + : [...record.items.values()]; + record.overlayLines = overlay ? [] : null; const polylines = new Cesium.PolylineCollection(); // Lines in the inertial frame, turned with the sky each frame. let inertial = null; @@ -2003,7 +2154,7 @@ export function createCesiumDraw({ // Lines with a depth-fail colour, beside the collection. let deep = null; const looks = lineLooks(); - for (const item of record.items.values()) { + for (const item of items) { if (item.mode === 'draped') { const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; const part = { @@ -2047,7 +2198,18 @@ export function createCesiumDraw({ 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 }); + const part = { look: lineLook(item), id, deep: primitive }; + if (item.overlaid) { + part.overlayFrom = flatPositions(item.positions); + part.overlayShape = overlayShape(item); + } + parts.set(item.id, part); + if (item.overlaid && primitive) + record.overlayLines.push({ + part, + shown: item.show !== false, + ends: overlayEnds(item.positions), + }); continue; } const id = pickId(record, item); @@ -2101,7 +2263,7 @@ export function createCesiumDraw({ let own = polylines; // Lines in the collection that can settle into a static batch draw // beside it once they do. - const settling = [...record.items.values()].some(settles); + const settling = items.some(settles); if (deep || settling || inertial) { own = new Cesium.PrimitiveCollection(); own.add(polylines); @@ -2295,6 +2457,17 @@ export function createCesiumDraw({ Boolean((was.polyline || was.batched) && was.shape) && was.shape === looks.shape(item); + /** + * Whether a line drawn over the surface for a draped one changes only its + * colour where it runs: it takes the new one in place + * (`overlayRecoloured`). + */ + const recolourableOverlay = (was, item, looks) => + Boolean(item.overlaid && was.deep && was.overlayShape) && + flatEquals(item.positions, was.overlayFrom) && + !revealed(item) && + was.overlayShape === overlayShape(item); + /** * The colours the glow lines sharing a material that `list` recolours * are given together: each such material and the item whose colour it @@ -2351,6 +2524,10 @@ export function createCesiumDraw({ function patchLines(record, list) { const parts = record.lineParts; if (record.kind !== 'lines' || !parts) return false; + // Where the scene cannot drape, draped lines are patched as the lines + // drawn over the surface for them, each built anew alone where it + // changes (as any line with a depth-fail colour is). + if (record.overlayLines) list = list.map(overlayLine); // Each draped line's positions, flattened once for both passes. const flats = new Map(); // Each item's look, in order: an item sent twice is changed twice. @@ -2364,7 +2541,8 @@ export function createCesiumDraw({ if ( was.look !== look && !recolourable(was, item, lookOf) && - !recolourableSolid(was, item, lookOf) + !recolourableSolid(was, item, lookOf) && + !recolourableOverlay(was, item, lookOf) ) return false; // A viewer destroyed under the set took its batch with it. @@ -2400,7 +2578,7 @@ export function createCesiumDraw({ patchUndraped(record, was, item, looks[k]); continue; } - if (was.look !== looks[k]) { + if (was.look !== looks[k] && was.deep === undefined) { // A line drawing on a shared material took its colour above. if (!was.shared || was.solo) was.material.uniforms.color = toColor(item.style.color); @@ -2408,6 +2586,10 @@ export function createCesiumDraw({ } if (was.deep !== undefined) { was.id.meta = item.meta; + was.look = looks[k]; + // One drawn for a draped line that runs where it ran takes its new + // look in place (heat-lines pulse every frame). + if (overlayRecoloured(record, was, item)) continue; // Built anew where it now runs, under the same pick id. const deep = record.deepLines; const old = was.deep; @@ -2418,6 +2600,8 @@ export function createCesiumDraw({ was.deep = depthFailLine(record, item, was.id); if (was.deep) deep.add(was.deep); if (old) deep.remove(old); + if (item.overlaid) overlayMoved(record, was, item); + else if (was.overlayFrom) overlayLeft(record, was); continue; } was.id.meta = item.meta; @@ -3653,13 +3837,13 @@ export function createCesiumDraw({ * drape them onto 3D tiles yet, so over shown tiles it is `overlay`. * Terrain and the ellipsoid take draped items wherever Cesium drapes at * all: its draped lines and image fills need depth textures, which every - * WebGL 2 context has; without them it says `overlay`. (It still builds - * them as ground primitives there: the overlay drawing itself is not - * built, since only a WebGL 1 context without the extension lacks them.) + * WebGL 2 context has; without them it says `overlay`, and draws draped + * lines over the surface (`overlayLine`). Clamped shapes there are still + * built as ground primitives: only a WebGL 1 context without the + * extension lacks depth textures. */ const clampState = () => - scene.frameState?.context?.depthTexture === false || - tilesets().some((tileset) => tileset.show) + !drapes() || tilesets().some((tileset) => tileset.show) ? 'overlay' : 'draped'; const clampListeners = listenerList(report); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index c3f4b35bc..95d4d7c8e 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -4594,7 +4594,6 @@ test('the traffic layer drapes its heat-lines on the tiles and pulses the jam on _presetDots: 'off', _heatJam: [], _heatLineCount: 0, - _heatSupported: true, _heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }), }; const rendering = createRendering({ @@ -4647,6 +4646,237 @@ test('the traffic layer drapes its heat-lines on the tiles and pulses the jam on }); }); +test('where the scene cannot drape, draped lines draw over the surface and hide past the horizon', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw, frame } = drawOver(scene); + assert.equal(draw.clampState(), 'overlay'); + const set = draw.lines({ id: 'heat', clampTo: 'tiles' }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0); + const firstPositions = [at(0), at(0.01)]; + set.set([ + { + id: 'jam', + positions: firstPositions, + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.8], power: 0.25 }, + }, + ]); + const host = scene.added[0]; + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(host); + assert.ok( + !all.some((p) => p instanceof Cesium.GroundPolylinePrimitive), + 'no ground polyline', + ); + const line = all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + assert.ok(line, 'drawn where the surface hides it too'); + const failColor = line.depthFailAppearance.material.uniforms.color; + assert.ok(Math.abs(failColor.red - 1) < 1e-6 && failColor.green === 0); + // The eye over the line's side of the Earth: shown. + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + assert.equal(line.show, true); + // The eye over the far side: past the horizon, hidden. + scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0); + frame(); + assert.equal(line.show, false); + // A recolour where it runs (a pulse) takes the colour in place, and the + // line stays hidden past the horizon: nothing is built anew. + const hostBefore = scene.added[0]; + set.upsert([ + { + id: 'jam', + positions: firstPositions, + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.4], power: 0.25 }, + }, + ]); + frame(); + assert.equal(line.show, false, 'still past the horizon'); + const after = []; + const walkAfter = (p) => { + after.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walkAfter(p.get(i)); + }; + walkAfter(scene.added[0]); + assert.equal(scene.added[0], hostBefore, 'the set is not rebuilt'); + assert.ok(after.includes(line), 'the same line draws'); + assert.ok( + Math.abs(line.appearance.material.uniforms.color.alpha - 0.4) < 1e-6, + ); + assert.ok( + Math.abs(line.depthFailAppearance.material.uniforms.color.alpha - 0.4) < + 1e-6, + ); + // In 2D there is no horizon: it shows as asked. + scene.mode = Cesium.SceneMode.SCENE2D; + frame(); + assert.equal(line.show, true, 'shown in 2D'); + scene.mode = Cesium.SceneMode.SCENE3D; + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + // Moved, it alone is built anew, still over the surface and culled. + set.upsert([ + { + id: 'jam', + positions: [at(0), at(0.02)], + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.4], power: 0.25 }, + }, + ]); + assert.equal(scene.added[0], hostBefore, 'patched, not rebuilt'); + const moved = []; + const walkMoved = (p) => { + moved.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walkMoved(p.get(i)); + }; + walkMoved(scene.added[0]); + const rebuilt = moved.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + assert.ok(rebuilt && rebuilt !== line, 'built anew where it moved'); + assert.ok(!moved.includes(line), 'the old line is gone'); + scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0); + frame(); + assert.equal(rebuilt.show, false); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('where the scene cannot drape, an overlay line is culled by its whole arc, and patched by what its positions hold', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw, frame } = drawOver(scene); + const set = draw.lines({ id: 'arc', clampTo: 'tiles' }); + const find = () => { + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(scene.added[0]); + return all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + }; + // Its ends are past the horizon, but the arc runs under the eye. + const a = Cesium.Cartesian3.fromDegrees(-80, 0, 0); + const b = Cesium.Cartesian3.fromDegrees(80, 0, 0); + const positions = new Float64Array([a.x, a.y, a.z, b.x, b.y, b.z]); + const item = (style) => ({ + id: 'arc', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: style }, + }); + set.set([item([1, 0, 0, 1])]); + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + const line = find(); + assert.equal(line.show, true, 'shown: its middle is in view'); + // The same buffer, changed in place: built anew where it now runs. + const c = Cesium.Cartesian3.fromDegrees(10, 0, 0); + positions.set([c.x, c.y, c.z], 3); + set.upsert([item([1, 0, 0, 1])]); + const moved = find(); + assert.notEqual(moved, line, 'built anew'); + // Moved past the horizon, then upserted as an ordinary line in view: + // it is no longer culled by where the overlay was. + const far = new Float64Array(6); + const f1 = Cesium.Cartesian3.fromDegrees(179, 0, 0); + const f2 = Cesium.Cartesian3.fromDegrees(179.5, 0, 0); + far.set([f1.x, f1.y, f1.z, f2.x, f2.y, f2.z]); + set.upsert([{ ...item([1, 0, 0, 1]), positions: far }]); + frame(); + assert.equal(find().show, false, 'past the horizon'); + set.upsert([ + { + id: 'arc', + positions: [ + Cesium.Cartesian3.fromDegrees(0, 0, 0), + Cesium.Cartesian3.fromDegrees(0.5, 0, 0), + ], + widthPx: 2, + mode: '3d', + depthFailColor: [1, 0, 0, 1], + style: { kind: 'solid', color: [1, 0, 0, 1] }, + }, + ]); + const plain = find(); + frame(); + assert.equal(plain.show, true, 'not culled by the overlay it was'); + set.dispose(); + })); + +test('where the scene cannot drape, a segmented draped line runs over its shown segments only', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw } = drawOver(scene); + const set = draw.lines({ id: 'trail', clampTo: 'tiles' }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0); + const positions = [at(0), at(0.01), at(0.02), at(0.03)]; + const red = [1, 0, 0, 1]; + const find = () => { + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(scene.added[0]); + return all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + }; + set.set([ + { + id: 'trail', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: red }, + segmentColors: [red, red, red], + segmentShow: [true, true, false], + }, + ]); + const line = find(); + assert.ok(line, 'drawn over the surface'); + const drawn = line.geometryInstances.geometry._positions; + assert.equal(drawn.length, 3, 'up to its last shown segment'); + assert.ok(Cesium.Cartesian3.equals(drawn[2], positions[2])); + set.set([ + { + id: 'trail', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: red }, + segmentColors: [red, red, red], + segmentShow: [false, false, false], + }, + ]); + assert.equal(find()?.show ?? false, false, 'hidden with none shown'); + set.dispose(); + })); + test('revealFraction draws a line up to that fraction of its length, and changes in place', () => withImageClasses(() => { const { scene, draw } = drawOver(); diff --git a/src/render/cesium/surfaceState.js b/src/render/cesium/surfaceState.js deleted file mode 100644 index d8ee9da5c..000000000 --- a/src/render/cesium/surfaceState.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @module render/cesium/surfaceState - * - * What a layer that samples heights off the drawn surface, or drapes lines - * on it, needs to know of it and the renderer contract cannot say: whether - * any 3D tileset is drawn (the globe port's settle states hold for none), - * which surface it is (the contract names no surface identity), and - * whether lines can be draped at all. Read off the Cesium scene. - */ -import * as Cesium from 'cesium'; - -/** - * Whether the scene can drape lines on the surface: Cesium's ground - * polylines need depth textures. - * @param {object|undefined} viewer - */ -export function drapesLines(viewer) { - const scene = viewer?.scene; - return ( - Boolean(scene?.frameState) && - Cesium.GroundPolylinePrimitive.isSupported(scene) - ); -} - -/** - * Whether the drawn surface has loaded what is in view: the - * globe's tiles while it is shown, otherwise every shown 3D tileset (and - * there is one). - * @param {object|undefined} viewer - */ -export function surfaceTilesReady(viewer) { - const scene = viewer?.scene; - if (!scene) return false; - if (scene.globe?.show) return scene.globe.tilesLoaded !== false; - let found = false; - for (let i = 0; i < (scene.primitives?.length || 0); i++) { - const primitive = scene.primitives.get(i); - if (!primitive.show || typeof primitive.tilesLoaded !== 'boolean') continue; - found = true; - if (!primitive.tilesLoaded) return false; - } - return found; -} - -// Stable ids for the objects heights are sampled from (tilesets, terrain). -const surfaceIds = new WeakMap(); -let nextSurfaceId = 1; -const surfaceId = (object) => { - if (!object || typeof object !== 'object') return 0; - if (!surfaceIds.has(object)) surfaceIds.set(object, nextSurfaceId++); - return surfaceIds.get(object); -}; - -/** - * Name what heights are sampled against: the terrain provider when the globe - * is shown, otherwise the set of visible 3D tilesets. A map-provider switch - * changes it and invalidates every cached height. - * @param {object|undefined} viewer - */ -const surfaceKeys = new WeakMap(); -export function surfaceKey(viewer) { - const scene = viewer?.scene; - if (!scene) return ''; - let state = surfaceKeys.get(scene); - if (!state) { - state = { globe: null, terrain: null, tiles: [], key: '' }; - surfaceKeys.set(scene, state); - } - const globe = Boolean(scene.globe?.show); - const terrain = globe ? scene.globe.terrainProvider : null; - let changed = state.globe !== globe || state.terrain !== terrain; - let count = 0; - if (!globe) { - for (let i = 0; i < (scene.primitives?.length || 0); i++) { - const primitive = scene.primitives.get(i); - if (!primitive?.show || typeof primitive.tilesLoaded !== 'boolean') - continue; - if (state.tiles[count] !== primitive) { - state.tiles[count] = primitive; - changed = true; - } - count++; - } - } - if (count !== state.tiles.length) { - state.tiles.length = count; - changed = true; - } - if (changed) { - state.globe = globe; - state.terrain = terrain; - // Allocate only when the actual map surface changes, never per frame. - state.key = globe - ? `globe:${surfaceId(terrain)}` - : `tiles:${state.tiles.map(surfaceId).join(',')}`; - } - return state.key; -} diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 0a0fa27e2..958491cd8 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -7,7 +7,6 @@ "src/cyberSonarGpu.js", "src/cyberSonarScene.js", "src/data/geoImportPins.js", - "src/layers/traffic/rendering.js", "src/layers/weather/shellRendering.js", "src/layers/wind/gpuRendering.js", "src/layers/wind/relief.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index ad171fa22..808235462 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -126,6 +126,13 @@ const DRAW_FROM_CALLER = new Set([ // Its layer draws and reads the view through the ports alone, and its mesh // floor sampler asks the camera, globe and query ports. './layers/transit/standalone', + // Its dots and heat-lines draw through `drawOf`; it reads the eye, the + // surface (its identity and whether it has loaded) and heights through + // the camera, globe and query ports. + './layers/traffic', + // It configures the sources of layers, the traffic layer's among them, + // that draw and read the surface through the ports alone. + './application/sources', ]); /** diff --git a/src/testSupport/fakeSceneSurface.mjs b/src/testSupport/fakeSceneSurface.mjs index 895c92db8..c53f073bd 100644 --- a/src/testSupport/fakeSceneSurface.mjs +++ b/src/testSupport/fakeSceneSurface.mjs @@ -8,7 +8,9 @@ * scene's `sampleHeight` where `sampleHeightSupported`), `project` * (`SceneTransforms.worldToWindowCoordinates`, which a test may mock), * `pickPosition` (the scene's), and null for every other pick. - * - globe: `isGlobeVisible` from `globe.show`. + * - globe: `isGlobeVisible` from `globe.show`; `isSettled('surface')` and + * `surfaceVersion` as the Cesium port reads them, off the double's globe + * and its primitives that say whether their tiles have loaded. * - camera (`withCamera`): `pose().position` from `camera.positionCartographic`, * `matrices()` from `camera.viewMatrix` and `frustum.projectionMatrix` * (undefined without them). @@ -22,6 +24,64 @@ import { fakeDrawPort } from './fakeDrawPort.mjs'; const carto = ({ lon, lat }) => Cesium.Cartographic.fromDegrees(lon, lat); const ecef = (p) => (p ? { x: p.x, y: p.y, z: p.z } : null); +/** + * The double's tilesets: its shown primitives that say whether their tiles + * have loaded. + */ +function* shownTilesets(s) { + const primitives = s.primitives; + for (let i = 0; i < (primitives?.length || 0); i++) { + const primitive = primitives.get(i); + if ( + primitive?.show && + !primitive.isDestroyed?.() && + typeof primitive.tilesLoaded === 'boolean' + ) + yield primitive; + } +} + +/** `isSettled('surface')` as the Cesium globe port answers it. */ +function surfaceLoaded(s) { + if (s.globe?.show) return s.globe.tilesLoaded !== false; + let found = false; + for (const tileset of shownTilesets(s)) { + found = true; + if (!tileset.tilesLoaded) return false; + } + return found; +} + +// `surfaceVersion` as the Cesium globe port keeps it: bumped when the globe +// is shown or hidden, its terrain swapped, or the set of shown tilesets +// changes (whether or not the globe is shown). +const versions = new WeakMap(); +let lastVersion = 0; +function surfaceVersion(s) { + let seen = versions.get(s); + if (!seen) { + seen = { globe: null, terrain: null, tiles: new Set(), version: 0 }; + versions.set(s, seen); + } + const globe = Boolean(s.globe?.show); + const terrain = s.globe?.terrainProvider ?? null; + let changed = + seen.version === 0 || seen.globe !== globe || seen.terrain !== terrain; + let count = 0; + for (const tileset of shownTilesets(s)) { + count++; + if (!seen.tiles.has(tileset)) changed = true; + } + if (count !== seen.tiles.size) changed = true; + if (changed) { + seen.globe = globe; + seen.terrain = terrain; + seen.tiles = new Set(shownTilesets(s)); + seen.version = ++lastVersion; + } + return seen.version; +} + /** The surface ports over `viewer.scene`. */ export function sceneSurfacePorts(viewer, { withCamera = false } = {}) { const scene = () => viewer.scene ?? {}; @@ -55,7 +115,11 @@ export function sceneSurfacePorts(viewer, { withCamera = false } = {}) { }; const ports = { query, - globe: { isGlobeVisible: () => Boolean(scene().globe?.show) }, + globe: { + isGlobeVisible: () => Boolean(scene().globe?.show), + isSettled: (kind) => kind !== 'surface' || surfaceLoaded(scene()), + surfaceVersion: () => surfaceVersion(scene()), + }, frame: { on(phase, cb) { const event = phase === 'postRender' ? scene().postRender : null;