From bbd6049e2160f4c6760ac86a0a65932ad1e7940a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 21:50:26 -0800 Subject: [PATCH] Draw the traffic dots through the draw port and read the road surface through renderer ports The traffic layer's vehicle dots are now a points set on the draw port, moved, added to and taken from in place each frame, instead of a Cesium point collection. Road surface heights and readiness read the query, camera, frame and globe ports and the heights service instead of the scene; the surface identity and "any tileset drawn" checks, which the contract cannot answer, move to rendering.js with the heat lines. animation.js, style.js and surface.js leave the Cesium allow-list. The Cesium draw port compares a moved point's look without allocating: colours by index, and a frozen colour or curve of plain data by identity, so a thousand dots moved every frame cost about what direct writes did. The traffic QA scripts read the dots' draw items. --- scripts/package-boundaries.json | 4 + scripts/qa-traffic-motion.mjs | 12 +- scripts/qa-traffic-oblique.mjs | 13 +- src/data/trafficTiming.test.mjs | 4 + src/layers/traffic/animation.js | 124 ++++----- src/layers/traffic/controls.js | 4 +- src/layers/traffic/deadline.test.mjs | 20 +- src/layers/traffic/flow.js | 2 - src/layers/traffic/ingestion.js | 8 +- src/layers/traffic/lifecycle.js | 43 +-- src/layers/traffic/motion.test.mjs | 34 ++- src/layers/traffic/navigation.test.mjs | 38 ++- src/layers/traffic/renderDemand.test.mjs | 1 + src/layers/traffic/rendering.js | 95 +++++++ src/layers/traffic/retention.js | 7 +- src/layers/traffic/state.js | 4 +- src/layers/traffic/style.js | 79 +++--- src/layers/traffic/style.test.mjs | 34 ++- src/layers/traffic/surface.js | 337 ++++++++++------------- src/layers/traffic/surface.test.mjs | 120 ++++---- src/render/cesium/draw.js | 87 +++++- src/render/cesium/draw.test.mjs | 150 ++++++++++ src/render/cesiumAllowList.json | 3 - src/testSupport/fakeSceneSurface.mjs | 116 ++++++++ 24 files changed, 872 insertions(+), 467 deletions(-) create mode 100644 src/testSupport/fakeSceneSurface.mjs diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 29d9dbad1..5ae57cd2b 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2342,6 +2342,10 @@ "src/layers/traffic/ingestion.js", "src/sources/requestDeadline.js", "src/layers/traffic/lifecycle.js", + "src/render/cesium/globe.js", + "src/maps/google3d.js", + "src/render/cesium/imagery.js", + "src/render/cesium/tileRequests.js", "src/layers/traffic/model.js", "src/geo/ellipsoid.js", "src/geo/vector.js", diff --git a/scripts/qa-traffic-motion.mjs b/scripts/qa-traffic-motion.mjs index af73c8d1c..b9c0f52d5 100644 --- a/scripts/qa-traffic-motion.mjs +++ b/scripts/qa-traffic-motion.mjs @@ -158,9 +158,13 @@ try { (window.__motion.holdStart === null ? '' : ` | camera stopped +${((now - window.__motion.holdStart) / 1000).toFixed(1)}s`); + // A layer dot is its draw item (`pos`, hidden only when `show` is + // false); a collection's point is Cesium's. const visit = (id, roadId, point) => { - if (!point.show) return; - const s = scene.cartesianToCanvasCoordinates(point.position); + if (point.show === false) return; + const s = scene.cartesianToCanvasCoordinates( + point.pos ?? point.position, + ); if (s && s.x >= 0 && s.y >= 0 && s.x <= 1280 && s.y <= 800) points.set(id, { x: s.x, y: s.y, roadId }); }; @@ -168,7 +172,7 @@ try { offRoad = 0; if (!baseline && layer.visitMotionDots) { layer.visitMotionDots((id, roadId, point, road) => { - if (point.show) { + if (point.show !== false) { const p = road?.roadProperties; const allowed = road?.directFlow ? [ @@ -195,7 +199,7 @@ try { p?.brunnel !== 'tunnel'; if (!allowed) offRoad++; } - if (point.show) n++; + if (point.show !== false) n++; visit(id, roadId, point); }); } else { diff --git a/scripts/qa-traffic-oblique.mjs b/scripts/qa-traffic-oblique.mjs index 6ea1c953d..a365bcd44 100644 --- a/scripts/qa-traffic-oblique.mjs +++ b/scripts/qa-traffic-oblique.mjs @@ -83,9 +83,10 @@ try { lower = 0; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; - const s = viewer.scene.cartesianToCanvasCoordinates(p.position); + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const s = viewer.scene.cartesianToCanvasCoordinates(dot.pos); if (s && s.x >= 240 && s.x <= 1040 && s.y >= 0 && s.y <= 800) { if (s.y < 400) upper++; else lower++; @@ -197,8 +198,10 @@ try { const camera = viewer.camera.positionWC; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const p = { position: dot.pos }; const q = viewer.scene.cartesianToCanvasCoordinates(p.position); if (q && q.x >= 240 && q.x <= 1040 && q.y >= 0 && q.y <= 800) { if (q.y < 400) upper++; diff --git a/src/data/trafficTiming.test.mjs b/src/data/trafficTiming.test.mjs index bb4c4dadc..3e4b00916 100644 --- a/src/data/trafficTiming.test.mjs +++ b/src/data/trafficTiming.test.mjs @@ -257,6 +257,10 @@ test('traffic timing pairs real ordering to the scheduling change and guards re- return { west: degrees(r.west), south: degrees(r.south), east: degrees(r.east), north: degrees(r.north) }; }, }, + // The dots' draw set: timing reads none of what it draws. + draw: { + points: () => ({ show: false, upsert() {}, remove() {}, clear() {}, dispose() {} }), + }, }); performance.clearMarks(); diff --git a/src/layers/traffic/animation.js b/src/layers/traffic/animation.js index 426d7a775..b412c582e 100644 --- a/src/layers/traffic/animation.js +++ b/src/layers/traffic/animation.js @@ -1,7 +1,7 @@ import { DOT_FADE_MS } from './retention.js'; import { flowBucket, flowSpeedScale } from '../../data/trafficFlowStyle.js'; -import { presetDotOutline } from '../../data/trafficPresetStyle.js'; -import * as Cesium from 'cesium'; +import { lerpInto } from '../../geo/vector.js'; +import { findFrame } from '../../render/rendererOf.js'; import { queuePlatoons, locateAlongRoad } from '../../data/trafficQueue.js'; import { SPEED_MPS, @@ -10,8 +10,6 @@ import { CREEP_MOVE_MS, CREEP_STOP_MS, CREEP_BURST, - HEAT_JAM_BASE_ALPHA, - HEAT_JAM_PULSE_ALPHA, } from './policy.js'; export function createAnimation({ @@ -20,13 +18,24 @@ export function createAnimation({ parts, source, }) { - /** Scratch point for the per-frame lerp, so a frame allocates nothing. */ - const scratchLerp = new Cesium.Cartesian3(); + /** The dots' point items, gathered once a frame for one upsert. */ + const frameItems = []; + + /** + * Send every dot's point item to the draw set: the set moves and + * restyles the points it has, and adds the new ones, in place. + */ + function flushDots() { + const dots = layerState._dots; + frameItems.length = dots.length; + for (let i = 0; i < dots.length; i++) frameItems[i] = dots[i].point; + layerState._dotSet?.upsert(frameItems); + } function syncRenderDemand() { const needed = Boolean( layerState._enabled && - (layerState._dots.length || layerState._heatJamPrim), + (layerState._dots.length || parts.rendering.heatPulsing?.()), ); // Height easing only runs in a held frame. Settle it before releasing, so // a population emptied mid-correction cannot report loading forever. @@ -36,7 +45,7 @@ export function createAnimation({ if (needed) { layerState._lastAnimTime = 0; services.render.holdContinuousRender('traffic'); - layerState._viewer?.scene?.requestRender?.(); + findFrame(layerState._viewer)?.requestRender('traffic'); } else services.render.releaseContinuousRender('traffic'); } @@ -78,18 +87,7 @@ export function createAnimation({ (bucket === 'jam' ? 1 : 0) + parts.style.activeSizeDelta(bucket); // Dark-halo outline under styled presets (null = shipped no-outline). - const outlineSpec = - bucket && layerState._presetDots === 'on' - ? presetDotOutline(layerState._stylePreset, bucket) - : null; - const outlineColor = outlineSpec - ? new Cesium.Color( - outlineSpec.rgba[0] / 255, - outlineSpec.rgba[1] / 255, - outlineSpec.rgba[2] / 255, - outlineSpec.rgba[3], - ) - : null; + const outline = bucket ? parts.style.outlineOf(bucket) : null; const flowSpeed = flow ? flowSpeedScale(flow.level) : 1; const now = Date.now(); @@ -113,8 +111,9 @@ export function createAnimation({ } } + const spawned = []; for (let i = 0; i < count; i++) { - if (layerState._dots.length >= MAX_DOTS) return; + if (layerState._dots.length >= MAX_DOTS) break; // Random start position: pick a random segment and offset within it — // unless this is a queued jam dot with a platoon placement. @@ -140,43 +139,44 @@ export function createAnimation({ ? 1 : -1; - // Compute initial Cartesian3 position via linear interpolation - Cesium.Cartesian3.lerp( - road.waypoints[segIdx], - road.waypoints[segIdx + 1], - t, - scratchLerp, - ); - // Grounded traffic respects building/terrain occlusion. The former // depth override made distant roads look like vehicles crossing roofs. const jamProminent = bucket === 'jam' && parts.style.jamDensityOn(); const id = layerState._nextDotId++; - const point = layerState._pointCollection.add({ - position: Cesium.Cartesian3.clone(scratchLerp), + // The dot's point item, kept and changed in place: its draw id stays + // while the dot's vehicle identity (`id`) is renewed at each recycle. + const point = { + id: `dot:${id}`, + // Its initial position, by linear interpolation. + pos: lerpInto(road.waypoints[segIdx], road.waypoints[segIdx + 1], t, { + x: 0, + y: 0, + z: 0, + }), pixelSize, // No flow data → today's exact simulated white. color: parts.style.dotColor(bucket), - scaleByDistance: new Cesium.NearFarScalar( - 100, - 1.5, - layerState._fadeScaleFar, - jamProminent ? JAM_DOT_FAR_SCALE : 0.3, - ), - translucencyByDistance: new Cesium.NearFarScalar( - 100, - 1.0, - layerState._fadeTransFar, - 0.0, - ), + // Frozen, as the colours are: the draw port then tells them + // unchanged by identity when the dots move each frame. + scaleByDistance: Object.freeze({ + near: 100, + nearValue: 1.5, + far: layerState._fadeScaleFar, + farValue: jamProminent ? JAM_DOT_FAR_SCALE : 0.3, + }), + fadeByDistance: Object.freeze({ + near: 100, + nearValue: 1.0, + far: layerState._fadeTransFar, + farValue: 0.0, + }), // Respect the sampled mesh at every viewing distance. - disableDepthTestDistance: 0, - // Preset dark halo (spread only when present — the keyless/normal - // path passes the exact shipped option set). - ...(outlineSpec - ? { outlineColor, outlineWidth: outlineSpec.width } - : {}), - }); + disableDepthTest: 0, + // Preset dark halo (only when present — the keyless/normal path + // passes the shipped look). + ...outline, + }; + spawned.push(point); layerState._bucketCounts[bucket || 'sim'] += 1; layerState._motion.added++; @@ -207,6 +207,8 @@ export function createAnimation({ : null, }); } + // Drawn at once, as they join; each frame moves them on. + if (spawned.length) layerState._dotSet?.upsert(spawned); syncRenderDemand(); } @@ -307,23 +309,16 @@ export function createAnimation({ if (now < dot.stoppedUntil) break; } - // Lerp between pre-computed Cartesian3 waypoints (no trig needed). - // Pass the scratch directly: PointPrimitive's position setter clones the - // value into its own storage (and skips the VBO dirty flag when equal), so - // the extra defensive clone here allocated 360–720k Cartesian3/s of pure - // garbage across 6000 dots. (perf item 5) + // Lerp between pre-computed ECEF waypoints (no trig needed), into the + // point item's own position: the draw set copies it. const a = dot.waypoints[dot.segIdx]; const b = dot.waypoints[dot.segIdx + 1]; - Cesium.Cartesian3.lerp(a, b, dot.t, scratchLerp); - dot.point.position = scratchLerp; + lerpInto(a, b, dot.t, dot.point.pos); } + flushDots(); - // Jam heat-lines throb (~1.6 s period) — one shared material uniform for - // the whole jam batch, no geometry rebuild. Null outside live heatline mode. - if (layerState._heatJamPrim?.appearance) { - layerState._heatJamPrim.appearance.material.uniforms.color.alpha = - HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260); - } + // Jam heat-lines throb (~1.6 s period); none outside live heatline mode. + parts.rendering.pulseHeatLines?.(now); layerState._animFrame++; } @@ -354,7 +349,7 @@ export function createAnimation({ services.credits?.hideOsmCredit?.(layerState._viewer, 'traffic'); parts.retention.clear(); if (layerState._dots.length) layerState._motion.rebuilds++; - if (layerState._pointCollection) layerState._pointCollection.removeAll(); + layerState._dotSet?.clear(); parts.rendering.removeHeatLines(); layerState._dots = []; layerState._roads = []; @@ -369,5 +364,6 @@ export function createAnimation({ maybeStopLight, clearDots, syncRenderDemand, + flushDots, }; } diff --git a/src/layers/traffic/controls.js b/src/layers/traffic/controls.js index 6570c7958..9eb433b7b 100644 --- a/src/layers/traffic/controls.js +++ b/src/layers/traffic/controls.js @@ -208,7 +208,7 @@ export function createControls({ state: layerState, services, parts, source }) { * @param {Object} [options] * @param {number} [options.maxCount] - Maximum objects to return (defaults to all). * @param {number} [options.seed] - Integer seed to offset the sampling start. - * @returns {Array<{position:Cesium.Cartesian3, id:string, type:string}>} + * @returns {Array<{position:{x:number, y:number, z:number}, id:string, type:string}>} */ getDetectableObjects(options = {}) { if (!layerState._enabled || layerState._dots.length === 0) return []; @@ -222,7 +222,7 @@ export function createControls({ state: layerState, services, parts, source }) { const result = []; for (let i = start; i < layerState._dots.length; i += stride) { - const pos = layerState._dots[i].point.position; + const pos = layerState._dots[i].point.pos; if (!pos) continue; const entry = { position: pos, diff --git a/src/layers/traffic/deadline.test.mjs b/src/layers/traffic/deadline.test.mjs index 5fba1c76f..31334906a 100644 --- a/src/layers/traffic/deadline.test.mjs +++ b/src/layers/traffic/deadline.test.mjs @@ -7,6 +7,7 @@ import { createRetention } from './retention.js'; import { createControls } from './controls.js'; import { createState } from './state.js'; import { bindRenderer } from '../../render/rendererOf.js'; +import { surfaceViewer } from '../../testSupport/fakeSceneSurface.mjs'; const bounds = { west: 0, east: 0.01, south: 0, north: 0.01 }; const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); }; @@ -212,20 +213,15 @@ function flowFixture(source) { _enabled: true, _roadMode: 'osm', _parseRoads: (data) => data.roads, - _viewer: { - get canvas() { - return this.scene?.canvas; - }, - scene: { - globe: { - show: true, - getHeight: () => { - calls.samples++; - return 100; - }, + _viewer: surfaceViewer({ + globe: { + show: true, + getHeight: () => { + calls.samples++; + return 100; }, }, - }, + }), }); const parts = { viewport: { diff --git a/src/layers/traffic/flow.js b/src/layers/traffic/flow.js index 534cf15cb..2bfef944f 100644 --- a/src/layers/traffic/flow.js +++ b/src/layers/traffic/flow.js @@ -479,7 +479,6 @@ export function createFlow({ state: layerState, services, parts, source }) { let prepared = await viewerRoadSurface(layerState._viewer).prepare( unresolved, services.ground, - [layerState._pointCollection], signal, options, ); @@ -500,7 +499,6 @@ export function createFlow({ state: layerState, services, parts, source }) { prepared = await viewerRoadSurface(layerState._viewer).prepare( prepared.pending, services.ground, - [layerState._pointCollection], signal, options, ); diff --git a/src/layers/traffic/ingestion.js b/src/layers/traffic/ingestion.js index 32a92e032..7b2236155 100644 --- a/src/layers/traffic/ingestion.js +++ b/src/layers/traffic/ingestion.js @@ -273,10 +273,10 @@ export function createIngestion({ let estimated = services.ground?.cachedGroundFloor?.(centerLat, centerLon); // A miss is the local mesh still loading. if (!Number.isFinite(estimated)) - estimated = viewerRoadSurface(layerState._viewer).loadedHeight( - { lon: centerLon, lat: centerLat }, - [layerState._pointCollection], - ); + estimated = viewerRoadSurface(layerState._viewer).loadedHeight({ + lon: centerLon, + lat: centerLat, + }); if (Number.isFinite(estimated) && Math.abs(estimated) <= 9000) layerState._viewHeightEstimate = estimated; diff --git a/src/layers/traffic/lifecycle.js b/src/layers/traffic/lifecycle.js index e3e73c219..1455d0372 100644 --- a/src/layers/traffic/lifecycle.js +++ b/src/layers/traffic/lifecycle.js @@ -1,15 +1,19 @@ import { observeTrafficSurface } from './surface.js'; -import * as Cesium from 'cesium'; -// Still Cesium for its points and events, so this layer loads the unbound -// camera factory (with its query port) its other parts reach the renderer -// through. +// Still Cesium for its events, so this layer loads the unbound +// camera factory (with its query port) and globe factory its other parts +// reach the renderer through. import '../../render/cesium/camera.js'; +import '../../render/cesium/globe.js'; import { TRAFFIC_TIMING_ENABLED } from './policy.js'; +import { drawOf } from '../../render/rendererOf.js'; import { claimCameraSensitivity, releaseCameraSensitivity, } from '../../data/cameraSensitivity.js'; +/** Numbers each layer instance's draw sets apart. */ +let instances = 0; + export function createLifecycle({ state: layerState, services, @@ -20,20 +24,19 @@ export function createLifecycle({ const methods = { /** - * One-time initialisation. Creates the PointPrimitiveCollection and adds it - * to the scene (hidden). The collection is never removed and re-added — only - * toggled via `.show` to avoid destroy-on-remove errors. + * One-time initialisation. Makes the dots' draw set (hidden); it is + * shown and hidden with the layer, and let go on destroy. * * @param {Cesium.Viewer} viewer - The Cesium viewer instance. */ init(viewer) { layerState._viewer = viewer; - layerState._pointCollection = new Cesium.PointPrimitiveCollection({ - blendOption: Cesium.BlendOption.TRANSLUCENT, + layerState._dotSet?.dispose(); + layerState._dotSet = drawOf(viewer).points({ + id: `traffic:${++instances}:dots`, + blend: 'translucent', + show: false, }); - // Add permanently — toggle with .show to avoid destroy-on-remove errors - viewer.scene.primitives.add(layerState._pointCollection); - layerState._pointCollection.show = false; layerState._dots = []; layerState._roads = []; layerState._count = 0; @@ -84,11 +87,11 @@ export function createLifecycle({ enable(viewer) { if (layerState._enabled) return; layerState._enabled = true; - layerState._surfaceFrameRemover = observeTrafficSurface(viewer.scene); + layerState._surfaceFrameRemover = observeTrafficSurface(viewer); if (layerState._roadMode !== 'tomtom') source.prefetch?.(); parts.animation.syncRenderDemand(); layerState._lastAnimTime = 0; - layerState._pointCollection.show = true; + if (layerState._dotSet) layerState._dotSet.show = true; layerState._preRenderRemover = viewer.scene.preRender.addEventListener( parts.animation.animate, @@ -187,21 +190,19 @@ export function createLifecycle({ layerState._arrivalRemover?.(); layerState._arrivalRemover = null; releaseCameraSensitivity(viewer.camera, 'traffic'); - if (layerState._pointCollection) layerState._pointCollection.show = false; + if (layerState._dotSet) layerState._dotSet.show = false; }, /** - * Permanently tear down the layer. Disables it, removes the point collection - * from the scene, and clears the tile cache. + * Permanently tear down the layer. Disables it, lets the dots' draw set + * go, and clears the tile cache. * * @param {Cesium.Viewer} viewer - The Cesium viewer instance. */ destroy(viewer) { this.disable(viewer); - if (layerState._pointCollection) { - viewer.scene.primitives.remove(layerState._pointCollection); - layerState._pointCollection = null; - } + layerState._dotSet?.dispose(); + layerState._dotSet = null; parts.rendering.removeHeatLines(); layerState._tileCache.clear(); resetFlowTileCache(); diff --git a/src/layers/traffic/motion.test.mjs b/src/layers/traffic/motion.test.mjs index 5a8a1f78b..84a837fca 100644 --- a/src/layers/traffic/motion.test.mjs +++ b/src/layers/traffic/motion.test.mjs @@ -7,6 +7,8 @@ import { createModel } from './model.js'; import { createAnimation } from './animation.js'; import { DOT_HEIGHT_OFFSET } from './policy.js'; import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { surfaceViewer } from '../../testSupport/fakeSceneSurface.mjs'; import '../../render/cesium/camera.js'; import { createRetention, @@ -31,7 +33,7 @@ function setup(t) { const state = createState({ services: {} }); state._enabled = true; state._liveMode = true; - state._pointCollection = new C.PointPrimitiveCollection(); + state._dotSet = fakeDrawPort().points({ id: 'traffic:test:dots' }); state._viewer = { scene: {}, get canvas() { @@ -92,7 +94,7 @@ function setup(t) { }; t.after(() => { parts.animation.clearDots(); - state._pointCollection.destroy(); + state._dotSet.dispose(); }); return { state, parts, roads, frame, settle, frames }; } @@ -180,7 +182,7 @@ test('density and replacement changes are bounded; removed roads fade out and te assert.equal(new Set(h.state._dots.map((d) => d.id)).size, 3000); h.parts.animation.clearDots(); h.frame(); - assert.equal(h.state._pointCollection.length, 0); + assert.equal(h.state._dotSet.size(), 0); assert.equal(h.state._dots.length, 0); assert.equal(h.frames.length, 0); }); @@ -233,12 +235,12 @@ test('stopped vehicles still follow smooth height refinement without moving alon h.settle(); const d = h.state._dots[0]; d.stoppedUntil = Date.now() + 100000; - const before = C.Cartographic.fromCartesian(d.point.position).height; + const before = C.Cartographic.fromCartesian(d.point.pos).height; const progress = d.t; h.parts.retention.reconcile(h.roads(0, 120), 450, true); h.frame(); assert.equal(d.t, progress); - const after = C.Cartographic.fromCartesian(d.point.position).height; + const after = C.Cartographic.fromCartesian(d.point.pos).height; assert.ok(after > before && after - before <= 2.01); }); @@ -309,7 +311,7 @@ test('major previews merge and never retry missing mesh ahead of the detail pass _dots: [], _detailRoadsReady: true, _motion: { added: 0 }, - _viewer: { scene }, + _viewer: surfaceViewer(scene), _enabled: true, _loadGeneration: 1, _roadSource: 'OpenStreetMap', @@ -444,7 +446,7 @@ test('measured preview heights select elevated detail roads before surface admis }; const state = { _dots: [], - _viewer: { scene }, + _viewer: surfaceViewer(scene), _enabled: true, _loadGeneration: 1, _roadSource: 'OpenStreetMap', @@ -527,7 +529,7 @@ test('provisional opposite-direction heights cannot overwrite a measured sibling }; const state = { _dots: [], - _viewer: { scene }, + _viewer: surfaceViewer(scene), _enabled: true, _loadGeneration: 1, _roadSource: 'OpenStreetMap', @@ -655,10 +657,10 @@ test('grounded vehicles respect mesh occlusion even after live congestion change h.parts.retention.reconcile(roads, 450, true); h.settle(); assert.ok(h.state._dots.length > 0); - assert.ok(h.state._dots.every((d) => d.point.disableDepthTestDistance === 0)); + assert.ok(h.state._dots.every((d) => d.point.disableDepthTest === 0)); for (const road of roads) road.flow = { level: 0.01, closure: false }; h.parts.model.recolorDotsInPlace('late jam'); - assert.ok(h.state._dots.every((d) => d.point.disableDepthTestDistance === 0)); + assert.ok(h.state._dots.every((d) => d.point.disableDepthTest === 0)); }); test('retained road density follows the settled view without requiring a toggle', (t) => { @@ -716,9 +718,9 @@ test('parsed roads carry plain ECEF waypoints that dots spawn on and move along' h.settle(); assert.ok(h.state._dots.length > 0); const dot = h.state._dots[0]; - const before = C.Cartesian3.clone(dot.point.position); + const before = C.Cartesian3.clone(dot.point.pos); h.frame(500); - const after = dot.point.position; + const after = dot.point.pos; assert.ok(Number.isFinite(after.x) && Number.isFinite(after.z)); assert.ok(C.Cartesian3.distance(before, after) > 0, 'the dot moves'); }); @@ -757,7 +759,9 @@ 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 }, query: { + sampleHeightNow: () => 0, pickPosition(x, y) { picks.push([x, y]); return C.Cartesian3.fromDegrees(0, 0, 400); @@ -810,7 +814,11 @@ test('selection asks the query port for depth and screen positions, and the came ); assert.deepEqual(picks[0], [500, 480], 'the depth probe below centre'); assert.equal(state._viewHeightEstimate, 400); - assert.equal(poses, 1, 'the eye is read once a pass'); + assert.equal( + poses, + 2, + 'the eye is read once a pass, by selection and by the surface', + ); assert.ok(rendered.includes(near), 'an on-canvas road is admitted'); assert.ok(!rendered.includes(offCanvas), 'an off-canvas road is not'); assert.ok(!rendered.includes(outOfRange), 'nor one out of range'); diff --git a/src/layers/traffic/navigation.test.mjs b/src/layers/traffic/navigation.test.mjs index e5800d648..ad437c08d 100644 --- a/src/layers/traffic/navigation.test.mjs +++ b/src/layers/traffic/navigation.test.mjs @@ -2,7 +2,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { createTrafficLayer } from './index.js'; +import { findCamera } from '../../render/rendererOf.js'; import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { sceneSurfacePorts } from '../../testSupport/fakeSceneSurface.mjs'; function deferred() { let resolve; @@ -56,7 +59,15 @@ function setup( }, }; // The layer reads the camera through its port. - bindFakeCesiumCamera(viewer, ports); + bindFakeCesiumCamera(viewer, { + ...sceneSurfacePorts(viewer), + draw: fakeDrawPort(), + ...ports, + }); + // The fake camera has view matrices only where a test gives it some. + const cameraPort = findCamera(viewer); + const matrices = cameraPort.matrices.bind(cameraPort); + cameraPort.matrices = () => (camera.viewMatrix ? matrices() : undefined); const layer = createTrafficLayer({ services: { credits: {}, @@ -461,6 +472,7 @@ test('an unready surface waits for drawn frames through the frame port, then ref listeners.add(cb); return () => listeners.delete(cb); }, + requestRender() {}, }; const { layer, viewer, tick } = setup( t, @@ -468,41 +480,40 @@ test('an unready surface waits for drawn frames through the frame port, then ref undefined, { frame }, ); - // The rendered-frame observer records on the scene's own postRender. + // The rendered-frame observer records on the frame port too, from the + // camera's matrices. viewer.camera.viewMatrix = Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY); viewer.camera.frustum = { projectionMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY), }; - viewer.scene.camera = viewer.camera; - viewer.scene.postRender = new Cesium.Event(); const drawn = (n) => { - // The frame port's listeners run first, as the renderer registers its - // frame listener before any layer's. for (const cb of [...listeners]) cb({ frame: n }); - viewer.scene.postRender.raiseEvent(); }; let samples = 0; viewer.scene.globe.getHeight = () => (samples++, 0); viewer.scene.globe.tilesLoaded = false; layer.enable(viewer); + // The observer, while the layer is enabled. + const observer = listeners.size; + assert.equal(observer, 1); + const waiting = () => listeners.size - observer; await tick(400); await tick(400); - assert.equal(listeners.size, 1, 'a drawn frame is awaited'); + assert.equal(waiting(), 1, 'a drawn frame is awaited'); drawn(1); await tick(400); - assert.equal(listeners.size, 1, 'still loading: keep waiting'); - // The frame that finishes loading refines, though the rendered-frame - // observer has not yet recorded it as ready. + assert.equal(waiting(), 1, 'still loading: keep waiting'); + // The frame that finishes loading refines. viewer.scene.globe.tilesLoaded = true; const before = samples; drawn(2); - assert.equal(listeners.size, 0, 'a ready frame starts the refinement'); + assert.equal(waiting(), 0, 'a ready frame starts the refinement'); await tick(400); await tick(400); assert.ok(samples > before, 'the refinement samples the surface again'); const after = samples; await tick(5000); - assert.equal(listeners.size, 0, 'and refines only once'); + assert.equal(waiting(), 0, 'and refines only once'); assert.equal(samples, after); layer.disable(viewer); await tick(5000); @@ -516,6 +527,7 @@ test('disabling while a refinement waits drops its frame listener', async (t) => listeners.add(cb); return () => listeners.delete(cb); }, + requestRender() {}, }; const { layer, viewer, tick } = setup( t, diff --git a/src/layers/traffic/renderDemand.test.mjs b/src/layers/traffic/renderDemand.test.mjs index df5965145..c9964dd69 100644 --- a/src/layers/traffic/renderDemand.test.mjs +++ b/src/layers/traffic/renderDemand.test.mjs @@ -16,6 +16,7 @@ test('traffic render demand follows animated population and jam lines across emp parts: { retention: { clear() {} }, rendering: { + heatPulsing: () => Boolean(state._heatJamPrim), removeHeatLines() { state._heatJamPrim = null; }, diff --git a/src/layers/traffic/rendering.js b/src/layers/traffic/rendering.js index 9c25a69fa..f263f8311 100644 --- a/src/layers/traffic/rendering.js +++ b/src/layers/traffic/rendering.js @@ -7,10 +7,88 @@ import { HEAT_SLOW_COLOR, HEAT_LINE_JAM_WIDTH, HEAT_JAM_BASE_ALPHA, + HEAT_JAM_PULSE_ALPHA, HEAT_LINE_SLOW_WIDTH, TRAFFIC_TIMING_ENABLED, } from './policy.js'; +/** + * Whether the surface the dots sit on has loaded what is in view: the + * globe's tiles while it is shown, otherwise every shown 3D tileset (and + * there is one). The globe port's settle states cannot say whether any + * tileset is drawn at all, so this reads the scene. + * @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. The renderer contract + * names no surface identity, so this reads the scene. + * @param {object|undefined} viewer + */ +const surfaceKeys = new WeakMap(); +export function trafficSurfaceKey(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; +} + export function createRendering({ state: layerState, services, @@ -166,6 +244,21 @@ export function createRendering({ } } + /** Whether jam heat-lines are drawn, which pulse every frame. */ + const heatPulsing = () => Boolean(layerState._heatJamPrim); + + /** + * Throb the jam heat-lines (~1.6 s period): one shared material uniform + * for the whole jam batch, no geometry rebuild. + * @param {number} now - Epoch ms. + */ + function pulseHeatLines(now) { + if (layerState._heatJamPrim?.appearance) { + layerState._heatJamPrim.appearance.material.uniforms.color.alpha = + HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260); + } + } + /** * Reconcile road populations without respawning retained dots. * @@ -317,6 +410,8 @@ export function createRendering({ } } return { + heatPulsing, + pulseHeatLines, visibleRoadsForAltitude, removeHeatLines, rebuildHeatLines, diff --git a/src/layers/traffic/retention.js b/src/layers/traffic/retention.js index 1485e041c..8be6e998d 100644 --- a/src/layers/traffic/retention.js +++ b/src/layers/traffic/retention.js @@ -68,6 +68,8 @@ export function createRetention({ state, parts }) { timer = null; if (!state._enabled) return; let budget = DOT_CHANGE_BUDGET; + // The dots that finished fading out, taken from the draw set at once. + const gone = []; let pending = false; const now = Date.now(); // Removing a road or reducing density fades only surplus dots. A retained @@ -84,7 +86,7 @@ export function createRetention({ state, parts }) { for (let i = record.dots.length - 1; i >= 0 && budget > 0; i--) { const dot = record.dots[i]; if (!dot.retiring || now - dot.retiring < DOT_FADE_MS) continue; - state._pointCollection.remove(dot.point); + gone.push(dot.point.id); const last = state._dots.pop(); if (last !== dot) { state._dots[dot.index] = last; @@ -127,6 +129,7 @@ export function createRetention({ state, parts }) { if (!record.target && !record.dots.length) records.delete(record.road.key); } + if (gone.length) state._dotSet?.remove(gone); refreshCounts(); state._populationPending = pending; if (pending) schedule(); @@ -136,7 +139,7 @@ export function createRetention({ state, parts }) { counts.free = counts.slow = counts.jam = counts.sim = 0; let count = 0; for (const dot of state._dots) { - if (!dot.point.show) continue; + if (dot.point.show === false) continue; counts[dot.bucket || 'sim']++; count++; } diff --git a/src/layers/traffic/state.js b/src/layers/traffic/state.js index 830837a39..8d08b7515 100644 --- a/src/layers/traffic/state.js +++ b/src/layers/traffic/state.js @@ -17,9 +17,9 @@ export function createState({ services }) { layerState._viewer = null; - /** @type {object|null} The dots' point collection. */ + /** @type {object|null} The dots' draw set (points), made at init. */ - layerState._pointCollection = null; + layerState._dotSet = null; /** @type {Array<{point:object, waypoints:Array<{x:number, y:number, z:number}>, segmentDist:number[], numSegments:number, segIdx:number, t:number, mps:number, direction:number, stoppedUntil:number}>} Active animated dots */ diff --git a/src/layers/traffic/style.js b/src/layers/traffic/style.js index 8fa23d181..e0e53a09c 100644 --- a/src/layers/traffic/style.js +++ b/src/layers/traffic/style.js @@ -4,7 +4,6 @@ import { presetDotRgba, presetDotOutline, } from '../../data/trafficPresetStyle.js'; -import * as Cesium from 'cesium'; import { SIZE_BY_TYPE, STYLED_MIN_BASE_PX, @@ -14,26 +13,9 @@ import { } from './policy.js'; export function createStyle({ state: layerState, services, parts, source }) { - // The dots' renderer colours as the point primitives take them, one per - // colour, so painting a dot allocates nothing. Keyed by identity: the - // colours are frozen, and a preset change makes new ones. - const pointColors = new WeakMap(); - - /** A renderer colour (`[r, g, b, a]`) as a point primitive colour. */ - function pointColor(rgba) { - let color = pointColors.get(rgba); - if (!color) { - color = new Cesium.Color(rgba[0], rgba[1], rgba[2], rgba[3]); - pointColors.set(rgba, color); - } - return color; - } - - /** The point colour of a dot in `bucket` (null: simulated white). */ + /** The colour of a dot in `bucket` (null: simulated white). */ function dotColor(bucket) { - return pointColor( - bucket ? layerState._activeBucketColors[bucket] : SIM_DOT_COLOR, - ); + return bucket ? layerState._activeBucketColors[bucket] : SIM_DOT_COLOR; } /** Paint a dot's point in its bucket's colour, as a late flow update does. */ @@ -48,12 +30,36 @@ export function createStyle({ state: layerState, services, parts, source }) { /** Keep a prominent jam dot larger at range. */ function emphasizeJamDot(dot) { - dot.point.scaleByDistance = new Cesium.NearFarScalar( - 100, - 1.5, - layerState._fadeScaleFar, - JAM_DOT_FAR_SCALE, - ); + dot.point.scaleByDistance = Object.freeze({ + near: 100, + nearValue: 1.5, + far: layerState._fadeScaleFar, + farValue: JAM_DOT_FAR_SCALE, + }); + } + + /** + * The preset's dark-halo outline for a coloured dot, as the point item's + * members, or null for the shipped no-outline state. + * @param {'free'|'slow'|'jam'|null} bucket - Flow bucket (null = sim). + * @returns {{outlineColor: number[], outlineWidth: number}|null} + */ + function outlineOf(bucket) { + const spec = + layerState._presetDots === 'on' + ? presetDotOutline(layerState._stylePreset, bucket) + : null; + return spec + ? { + outlineColor: Object.freeze([ + spec.rgba[0] / 255, + spec.rgba[1] / 255, + spec.rgba[2] / 255, + spec.rgba[3], + ]), + outlineWidth: spec.width, + } + : null; } /** @returns {boolean} A non-normal preset profile is active and enabled. */ @@ -111,26 +117,14 @@ export function createStyle({ state: layerState, services, parts, source }) { * it back to the shipped no-outline state). NVG's auto-gain saturates the * scene, so brightness alone cannot separate a dot from a bright road — * the dark ring restores local contrast through every luma-mapping shader. - * @param {Cesium.PointPrimitive} point - The dot primitive. + * @param {object} point - The dot's point item. * @param {'free'|'slow'|'jam'|null} bucket - Flow bucket (null = sim). */ function applyOutline(point, bucket) { - const spec = - layerState._presetDots === 'on' - ? presetDotOutline(layerState._stylePreset, bucket) - : null; - if (spec) { - point.outlineColor = new Cesium.Color( - spec.rgba[0] / 255, - spec.rgba[1] / 255, - spec.rgba[2] / 255, - spec.rgba[3], - ); - point.outlineWidth = spec.width; - } else { - point.outlineWidth = 0; - } + const outline = outlineOf(bucket); + if (outline) Object.assign(point, outline); + else point.outlineWidth = 0; } /** @@ -187,6 +181,7 @@ export function createStyle({ state: layerState, services, parts, source }) { } return { dotColor, + outlineOf, paintDot, showDot, emphasizeJamDot, diff --git a/src/layers/traffic/style.test.mjs b/src/layers/traffic/style.test.mjs index 0c302a1ff..2aba594f1 100644 --- a/src/layers/traffic/style.test.mjs +++ b/src/layers/traffic/style.test.mjs @@ -1,6 +1,6 @@ // src/layers/traffic/style.test.mjs — the traffic layer keeps its dot -// colours as renderer colours and paints them onto the points as the colours -// they always were. +// colours as renderer colours and paints them onto the points' items as the +// colours they always were. import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; @@ -13,6 +13,9 @@ import { import { presetDotRgba } from '../../data/trafficPresetStyle.js'; import { createState } from './state.js'; +/** A renderer colour (`[r, g, b, a]`) as Cesium draws it. */ +const asColor = (rgba) => new Cesium.Color(...rgba); + function style(preset = 'normal') { const state = createState({ services: {} }); state._stylePreset = preset; @@ -32,11 +35,14 @@ test('bucket colours are the shipped palette, painted as before', () => { }; for (const bucket of ['free', 'slow', 'jam']) assert.ok( - Cesium.Color.equals(s.dotColor(bucket), expected[bucket]), + Cesium.Color.equals(asColor(s.dotColor(bucket)), expected[bucket]), bucket, ); assert.ok( - Cesium.Color.equals(s.dotColor(null), Cesium.Color.WHITE.withAlpha(0.85)), + Cesium.Color.equals( + asColor(s.dotColor(null)), + Cesium.Color.WHITE.withAlpha(0.85), + ), ); assert.deepEqual(SIM_DOT_COLOR, [1, 1, 1, 0.85]); assert.equal(s.dotColor('jam'), s.dotColor('jam'), 'one colour per bucket'); @@ -51,12 +57,12 @@ test('a dot is painted, shown and emphasised on its point', () => { s.showDot(dot, false); assert.equal(dot.point.show, false); s.emphasizeJamDot(dot); - assert.ok( - Cesium.NearFarScalar.equals( - dot.point.scaleByDistance, - new Cesium.NearFarScalar(100, 1.5, 9000, JAM_DOT_FAR_SCALE), - ), - ); + assert.deepEqual(dot.point.scaleByDistance, { + near: 100, + nearValue: 1.5, + far: 9000, + farValue: JAM_DOT_FAR_SCALE, + }); }); test('a styled preset recolours the buckets', () => { @@ -67,7 +73,7 @@ test('a styled preset recolours the buckets', () => { const [r, g, b, a] = presetDotRgba('surveillance', 'jam'); assert.ok( Cesium.Color.equals( - s.dotColor('jam'), + asColor(s.dotColor('jam')), new Cesium.Color(r / 255, g / 255, b / 255, a), ), ); @@ -84,9 +90,9 @@ test('switching presets and back repaints dots with the shipped colours', () => state._dots = [dot]; const shipped = Cesium.Color.fromCssColorString('#2ecc71').withAlpha(0.9); parts.style.setStylePreset('surveillance'); - assert.ok(!Cesium.Color.equals(dot.point.color, shipped)); - assert.ok(Cesium.Color.equals(dot.point.color, parts.style.dotColor('free'))); + assert.ok(!Cesium.Color.equals(asColor(dot.point.color), shipped)); + assert.equal(dot.point.color, parts.style.dotColor('free')); parts.style.setStylePreset('normal'); - assert.ok(Cesium.Color.equals(dot.point.color, shipped)); + assert.ok(Cesium.Color.equals(asColor(dot.point.color), shipped)); assert.deepEqual(state._activeBucketColors.free, FLOW_BUCKET_COLORS.free); }); diff --git a/src/layers/traffic/surface.js b/src/layers/traffic/surface.js index c832257af..8541a7c2c 100644 --- a/src/layers/traffic/surface.js +++ b/src/layers/traffic/surface.js @@ -1,66 +1,76 @@ import { phaseTiming } from '../../sources/phaseTiming.js'; -import * as Cesium from 'cesium'; import { DOT_HEIGHT_OFFSET, MAX_WAYPOINTS_PER_ROAD } from './policy.js'; -import { heightsFor } from '../../render/cesium/heights.js'; +import { heightsOf } from '../../queries/heights.js'; +import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js'; +import { distanceSquared } from '../../geo/vector.js'; +import { + canvasOf, + findCamera, + findFrame, + findGlobe, + findQuery, +} from '../../render/rendererOf.js'; +import { surfaceTilesReady, trafficSurfaceKey } from './rendering.js'; -function surfaceTilesReady(scene) { - 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; +export { trafficSurfaceKey }; + +/** Whether the globe surface is drawn (else tiles alone are). */ +const globeShown = (viewer) => findGlobe(viewer)?.isGlobeVisible?.() === true; + +/** The camera's view and projection now, when the renderer reports them. */ +function cameraMatrices(viewer) { + const camera = findCamera(viewer); + return typeof camera?.matrices === 'function' + ? (camera.matrices() ?? null) + : null; } +const sameMatrix = (a, b) => + a.length === b.length && a.every((value, i) => value === b[i]); + const renderedFrames = new WeakMap(); /** Observe completed frames only while an enabled traffic consumer owns them. */ -export function observeTrafficSurface(scene) { - if (!scene.postRender?.addEventListener || !scene.camera?.viewMatrix) - return () => {}; - let frame = renderedFrames.get(scene); - if (!frame) { - frame = { - view: new Cesium.Matrix4(), - projection: new Cesium.Matrix4(), - owners: 0, - }; - renderedFrames.set(scene, frame); - frame.remove = scene.postRender.addEventListener(() => { - Cesium.Matrix4.clone(scene.camera.viewMatrix, frame.view); - Cesium.Matrix4.clone( - scene.camera.frustum.projectionMatrix, - frame.projection, - ); - frame.surface = trafficSurfaceKey(scene); - frame.ready = surfaceTilesReady(scene); +export function observeTrafficSurface(viewer) { + const frame = findFrame(viewer); + if (!frame || !cameraMatrices(viewer)) return () => {}; + let rendered = renderedFrames.get(viewer); + if (!rendered) { + rendered = { view: null, projection: null, owners: 0 }; + renderedFrames.set(viewer, rendered); + rendered.remove = frame.on('postRender', () => { + const matrices = cameraMatrices(viewer); + rendered.view = matrices?.view ?? null; + rendered.projection = matrices?.projection ?? null; + rendered.surface = trafficSurfaceKey(viewer); + rendered.ready = surfaceTilesReady(viewer); }); } - frame.owners++; + rendered.owners++; let released = false; return () => { if (released) return; released = true; - if (--frame.owners === 0) { - frame.remove(); - renderedFrames.delete(scene); + if (--rendered.owners === 0) { + rendered.remove(); + renderedFrames.delete(viewer); } }; } -function currentRenderedFrame(scene) { - if (!scene.postRender?.addEventListener || !scene.camera?.viewMatrix) - return { ready: surfaceTilesReady(scene) }; - const frame = renderedFrames.get(scene); - return frame && - frame.surface === trafficSurfaceKey(scene) && - Cesium.Matrix4.equals(frame.view, scene.camera.viewMatrix) && - Cesium.Matrix4.equals( - frame.projection, - scene.camera.frustum.projectionMatrix, - ) +/** + * The completed frame drawn from the camera as it is now, of the surface + * drawn now; null when the camera has moved or the surface changed since. + * Without a frame port or camera matrices, the surface's readiness alone. + */ +function currentRenderedFrame(viewer) { + if (!findFrame(viewer)) return { ready: surfaceTilesReady(viewer) }; + const matrices = cameraMatrices(viewer); + if (!matrices) return { ready: surfaceTilesReady(viewer) }; + const frame = renderedFrames.get(viewer); + return frame?.view && + frame.surface === trafficSurfaceKey(viewer) && + sameMatrix(frame.view, matrices.view) && + sameMatrix(frame.projection, matrices.projection) ? frame : null; } @@ -71,28 +81,26 @@ function currentRenderedFrame(scene) { * rendered-frame observer is recording for this same frame, which a frame * listener may run before. */ -export function drawnSurfaceReady(scene) { - return surfaceTilesReady(scene); +export function drawnSurfaceReady(viewer) { + return surfaceTilesReady(viewer); } /** Only a completed render of this camera can certify cached surface heights. */ -export function trafficSurfaceReady(scene) { - return currentRenderedFrame(scene)?.ready === true; +export function trafficSurfaceReady(viewer) { + return currentRenderedFrame(viewer)?.ready === true; } /** - * The surface reads here over the scene `viewer` draws, for code that holds - * the viewer: the scene is read once, as this is called. + * The surface reads here over what `viewer` draws, through its renderer's + * ports. * @param {object|undefined} viewer */ export function viewerRoadSurface(viewer) { - const scene = viewer?.scene; return { - drawnReady: () => drawnSurfaceReady(scene), - ready: () => trafficSurfaceReady(scene), - prepare: (roads, ...rest) => prepareRoadSurfaces(roads, scene, ...rest), - loadedHeight: (location, exclude) => - loadedSurfaceHeight(scene, location, exclude), + drawnReady: () => drawnSurfaceReady(viewer), + ready: () => trafficSurfaceReady(viewer), + prepare: (roads, ...rest) => prepareRoadSurfaces(roads, viewer, ...rest), + loadedHeight: (location) => loadedSurfaceHeight(viewer, location), }; } @@ -166,19 +174,19 @@ const validHeight = (height) => /** * One loaded-surface height at a point, for the view-height estimate road * selection starts from: terrain while the globe is shown, otherwise what is - * drawn (seeing through `exclude`, the layer's own dots) where the scene can - * sample it. Undefined when the scene cannot say. - * @param {object|undefined} scene + * drawn where the renderer can sample it (draw sets, the layer's own dots + * among them, are seen through). Undefined when it cannot say. + * @param {object|undefined} viewer * @param {{lon: number, lat: number}} location Degrees. - * @param {object[]} exclude * @returns {number|null|undefined} */ -export function loadedSurfaceHeight(scene, location, exclude) { - if (!scene) return undefined; - return scene.globe?.show - ? heightsFor(scene).now(location, { against: 'terrain' }) - : scene.sampleHeightSupported - ? heightsFor(scene).now(location, { exclude }) +export function loadedSurfaceHeight(viewer, location) { + if (!viewer) return undefined; + const heights = heightsOf(viewer); + return globeShown(viewer) + ? heights.now(location, { against: 'terrain' }) + : heights.supported().surface + ? heights.now(location) : undefined; } @@ -186,106 +194,54 @@ export function loadedSurfaceHeight(scene, location, exclude) { * Reuse the rendered depth buffer instead of drawing a new pick frustum per * station. Iteration corrects the projection's height estimate. A depth hit * is accepted only at this road coordinate (2 m), never on a foreground roof - * or hillside projected onto a different geographic point. Translucent traffic - * is absent from Cesium's default pickPosition depth pass. + * or hillside projected onto a different geographic point. The query port's + * depth pick answers against tiles and terrain, never the translucent dots. + * `rendered` is the completed frame of this camera, as `prepareRoadSurfaces` + * read it for its current slice. */ -export function renderedRoadHeight(scene, lon, lat, estimate) { - if ( - !scene.pickPositionSupported || - scene.pickTranslucentDepth || - !currentRenderedFrame(scene) || - !scene.canvas?.clientWidth || - !scene.frameState - ) - return undefined; +export function renderedRoadHeight( + viewer, + lon, + lat, + estimate, + rendered = currentRenderedFrame(viewer), +) { + const query = findQuery(viewer); + const canvas = canvasOf(viewer); + if (!query || !rendered || !canvas?.clientWidth) return undefined; let height = validHeight(estimate) ? estimate : 0; - const point = new Cesium.Cartesian3(); - const screen = new Cesium.Cartesian2(); + const point = { x: 0, y: 0, z: 0 }; for (let attempt = 0; attempt < 4; attempt++) { - Cesium.Cartesian3.fromDegrees(lon, lat, height, undefined, point); + fromDegreesInto(lon, lat, height, point); + const screen = query.project(point); if ( - !Cesium.SceneTransforms.worldToWindowCoordinates(scene, point, screen) || - screen.x < 0 || - screen.y < 0 || - screen.x >= scene.canvas.clientWidth || - screen.y >= scene.canvas.clientHeight + !screen || + !(screen.x >= 0) || + !(screen.y >= 0) || + screen.x >= canvas.clientWidth || + screen.y >= canvas.clientHeight ) return undefined; let hit; try { - hit = scene.pickPosition(screen); + hit = query.pickPosition(screen.x, screen.y); } catch { return undefined; } if (!hit) return undefined; - const location = Cesium.Cartographic.fromCartesian(hit); + const location = toLonLatH(hit); if (!location || !validHeight(location.height)) return undefined; - const dx = - (Cesium.Math.toDegrees(location.longitude) - lon) * - Math.cos((lat * Math.PI) / 180) * - 111320; - const dy = (Cesium.Math.toDegrees(location.latitude) - lat) * 111320; + const dx = (location.lon - lon) * Math.cos((lat * Math.PI) / 180) * 111320; + const dy = (location.lat - lat) * 111320; if (Math.hypot(dx, dy) <= 2) return location.height; height = location.height; } return undefined; } -// Per-scene, coordinate-keyed LRU. Never writes raw samples into shared ground floors. +// Per-viewer, coordinate-keyed LRU. Never writes raw samples into shared ground floors. const sceneCaches = new WeakMap(); -// 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. - */ -const surfaceKeys = new WeakMap(); -export function trafficSurfaceKey(scene) { - 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; -} - /** * Level-of-detail band for a point seen from the camera: log2 of the * camera-to-point distance in 100 m steps. Streamed meshes refine roughly @@ -309,29 +265,26 @@ const nextSlice = (hasSurface) => /** Prepare only admitted roads in bounded slices; locally missing surfaces defer that road. */ export async function prepareRoadSurfaces( roads, - scene, + viewer, ground, - excluded, signal, { onReady, onMetrics, frameBudgetMs = 12, revalidate = false } = {}, ) { // Cached heights are only as good as the surface and detail they came // from: a provider switch drops them all, and a point now seen from a // closer band than its sample is re-sampled against the finer mesh. - const surface = trafficSurfaceKey(scene); - let cache = sceneCaches.get(scene); + const surface = trafficSurfaceKey(viewer); + let cache = sceneCaches.get(viewer); if (!cache || cache.surface !== surface) { cache = { surface, heights: new Map() }; - sceneCaches.set(scene, cache); + sceneCaches.set(viewer, cache); } - const cameraCarto = scene.camera?.positionCartographic; - const cameraLon = cameraCarto - ? Cesium.Math.toDegrees(cameraCarto.longitude) - : 0; - const cameraLat = cameraCarto - ? Cesium.Math.toDegrees(cameraCarto.latitude) - : 0; - const cameraHeight = cameraCarto ? cameraCarto.height : NaN; + const eye = findCamera(viewer)?.pose()?.position; + const cameraAt = eye ? toLonLatH(eye) : null; + const cameraLon = cameraAt ? cameraAt.lon : 0; + const cameraLat = cameraAt ? cameraAt.lat : 0; + const cameraHeight = cameraAt ? cameraAt.height : NaN; + const heights = heightsOf(viewer); const start = performance.now(); const metrics = { sampleCount: 0, @@ -343,20 +296,28 @@ export async function prepareRoadSurfaces( maxSliceMs: 0, }; let sliceStart = performance.now(); - const carto = new Cesium.Cartographic(); + // What the view holds can only change between slices (no frame draws + // within one), so each slice reads it once. + let rendered, settled, globe; + const readView = () => { + rendered = currentRenderedFrame(viewer); + settled = rendered?.ready === true; + globe = globeShown(viewer); + }; + readView(); + const location = { lon: 0, lat: 0 }; const ready = [], pending = []; for (const road of roads) { let resolved = true; let settledRoad = true; const { indices, distances } = roadHeightStations(road.coords); - const heights = new Array(road.coords.length); + const stationHeights = new Array(road.coords.length); for (const i of indices) { signal?.throwIfAborted(); const [lon, lat] = road.coords[i]; const key = `${lon.toFixed(6)},${lat.toFixed(6)}`; const cached = cache.heights.get(key); - const settled = trafficSurfaceReady(scene); const band = detailBand(cameraLon, cameraLat, cameraHeight, lon, lat); let height = cached && @@ -372,37 +333,25 @@ export async function prepareRoadSurfaces( cache.heights.set(key, cached); } else { if (!settled) settledRoad = false; - carto.longitude = Cesium.Math.toRadians(lon); - carto.latitude = Cesium.Math.toRadians(lat); - carto.height = 0; + location.lon = lon; + location.lat = lat; const floor = ground?.cachedGroundFloor?.(lat, lon); let sampled; - // sampleHeight reads the locally rendered mesh, not unresolved/offscreen - // tiles. Global tilesLoaded can stay false while this street is usable. - if (scene.globe?.show) - sampled = heightsFor(scene).now(carto, { against: 'terrain' }); + // A height now reads the locally rendered mesh, not unresolved or + // offscreen tiles. Global readiness can stay false while this street + // is usable. + if (globe) sampled = heights.now(location, { against: 'terrain' }); else { - const estimate = Cesium.Cartographic.fromCartesian( - road.waypoints[i], - )?.height; - sampled = renderedRoadHeight(scene, lon, lat, estimate); + const estimate = toLonLatH(road.waypoints[i])?.height; + sampled = renderedRoadHeight(viewer, lon, lat, estimate, rendered); if (validHeight(sampled)) metrics.depthHits++; } - if ( - !scene.globe?.show && - !validHeight(sampled) && - scene.sampleHeightSupported - ) { + if (!globe && !validHeight(sampled) && heights.supported().surface) { const sampleStart = performance.now(); metrics.sampleCount++; - const shown = (excluded || []).filter((p) => p?.show); - for (const primitive of shown) primitive.show = false; - try { - // A miss is the local mesh still missing. - sampled = heightsFor(scene).now(carto, { exclude: excluded }); - } finally { - for (const primitive of shown) primitive.show = true; - } + // A miss is the local mesh still missing. Draw sets, the dots + // among them, are seen through. + sampled = heights.now(location); metrics.sampleMs += performance.now() - sampleStart; } // A shared floor is a safe provisional waypoint, but not permission to @@ -428,13 +377,14 @@ export async function prepareRoadSurfaces( cache.heights.delete(cache.heights.keys().next().value); } } - heights[i] = height; + stationHeights[i] = height; const elapsed = performance.now() - sliceStart; if (elapsed >= frameBudgetMs) { metrics.maxSliceMs = Math.max(metrics.maxSliceMs, elapsed); // Before the first local mesh exists, give its tile/worker tasks the // normal queue priority instead of repeatedly probing an empty scene. await nextSlice(metrics.cacheHits + metrics.depthHits > 0); + readView(); sliceStart = performance.now(); } } @@ -445,22 +395,21 @@ export async function prepareRoadSurfaces( b = indices[station]; const span = distances[b] - distances[a]; const t = span > 0 ? (distances[i] - distances[a]) / span : 0; - const height = heights[a] + (heights[b] - heights[a]) * t; + const height = + stationHeights[a] + (stationHeights[b] - stationHeights[a]) * t; const [lon, lat] = road.coords[i]; const floor = ground?.cachedGroundFloor?.(lat, lon); - Cesium.Cartesian3.fromDegrees( + fromDegreesInto( lon, lat, (validHeight(floor) ? Math.max(height, floor) : height) + DOT_HEIGHT_OFFSET, - undefined, road.waypoints[i], ); } for (let i = 0; i < road.segmentDist.length; i++) - road.segmentDist[i] = Cesium.Cartesian3.distance( - road.waypoints[i], - road.waypoints[i + 1], + road.segmentDist[i] = Math.sqrt( + distanceSquared(road.waypoints[i], road.waypoints[i + 1]), ); road.surfaceReady = resolved; road.surfaceSettled = settledRoad; diff --git a/src/layers/traffic/surface.test.mjs b/src/layers/traffic/surface.test.mjs index 2047d6974..9b92315b5 100644 --- a/src/layers/traffic/surface.test.mjs +++ b/src/layers/traffic/surface.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as C from 'cesium'; +import { surfaceViewer } from '../../testSupport/fakeSceneSurface.mjs'; import { detailBand, loadedSurfaceHeight, @@ -64,12 +65,13 @@ test('per-vertex mesh heights follow terrain, reject invalid samples, and leave sampleHeightSupported: true, sampleHeight: () => heights[samples++], }; + const viewer = surfaceViewer(scene); const ground = { cachedGroundFloor: () => 50, reportMeshFloorCell: () => assert.fail('raw sample poisoned shared floor'), }; let metrics; - const prepared = await prepareRoadSurfaces([r], scene, ground, [], null, { + const prepared = await prepareRoadSurfaces([r], viewer, ground, null, { onMetrics: (value) => (metrics = value), }); assert.equal(metrics.sampleCount, 5); @@ -80,9 +82,9 @@ test('per-vertex mesh heights follow terrain, reject invalid samples, and leave ); assert.deepEqual(actual, [103, 203, 53, 53, 53]); tileset.tilesLoaded = false; - assert.equal(trafficSurfaceReady(scene), false); + assert.equal(trafficSurfaceReady(viewer), false); scene.sampleHeight = () => 75; - const resumed = await prepareRoadSurfaces([r], scene, ground, []); + const resumed = await prepareRoadSurfaces([r], viewer, ground); assert.equal( resumed.ready.length, 1, @@ -93,14 +95,13 @@ test('per-vertex mesh heights follow terrain, reject invalid samples, and leave picks++; return 75; }; - await prepareRoadSurfaces([r], scene, ground, []); + await prepareRoadSurfaces([r], viewer, ground); assert.equal(picks, 0, 'validated coordinate heights survive cache hits'); const abort = new AbortController(); abort.abort(); - await assert.rejects( - prepareRoadSurfaces([r], scene, ground, [], abort.signal), - { name: 'AbortError' }, - ); + await assert.rejects(prepareRoadSurfaces([r], viewer, ground, abort.signal), { + name: 'AbortError', + }); }); test('visible-globe roads floor each vertex without mesh picks', async () => { const r = road([ @@ -110,12 +111,12 @@ test('visible-globe roads floor each vertex without mesh picks', async () => { let calls = 0; await prepareRoadSurfaces( [r], - { + surfaceViewer({ globe: { show: true, tilesLoaded: true, getHeight: () => ++calls * 100 }, + sampleHeightSupported: true, sampleHeight: () => assert.fail('mesh sampled'), - }, + }), { cachedGroundFloor: () => 20 }, - [], ); assert.equal(calls, 2); assert.deepEqual( @@ -142,26 +143,27 @@ test('cached heights follow detail and provider; same-detail revisits sample not sampleHeight: () => (samples++, mesh), camera: camera(3000), }; + const viewer = surfaceViewer(scene); const heightAt = () => Math.round(C.Cartographic.fromCartesian(r.waypoints[0]).height); // Settled but coarse: sampled from 3 km. - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 2); assert.equal(heightAt(), 43); // Same detail band on a revisit: zero samples. - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 2); // Zooming out never re-samples a finer height either. scene.camera = camera(6000); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 2); // Closer view, finer mesh: re-sampled and the waypoint follows it. mesh = 47; scene.camera = camera(250); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 4); assert.equal(heightAt(), 50); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 4, 'the finer sample is now the cached one'); // A different photoreal tileset (map provider switch) invalidates all, // even from a coarser view that would otherwise reuse the finer sample. @@ -169,13 +171,13 @@ test('cached heights follow detail and provider; same-detail revisits sample not scene.primitives.get = () => other; scene.camera = camera(3000); mesh = 30; - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 6); assert.equal(heightAt(), 33); // A finer sample that fails keeps the coarser measured height. scene.camera = camera(250); mesh = NaN; - const kept = await prepareRoadSurfaces([r], scene, null, []); + const kept = await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 8); assert.equal(kept.ready.length, 1); assert.equal(heightAt(), 33); @@ -204,13 +206,14 @@ test('a camera jump cannot certify old rendered depth or cache coarse heights as sampleHeightSupported: true, sampleHeight: () => (samples++, height), }; - assert.equal(trafficSurfaceReady(scene), false); - const removeSurfaceObserver = observeTrafficSurface(scene); + const viewer = surfaceViewer(scene); + assert.equal(trafficSurfaceReady(viewer), false); + const removeSurfaceObserver = observeTrafficSurface(viewer); scene.postRender.raiseEvent(); - assert.equal(trafficSurfaceReady(scene), true); + assert.equal(trafficSurfaceReady(viewer), true); scene.camera.viewMatrix[12] = 100; assert.equal( - trafficSurfaceReady(scene), + trafficSurfaceReady(viewer), false, 'old camera readiness is stale', ); @@ -218,18 +221,18 @@ test('a camera jump cannot certify old rendered depth or cache coarse heights as [0, 0], [0.001, 0], ]); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(r.surfaceSettled, false); height = 80; scene.postRender.raiseEvent(); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 4, 'the first fresh render revalidates coarse heights'); assert.equal(r.surfaceSettled, true); assert.ok( Math.abs(C.Cartographic.fromCartesian(r.waypoints[0]).height - 83) < 0.01, ); height = 100; - await prepareRoadSurfaces([r, r], scene, null, [], null, { + await prepareRoadSurfaces([r, r], viewer, null, null, { revalidate: true, }); assert.equal( @@ -241,9 +244,9 @@ test('a camera jump cannot certify old rendered depth or cache coarse heights as assert.ok( Math.abs(C.Cartographic.fromCartesian(r.waypoints[0]).height - 103) < 0.01, ); - await prepareRoadSurfaces([r], scene, null, []); + await prepareRoadSurfaces([r], viewer, null); assert.equal(samples, 6, 'ordinary same-band revisits still reuse the cache'); - await prepareRoadSurfaces([r], scene, null, [], null, { revalidate: true }); + await prepareRoadSurfaces([r], viewer, null, null, { revalidate: true }); assert.equal( samples, 6, @@ -264,7 +267,7 @@ test('height stations preserve bends while bounding sample spacing along the roa let picks = 0; await prepareRoadSurfaces( [r], - { + surfaceViewer({ globe: { show: true, tilesLoaded: true, @@ -273,9 +276,8 @@ test('height stations preserve bends while bounding sample spacing along the roa return C.Math.toDegrees(c.longitude) * 1000; }, }, - }, + }), null, - [], ); assert.equal(picks, indices.length); for (let i = 0; i < coords.length; i++) { @@ -306,7 +308,8 @@ test('rendered road depth is geographically checked, bounded, and avoids mesh re sampleHeight: () => assert.fail('valid depth must not draw another pick frustum'), }; - assert.ok(Math.abs(renderedRoadHeight(scene, -97, 30, 0) - 100) < 0.001); + const viewer = surfaceViewer(scene); + assert.ok(Math.abs(renderedRoadHeight(viewer, -97, 30, 0) - 100) < 0.001); const r = road([ [-97, 30], [-97, 30.000005], @@ -314,7 +317,7 @@ test('rendered road depth is geographically checked, bounded, and avoids mesh re r.waypoints = r.coords.map(([lon, lat]) => C.Cartesian3.fromDegrees(lon, lat, 50), ); - const result = await prepareRoadSurfaces([r], scene, null, []); + const result = await prepareRoadSurfaces([r], viewer, null); assert.equal(result.metrics.depthHits, 2); assert.equal(result.metrics.sampleCount, 0); let calls = 0; @@ -323,19 +326,24 @@ test('rendered road depth is geographically checked, bounded, and avoids mesh re return C.Cartesian3.fromDegrees(-97.001, 30, 150); }; assert.equal( - renderedRoadHeight(scene, -97, 30, 0), + renderedRoadHeight(viewer, -97, 30, 0), undefined, 'foreground roof is not the road coordinate', ); assert.equal(calls, 4); scene.pickPosition = () => C.Cartesian3.fromDegrees(-97, 30, 10000); - assert.equal(renderedRoadHeight(scene, -97, 30, 0), undefined); + assert.equal(renderedRoadHeight(viewer, -97, 30, 0), undefined); scene.pickPosition = () => { throw new Error('depth unavailable'); }; - assert.equal(renderedRoadHeight(scene, -97, 30, 0), undefined); - scene.pickTranslucentDepth = true; - assert.equal(renderedRoadHeight(scene, -97, 30, 0), undefined); + assert.equal(renderedRoadHeight(viewer, -97, 30, 0), undefined); + scene.pickPositionSupported = false; + scene.pickPosition = () => C.Cartesian3.fromDegrees(-97, 30, 100); + assert.equal( + renderedRoadHeight(viewer, -97, 30, 0), + undefined, + 'no depth pick, no depth height', + ); }); test('surface keys reuse identity without building arrays or strings on unchanged frames', (t) => { @@ -357,8 +365,9 @@ test('surface keys reuse identity without building arrays or strings on unchange }, postRender: new C.Event(), }; - const first = trafficSurfaceKey(scene); - const remove = observeTrafficSurface(scene); + const viewer = surfaceViewer(scene); + const first = trafficSurfaceKey(viewer); + const remove = observeTrafficSurface(viewer); const originalMap = Array.prototype.map; const originalJoin = Array.prototype.join; let maps = 0, @@ -374,7 +383,7 @@ test('surface keys reuse identity without building arrays or strings on unchange try { for (let i = 0; i < 1000; i++) { scene.postRender.raiseEvent(); - assert.equal(trafficSurfaceKey(scene), first); + assert.equal(trafficSurfaceKey(viewer), first); } } finally { Array.prototype.map = originalMap; @@ -383,23 +392,23 @@ test('surface keys reuse identity without building arrays or strings on unchange assert.equal(maps, 0); assert.equal(joins, 0); tiles[1].show = false; - const hidden = trafficSurfaceKey(scene); + const hidden = trafficSurfaceKey(viewer); assert.notEqual(hidden, first); tiles[1] = { show: true, tilesLoaded: true }; assert.notEqual( - trafficSurfaceKey(scene), + trafficSurfaceKey(viewer), first, 'same-count tileset replacement is a new surface', ); scene.globe.show = true; - const terrain = trafficSurfaceKey(scene); + const terrain = trafficSurfaceKey(viewer); scene.globe.terrainProvider = {}; - assert.notEqual(trafficSurfaceKey(scene), terrain); + assert.notEqual(trafficSurfaceKey(viewer), terrain); remove(); remove(); assert.equal(scene.postRender.numberOfListeners, 0); assert.equal( - trafficSurfaceReady(scene), + trafficSurfaceReady(viewer), false, 'readiness cannot recreate a subscription', ); @@ -407,26 +416,25 @@ test('surface keys reuse identity without building arrays or strings on unchange test('the view-height estimate reads terrain under a shown globe, else the drawn surface past the dots', () => { const at = { lon: -97.7431, lat: 30.2672 }; - const dots = {}; const seen = []; - const terrain = { + const terrain = surfaceViewer({ globe: { show: true, getHeight: (carto) => (seen.push(carto), 151) }, // A shown globe wins even where the scene could sample what is drawn. sampleHeightSupported: true, sampleHeight: () => assert.fail('terrain, not the drawn surface'), - }; - assert.equal(loadedSurfaceHeight(terrain, at, [dots]), 151); + }); + assert.equal(loadedSurfaceHeight(terrain, at), 151); assert.ok(Math.abs(C.Math.toDegrees(seen[0].longitude) - at.lon) < 1e-12); - const tiles = { + // The query port sees through draw sets (the dots among them) itself. + const tiles = surfaceViewer({ globe: { show: false }, sampleHeightSupported: true, - sampleHeight: (_carto, exclude) => (seen.push(exclude), 188), - }; - assert.equal(loadedSurfaceHeight(tiles, at, [dots]), 188); - assert.deepEqual(seen[1], [dots], 'sees through the layer dots'); + sampleHeight: () => 188, + }); + assert.equal(loadedSurfaceHeight(tiles, at), 188); assert.equal( - loadedSurfaceHeight({ globe: { show: false } }, at, [dots]), + loadedSurfaceHeight(surfaceViewer({ globe: { show: false } }), at), undefined, ); - assert.equal(loadedSurfaceHeight(undefined, at, [dots]), undefined); + assert.equal(loadedSurfaceHeight(undefined, at), undefined); }); diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 8637eb3a8..985904238 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -1049,8 +1049,31 @@ export function createCesiumDraw({ 'displayRange', ]; + /** + * What a point's look keeps of an item member: a frozen value of plain + * members (a frozen colour or curve) as it is, since it cannot change and + * is then told unchanged by identity; anything else as a `plainCopy`. + */ + function lookCopy(value) { + if (!value || typeof value !== 'object' || !Object.isFrozen(value)) + return plainCopy(value); + // Only plain data cannot change: no getters, nothing inherited. + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== Array.prototype) + return plainCopy(value); + for (const key of Reflect.ownKeys(value)) { + const member = Object.getOwnPropertyDescriptor(value, key); + if ( + !('value' in member) || + (member.value !== null && typeof member.value === 'object') + ) + return plainCopy(value); + } + return value; + } + /** A copy of the item members a point's look is drawn from. */ - const pointLookOf = (item) => LOOK_FROM.map((key) => plainCopy(item[key])); + const pointLookOf = (item) => LOOK_FROM.map((key) => lookCopy(item[key])); /** * Whether `value` holds what `kept` (a `plainCopy` of a colour, curve or @@ -1067,6 +1090,13 @@ export function createCesiumDraw({ ) return false; if (Array.isArray(kept) !== Array.isArray(value)) return false; + if (Array.isArray(value)) { + // Colours, read by index: a `for...in` over an array is far slower. + if (kept.length !== value.length) return false; + for (let i = 0; i < value.length; i++) + if (!Object.is(kept[i], value[i])) return false; + return true; + } let count = 0; for (const key in value) { if (value[key] === undefined) continue; @@ -1083,28 +1113,57 @@ export function createCesiumDraw({ const value = item[LOOK_FROM[i]]; if (sameLookValue(was.look[i], value)) continue; was.primitive[LOOK[i][0]] = LOOK[i][1](item); - was.look[i] = plainCopy(value); + was.look[i] = lookCopy(value); } } - const PLACE_KEYS = ['x', 'y', 'z', 'lon', 'lat', 'height']; - /** * Where an item is, as its values when drawn: a caller may change the * position object it passes and send the same one again. */ - const placeOf = (item) => - PLACE_KEYS.map((key) => item.pos?.[key]).concat(item.height); + const placeOf = (item) => { + const pos = item.pos; + return [ + pos?.x, + pos?.y, + pos?.z, + pos?.lon, + pos?.lat, + pos?.height, + item.height, + ]; + }; - /** Whether an item is somewhere else than `at`; if so, `at` takes it. */ + /** + * Whether an item is somewhere else than `at`; if so, `at` takes it. Read + * member by member, by name: points moved every frame are compared every + * frame. + */ function movedFrom(at, item) { - let moved = !Object.is(item.height, at[PLACE_KEYS.length]); - for (let i = 0; !moved && i < PLACE_KEYS.length; i++) - moved = !Object.is(item.pos?.[PLACE_KEYS[i]], at[i]); - if (!moved) return false; - for (let i = 0; i < PLACE_KEYS.length; i++) - at[i] = item.pos?.[PLACE_KEYS[i]]; - at[PLACE_KEYS.length] = item.height; + const pos = item.pos; + const x = pos?.x; + const y = pos?.y; + const z = pos?.z; + const lon = pos?.lon; + const lat = pos?.lat; + const height = pos?.height; + if ( + Object.is(x, at[0]) && + Object.is(y, at[1]) && + Object.is(z, at[2]) && + Object.is(lon, at[3]) && + Object.is(lat, at[4]) && + Object.is(height, at[5]) && + Object.is(item.height, at[6]) + ) + return false; + at[0] = x; + at[1] = y; + at[2] = z; + at[3] = lon; + at[4] = lat; + at[5] = height; + at[6] = item.height; return true; } diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index bd1559c0b..4caaac7eb 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -912,6 +912,127 @@ test('the bikeshare layer draws its stations as point primitives on a viewer of assert.equal(scene.added.length, 0); }); +test('the traffic layer draws its dots as one point collection moved, added to and taken from in place on a viewer of its own', async (t) => { + const { createState } = await import('../../layers/traffic/state.js'); + const { createStyle } = await import('../../layers/traffic/style.js'); + const { createModel } = await import('../../layers/traffic/model.js'); + const { createAnimation } = await import('../../layers/traffic/animation.js'); + const { JAM_DOT_FAR_SCALE } = await import('../../layers/traffic/policy.js'); + let now = 10000; + t.mock.method(Date, 'now', () => now); + const { scene, draw } = drawOver(); + const state = createState({ services: {} }); + state._enabled = true; + state._fadeScaleFar = 8000; + state._fadeTransFar = 10000; + state._dotSet = draw.points({ id: 'traffic:1:dots', blend: 'translucent' }); + const parts = { + rendering: { removeHeatLines() {}, rebuildHeatLines() {} }, + retention: { easeHeights() {}, finishHeights() {}, clear() {} }, + }; + const context = { + state, + services: { + render: { holdContinuousRender() {}, releaseContinuousRender() {} }, + }, + parts, + source: {}, + }; + parts.style = createStyle(context); + parts.model = createModel(context); + parts.animation = createAnimation(context); + parts.style.refreshBucketColors(); + const [road] = parts.model.parseRoads({ + roads: [ + { + type: 'primary', + oneway: 1, + coordinates: [ + [-97.74, 30.26], + [-97.737, 30.26], + ], + }, + ], + }); + parts.animation.spawnDotsForRoad(road, 450, 3); + const host = scene.added[0]; + assert.ok(host instanceof Cesium.PointPrimitiveCollection); + assert.equal(host.blendOption, Cesium.BlendOption.TRANSLUCENT); + assert.equal(host.length, 3, 'drawn as they join'); + const point = host.get(0); + assert.equal(point.id.set, 'traffic:1:dots'); + assert.ok( + Cesium.Color.equals(point.color, Cesium.Color.WHITE.withAlpha(0.85)), + 'the simulated white', + ); + assert.equal(point.disableDepthTestDistance, 0); + const before = Cesium.Cartesian3.clone(point.position); + now += 500; + parts.animation.animate(); + assert.equal(scene.added[0], host, 'moved where it is'); + assert.equal(host.get(0), point); + assert.ok(!Cesium.Cartesian3.equals(point.position, before), 'it moves'); + assert.ok( + Cesium.NearFarScalar.equals( + point.scaleByDistance, + new Cesium.NearFarScalar(100, 1.5, 8000, 0.3), + ), + ); + assert.ok( + Cesium.NearFarScalar.equals( + point.translucencyByDistance, + new Cesium.NearFarScalar(100, 1, 10000, 0), + ), + ); + // What the style part changes on a dot reaches its point at the next + // frame, on the point it has. + const dot = state._dots[0]; + parts.style.paintDot(dot, 'jam'); + parts.style.emphasizeJamDot(dot); + dot.point.outlineColor = Object.freeze([0, 0, 0, 0.5]); + dot.point.outlineWidth = 2; + now += 16; + parts.animation.animate(); + assert.equal(host.get(0), point); + assert.ok( + Cesium.Color.equals( + point.color, + new Cesium.Color(...state._activeBucketColors.jam), + ), + 'painted', + ); + assert.ok( + Cesium.NearFarScalar.equals( + point.scaleByDistance, + new Cesium.NearFarScalar(100, 1.5, 8000, JAM_DOT_FAR_SCALE), + ), + 'emphasised', + ); + assert.ok( + Cesium.Color.equals(point.outlineColor, new Cesium.Color(0, 0, 0, 0.5)), + ); + assert.equal(point.outlineWidth, 2); + parts.style.showDot(dot, false); + now += 16; + parts.animation.animate(); + assert.equal(point.show, false, 'hidden'); + parts.style.showDot(dot, true); + now += 16; + parts.animation.animate(); + assert.equal(point.show, true); + parts.animation.spawnDotsForRoad(road, 450, 2); + assert.equal(scene.added[0], host, 'joined where it is'); + assert.equal(host.length, 5); + // A dot that has faded out leaves the collection where it is, as the + // retention part takes it. + state._dotSet.remove([state._dots[0].point.id]); + assert.equal(scene.added[0], host); + assert.equal(state._dotSet.size(), 4); + parts.animation.clearDots(); + state._dotSet.dispose(); + assert.equal(scene.added.length, 0); +}); + test('a rebuilt set keeps its place among the scene primitives, and names its host', async () => { const { registerSpriteSet, @@ -1186,6 +1307,35 @@ test('a point moved in place sets only the members of its look that changed', () item.color[1] = 1; set.upsert([item]); assert.deepEqual(written, ['color', 'scaleByDistance', 'color']); + // A frozen colour or curve is kept as it is, and told unchanged by + // identity; an equal one sent anew still sets nothing. + item.color = Object.freeze([0, 0, 1, 1]); + set.upsert([item]); + set.upsert([item]); + item.color = Object.freeze([0, 0, 1, 1]); + set.upsert([item]); + assert.deepEqual(written, ['color', 'scaleByDistance', 'color', 'color']); + // A frozen curve read through a getter can change, so it is copied and + // compared by value. + let farValue = 0.3; + item.scaleByDistance = Object.freeze( + Object.defineProperties( + {}, + { + near: { value: 100, enumerable: true }, + nearValue: { value: 1.5, enumerable: true }, + far: { value: 12000, enumerable: true }, + farValue: { get: () => farValue, enumerable: true }, + }, + ), + ); + set.upsert([item]); + const writes = written.length; + set.upsert([item]); + assert.equal(written.length, writes, 'unchanged'); + farValue = 0.8; + set.upsert([item]); + assert.equal(written.at(-1), 'scaleByDistance', 'the change is seen'); set.dispose(); }); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 6fef63f35..22d400f52 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -28,11 +28,8 @@ "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", - "src/layers/traffic/animation.js", "src/layers/traffic/lifecycle.js", "src/layers/traffic/rendering.js", - "src/layers/traffic/style.js", - "src/layers/traffic/surface.js", "src/layers/transit/rendering.js", "src/layers/weather/shellRendering.js", "src/layers/wind/gpuRendering.js", diff --git a/src/testSupport/fakeSceneSurface.mjs b/src/testSupport/fakeSceneSurface.mjs new file mode 100644 index 000000000..895c92db8 --- /dev/null +++ b/src/testSupport/fakeSceneSurface.mjs @@ -0,0 +1,116 @@ +/** + * Renderer ports over a scene double, for tests of code that reads the + * surface through the query, globe, camera and frame ports: they answer + * from the double's Cesium-shaped members, read when asked, so a test that + * changes its scene is seen. + * + * - query: `sampleHeightNow` (terrain from `globe.getHeight`, else the + * 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`. + * - camera (`withCamera`): `pose().position` from `camera.positionCartographic`, + * `matrices()` from `camera.viewMatrix` and `frustum.projectionMatrix` + * (undefined without them). + * - frame: `on('postRender')` on the scene's `postRender`, when it has one. + * - capabilities: `sampleHeight` while the scene is `sampleHeightSupported`. + */ +import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +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 surface ports over `viewer.scene`. */ +export function sceneSurfacePorts(viewer, { withCamera = false } = {}) { + const scene = () => viewer.scene ?? {}; + const query = { + sampleHeightNow(point, { against } = {}) { + const s = scene(); + if (against === 'terrain') + return s.globe?.getHeight?.(carto(point)) ?? null; + return s.sampleHeightSupported + ? (s.sampleHeight?.(carto(point)) ?? null) + : null; + }, + project(position) { + const at = Cesium.SceneTransforms.worldToWindowCoordinates( + scene(), + new Cesium.Cartesian3(position.x, position.y, position.z), + new Cesium.Cartesian2(), + ); + return at ? { x: at.x, y: at.y } : null; + }, + pickPosition(x, y) { + const s = scene(); + if (!s.pickPositionSupported) return null; + return ecef(s.pickPosition?.(new Cesium.Cartesian2(x, y))); + }, + pickEllipsoid: () => null, + pickRay: () => null, + pick: () => null, + drillPick: () => [], + isOccluded: () => false, + }; + const ports = { + query, + globe: { isGlobeVisible: () => Boolean(scene().globe?.show) }, + frame: { + on(phase, cb) { + const event = phase === 'postRender' ? scene().postRender : null; + return event?.addEventListener?.(cb) ?? (() => {}); + }, + requestRender() {}, + }, + get capabilities() { + return new Set(scene().sampleHeightSupported ? ['sampleHeight'] : []); + }, + get canvas() { + return scene().canvas; + }, + }; + if (withCamera) + ports.camera = { + pose() { + const c = scene().camera?.positionCartographic; + return { + position: c + ? ecef( + Cesium.Cartesian3.fromRadians( + c.longitude, + c.latitude, + c.height, + ), + ) + : null, + }; + }, + matrices() { + const camera = scene().camera; + if (!camera?.viewMatrix || !camera.frustum?.projectionMatrix) + return undefined; + return { + view: Float64Array.from(Cesium.Matrix4.toArray(camera.viewMatrix)), + projection: Float64Array.from( + Cesium.Matrix4.toArray(camera.frustum.projectionMatrix), + ), + }; + }, + }; + return ports; +} + +/** + * A viewer over `scene` bound to the surface ports, its camera and a fake + * draw port. + * @returns {{scene: object}} + */ +export function surfaceViewer(scene) { + const viewer = { scene }; + bindRenderer(viewer, { + ...sceneSurfacePorts(viewer, { withCamera: true }), + draw: fakeDrawPort(), + }); + return viewer; +}