diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ed549dd71..713090c5e 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. +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 and bikeshare expose factories through `./layers/traffic` and `./layers/bikeshare`. Traffic separates road requests, ingestion, animation, @@ -6277,8 +6277,9 @@ on it. Every failed read cancels its body and aborts its owned request, including declared and streaming byte-cap failures. - Development captures opened with `?trafficDebug=1` mint an interaction anchor - from the exact `camera.changed` event that arms each debounced load, then emit - scheduling-correlated User Timing entries for production `response.json`, road + from the exact camera-port `changed` event that arms each debounced load, + then emit scheduling-correlated User Timing entries for production + `response.json`, road parse, dot construction, heat-line rebuild, and next-post-render boundaries. Every trace is paired with the exact camera-change that scheduled its load; mismatches are counted drops. Cesium's `moveEnd` remains a diagnostic diff --git a/scripts/qa-traffic-baseline.mjs b/scripts/qa-traffic-baseline.mjs index 7059bf438..4a73d6be2 100644 --- a/scripts/qa-traffic-baseline.mjs +++ b/scripts/qa-traffic-baseline.mjs @@ -117,8 +117,9 @@ async function moveCamera(page, view) { }); // setView normally propagates through Cesium's render loop. Raising these // explicitly makes the capture boundary deterministic across GPU speeds. - // Pairing still flows through camera.changed's schedule-time anchor; the - // synthetic moveEnd is emitted only as the same diagnostic used naturally. + // Traffic hears the synthetic moveEnd through the camera port and loads at + // once; the port measures its own `changed` on the next rendered tick, so + // the synthetic camera.changed reaches only the layers still on Cesium. gev.viewer.camera.changed.raiseEvent(); gev.viewer.camera.moveEnd.raiseEvent(); return { beforeLastUpdate, boundaryTime }; diff --git a/src/data/cameraSensitivity.js b/src/data/cameraSensitivity.js index f6d764f72..0db765a8e 100644 --- a/src/data/cameraSensitivity.js +++ b/src/data/cameraSensitivity.js @@ -4,9 +4,10 @@ * * `camera.changed` fires once the view has moved by this fraction, and it is a * single number on the camera that every listener in the app shares. Several - * layers want it finer than the default — traffic and transit ask for 0.05 so - * they notice they have entered a coverage area (bikeshare did too, before it - * listened through the renderer's camera port at its own threshold) — and + * layers want it finer than the default — transit asks for 0.05 so it + * notices it has entered a coverage area (bikeshare and traffic did too, + * before they listened through the renderer's camera port at their own + * threshold) — and * each of them used to write the number directly and hand back whatever it * remembered. * diff --git a/src/data/trafficTiming.test.mjs b/src/data/trafficTiming.test.mjs index f22831abb..977825cb6 100644 --- a/src/data/trafficTiming.test.mjs +++ b/src/data/trafficTiming.test.mjs @@ -245,8 +245,16 @@ test('traffic timing pairs real ordering to the scheduling change and guards re- // The layer reads the camera through the renderer's camera port. const { bindRenderer } = await server.ssrLoadModule('/src/render/rendererOf.js'); const degrees = (radians) => radians * 180 / Math.PI; + const cameraEvents = { moveEnd, changed }; + const frameEvents = { preRender, postRender }; bindRenderer(viewer, { + // The scene's channels, raised by the test as Cesium would. + frame: { + on: (phase, cb) => frameEvents[phase].addEventListener(cb), + requestRender() {}, + }, camera: { + on: (event, cb) => cameraEvents[event].addEventListener(cb), pose: () => ({ lon: degrees(camera.positionCartographic.longitude), lat: degrees(camera.positionCartographic.latitude), diff --git a/src/layers/traffic/lifecycle.js b/src/layers/traffic/lifecycle.js index 166426367..7a9b2d278 100644 --- a/src/layers/traffic/lifecycle.js +++ b/src/layers/traffic/lifecycle.js @@ -1,15 +1,6 @@ import { observeTrafficSurface } from './surface.js'; -// 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'; +import { CAMERA_CHANGED_THRESHOLD, TRAFFIC_TIMING_ENABLED } from './policy.js'; +import { cameraOf, drawOf, frameOf } from '../../render/rendererOf.js'; /** Numbers each layer instance's draw sets apart. */ let instances = 0; @@ -89,9 +80,9 @@ export function createLifecycle({ }, /** - * Enable the traffic layer. Shows the point collection, subscribes to the - * preRender animation loop and camera-change events, and kicks off an - * initial viewport check. + * Enable the traffic layer. Shows the dots, subscribes to the frame + * port's preRender for the animation and to the camera port's events, + * and kicks off an initial viewport check. * * @param {Cesium.Viewer} viewer - The Cesium viewer instance. */ @@ -104,27 +95,33 @@ export function createLifecycle({ layerState._lastAnimTime = 0; if (layerState._dotSet) layerState._dotSet.show = true; - layerState._preRenderRemover = viewer.scene.preRender.addEventListener( + const camera = cameraOf(viewer); + layerState._preRenderRemover = frameOf(viewer).on( + 'preRender', parts.animation.animate, ); if (TRAFFIC_TIMING_ENABLED) { parts.timing.clearTrafficTimingEntries(); layerState._trafficTimingCurrentAnchor = null; layerState._trafficTimingPostRenderRemovers = new Set(); - layerState._trafficTimingMoveEndRemover = - viewer.camera.moveEnd.addEventListener( - parts.timing.markTrafficTimingMoveEnd, - ); + layerState._trafficTimingMoveEndRemover = camera.on( + 'moveEnd', + parts.timing.markTrafficTimingMoveEnd, + ); } - // Share the 5% movement threshold with other camera-driven layers. - viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged); + // Its own 5% movement threshold: the camera measures it for this + // listener alone. + layerState._cameraRemover = camera.on( + 'changed', + () => parts.viewport.onCameraChanged(), + { threshold: CAMERA_CHANGED_THRESHOLD }, + ); // Always inspect the final view, even when the last flight step is below - // camera.changed's movement threshold. - layerState._arrivalRemover = viewer.camera.moveEnd.addEventListener(() => + // the changed threshold. + layerState._arrivalRemover = camera.on('moveEnd', () => parts.viewport.onCameraChanged({ immediate: true }), ); - claimCameraSensitivity(viewer.camera, 'traffic', 0.05); // Enabling is explicit intent, not a camera gesture that needs settling. parts.viewport.onCameraChanged({ immediate: true }); @@ -197,10 +194,10 @@ export function createLifecycle({ layerState._trafficTimingCurrentAnchor = null; } - viewer.camera.changed.removeEventListener(parts.viewport.onCameraChanged); + layerState._cameraRemover?.(); + layerState._cameraRemover = null; layerState._arrivalRemover?.(); layerState._arrivalRemover = null; - releaseCameraSensitivity(viewer.camera, 'traffic'); if (layerState._dotSet) layerState._dotSet.show = false; }, diff --git a/src/layers/traffic/navigation.test.mjs b/src/layers/traffic/navigation.test.mjs index ad437c08d..3494b5636 100644 --- a/src/layers/traffic/navigation.test.mjs +++ b/src/layers/traffic/navigation.test.mjs @@ -3,7 +3,12 @@ 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 { + bindFakeCesiumCamera, + fakeCameraPort, +} from '../../testSupport/fakeCameraPort.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { createLifecycle } from './lifecycle.js'; import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; import { sceneSurfacePorts } from '../../testSupport/fakeSceneSurface.mjs'; @@ -225,6 +230,75 @@ test('arrival below the camera change threshold loads the final city and unsubsc assert.equal(viewer.camera.changed.numberOfListeners, ported.changed); }); +test('the layer animates on the frame port and leaves the shared camera threshold alone', async (t) => { + const frames = []; + const frame = { + on(phase, cb) { + const entry = { phase, cb }; + frames.push(entry); + return () => frames.splice(frames.indexOf(entry), 1); + }, + requestRender() {}, + }; + const { layer, viewer, tick } = setup( + t, + async (bounds) => roads(bounds), + undefined, + { frame }, + ); + layer.enable(viewer); + assert.deepEqual( + frames.map((f) => f.phase), + ['preRender'], + ); + assert.equal( + viewer.camera.percentageChanged, + 0.5, + 'the shared threshold is left alone', + ); + await tick(400); + layer.disable(viewer); + assert.equal(frames.length, 0); +}); + +test('the camera tells the layer once the view has moved 5%', (t) => { + const noop = () => {}; + const calls = []; + const lifecycle = createLifecycle({ + state: { _loadGeneration: 0 }, + services: {}, + source: {}, + parts: { + animation: { animate: noop, clearDots: noop, syncRenderDemand: noop }, + viewport: { onCameraChanged: (options) => calls.push(options) }, + ingestion: { cancelActiveFetch: noop }, + }, + }).methods; + const camera = fakeCameraPort({ pose: { height: 1000 } }); + const viewer = {}; + t.after( + bindRenderer(viewer, { + camera: camera.port, + frame: { on: () => noop, requestRender: noop }, + }), + ); + t.mock.timers.enable({ apis: ['setInterval'] }); + lifecycle.enable(viewer); + calls.length = 0; + camera.stepChanged(); + camera.setPose({ position: { x: 30, y: 0, z: 0 } }); + camera.stepChanged(); + assert.equal(calls.length, 0, '3% is not enough'); + camera.setPose({ position: { x: 70, y: 0, z: 0 } }); + camera.stepChanged(); + assert.deepEqual(calls, [undefined], '7% is, debounced as a camera move'); + camera.emit('moveEnd'); + assert.deepEqual(calls[1], { immediate: true }, 'arrival is immediate'); + lifecycle.disable(viewer); + assert.equal(camera.listenerCount('changed'), 0); + assert.equal(camera.listenerCount('moveEnd'), 0); +}); + test('parked failures back off and disabling cancels the scheduled retry', async (t) => { let calls = 0; const { layer, viewer, tick } = setup(t, async () => { @@ -466,8 +540,10 @@ test('partial coverage retries while coarse roads render, then stops after three test('an unready surface waits for drawn frames through the frame port, then refines once', async (t) => { const listeners = new Set(); + // The drawn frames; the animation runs on preRender. const frame = { on(phase, cb) { + if (phase === 'preRender') return () => {}; assert.equal(phase, 'postRender'); listeners.add(cb); return () => listeners.delete(cb); @@ -523,7 +599,8 @@ test('an unready surface waits for drawn frames through the frame port, then ref test('disabling while a refinement waits drops its frame listener', async (t) => { const listeners = new Set(); const frame = { - on(_phase, cb) { + on(phase, cb) { + if (phase === 'preRender') return () => {}; listeners.add(cb); return () => listeners.delete(cb); }, diff --git a/src/layers/traffic/policy.js b/src/layers/traffic/policy.js index 4bc5ab02d..159039a8b 100644 --- a/src/layers/traffic/policy.js +++ b/src/layers/traffic/policy.js @@ -10,6 +10,13 @@ import { hexColor } from '../../render/color.js'; export const ACTIVATION_ALTITUDE = 8000; +/** + * How far the view moves before the camera tells the layer (the camera's + * `changed` threshold): fine, so it notices entering a coverage area. + */ + +export const CAMERA_CHANGED_THRESHOLD = 0.05; + /** @const {number} Meters — above this altitude, only major roads are fetched */ export const FAST_FETCH_ALTITUDE = 4500; diff --git a/src/layers/traffic/rendering.js b/src/layers/traffic/rendering.js index 4afe315d5..54cb696cd 100644 --- a/src/layers/traffic/rendering.js +++ b/src/layers/traffic/rendering.js @@ -12,6 +12,11 @@ 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 { diff --git a/src/layers/traffic/state.js b/src/layers/traffic/state.js index 4c08ead44..ecd643fbc 100644 --- a/src/layers/traffic/state.js +++ b/src/layers/traffic/state.js @@ -41,11 +41,11 @@ export function createState({ services }) { layerState._enabled = false; - /** @type {Function|null} Disposer returned by preRender event subscription */ + /** @type {Function|null} Disposer of the frame port's preRender listener */ layerState._preRenderRemover = null; - /** @type {Function|null} Disposer returned by camera.changed event subscription */ + /** @type {Function|null} Disposers of the camera port's changed and moveEnd listeners */ layerState._cameraRemover = null; layerState._arrivalRemover = null; @@ -90,10 +90,6 @@ export function createState({ services }) { layerState._lastViewCenter = null; - /** @type {number|null} camera.percentageChanged value before we overrode it, restored on disable */ - - layerState._prevPercentageChanged = null; - /** @type {boolean} Live TomTom flow mode — true iff /api/tomtom/status reports a key */ layerState._liveMode = false; diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index a5ff5c00e..2977688cb 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -3617,7 +3617,7 @@ test('reject then selected history backfill cannot resurrect a 111 km displaceme assert.equal(entry.track.resets, 0); }); -test('actual Traffic and Transit lifecycles retain sensitivity in every enable/disable order, Bikeshare among them', async (t) => { +test('the actual Transit lifecycle retains its sensitivity in every enable/disable order, Traffic and Bikeshare among them', async (t) => { const { createLifecycle: trafficLifecycle } = await import('../traffic/lifecycle.js'); const { createLifecycle: bikeLifecycle } = @@ -3670,15 +3670,33 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d const bikeViewer = {}; const unbindBike = bindRenderer(bikeViewer, { camera: bikeCamera.port }); t.after(unbindBike); + // So does traffic, which animates on its renderer's frame port. + const trafficCamera = fakeCameraPort(); + const trafficViewer = {}; + const trafficFrames = new Set(); + const unbindTraffic = bindRenderer(trafficViewer, { + camera: trafficCamera.port, + frame: { + on(_phase, cb) { + trafficFrames.add(cb); + return () => trafficFrames.delete(cb); + }, + requestRender: noop, + }, + }); + t.after(unbindTraffic); const layers = { - traffic, + traffic: { + enable: () => traffic.enable(trafficViewer), + disable: () => traffic.disable(trafficViewer), + }, bikeshare: { enable: () => bike.enable(bikeViewer), disable: () => bike.disable(bikeViewer), }, transit: app.layer, }; - const claimants = new Set(['traffic', 'transit']); + const claimants = new Set(['transit']); const orders = [ ['traffic', 'bikeshare', 'transit'], ['traffic', 'transit', 'bikeshare'], @@ -3696,6 +3714,10 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d if (claimants.has(id)) active.add(id); if (id === 'bikeshare') assert.equal(bikeCamera.listenerCount('changed'), 1); + if (id === 'traffic') { + assert.equal(trafficCamera.listenerCount('changed'), 1); + assert.equal(trafficFrames.size, 1); + } assert.equal( app.viewer.camera.percentageChanged, active.size ? 0.05 : 0.5, @@ -3719,6 +3741,9 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d ); } assert.equal(bikeCamera.listenerCount('changed'), 0); + assert.equal(trafficCamera.listenerCount('changed'), 0); + assert.equal(trafficCamera.listenerCount('moveEnd'), 0); + assert.equal(trafficFrames.size, 0); } } finally { for (const layer of Object.values(layers)) layer.disable(app.viewer); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 22d400f52..636c8baae 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -28,7 +28,6 @@ "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", - "src/layers/traffic/lifecycle.js", "src/layers/traffic/rendering.js", "src/layers/transit/rendering.js", "src/layers/weather/shellRendering.js",