Skip to content

3D engine that AI agents drive

Add idle sleep, offscreen pause and automatic compact HDR for live rendering (#2179)

Nguyen Xuan Anb95252222a97
diff --git a/changes/2179.md b/changes/2179.md
new file mode 100644
index 00000000..b55de67b
--- /dev/null
+++ b/changes/2179.md
@@ -0,0 +1 @@
+- Live loops sleep at zero draws when idle and pause offscreen, and an opaque HDR canvas stores its frame as `R11F_G11F_B10F`, 39.55 MB less at 1080p with 4 samples (#2179)
diff --git a/changes/2179.size.md b/changes/2179.size.md
new file mode 100644
index 00000000..91e5b343
--- /dev/null
+++ b/changes/2179.size.md
@@ -0,0 +1,9 @@
+- entry:core: about 330 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- entry:core+lazy: about 330 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- entry:runtime: about 640 bytes gzip for the shared idle-sleep, hidden-tab and offscreen governor, which takes over the runtime's own visibility code
+- scene:lit-box: about 320 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- scene:lit-box+lazy: about 320 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- scene:gltf-box: about 330 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- scene:gltf-box+lazy: about 330 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- scene:agent-scene: about 315 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
+- scene:agent-scene+lazy: about 315 bytes gzip for the 39.55 MB render-target cut at 1080p plus its device check and fallback
diff --git a/docs/runtime.md b/docs/runtime.md
index 9b349665..b8bd5e95 100644
--- a/docs/runtime.md
+++ b/docs/runtime.md
@@ -43,7 +43,11 @@ Two guards stop a slow frame from spiralling. A frame longer than `maximumFrameS
| `systems` | `[]` | System objects, in the order they run |
| `frame` | `context => ({ time })` | Returns the object passed to `target.render`. Move parts with `renderer.updateParts` here. |
| `pauseWhenHidden` | `true` | Stop frames while the tab is hidden |
-| `scheduler`, `clock`, `visibility` | browser | `{ request(callback), cancel(handle) }`, `() => milliseconds` and `{ hidden, subscribe(callback) }`, injected by tests and headless runs |
+| `pauseWhenOffscreen` | `true` | With `element`, stop frames while the canvas is scrolled out of view (an `IntersectionObserver`) |
+| `element` | none | The canvas or its container, watched for `pauseWhenOffscreen` |
+| `isIdle` | none | `context => boolean`, true when nothing changed: no system is moving anything and no temporal accumulation is converging. The loop then draws no frame and schedules none, so it costs no GPU and no CPU, until `wake()`. Without it the loop never sleeps, because a runtime cannot know whether its systems change the picture. |
+| `idleSleep` | `true` | `false` keeps drawing every frame even when `isIdle` says idle |
+| `scheduler`, `clock`, `visibility`, `observe` | browser | `{ request(callback), cancel(handle) }`, `() => milliseconds`, `{ hidden, subscribe(callback) }` and `(element, callback(onscreen)) => stop`, injected by tests and headless runs |
The first argument is any object with `render(frame)`, such as `CrucibleRenderer`.
@@ -51,6 +55,7 @@ The first argument is any object with `render(frame)`, such as `CrucibleRenderer
- `start()` initialises the systems once and schedules frames; a system whose `init` threw is initialised again by the next `start()`. `stop()` ends the loop and drops the partial step; systems stay initialised, so `start()` continues the same world.
- `pause()` and `resume()` hold and release the loop. The time spent paused is never simulated. A hidden tab pauses the same way and resumes when it shows again.
+- `wake()` draws the next frame after input or a state change when the loop sleeps because of `isIdle`; `sleeping` is true while it waits. Call it from your input handlers and whenever a system changes something. A frame that follows a sleep, a hidden tab or an offscreen pause starts with a zero time step, so the sleep is never simulated.
- `step(milliseconds)` runs one frame without a scheduler, for tests and for stepping while paused.
- `addSystem(system, index)`, `replaceSystem(name, system)`, `removeSystem(name)`, `getSystem(name)` and `systems` (the names, in order). A system added to a started runtime is initialised at once; a replaced or removed one is disposed.
- `dispose()` stops the loop and disposes every system in reverse order. The runtime cannot start again.
diff --git a/src/compact-color.js b/src/compact-color.js
index e5d9c755..0570de29 100644
--- a/src/compact-color.js
+++ b/src/compact-color.js
@@ -1,12 +1,26 @@
-// Opt-in addon (issue #287): stores the HDR frame and its multisample colour as R11F_G11F_B10F, 4 bytes a pixel instead of 8.
+// Stores the HDR frame and its multisample colour as R11F_G11F_B10F, 4 bytes a pixel instead of 8 (issues #287 and #2179).
// At 1920 x 1080 with 4 samples that is 39.55 MB less. The format has no alpha, drops negative values and keeps 6 or 5 mantissa
-// bits, so pictures differ from the default by a small amount (docs/guide.md). Without this addon the core keeps RGBA16F.
+// bits, so pictures differ from the default by a small amount (docs/guide.md). The renderer picks it by itself for an opaque
+// HDR canvas when the device allows it (canUseCompactColor); `compactColor: false` keeps RGBA16F, and a transparent canvas always does.
const COMPACT_FORMAT = 'R11F_G11F_B10F';
-function respecifyColorTargets(renderer) {
+/** True for an opaque HDR renderer whose device can store the format at the sample count in use. Never throws. */
+export function canUseCompactColor(renderer) {
+ if (!renderer.hdr || renderer.transparent || renderer.compactColor === false) return false;
+ try {
+ const context = renderer.context;
+ if (!(renderer.multisampleSamples > 0)) return true;
+ const supported = context.getInternalformatParameter(context.RENDERBUFFER, context[COMPACT_FORMAT], context.SAMPLES);
+ return Array.from(supported).includes(renderer.multisampleSamples);
+ } catch {
+ return false;
+ }
+}
+
+/** Respecifies the frame and multisample colour of freshly allocated targets. Throws when the device refuses the framebuffers. */
+export function respecifyColorTargets(renderer, width = renderer.canvas.width, height = renderer.canvas.height) {
const context = renderer.context;
if (!renderer.multisampleFramebuffer) return;
- const { width, height } = renderer.canvas;
context.bindRenderbuffer(context.RENDERBUFFER, renderer.multisampleColor);
context.renderbufferStorageMultisample(context.RENDERBUFFER, renderer.multisampleSamples, context[COMPACT_FORMAT], width, height);
context.bindTexture(context.TEXTURE_2D, renderer.frameTexture);
@@ -18,21 +32,17 @@ function respecifyColorTargets(renderer) {
context.bindFramebuffer(context.FRAMEBUFFER, null);
renderer.renderTargets.record('multisampleColor', { width, height, format: COMPACT_FORMAT, samples: renderer.multisampleSamples });
renderer.renderTargets.record('frameColor', { width, height, format: COMPACT_FORMAT });
+ renderer.colorFormat = COMPACT_FORMAT;
}
-/** Switches the frame and multisample colour to R11F_G11F_B10F. Needs `hdr: true` and an opaque canvas. Returns the renderer. */
+/** Switches the frame and multisample colour to R11F_G11F_B10F now and after every resize. Needs `hdr: true` and an opaque canvas. Returns the renderer. */
export function useCompactColor(renderer) {
if (!renderer.hdr || renderer.transparent) throw new Error('Compact colour needs hdr: true with negotiated HDR support and an opaque canvas, because it has no alpha.');
if (renderer.colorFormat === COMPACT_FORMAT) return renderer;
+ renderer.compactColor = true;
const context = renderer.context;
const supported = context.getInternalformatParameter(context.RENDERBUFFER, context[COMPACT_FORMAT], context.SAMPLES);
if (renderer.multisampleSamples > 0 && !Array.from(supported).includes(renderer.multisampleSamples)) throw new Error(`Compact colour does not support ${renderer.multisampleSamples} samples on this device.`);
- const allocateFrameTargets = renderer.allocateFrameTargets;
- renderer.allocateFrameTargets = function allocateCompactColorTargets(width, height) {
- allocateFrameTargets.call(this, width, height);
- respecifyColorTargets(this);
- };
- renderer.colorFormat = COMPACT_FORMAT;
respecifyColorTargets(renderer);
return renderer;
}
diff --git a/src/frame-governor.js b/src/frame-governor.js
new file mode 100644
index 00000000..cf18ca0f
--- /dev/null
+++ b/src/frame-governor.js
@@ -0,0 +1,165 @@
+// Resource governor for live web rendering (issue #2179). It owns one question: should the next frame be drawn at all?
+// A frame is drawn only while something changes. When the loop reports it is idle the governor stops asking the browser for
+// frames, so the page costs no GPU and no CPU, and it starts again on wake(). It also pauses while the tab is hidden and
+// while the canvas is scrolled out of view. The scheduler, visibility and observer are injected, so tests run it without a browser.
+
+function defaultScheduler() {
+ if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function') {
+ throw new TypeError('createFrameGovernor found no requestAnimationFrame. Pass options.scheduler as { request(callback), cancel(handle) }.');
+ }
+ return { request: callback => requestAnimationFrame(callback), cancel: handle => cancelAnimationFrame(handle) };
+}
+
+function defaultVisibility() {
+ if (typeof document === 'undefined') return { hidden: false, subscribe: () => () => {} };
+ return {
+ get hidden() { return document.hidden; },
+ subscribe(callback) {
+ document.addEventListener('visibilitychange', callback);
+ return () => document.removeEventListener('visibilitychange', callback);
+ },
+ };
+}
+
+/** Calls `callback(onscreen)` whenever the element enters or leaves the viewport. Returns a function that stops watching. */
+function defaultObserve(element, callback) {
+ if (typeof IntersectionObserver !== 'function') return () => {};
+ const observer = new IntersectionObserver(entries => {
+ const latest = entries[entries.length - 1];
+ if (latest) callback(latest.isIntersecting);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+}
+
+/**
+ * Decides when a live loop draws.
+ * - `draw(timestamp, resumed)` renders one frame; `resumed` is true when the frame follows a sleep, a pause or the start.
+ * - `isBusy()` says whether another frame is needed (animation playing, temporal accumulation still converging, input easing).
+ * Return false once the picture has settled and the governor sleeps until `wake()`.
+ * - `idleSleep: false` keeps drawing every frame, the old behaviour. Hidden tabs and offscreen canvases still pause.
+ * - `element` is watched with an IntersectionObserver; `pauseWhenOffscreen: false` skips that. `pauseWhenHidden: false` skips the tab check.
+ */
+export function createFrameGovernor(options) {
+ if (options === null || typeof options !== 'object' || typeof options.draw !== 'function') {
+ throw new TypeError('createFrameGovernor needs { draw(timestamp, resumed) }, such as createFrameGovernor({ draw, isBusy }).');
+ }
+ if (options.isBusy !== undefined && typeof options.isBusy !== 'function') {
+ throw new TypeError('createFrameGovernor isBusy must be a function () => boolean, or left out.');
+ }
+ for (const name of ['idleSleep', 'pauseWhenHidden', 'pauseWhenOffscreen']) {
+ if (options[name] !== undefined && typeof options[name] !== 'boolean') throw new TypeError(`createFrameGovernor ${name} must be a boolean, got ${String(options[name])}.`);
+ }
+ const { draw } = options;
+ const isBusy = options.isBusy ?? (() => false);
+ const idleSleep = options.idleSleep ?? true;
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
+ const pauseWhenOffscreen = options.pauseWhenOffscreen ?? true;
+ const scheduler = options.scheduler ?? defaultScheduler();
+ const visibility = options.visibility ?? defaultVisibility();
+ const observe = options.observe ?? defaultObserve;
+
+ let started = false;
+ let held = false;
+ let onscreen = true;
+ let handle = null;
+ let continuous = false;
+ let draws = 0;
+ let unsubscribeVisibility = null;
+ let unobserve = null;
+
+ const isPaused = () => held || (pauseWhenHidden && visibility.hidden === true) || (pauseWhenOffscreen && !onscreen);
+
+ function cancelFrame() {
+ if (handle === null) return;
+ scheduler.cancel(handle);
+ handle = null;
+ }
+
+ function tick(timestamp) {
+ handle = null;
+ if (!started || isPaused()) return;
+ const resumed = !continuous;
+ continuous = false;
+ draw(timestamp, resumed);
+ draws += 1;
+ if (!started || isPaused()) return;
+ if (!idleSleep || isBusy()) {
+ continuous = true;
+ schedule();
+ }
+ }
+
+ function schedule() {
+ if (started && handle === null && !isPaused()) handle = scheduler.request(tick);
+ }
+
+ function onStateChange() {
+ if (isPaused()) {
+ cancelFrame();
+ continuous = false;
+ return;
+ }
+ schedule();
+ }
+
+ const governor = {
+ /** Starts the loop and draws the first frame. Starting a started governor does nothing. */
+ start() {
+ if (started) return governor;
+ started = true;
+ continuous = false;
+ unsubscribeVisibility ??= visibility.subscribe(onStateChange);
+ if (pauseWhenOffscreen && options.element && unobserve === null) {
+ unobserve = observe(options.element, isOnscreen => {
+ onscreen = isOnscreen;
+ onStateChange();
+ });
+ }
+ schedule();
+ return governor;
+ },
+
+ /** Asks for one more frame after something changed: input, state, a resize. Does nothing while paused or already scheduled. */
+ wake() {
+ schedule();
+ return governor;
+ },
+
+ /** Holds the loop without ending it, for a manual pause. */
+ hold() {
+ held = true;
+ cancelFrame();
+ continuous = false;
+ return governor;
+ },
+
+ release() {
+ held = false;
+ schedule();
+ return governor;
+ },
+
+ stop() {
+ started = false;
+ cancelFrame();
+ continuous = false;
+ return governor;
+ },
+
+ dispose() {
+ governor.stop();
+ unsubscribeVisibility?.();
+ unsubscribeVisibility = null;
+ unobserve?.();
+ unobserve = null;
+ },
+
+ get running() { return started; },
+ get paused() { return started && isPaused(); },
+ /** True while started, unpaused and waiting for wake(): the state that costs nothing. */
+ get sleeping() { return started && !isPaused() && handle === null; },
+ get draws() { return draws; },
+ };
+ return governor;
+}
diff --git a/src/renderer.js b/src/renderer.js
index 70acdb48..e71d87bb 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -22,6 +22,7 @@ import { materialLayerState, materialLayerValue } from './material-layers.js';
import { MaterialSnapshot } from './material-snapshot.js';
import { wearUniformValues } from './material-wear.js';
import { fittedFogDensity } from './fog-fit.js';
+import { canUseCompactColor, respecifyColorTargets } from './compact-color.js';
import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';
import { fitWorldShadowView, resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';
import { MAX_MORPH_TARGETS, requireFeatureCode, deformationSupport, requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';
@@ -710,7 +711,7 @@ export function samplesForDensity(parts, canvas, pixelRatio, samples, denseSampl
}
export class CrucibleRenderer {
- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, denseSamples = null, hdr = false, depth = false, memoryBudgetMiB, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null, resolveCoplanar = false, reversedDepth = 'auto', exactFrames = false, deferProgramLink = false, deferEnvironmentPrefilter = false, background = null, maximumMemoryBudgetMiB } = {}) {
+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, denseSamples = null, hdr = false, compactColor = true, depth = false, memoryBudgetMiB, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null, resolveCoplanar = false, reversedDepth = 'auto', exactFrames = false, deferProgramLink = false, deferEnvironmentPrefilter = false, background = null, maximumMemoryBudgetMiB } = {}) {
this.background = background ? resolveBackground(background) : null;
this.canvas = canvas;
this.sceneParts = parts;
@@ -768,6 +769,7 @@ export class CrucibleRenderer {
this.lookSource = null;
this.selectViewTransform(viewTransform, look);
this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));
+ this.compactColor = compactColor !== false;
if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');
this.baseSamples = samples;
this.denseSamples = denseSamples;
@@ -2156,6 +2158,20 @@ export class CrucibleRenderer {
this.bloomWidth = Math.max(1, Math.ceil(width / 2));
this.bloomHeight = Math.max(1, Math.ceil(height / 2));
context.bindFramebuffer(context.FRAMEBUFFER, null);
+ this.chooseColorFormat(width, height);
+ }
+
+ // An opaque canvas never reads the frame's alpha, so the frame and multisample colour take 4 bytes a pixel instead of 8 (#2179).
+ // A device that refuses the compact framebuffers gets the RGBA16F targets back.
+ chooseColorFormat(width, height) {
+ this.colorFormat = this.hdr ? 'RGBA16F' : 'RGBA8';
+ if (!canUseCompactColor(this)) return;
+ try {
+ respecifyColorTargets(this, width, height);
+ } catch {
+ this.compactColor = false;
+ this.allocateFrameTargets(width, height);
+ }
}
// The prefilter and BRDF programs build while the other programs do, instead of after them.
diff --git a/src/runtime.js b/src/runtime.js
index 5a7d8fcd..44dbe1c7 100644
--- a/src/runtime.js
+++ b/src/runtime.js
@@ -4,6 +4,8 @@
// without real time. Systems (physics, input, animation, audio, game code) plug in through the interface in
// docs/runtime.md and can be added, replaced or left out.
+import { createFrameGovernor } from './frame-governor.js';
+
export const RUNTIME_MODES = Object.freeze(['fixed', 'variable', 'both']);
export const RUNTIME_LIMITS = Object.freeze({
@@ -47,31 +49,10 @@ function validateSystem(system, existingNames) {
}
}
-function defaultScheduler() {
- if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function') {
- throw new TypeError('createRuntime found no requestAnimationFrame. Pass options.scheduler as { request(callback), cancel(handle) }.');
- }
- return {
- request: callback => requestAnimationFrame(callback),
- cancel: handle => cancelAnimationFrame(handle),
- };
-}
-
function defaultClock() {
return () => performance.now();
}
-function defaultVisibility() {
- if (typeof document === 'undefined') return { hidden: false, subscribe: () => () => {} };
- return {
- get hidden() { return document.hidden; },
- subscribe(callback) {
- document.addEventListener('visibilitychange', callback);
- return () => document.removeEventListener('visibilitychange', callback);
- },
- };
-}
-
function validateOptions(target, options) {
if (target === null || typeof target !== 'object' || typeof target.render !== 'function') {
throw new TypeError('createRuntime needs a renderer as its first argument: an object with a render(frame) method, such as a CrucibleRenderer.');
@@ -93,7 +74,12 @@ function validateOptions(target, options) {
if (options.frame !== undefined && typeof options.frame !== 'function') {
throw new TypeError('createRuntime frame must be a function (context) => frame for target.render, or left out.');
}
- if (typeof (options.pauseWhenHidden ?? true) !== 'boolean') throw new TypeError('createRuntime pauseWhenHidden must be a boolean.');
+ for (const name of ['pauseWhenHidden', 'pauseWhenOffscreen', 'idleSleep']) {
+ if (typeof (options[name] ?? true) !== 'boolean') throw new TypeError(`createRuntime ${name} must be a boolean.`);
+ }
+ if (options.isIdle !== undefined && typeof options.isIdle !== 'function') {
+ throw new TypeError('createRuntime isIdle must be a function (context) => boolean that is true when nothing changed, or left out.');
+ }
const systems = options.systems ?? [];
if (!Array.isArray(systems)) throw new TypeError('createRuntime systems must be an array of system objects, in the order they run.');
return { mode, fixedStepSeconds, maximumFrameSeconds, maximumStepsPerFrame, systems };
@@ -102,10 +88,7 @@ function validateOptions(target, options) {
export function createRuntime(target, options = {}) {
const settings = validateOptions(target, options);
const { mode, fixedStepSeconds, maximumFrameSeconds, maximumStepsPerFrame } = settings;
- const scheduler = options.scheduler ?? defaultScheduler();
const now = options.clock ?? defaultClock();
- const visibility = options.visibility ?? defaultVisibility();
- const pauseWhenHidden = options.pauseWhenHidden ?? true;
const buildFrame = options.frame ?? (context => ({ time: context.elapsedSeconds }));
const usesFixed = mode !== 'variable';
const usesVariable = mode !== 'fixed';
@@ -119,12 +102,21 @@ export function createRuntime(target, options = {}) {
let running = false;
let manuallyPaused = false;
let disposed = false;
- let handle = null;
let lastTime = null;
let accumulator = 0;
- let unsubscribeVisibility = null;
-
- const isPaused = () => manuallyPaused || (pauseWhenHidden && visibility.hidden === true);
+ // Sleeping needs a signal that nothing changed: a runtime with systems cannot know that by itself, so it never sleeps
+ // unless options.isIdle says so (docs/runtime.md). Offscreen and hidden pauses need no signal and are on by default.
+ const governor = createFrameGovernor({
+ draw: renderFrame,
+ isBusy: () => options.isIdle === undefined || options.isIdle(context) !== true,
+ idleSleep: options.idleSleep ?? true,
+ pauseWhenHidden: options.pauseWhenHidden ?? true,
+ pauseWhenOffscreen: options.pauseWhenOffscreen ?? true,
+ element: options.element,
+ observe: options.observe,
+ scheduler: options.scheduler,
+ visibility: options.visibility,
+ });
function callHook(system, hook, ...args) {
if (!system[hook]) return;
@@ -148,16 +140,6 @@ export function createRuntime(target, options = {}) {
callHook(system, 'dispose');
}
- function cancelFrame() {
- if (handle === null) return;
- scheduler.cancel(handle);
- handle = null;
- }
-
- function scheduleFrame() {
- if (running && handle === null && !isPaused()) handle = scheduler.request(tick);
- }
-
function recordFrameTime(milliseconds) {
frameTimes.push(milliseconds);
if (frameTimes.length > RUNTIME_LIMITS.frameWindow) frameTimes.shift();
@@ -192,9 +174,8 @@ export function createRuntime(target, options = {}) {
context.alpha = mode === 'both' ? accumulator / fixedStepSeconds : 1;
}
- function tick() {
- handle = null;
- if (!running || isPaused()) return;
+ function renderFrame(timestamp, resumed) {
+ if (resumed) lastTime = null;
const frameStart = now();
const measuredMilliseconds = lastTime === null ? 0 : frameStart - lastTime;
// A clock that returns NaN once would otherwise turn the accumulator and elapsed time into NaN for good.
@@ -215,25 +196,15 @@ export function createRuntime(target, options = {}) {
stats.frames += 1;
stats.frameMilliseconds = elapsedMilliseconds;
if (stats.frames > 1) recordFrameTime(elapsedMilliseconds);
- scheduleFrame();
}
function stopLoop() {
running = false;
- cancelFrame();
+ governor.stop();
lastTime = null;
accumulator = 0;
}
- function onVisibilityChange() {
- if (isPaused()) {
- cancelFrame();
- return;
- }
- lastTime = null;
- scheduleFrame();
- }
-
function assertUsable(action) {
if (disposed) throw new Error(`Cannot ${action}: this runtime was disposed. Call createRuntime again.`);
}
@@ -241,7 +212,9 @@ export function createRuntime(target, options = {}) {
const runtime = {
get mode() { return mode; },
get running() { return running; },
- get paused() { return running && isPaused(); },
+ get paused() { return running && (manuallyPaused || governor.paused); },
+ /** True while the loop waits for wake() because options.isIdle reported nothing changed: zero draws, zero scheduled frames. */
+ get sleeping() { return running && governor.sleeping; },
get systems() { return systems.map(system => system.name); },
// Initialises the systems once, then schedules frames. Starting a running runtime does nothing.
@@ -256,8 +229,7 @@ export function createRuntime(target, options = {}) {
running = false;
throw error;
}
- unsubscribeVisibility ??= visibility.subscribe(onVisibilityChange);
- scheduleFrame();
+ governor.start();
return runtime;
},
@@ -270,7 +242,7 @@ export function createRuntime(target, options = {}) {
// Holds the loop without ending it. The time while paused is never simulated.
pause() {
manuallyPaused = true;
- cancelFrame();
+ governor.hold();
return runtime;
},
@@ -278,7 +250,14 @@ export function createRuntime(target, options = {}) {
assertUsable('resume');
manuallyPaused = false;
lastTime = null;
- scheduleFrame();
+ governor.release();
+ return runtime;
+ },
+
+ // Call after input or a state change that options.isIdle would now report as busy: it draws the next frame at once.
+ wake() {
+ assertUsable('wake');
+ governor.wake();
return runtime;
},
@@ -351,8 +330,7 @@ export function createRuntime(target, options = {}) {
dispose() {
if (disposed) return;
stopLoop();
- unsubscribeVisibility?.();
- unsubscribeVisibility = null;
+ governor.dispose();
disposed = true;
for (const system of [...systems].reverse()) disposeSystem(system);
systems.length = 0;
diff --git a/tests/frame-governor.test.js b/tests/frame-governor.test.js
new file mode 100644
index 00000000..36e42edb
--- /dev/null
+++ b/tests/frame-governor.test.js
@@ -0,0 +1,193 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createFrameGovernor } from '../src/frame-governor.js';
+import { createRuntime } from '../src/runtime.js';
+
+function createHarness(options = {}) {
+ let pending = null;
+ let nextHandle = 1;
+ const visibilityCallbacks = new Set();
+ const visibility = { hidden: false, subscribe: callback => { visibilityCallbacks.add(callback); return () => visibilityCallbacks.delete(callback); } };
+ let observerCallback = null;
+ let observerStopped = false;
+ const scheduler = {
+ request(callback) { pending = { callback, handle: nextHandle }; nextHandle += 1; return pending.handle; },
+ cancel(handle) { if (pending?.handle === handle) pending = null; },
+ };
+ const drawn = [];
+ const state = { busy: true };
+ const governor = createFrameGovernor({
+ draw: (timestamp, resumed) => drawn.push({ timestamp, resumed }),
+ isBusy: () => state.busy,
+ scheduler,
+ visibility,
+ element: options.element ?? {},
+ observe: (element, callback) => { observerCallback = callback; return () => { observerStopped = true; }; },
+ ...options.governor,
+ });
+ return {
+ governor, drawn, state, visibility,
+ pending: () => pending !== null,
+ frame(timestamp = 0) { const { callback } = pending; pending = null; callback(timestamp); },
+ setHidden(hidden) { visibility.hidden = hidden; for (const callback of visibilityCallbacks) callback(); },
+ setOnscreen(onscreen) { observerCallback(onscreen); },
+ observerStopped: () => observerStopped,
+ };
+}
+
+test('a busy loop keeps drawing and an idle loop schedules nothing', () => {
+ const harness = createHarness();
+ harness.governor.start();
+ harness.frame();
+ assert.equal(harness.pending(), true);
+ harness.state.busy = false;
+ harness.frame();
+ assert.equal(harness.pending(), false);
+ assert.equal(harness.governor.sleeping, true);
+ assert.equal(harness.governor.draws, 2);
+});
+
+test('wake draws one frame after sleep, marked as resumed, and sleeps again when still idle', () => {
+ const harness = createHarness();
+ harness.state.busy = false;
+ harness.governor.start();
+ harness.frame();
+ assert.equal(harness.pending(), false);
+ harness.governor.wake();
+ harness.governor.wake();
+ harness.frame(16);
+ assert.equal(harness.governor.draws, 2);
+ assert.deepEqual(harness.drawn.map(entry => entry.resumed), [true, true]);
+ assert.equal(harness.pending(), false);
+});
+
+test('a loop that stays busy is not marked as resumed after its first frame', () => {
+ const harness = createHarness();
+ harness.governor.start();
+ harness.frame();
+ harness.frame();
+ assert.deepEqual(harness.drawn.map(entry => entry.resumed), [true, false]);
+});
+
+test('idleSleep false never sleeps', () => {
+ const harness = createHarness({ governor: { idleSleep: false } });
+ harness.state.busy = false;
+ harness.governor.start();
+ harness.frame();
+ assert.equal(harness.pending(), true);
+});
+
+test('an offscreen canvas draws nothing and comes back with one frame when it scrolls into view', () => {
+ const harness = createHarness();
+ harness.governor.start();
+ harness.frame();
+ harness.setOnscreen(false);
+ assert.equal(harness.pending(), false);
+ assert.equal(harness.governor.paused, true);
+ harness.governor.wake();
+ assert.equal(harness.pending(), false);
+ harness.setOnscreen(true);
+ assert.equal(harness.pending(), true);
+ harness.frame();
+ assert.equal(harness.drawn.at(-1).resumed, true);
+});
+
+test('a hidden tab pauses and showing it resumes', () => {
+ const harness = createHarness();
+ harness.governor.start();
+ harness.setHidden(true);
+ assert.equal(harness.pending(), false);
+ harness.setHidden(false);
+ assert.equal(harness.pending(), true);
+});
+
+test('pauseWhenOffscreen false ignores the observer and pauseWhenHidden false ignores the tab', () => {
+ const offscreen = createHarness({ governor: { pauseWhenOffscreen: false } });
+ offscreen.governor.start();
+ assert.equal(offscreen.pending(), true);
+ const hidden = createHarness({ governor: { pauseWhenHidden: false } });
+ hidden.governor.start();
+ hidden.setHidden(true);
+ assert.equal(hidden.pending(), true);
+});
+
+test('hold and release, stop and dispose', () => {
+ const harness = createHarness();
+ harness.governor.start();
+ harness.governor.hold();
+ assert.equal(harness.pending(), false);
+ harness.governor.wake();
+ assert.equal(harness.pending(), false);
+ harness.governor.release();
+ assert.equal(harness.pending(), true);
+ harness.governor.dispose();
+ assert.equal(harness.pending(), false);
+ assert.equal(harness.observerStopped(), true);
+});
+
+test('options are validated with messages that say what to pass', () => {
+ assert.throws(() => createFrameGovernor({}), /needs \{ draw/);
+ assert.throws(() => createFrameGovernor({ draw() {}, isBusy: 1 }), /isBusy must be a function/);
+ assert.throws(() => createFrameGovernor({ draw() {}, idleSleep: 'no' }), /idleSleep must be a boolean/);
+});
+
+test('a runtime with isIdle sleeps at zero draws and wake() brings the next frame', () => {
+ let time = 0;
+ let pending = null;
+ let idle = false;
+ const rendered = [];
+ const runtime = createRuntime({ render: frame => rendered.push(frame) }, {
+ scheduler: { request(callback) { pending = callback; return 1; }, cancel() { pending = null; } },
+ clock: () => time,
+ visibility: { hidden: false, subscribe: () => () => {} },
+ isIdle: () => idle,
+ });
+ runtime.start();
+ time += 16;
+ pending();
+ assert.notEqual(pending, null);
+ idle = true;
+ time += 16;
+ const callback = pending;
+ pending = null;
+ callback();
+ assert.equal(pending, null);
+ assert.equal(runtime.sleeping, true);
+ assert.equal(rendered.length, 2);
+ idle = false;
+ runtime.wake();
+ assert.notEqual(pending, null);
+ assert.equal(runtime.sleeping, false);
+});
+
+test('a runtime without isIdle never sleeps', () => {
+ let pending = null;
+ const runtime = createRuntime({ render() {} }, {
+ scheduler: { request(callback) { pending = callback; return 1; }, cancel() { pending = null; } },
+ visibility: { hidden: false, subscribe: () => () => {} },
+ });
+ runtime.start();
+ const callback = pending;
+ pending = null;
+ callback();
+ assert.notEqual(pending, null);
+ assert.equal(runtime.sleeping, false);
+});
+
+test('a runtime pauses an offscreen element and rejects a bad isIdle', () => {
+ let notify = null;
+ let pending = null;
+ const runtime = createRuntime({ render() {} }, {
+ scheduler: { request(callback) { pending = callback; return 1; }, cancel() { pending = null; } },
+ visibility: { hidden: false, subscribe: () => () => {} },
+ element: {},
+ observe: (element, callback) => { notify = callback; return () => {}; },
+ });
+ runtime.start();
+ notify(false);
+ assert.equal(pending, null);
+ assert.equal(runtime.paused, true);
+ notify(true);
+ assert.notEqual(pending, null);
+ assert.throws(() => createRuntime({ render() {} }, { scheduler: { request() {}, cancel() {} }, isIdle: true }), /isIdle must be a function/);
+});
diff --git a/tests/render-target-memory.test.js b/tests/render-target-memory.test.js
index 0c2f5386..cad51e02 100644
--- a/tests/render-target-memory.test.js
+++ b/tests/render-target-memory.test.js
@@ -126,8 +126,10 @@ function supportingSamples(renderer, samples) {
renderer.context = new Proxy(base, { get: (target, name) => (name === 'getInternalformatParameter' ? () => samples : target[name]) });
}
-test('without the compact colour addon the frame and multisample colour stay RGBA16F', () => {
+test('compactColor false keeps the frame and multisample colour RGBA16F', () => {
const renderer = frameTargetRenderer(false);
+ renderer.compactColor = false;
+ supportingSamples(renderer, [4]);
renderer.allocateFrameTargets(1920, 1080);
const byName = Object.fromEntries(renderer.memoryReport().targets.map(target => [target.name, target]));
assert.equal(byName.multisampleColor.format, 'RGBA16F');
@@ -137,6 +139,7 @@ test('without the compact colour addon the frame and multisample colour stay RGB
test('compact colour halves the frame and multisample colour and keeps the other targets', () => {
const renderer = frameTargetRenderer(false);
renderer.canvas = { width: 1920, height: 1080 };
+ renderer.compactColor = false;
supportingSamples(renderer, [4, 8]);
renderer.allocateFrameTargets(1920, 1080);
const before = Object.fromEntries(renderer.memoryReport().targets.map(target => [target.name, target]));
@@ -156,3 +159,53 @@ test('compact colour needs HDR, an opaque canvas and a sample count the format s
supportingSamples(unsupported, [2]);
assert.throws(() => useCompactColor(unsupported), /does not support 4 samples/);
});
+
+function byTargetName(renderer) {
+ return Object.fromEntries(renderer.memoryReport().targets.map(target => [target.name, target]));
+}
+
+test('an opaque HDR canvas takes compact colour by itself and saves 39.55 MB at 1080p with 4 samples', () => {
+ const legacy = frameTargetRenderer(false);
+ legacy.compactColor = false;
+ legacy.allocateFrameTargets(1920, 1080);
+ const automatic = frameTargetRenderer(false);
+ supportingSamples(automatic, [4, 8]);
+ automatic.allocateFrameTargets(1920, 1080);
+ const saved = legacy.memoryReport().totalBytes - automatic.memoryReport().totalBytes;
+ assert.equal(Number((saved / BYTES_PER_MEGABYTE).toFixed(2)), 39.55);
+ assert.equal(byTargetName(automatic).multisampleColor.format, 'R11F_G11F_B10F');
+ assert.equal(automatic.colorFormat, 'R11F_G11F_B10F');
+});
+
+test('a transparent canvas, a device without the format and a non-HDR canvas keep their old colour format', () => {
+ const transparent = frameTargetRenderer(false);
+ transparent.transparent = true;
+ supportingSamples(transparent, [4]);
+ transparent.allocateFrameTargets(64, 64);
+ assert.equal(byTargetName(transparent).frameColor.format, 'RGBA16F');
+ const unsupported = frameTargetRenderer(false);
+ supportingSamples(unsupported, [2]);
+ unsupported.allocateFrameTargets(64, 64);
+ assert.equal(byTargetName(unsupported).frameColor.format, 'RGBA16F');
+ const standard = frameTargetRenderer(false);
+ standard.hdr = false;
+ supportingSamples(standard, [4]);
+ standard.allocateFrameTargets(64, 64);
+ assert.equal(byTargetName(standard).frameColor.format, 'RGBA8');
+});
+
+test('a device that refuses the compact framebuffer gets the RGBA16F targets back', () => {
+ const renderer = frameTargetRenderer(false);
+ const base = renderer.context;
+ let statusChecks = 0;
+ renderer.context = new Proxy(base, { get(target, name) {
+ if (name === 'getInternalformatParameter') return () => [4];
+ // The first allocation checks the multisample and resolve framebuffers; the compact respecify then checks them again and fails.
+ if (name === 'checkFramebufferStatus') return () => { statusChecks += 1; return statusChecks <= 2 || renderer.compactColor === false ? target.FRAMEBUFFER_COMPLETE : 0; };
+ return target[name];
+ } });
+ renderer.allocateFrameTargets(64, 64);
+ assert.equal(renderer.compactColor, false);
+ assert.equal(renderer.colorFormat, 'RGBA16F');
+ assert.equal(byTargetName(renderer).frameColor.format, 'RGBA16F');
+});