Wait for drawn street traffic frames through the frame port

Road surface refinement and the development timing marks now listen for
drawn frames on the renderer's frame port instead of the scene's own
postRender event. Refinement reads the drawn frame's surface readiness
directly, since frame-port listeners run before the rendered-frame
observer. The view-height estimate's globe and sample-height reads move
into the surface module, which stays on the Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-07 00:09:10 -08:00
1 parent 0933ff49ff
commit f0427fc63e
8 files changed
+251 -19

No files matched your search

+8 -4
View File
@@ -1,8 +1,9 @@
import { roadIdentity } from './retention.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { copyInto, distance, distanceSquared } from '../../geo/vector.js';
import { findCamera, findQuery } from '../../render/rendererOf.js';
import { findCamera, findFrame, findQuery } from '../../render/rendererOf.js';
import {
drawnSurfaceReady,
prepareRoadSurfaces,
roadHeightStations,
trafficSurfaceReady,
@@ -508,11 +509,14 @@ export function createFlow({ state: layerState, services, parts, source }) {
}
paint(true);
if (current()) layerState._surfacePending = prepared.pending.length;
// The frame port says when a frame has drawn, and so when the surface
// may have loaded the finer tiles a refinement waits for.
const frame = findFrame(layerState._viewer);
if (
current() &&
!preview &&
!label.includes('refined') &&
scene.postRender &&
frame &&
(!trafficSurfaceReady(scene) ||
prepared.pending.length ||
ready.some((road) => road.surfaceSettled === false))
@@ -524,12 +528,12 @@ export function createFlow({ state: layerState, services, parts, source }) {
if (layerState._surfaceRefineRemove === stop)
layerState._surfaceRefineRemove = null;
};
const remove = scene.postRender.addEventListener(() => {
const remove = frame.on('postRender', () => {
if (!current()) {
stop();
return;
}
if (!trafficSurfaceReady(scene)) return;
if (!drawnSurfaceReady(scene)) return;
stop();
// Revalidate only local samples taken at a coarser rendered LOD. This
// background upgrade never holds road acquisition or first paint.
+7 -12
View File
@@ -2,6 +2,7 @@ import { requestWithDeadline } from '../../sources/requestDeadline.js';
import { resolveRoadMode, ROAD_SOURCE_LABELS } from './roadModes.js';
import { phaseTiming } from '../../sources/phaseTiming.js';
import { RoadRequestError, roadRequestError } from './source.js';
import { loadedSurfaceHeight } from './surface.js';
import {
isUnavailableCapability,
sourceResponseError,
@@ -11,7 +12,6 @@ import {
TILE_CACHE_MAX_ENTRIES,
FAST_FETCH_ALTITUDE,
} from './policy.js';
import { heightsFor } from '../../queries/heights.js';
/** Retain complete parsed snapshots under both an LRU entry cap and a byte budget. */
export function cacheRoadSnapshot(
@@ -270,19 +270,14 @@ export function createIngestion({
layerState._viewHeightEstimate = 0;
const centerLat = (clamped.south + clamped.north) / 2;
const centerLon = (clamped.west + clamped.east) / 2;
const scene = layerState._viewer?.scene;
const location = { lon: centerLon, lat: centerLat };
let estimated = services.ground?.cachedGroundFloor?.(centerLat, centerLon);
// A miss is the local mesh still loading.
if (!Number.isFinite(estimated) && scene) {
estimated = scene.globe?.show
? heightsFor(scene).now(location, { against: 'terrain' })
: scene.sampleHeightSupported
? heightsFor(scene).now(location, {
exclude: [layerState._pointCollection],
})
: undefined;
}
if (!Number.isFinite(estimated))
estimated = loadedSurfaceHeight(
layerState._viewer?.scene,
{ lon: centerLon, lat: centerLat },
[layerState._pointCollection],
);
if (Number.isFinite(estimated) && Math.abs(estimated) <= 9000)
layerState._viewHeightEstimate = estimated;
+81
View File
@@ -452,3 +452,84 @@ test('partial coverage retries while coarse roads render, then stops after three
assert.equal(calls, initial * 4, 'initial load plus three bounded retries');
assert.ok(layer.getStats().count > 0);
});
test('an unready surface waits for drawn frames through the frame port, then refines once', async (t) => {
const listeners = new Set();
const frame = {
on(phase, cb) {
assert.equal(phase, 'postRender');
listeners.add(cb);
return () => listeners.delete(cb);
},
};
const { layer, viewer, tick } = setup(
t,
async (bounds) => roads(bounds),
undefined,
{ frame },
);
// The rendered-frame observer records on the scene's own postRender.
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);
await tick(400);
await tick(400);
assert.equal(listeners.size, 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.
viewer.scene.globe.tilesLoaded = true;
const before = samples;
drawn(2);
assert.equal(listeners.size, 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(samples, after);
layer.disable(viewer);
await tick(5000);
assert.equal(listeners.size, 0, 'late work cannot resubscribe');
});
test('disabling while a refinement waits drops its frame listener', async (t) => {
const listeners = new Set();
const frame = {
on(_phase, cb) {
listeners.add(cb);
return () => listeners.delete(cb);
},
};
const { layer, viewer, tick } = setup(
t,
async (bounds) => roads(bounds),
undefined,
{ frame },
);
viewer.scene.globe.tilesLoaded = false;
layer.enable(viewer);
await tick(400);
await tick(400);
assert.equal(listeners.size, 1);
layer.disable(viewer);
assert.equal(listeners.size, 0);
await tick(5000);
assert.equal(listeners.size, 0, 'late work cannot resubscribe');
});
+29
View File
@@ -65,6 +65,16 @@ function currentRenderedFrame(scene) {
: null;
}
/**
* Whether the frame being drawn has its surface loaded, read while it
* finishes (from a frame-port `postRender` listener). It answers what the
* rendered-frame observer is recording for this same frame, which a frame
* listener may run before.
*/
export function drawnSurfaceReady(scene) {
return surfaceTilesReady(scene);
}
/** Only a completed render of this camera can certify cached surface heights. */
export function trafficSurfaceReady(scene) {
return currentRenderedFrame(scene)?.ready === true;
@@ -137,6 +147,25 @@ export function roadHeightStations(coords) {
const validHeight = (height) =>
Number.isFinite(height) && Math.abs(height) <= 9000;
/**
* 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
* @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 })
: undefined;
}
/**
* Reuse the rendered depth buffer instead of drawing a new pick frustum per
* station. Iteration corrects the projection's height estimate. A depth hit
+27
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import * as C from 'cesium';
import {
detailBand,
loadedSurfaceHeight,
renderedRoadHeight,
prepareRoadSurfaces,
roadSurfaceChunks,
@@ -403,3 +404,29 @@ test('surface keys reuse identity without building arrays or strings on unchange
'readiness cannot recreate a subscription',
);
});
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 = {
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.ok(Math.abs(C.Math.toDegrees(seen[0].longitude) - at.lon) < 1e-12);
const tiles = {
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');
assert.equal(
loadedSurfaceHeight({ globe: { show: false } }, at, [dots]),
undefined,
);
assert.equal(loadedSurfaceHeight(undefined, at, [dots]), undefined);
});
+5 -3
View File
@@ -1,5 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import { findFrame } from '../../render/rendererOf.js';
import { roadSurfaceChunks } from './surface.js';
import { TRAFFIC_TIMING_ENABLED, DOT_HEIGHT_OFFSET } from './policy.js';
@@ -315,7 +316,7 @@ export function createTiming({ state: layerState, services, parts, source }) {
return trafficTimingPass(trace, pass, source);
}
/** Record the first Cesium postRender following a completed dot render. */
/** Record the first drawn frame following a completed dot render. */
function scheduleTrafficTimingPostRender(
state,
@@ -323,9 +324,10 @@ export function createTiming({ state: layerState, services, parts, source }) {
renderId,
renderMetrics,
) {
if (!layerState._viewer?.scene) return;
const frame = findFrame(layerState._viewer);
if (!frame) return;
let remove = null;
remove = layerState._viewer.scene.postRender.addEventListener(() => {
remove = frame.on('postRender', () => {
remove?.();
layerState._trafficTimingPostRenderRemovers?.delete(remove);
const visibleTime = performance.now();
+93
View File
@@ -0,0 +1,93 @@
// src/layers/traffic/timing.test.mjs — the development timing trace marks
// the first drawn frame after a dot render through the renderer's frame
// port.
import test from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { createTiming } from './timing.js';
function fakeFrame() {
const listeners = new Map();
return {
port: {
on(phase, cb) {
if (!listeners.has(phase)) listeners.set(phase, new Set());
listeners.get(phase).add(cb);
return () => listeners.get(phase).delete(cb);
},
},
count: (phase) => listeners.get(phase)?.size ?? 0,
fire: (phase) => {
for (const cb of [...(listeners.get(phase) ?? [])]) cb({ frame: 1 });
},
};
}
test('the next drawn frame after a render is marked and measured once', () => {
const viewer = { scene: {} };
const frame = fakeFrame();
const unbind = bindRenderer(viewer, { frame: frame.port });
const layerState = {
_viewer: viewer,
_trafficTimingSequence: 0,
_trafficTimingPostRenderRemovers: new Set(),
};
const timing = createTiming({
state: layerState,
services: {},
parts: {},
source: {},
});
performance.clearMarks();
performance.clearMeasures();
performance.mark('fam-camera');
performance.mark('fam-render-end');
const trace = {
pass: 'full',
trace: { id: 'trace-1', cameraChangeMark: 'fam-camera' },
};
try {
timing.scheduleTrafficTimingPostRender(trace, 'fam-render-end', 7, {
dots: 3,
});
assert.equal(frame.count('postRender'), 1);
assert.equal(layerState._trafficTimingPostRenderRemovers.size, 1);
frame.fire('postRender');
frame.fire('postRender');
const marks = performance
.getEntriesByType('mark')
.filter((m) => m.name.startsWith('traffic:trace-1:full:'));
assert.deepEqual(
marks.map((m) => m.name.split(':')[3]),
['next-post-render', 'first-visible-pixel'],
);
assert.equal(marks[0].detail.renderId, 7);
assert.ok(
performance
.getEntriesByName('traffic:render-to-post-render:full')
.some((m) => m.detail.renderId === 7),
);
assert.equal(frame.count('postRender'), 0, 'one frame, then gone');
assert.equal(layerState._trafficTimingPostRenderRemovers.size, 0);
} finally {
unbind();
performance.clearMarks();
performance.clearMeasures();
}
});
test('without a frame port nothing is scheduled', () => {
const layerState = {
_viewer: null,
_trafficTimingSequence: 0,
_trafficTimingPostRenderRemovers: new Set(),
};
const timing = createTiming({
state: layerState,
services: {},
parts: {},
source: {},
});
timing.scheduleTrafficTimingPostRender({}, 'none', 1, {});
assert.equal(layerState._trafficTimingPostRenderRemovers.size, 0);
});