A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a game can draw only the frames that can look different
yhhd17b6b22f354
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b5d44b23c..541ef089b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Drawing only the frames that can look different.** `quality.renderOnDemand` (off unless a game turns it on): a still screen costs the game's logic and nothing else. A frame is drawn when the player did something (a key, a button, a finger, the pointer moved), the surface changed size, entities were created or destroyed, shaders are still compiling, or the game asked (`app.pipeline.demand.request()`), and for `renderOnDemandTail` frames (30) after the last of those; `demand.hold()` keeps every frame drawn while a tween, a video or an animation the engine cannot see move is playing. On the UI template a still screen made 11,600 draw calls in 3 seconds before and none with this on, and a click drew again at once. What the engine does not see is a script changing a value or an animation playing, which is what `request` and `hold` are for.- **Shaders that compile without stopping the frame.** `quality.asyncShaderCompile` (off unless a game turns it on): a draw whose shader the browser is still compiling is left out until it is ready, and every shader asked for in the meantime compiles at once, where before each was waited for in turn. On a first visit the Terrain & Water example's shaders took 43 seconds of a frozen page on Chrome and D3D11 (the heavy lit ones 3 to 10 seconds each, the worst frame 10 seconds); with this on the page was blocked for about a second in all and the whole scene was drawn at 20 seconds, not 56. The same scene, once everything has compiled, is the same picture. `renderer_getPendingShaders()` says how many are still compiling, for a loading screen. Off, nothing changes. WebGL2 only (a WebGPU pipeline is not compiled this way). With `quality.prewarmShaders` (and `prewarmTimeoutMs`, default 30 s) a packaged game draws its first scene out of sight behind the loading screen until nothing is compiling, and opens complete; `warmShaders(app)` does the same from code, `shadersCompiled(module)` waits for the queue, and a scene prepared ahead (`readyRenderPrograms`) now claims its programs ready only once they have compiled. The lit shaders also link about 23% faster on a first visit: a light that comes from the tiles no longer carries a second copy of the shadow lookup in the program.- **A depth prepass for the opaque scene.** A quality level can draw the opaque meshes twice, depth alone first, so a pixel is shaded for the surface that is in front of it and not for every one drawn there on the way: `QualityProfile.depthPrepass` (on for `high` and `medium`, off for `low` and with the quality system off), and `renderer_setDepthPrepass` for a host without one. Cut-out leaves take part, with the coverage their own shader writes. A surface whose material bends its vertices with a hook takes part too, unless it is also a cut-out. On the Terrain & Water example, on an RTX 3060, a frame is 4 to 39 ms shorter, most where trees stand thick.- **A third mesh for a plant.** A part of a world's plants can name `lod2Mesh` and its kind `lod2Distance`: past that distance the third mesh stands in for the cheaper one, until the kind stops being drawn as itself. The Terrain & Water example's trees have one (a tenth of the triangles, made by `tools/plant-lod2.mjs`) from 80 m, which takes 9 to 15 ms off a frame on an RTX 3060 where trees stand between 60 and 170 m. `tools/terrain-water-cost.mjs` measures what each part of that example costs a frame headless, and `docs/TERRAIN_WATER_GPU_COST.md` has the numbers.diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 5a20eb360..066556f00 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -969,6 +969,8 @@ async function boot(): Promise<void> {console.warn('[game] shader warm-up failed', error);}}+ // After the warm-up above: its frames exist to be drawn.+ if (cfg.quality?.renderOnDemand) app.pipeline?.demand.enable({ tailFrames: cfg.quality.renderOnDemandTail });// Before run(), not after: run() may hand control to the emscripten loop and// never return, and the fade is what the first frames should arrive through.splash?.reach('ready');diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 876549652..b2a36d48d 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1872 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1874 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -7630,6 +7630,8 @@ mode: QualityMode | undefinedprewarmShaders: boolean | undefinedprewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined+renderOnDemand: boolean | undefined+renderOnDemandTail: number | undefinedtargetFps: number | undefined```@@ -7897,6 +7899,24 @@ static prototype: RemovedQueryInstance<any>'webgl2' | 'webgpu' | 'auto'```+## RenderDemand — class @experimental+```+disable: () => void+enable: (options?: RenderOnDemandOptions) => void+enabled: boolean+hold: () => () => void+request: () => void+shouldRender: (probe: RenderDemandProbe) => boolean+stats: { drawn: number; skipped: number; }+static new (): RenderDemand+static prototype: RenderDemand+```++## RenderOnDemandOptions — interface @experimental+```+tailFrames: number | undefined+```+## RenderOriginState — interface @experimental```step: number@@ -7922,6 +7942,7 @@ addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: FladdScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => voidbeginFrame: (elapsedSec?: number) => voidbeginScreenCapture: () => void+demand: RenderDemandendFrame: () => voidendScreenCapture: () => voidframeElapsed: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 0b0ddf2ad..b6624bdc7 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 1891 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1893 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -7833,6 +7833,8 @@ mode: QualityMode | undefinedprewarmShaders: boolean | undefinedprewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined+renderOnDemand: boolean | undefined+renderOnDemandTail: number | undefinedtargetFps: number | undefined```@@ -8110,6 +8112,24 @@ static prototype: RemovedQueryInstance<any>'webgl2' | 'webgpu' | 'auto'```+## RenderDemand — class @experimental+```+disable: () => void+enable: (options?: RenderOnDemandOptions) => void+enabled: boolean+hold: () => () => void+request: () => void+shouldRender: (probe: RenderDemandProbe) => boolean+stats: { drawn: number; skipped: number; }+static new (): RenderDemand+static prototype: RenderDemand+```++## RenderOnDemandOptions — interface @experimental+```+tailFrames: number | undefined+```+## RenderOriginState — interface @experimental```step: number@@ -8135,6 +8155,7 @@ addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: FladdScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => voidbeginFrame: (elapsedSec?: number) => voidbeginScreenCapture: () => void+demand: RenderDemandendFrame: () => voidendScreenCapture: () => voidframeElapsed: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 508775ca6..84c5b5c0d 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1871 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1873 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7625,6 +7625,8 @@ mode: QualityMode | undefinedprewarmShaders: boolean | undefinedprewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined+renderOnDemand: boolean | undefined+renderOnDemandTail: number | undefinedtargetFps: number | undefined```@@ -7892,6 +7894,24 @@ static prototype: RemovedQueryInstance<any>'webgl2' | 'webgpu' | 'auto'```+## RenderDemand — class @experimental+```+disable: () => void+enable: (options?: RenderOnDemandOptions) => void+enabled: boolean+hold: () => () => void+request: () => void+shouldRender: (probe: RenderDemandProbe) => boolean+stats: { drawn: number; skipped: number; }+static new (): RenderDemand+static prototype: RenderDemand+```++## RenderOnDemandOptions — interface @experimental+```+tailFrames: number | undefined+```+## RenderOriginState — interface @experimental```step: number@@ -7917,6 +7937,7 @@ addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: FladdScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => voidbeginFrame: (elapsedSec?: number) => voidbeginScreenCapture: () => void+demand: RenderDemandendFrame: () => voidendScreenCapture: () => voidframeElapsed: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 9f92cf3e5..7a1968eba 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1893 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1895 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7918,6 +7918,8 @@ mode: QualityMode | undefinedprewarmShaders: boolean | undefinedprewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined+renderOnDemand: boolean | undefined+renderOnDemandTail: number | undefinedtargetFps: number | undefined```@@ -8185,6 +8187,24 @@ static prototype: RemovedQueryInstance<any>'webgl2' | 'webgpu' | 'auto'```+## RenderDemand — class @experimental+```+disable: () => void+enable: (options?: RenderOnDemandOptions) => void+enabled: boolean+hold: () => () => void+request: () => void+shouldRender: (probe: RenderDemandProbe) => boolean+stats: { drawn: number; skipped: number; }+static new (): RenderDemand+static prototype: RenderDemand+```++## RenderOnDemandOptions — interface @experimental+```+tailFrames: number | undefined+```+## RenderOriginState — interface @experimental```step: number@@ -8210,6 +8230,7 @@ addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: FladdScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => voidbeginFrame: (elapsedSec?: number) => voidbeginScreenCapture: () => void+demand: RenderDemandendFrame: () => voidendScreenCapture: () => voidframeElapsed: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 7a29b70b2..cd0bc2fe7 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1884 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1886 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7632,6 +7632,8 @@ mode: QualityMode | undefinedprewarmShaders: boolean | undefinedprewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined+renderOnDemand: boolean | undefined+renderOnDemandTail: number | undefinedtargetFps: number | undefined```@@ -7899,6 +7901,24 @@ static prototype: RemovedQueryInstance<any>'webgl2' | 'webgpu' | 'auto'```+## RenderDemand — class @experimental+```+disable: () => void+enable: (options?: RenderOnDemandOptions) => void+enabled: boolean+hold: () => () => void+request: () => void+shouldRender: (probe: RenderDemandProbe) => boolean+stats: { drawn: number; skipped: number; }+static new (): RenderDemand+static prototype: RenderDemand+```++## RenderOnDemandOptions — interface @experimental+```+tailFrames: number | undefined+```+## RenderOriginState — interface @experimental```step: number@@ -7924,6 +7944,7 @@ addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: FladdScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => voidbeginFrame: (elapsedSec?: number) => voidbeginScreenCapture: () => void+demand: RenderDemandendFrame: () => voidendScreenCapture: () => voidframeElapsed: numberdiff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.tsindex 10dd57726..3fac5aed9 100644--- a/sdk/src/camera/CameraPlugin.ts+++ b/sdk/src/camera/CameraPlugin.ts@@ -30,6 +30,8 @@ import { ScreenScaling, DEFAULT_SCREEN_SCALING, SCREEN_FIT_OFF } from './ScreenSimport { planPresent, viewportPixels, RenderResolution } from './presentPlan';import { CameraDirector, createDirectorState, resolveMainPOV } from './CameraDirector';import { RenderPipeline } from '../render/renderPipeline';+import { Input } from '../input/input';+import { pendingShaders } from '../render/shaderWarmup';import { renderTargetSize } from '../render/renderTexture';import { Renderer } from '../render/renderer';import { followRenderOrigin, pushRenderOrigin, renderOrigin } from '../render/renderOrigin';@@ -849,6 +851,13 @@ export function cameraPlugin(if (!pipeline.renderingEnabled) return;const { width, height } = viewport();if (width === 0 || height === 0) return;+ // A game that asked for only the frames that can look different leaves the others out: the screen keeps the last picture.+ if (pipeline.demand.enabled && !pipeline.demand.shouldRender({+ width, height,+ worldVersion: app.world.getWorldVersion(),+ pendingShaders: pendingShaders(module),+ input: app.hasResource(Input) ? app.getResource(Input) : null,+ })) return;const canvasEntity = canvasEntityOf(module, cppRegistry);let clearColor: { x: number; y: number; z: number; w: number } | undefined;if (canvasEntity >= 0) {diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex c434d39b4..66762a8a8 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -342,4 +342,6 @@ export type {} from './render/quality';export { Quality } from './render/qualityRuntime';export { warmShaders, shadersCompiled, pendingShaders } from './render/shaderWarmup';+export { RenderDemand } from './render/renderDemand';+export type { RenderOnDemandOptions } from './render/renderDemand';export type { ShaderWarmup, ShaderWarmupOptions } from './render/shaderWarmup';diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.tsindex fdd8ecf81..dc21fd93a 100644--- a/sdk/src/render/quality.ts+++ b/sdk/src/render/quality.ts@@ -85,6 +85,13 @@ export interface QualityConfig {* complete instead of filling in (see `warmShaders`). The wait is bounded by `prewarmTimeoutMs`.*/prewarmShaders?: boolean;+ /**+ * Draw only the frames that can look different (see `RenderDemand`): a still screen costs the game's logic and nothing else. Off unless a game+ * turns it on, because what the engine cannot see change (a script setting a colour, an animation) has to be said with `request` or `hold`.+ */+ renderOnDemand?: boolean;+ /** Frames still drawn after the last reason to draw. Default 30. */+ renderOnDemandTail?: number;/** The longest the loading screen waits for the shaders. Default 30000. */prewarmTimeoutMs?: number;profiles?: Partial<Record<QualityLevel, Partial<QualityProfile>>>;@@ -141,6 +148,8 @@ export function parseQualityConfig(value: unknown): QualityConfig {dynamicResolution: raw.dynamicResolution === true,asyncShaderCompile: raw.asyncShaderCompile === true,prewarmShaders: raw.prewarmShaders === true,+ renderOnDemand: raw.renderOnDemand === true,+ renderOnDemandTail: finite(raw.renderOnDemandTail, 30, 1, 600),prewarmTimeoutMs: finite(raw.prewarmTimeoutMs, 30000, 1000, 600000),};if (raw.profiles) {diff --git a/sdk/src/render/renderDemand.ts b/sdk/src/render/renderDemand.tsnew file mode 100644index 000000000..6e1c97399--- /dev/null+++ b/sdk/src/render/renderDemand.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file renderDemand.ts+ * @brief Drawing only the frames that can look different: a still screen costs the game's logic and nothing else.+ *+ * A card table, a puzzle between moves, a menu: for most of a session such a game's picture does not change, and the GPU draws it sixty times a+ * second anyway, which is the heat and the battery. With render-on-demand on, a frame is drawn when+ * - something asked for it ({@link RenderDemand.request}) or is holding the screen live ({@link RenderDemand.hold}: a tween, a video, a+ * particle burst, anything the engine cannot see move on its own);+ * - the player did something (a key, a button, a finger, the pointer moved, the wheel turned);+ * - the surface changed size, or entities were created or destroyed;+ * - shaders are still compiling in the background, which leaves draws out until they are ready.+ * and for `tailFrames` frames after the last of those, so what settles over a few frames (an exposure adapting, a blend finishing) does.+ *+ * What the engine does NOT see is a component's value changing by script or an animation playing: those are what `request` and `hold` are for.+ * That is why this is opt-in; a game that turns it on states which of its screens are still.+ */+import type { InputState } from '../input/input';++/** @experimental */+export interface RenderOnDemandOptions {+ /** Frames still drawn after the last reason to draw. Default 30: a half second, enough for an exposure or a fade to settle. */+ tailFrames?: number;+}++/** What one frame is asked about. */+export interface RenderDemandProbe {+ width: number;+ height: number;+ /** The world's structural version (entities and components added or removed). */+ worldVersion: number;+ /** Shaders still compiling in the background. */+ pendingShaders: number;+ input: InputState | null;+}++/** Everything about the player's hands that can show in a picture, folded into one number that changes when any of it does. */+export function inputSignature(input: InputState): number {+ let h = 17;+ const mix = (v: number): void => { h = (Math.imul(h, 31) + (v | 0) + ((v * 1024) | 0)) | 0; };+ mix(input.mouseX); mix(input.mouseY);+ mix(input.scrollDeltaX); mix(input.scrollDeltaY);+ mix(input.keysDown.size); mix(input.keysPressed.size); mix(input.keysReleased.size);+ mix(input.mouseButtons.size); mix(input.mouseButtonsPressed.size); mix(input.mouseButtonsReleased.size);+ mix(input.touches.size); mix(input.touchesStarted.size); mix(input.touchesEnded.size);+ for (const touch of input.touches.values()) { mix(touch.x); mix(touch.y); }+ return h;+}++/** @experimental */+export class RenderDemand {+ private enabled_ = false;+ private tailFrames_ = 30;+ private remaining_ = 0;+ private requested_ = false;+ private holds_ = 0;+ private lastWidth_ = -1;+ private lastHeight_ = -1;+ private lastWorldVersion_ = -1;+ private lastInput_ = 0;+ private drawn_ = 0;+ private skipped_ = 0;++ get enabled(): boolean { return this.enabled_; }+ /** Frames drawn and frames left out since this was turned on. */+ get stats(): { drawn: number; skipped: number } { return { drawn: this.drawn_, skipped: this.skipped_ }; }++ enable(options: RenderOnDemandOptions = {}): void {+ this.enabled_ = true;+ this.tailFrames_ = Math.max(1, Math.floor(options.tailFrames ?? 30));+ this.remaining_ = this.tailFrames_;+ this.drawn_ = this.skipped_ = 0;+ }++ disable(): void {+ this.enabled_ = false;+ }++ /** Draw the next frame (and the tail after it): something changed that the engine could not see. */+ request(): void {+ this.requested_ = true;+ }++ /**+ * Draw every frame until the returned function is called: for what moves on its own (a tween, a video, an animation). Holds add up, so two+ * owners do not release each other's.+ */+ hold(): () => void {+ ++this.holds_;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.holds_ = Math.max(0, this.holds_ - 1);+ this.requested_ = true;+ };+ }++ /** Asked once per frame, by the frame that would draw. False leaves the frame out; the screen keeps the last picture. */+ shouldRender(probe: RenderDemandProbe): boolean {+ if (!this.enabled_) return true;+ let reason = this.requested_ || this.holds_ > 0 || probe.pendingShaders > 0;+ this.requested_ = false;+ if (probe.width !== this.lastWidth_ || probe.height !== this.lastHeight_) reason = true;+ if (probe.worldVersion !== this.lastWorldVersion_) reason = true;+ if (probe.input) {+ // A held key, button or finger is a player steering something the engine cannot see move: it draws for as long as it is down.+ if (probe.input.keysDown.size > 0 || probe.input.mouseButtons.size > 0 || probe.input.touches.size > 0) reason = true;+ const signature = inputSignature(probe.input);+ if (signature !== this.lastInput_) reason = true;+ this.lastInput_ = signature;+ }+ this.lastWidth_ = probe.width;+ this.lastHeight_ = probe.height;+ this.lastWorldVersion_ = probe.worldVersion;+ if (reason) this.remaining_ = this.tailFrames_;+ else if (this.remaining_ > 0) --this.remaining_;+ else {+ ++this.skipped_;+ return false;+ }+ ++this.drawn_;+ return true;+ }+}diff --git a/sdk/src/render/renderPipeline.ts b/sdk/src/render/renderPipeline.tsindex 9b2593ebd..e5a32064d 100644--- a/sdk/src/render/renderPipeline.ts+++ b/sdk/src/render/renderPipeline.ts@@ -20,6 +20,7 @@ import {import { log } from '../util/logger';import { planPresent, RenderResolution } from '../camera/presentPlan';import type { QualityController } from './quality';+import { RenderDemand } from './renderDemand';export interface Viewport {x: number;@@ -69,6 +70,8 @@ export class RenderPipeline {private frameElapsed_ = 0;get frameElapsed(): number { return this.frameElapsed_; }private renderingEnabled_ = true;+ /** Which frames are drawn, when the game has asked for only those that can look different. */+ readonly demand = new RenderDemand();private lastWidth_ = 0;private lastHeight_ = 0;private activeScenes_: Set<string> | null = null;diff --git a/sdk/tests/render-demand.test.ts b/sdk/tests/render-demand.test.tsnew file mode 100644index 000000000..3b77849b1--- /dev/null+++ b/sdk/tests/render-demand.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { InputState } from '../src/input/input';+import { RenderDemand, type RenderDemandProbe } from '../src/render/renderDemand';+import { parseQualityConfig } from '../src/render/quality';++const still = (input: InputState | null = null): RenderDemandProbe =>+ ({ width: 800, height: 600, worldVersion: 1, pendingShaders: 0, input });++/** How many of `frames` frames are drawn while `probe` describes each one. */+function drawn(demand: RenderDemand, frames: number, probe: () => RenderDemandProbe): number {+ let n = 0;+ for (let i = 0; i < frames; i++) if (demand.shouldRender(probe())) ++n;+ return n;+}++describe('render on demand', () => {+ it('draws every frame while off', () => {+ const demand = new RenderDemand();+ expect(drawn(demand, 50, () => still())).toBe(50);+ });++ it('settles to nothing on a still screen, after the tail', () => {+ const demand = new RenderDemand();+ demand.enable({ tailFrames: 5 });+ // The first frame sees a size and a world it has not seen, then the tail, then silence.+ expect(drawn(demand, 100, () => still())).toBe(1 + 5);+ expect(demand.stats.skipped).toBe(94);+ });++ it('draws again for a request, a hold, a resize, a new entity and pending shaders', () => {+ const demand = new RenderDemand();+ demand.enable({ tailFrames: 2 });+ drawn(demand, 20, () => still());+ demand.request();+ expect(drawn(demand, 20, () => still())).toBe(1 + 2);+ const release = demand.hold();+ expect(drawn(demand, 10, () => still())).toBe(10);+ release();+ expect(drawn(demand, 20, () => still())).toBe(1 + 2);+ expect(drawn(demand, 20, (() => { let w = 801; return () => ({ ...still(), width: w++ }); })())).toBe(20);+ drawn(demand, 10, () => still());+ expect(demand.shouldRender({ ...still(), worldVersion: 2 })).toBe(true);+ drawn(demand, 10, () => ({ ...still(), worldVersion: 2 }));+ expect(drawn(demand, 5, () => ({ ...still(), worldVersion: 2, pendingShaders: 3 }))).toBe(5);+ });++ it('holds add up: one owner cannot release another', () => {+ const demand = new RenderDemand();+ demand.enable({ tailFrames: 1 });+ const a = demand.hold();+ const b = demand.hold();+ a(); a();+ expect(drawn(demand, 10, () => still())).toBe(10);+ b();+ expect(drawn(demand, 10, () => still())).toBe(1 + 1);+ });++ it('draws for the player: pointer moves, edges, and anything held down', () => {+ const demand = new RenderDemand();+ demand.enable({ tailFrames: 1 });+ const input = new InputState();+ drawn(demand, 10, () => still(input));+ input.mouseX = 40;+ expect(demand.shouldRender(still(input))).toBe(true);+ drawn(demand, 5, () => still(input));+ input.noteMouseDown(0);+ // A button held is a player steering something the engine cannot see move.+ expect(drawn(demand, 10, () => still(input))).toBe(10);+ input.noteMouseUp(0);+ input.clearFrameState();+ expect(drawn(demand, 10, () => still(input))).toBeLessThanOrEqual(3);+ input.noteKeyDown('ArrowRight');+ expect(drawn(demand, 10, () => still(input))).toBe(10);+ input.noteKeyUp('ArrowRight');+ input.clearFrameState();+ drawn(demand, 10, () => still(input));+ expect(demand.shouldRender(still(input))).toBe(false);+ });++ it('is configured from the package quality config', () => {+ expect(parseQualityConfig({})?.renderOnDemand).toBeFalsy();+ const on = parseQualityConfig({ renderOnDemand: true, renderOnDemandTail: 12 });+ expect(on?.renderOnDemand).toBe(true);+ expect(on?.renderOnDemandTail).toBe(12);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ddaace080..6cba29816 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3000,4 +3000,6 @@ export const NOTED = {{"note":"Shaders that compile without stopping the frame."},"feat(render): a loading screen can wait for the shaders, and the lit programs link a quarter faster":{"note":"Shaders that compile without stopping the frame."},+ "feat(render): a game can draw only the frames that can look different":+ {"note":"Drawing only the frames that can look different."},};