Complete the Cesium frame port

The frame port now does everything the contract asks of it on Cesium:
preUpdate says whether the tick draws (Cesium's own render test, read
live until the tick is over), holds are counted per reason, and suspend,
target fps, renderNow and diagnostics are real. Releasing the last hold
asks for one more frame.

whenSettled also waits until Cesium stops redrawing on its own. Each
request or worker task Cesium completes queues a redraw (a terrain
picker build after the camera moved, say), which no loading flag shows,
so it now waits for quiet frames and then a short stretch in which the
loop draws nothing by itself. It is bounded by its timeout, names a
stopped loop, and ends on destroy.

The app renderer still leaves out the members that steer the loop:
the render governor and the page's visibility handling own those
settings until they move onto the port.

The new frame.prediction check compares the preUpdate answer with what
each tick drew.
This commit is contained in:
Sameh Khamis committed 2026-11-05 17:11:25 -08:00
1 parent 1a9bdd9b63
commit e6d22e55d7
11 files changed
+842 -55

No files matched your search

+128 -15
View File
@@ -15,6 +15,7 @@
* Members it does not have are absent, never stubbed.
*/
import * as Cesium from 'cesium';
import { onEngineWorkCompleted, renderPending } from './internals.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
export { toCartesian, toColor, toImage } from './ports.js';
@@ -114,26 +115,136 @@ export async function createCesiumSceneRenderer({
// --- Renderer --------------------------------------------------------------
let destroyed = false;
// Idle watches in progress; destroy ends them rather than leave them
// waiting on a scene that will not tick again.
const watching = new Set();
/** How long the loop must stay idle, drawing nothing, to be settled. */
const IDLE_MS = 100;
/** How long without a tick a loop counts as stopped. */
const STALL_MS = 250;
/**
* Watches the loop, without asking for frames, for at least two whole
* ticks and `IDLE_MS`. Resolves `'idle'` if in that time it drew nothing
* of its own accord and `busy()` stayed false; `'busy'` as soon as it did;
* `'ended'` if the renderer is destroyed or `end` passes first. A draw while a hold keeps
* the loop drawing every frame is the hold's, not the scene's own; `busy`
* is asked at each tick's start, before Cesium decides whether it draws.
* @param {number} end
* @param {() => boolean} busy Whether work landed that will draw again.
*/
function watchIdle(end, busy) {
return new Promise((resolve) => {
const from = performance.now();
let ticks = 0;
const offDraw = scene.postRender.addEventListener(() => {
if (scene.requestRenderMode) finish('busy');
});
// Each preUpdate also ends the tick before it.
const offTick = scene.preUpdate.addEventListener(() => {
if (busy()) return finish('busy');
ticks += 1;
if (ticks > 2 && performance.now() - from >= IDLE_MS) finish('idle');
});
const timer = setTimeout(
() => finish('ended'),
Math.max(0, end - performance.now()),
);
watching.add(finish);
function finish(outcome) {
watching.delete(finish);
offDraw();
offTick();
clearTimeout(timer);
resolve(outcome);
}
});
}
async function whenSettled({ timeoutMs = 20000 } = {}) {
const models = ports.modelSets;
const end = performance.now() + timeoutMs;
let quiet = 0;
while (performance.now() < end) {
await ports.nextPostRender();
if (models().some((r) => r.host.failed > 0))
return { state: 'failed', blockers: ['models'] };
// Cesium redraws on its own after each request or worker task it
// completes (a terrain picker build after the camera moved, say), which
// no loading flag shows; settled means that has stopped too. Every
// scene in the page redraws for any completion, so another scene's work
// keeps this one from settling: it is drawing.
let completed = 0;
// Whether the last look found the engine still at work.
let busy = false;
// When the loop last ticked: one that stopped (suspended, say) is named
// in a timeout, not one that merely ran out of time mid-frame.
let lastTick = performance.now();
const offTick = scene.preUpdate.addEventListener(
() => (lastTick = performance.now()),
);
const off = onEngineWorkCompleted(Cesium, () => (completed += 1));
try {
let quiet = 0;
while (performance.now() < end) {
completed = 0;
if (destroyed) return { state: 'failed', blockers: ['destroyed'] };
// Bounded by the time left: a suspended loop draws nothing.
const drawn = await ports
.nextPostRender({ timeoutMs: Math.max(0, end - performance.now()) })
.then(
() => true,
() => false,
);
if (destroyed) return { state: 'failed', blockers: ['destroyed'] };
if (!drawn) break;
if (models().some((r) => r.host.failed > 0))
return { state: 'failed', blockers: ['models'] };
const icons = ports.iconState();
if (icons === 'failed') return { state: 'failed', blockers: ['icons'] };
quiet = loaded() && !idleBlocked() ? quiet + 1 : 0;
if (quiet < 3) continue;
// Then the loop left alone must draw nothing by itself for a while:
// a worker's first task can take tens of milliseconds, and what is
// in flight cannot be counted. Something that starts loading
// meanwhile ends the watch too; the next pass sees it, or its
// failure.
const outcome = await watchIdle(end, () => !loaded() || idleBlocked());
if (outcome === 'idle') return { state: 'settled', blockers: [] };
if (outcome !== 'busy') break;
// Work or a draw, unless it was something loading.
busy = loaded();
quiet = 0;
}
if (destroyed) return { state: 'failed', blockers: ['destroyed'] };
const blockers = [];
if (!scene.globe.tilesLoaded) blockers.push('globe');
if (models().some((r) => r.host.loading > 0)) blockers.push('models');
if (ports.iconState() !== 'settled') blockers.push('icons');
if (busy) blockers.push('redraw');
if (performance.now() - lastTick >= STALL_MS) blockers.push('frames');
return { state: 'timeout', blockers };
} finally {
off();
offTick();
}
/** Whether what is in view has loaded, nothing failing. */
function loaded() {
const icons = ports.iconState();
if (icons === 'failed') return { state: 'failed', blockers: ['icons'] };
const loading =
models().some((r) => r.host.loading > 0) || icons === 'loading';
quiet = scene.globe.tilesLoaded && !loading ? quiet + 1 : 0;
if (quiet >= 3) return { state: 'settled', blockers: [] };
return (
scene.globe.tilesLoaded &&
icons === 'settled' &&
!models().some((r) => r.host.loading > 0 || r.host.failed > 0)
);
}
/**
* Work since the last look that will draw again, or a draw queued (one a
* hold makes anyway is the hold's).
*/
function idleBlocked() {
busy = completed > 0 || (scene.requestRenderMode && renderPending(scene));
completed = 0;
return busy;
}
const blockers = [];
if (!scene.globe.tilesLoaded) blockers.push('globe');
if (models().some((r) => r.host.loading > 0)) blockers.push('models');
if (ports.iconState() !== 'settled') blockers.push('icons');
return { state: 'timeout', blockers };
}
return {
@@ -155,6 +266,8 @@ export async function createCesiumSceneRenderer({
whenSettled,
resize: () => widget.resize(),
destroy() {
destroyed = true;
for (const finish of [...watching]) finish('ended');
ports.dispose();
widget.destroy();
},