Skip to content

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.

feat(bench): the frame a host with no JIT actually pays

yhhbd30aa878890
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8bc7bac9f..750948999 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,60 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **The no-JIT frame, measured — the number AOT was built for.** Every frame
+ number this engine had published came from a host with a JIT: V8 on the
+ desktop, Chromium on a phone. The plan's way to get the other one was a Mac
+ running JavaScriptCore with the JIT off, and after that an iPhone.
+
+ Neither is needed. The native host embeds QuickJS-ng, which has no JIT, and it
+ is the same host on iOS, Android and the desktop — one platform seam apart. So
+ the interpreter an iOS build ships is the interpreter a Windows build ships;
+ only the CPU differs. And since the AOT native road landed, that host
+ dispatches to compiled systems, so both halves of the comparison ship.
+
+ `bench/aot-native/frame-bench.mjs` exports one project twice from one tree
+ (`export` and `export --no-aot`, which compiles nothing at all), runs both
+ under the real host, and reads the host's own frame clock off each. At 5,000
+ entities, one system doing three multiply-adds costs **51 ms** interpreted —
+ 19 fps, missing 60 fps by 3.1x — and **1.7 ms** compiled, of which 1.5 ms is
+ everything else in the frame.
+
+ Three things the JIT numbers could not say. The no-JIT penalty on a real frame
+ is **61x** (9,907 ns/entity here against 162 on V8) where a bare loop in
+ Stage 0 said 154–385x. A **script component is 3.6x CHEAPER than an engine
+ one** on this host — the opposite sign from the web, because the SDK is given
+ the engine's heap as one ArrayBuffer while an engine component's address is a
+ QuickJS→C++ call per entity per frame. And a body that writes `position.z`
+ turns one draw call into 4,998, so most of its "compiled frame" is render: the
+ report carries a `draws` column because a cost that lands where the report
+ cannot see it reads as the system's.
+
+ **`--gate` makes it a release criterion**, because the failure this road can
+ have is silent. `AotDispatcher.run` returns whether it took the system, and
+ false sends it back to the interpreter — deliberately, the no-cliff rule — so a
+ regression that unbinds every system raises no error, refuses no module and
+ changes no pixel. It only costs time, and nothing was measuring time. Verified
+ in both directions: taking the `@compiled` marker off the body drops the ratio
+ from 15.2x to **1.01x** and the gate goes red.
+
+- **`WebGPUDevice::setPresentUncapped`** — a swapchain that does not wait for the
+ display. Off by default and a shipped game should leave it off; it exists so a
+ frame can be measured at all. Under Fifo every frame cheaper than the refresh
+ interval reads as exactly the refresh interval and every frame dearer than it
+ reads as a multiple of one: before this existed, the 51 ms frame above and the
+ 1.7 ms one read as "52 ms" and "16.5 ms" — a 30x difference quantised into a
+ 3x one. Best effort, from what the surface advertises: Mailbox, then Immediate,
+ then Fifo.
+
+- **`native/host/Bench.{hpp,cpp}`** — the host's own frame clock, driven by the
+ environment so nothing about a shipped game changes. It reports four spans, and
+ `update` is one of them only so that nobody mistakes it for the tick again:
+ `App.tick` is async, so the `update` call returns at its first await and is ~8 µs
+ of a 51 ms frame. The systems, and the render they drive, run in the microtask
+ drain after it.
+
## [0.58.0] - 2026-08-26
### Added
diff --git a/bench/aot-native/README.md b/bench/aot-native/README.md
new file mode 100644
index 000000000..01099d8ec
--- /dev/null
+++ b/bench/aot-native/README.md
@@ -0,0 +1,147 @@
+# The no-JIT frame — what a compiled system buys where there is no JIT
+
+`bench/aot-frame` measured this engine's frame twice: on V8 (desktop) and on a
+Snapdragon 8 Elite's Chromium. Both have a JIT. Its own README says what is missing:
+
+> **A no-JIT number, and that is the number AOT exists for.**
+
+The plan's proxy for it was a Mac running Bun/JavaScriptCore with the JIT switched off
+(`bench/README.md`), and beyond that an iPhone.
+
+**Neither is needed to get the number.** The native host embeds
+[QuickJS-ng](https://github.com/quickjs-ng/quickjs), which has no JIT — and it is *the
+same host on iOS, Android and the desktop*, one platform seam apart (`native/README.md`).
+So the JS engine an iOS build interprets with is the JS engine a Windows build
+interprets with. Only the CPU differs. And since the AOT native road landed, that host
+dispatches to compiled systems, so both halves of the comparison ship.
+
+This runs the real host, the real SDK and a real exported project, twice from one tree:
+
+```sh
+node bench/aot-native/frame-bench.mjs
+BENCH_ENTITIES=20000 BENCH_BODIES=thin,heavy,script BENCH_IDLE=1 node bench/aot-native/frame-bench.mjs
+```
+
+`estella export` gives the compiled build and `estella export --no-aot` gives the
+interpreted twin — `--no-aot` is `mode: 'dev'`, which compiles *nothing*, so the second
+build has no module to fall back from. The systems are copied from
+`bench/aot-frame/project/src/systems.ts`: one source for both benchmarks, so a ratio
+measured here and one measured there are about the same code. The scene is materialized
+per run, never committed — an entity count is a parameter, and a scene file per count is
+a file per parameter.
+
+Both runs print a checksum of every entity's position from the frame the timed run ends
+on, and a run where the two disagree fails. Two worlds that computed different things
+have no ratio between them.
+
+## Run it as a criterion
+
+```sh
+node bench/aot-native/frame-bench.mjs --gate
+```
+
+**The failure this exists for is silent.** `AotDispatcher.run` returns whether it took
+the system, and false sends it back to the interpreter for that frame — deliberately,
+the no-cliff rule. So a regression that unbinds every system raises no error, refuses no
+module and changes no pixel. It only costs time, and nothing was measuring time. A
+same-machine ratio sees it: an engine that stopped dispatching reads ~1x. A millisecond
+ceiling would not — one calibrated on this machine fails on slower ones and passes on
+faster ones regardless of the code.
+
+## What was measured (2026-08-27, i5-14600K, Windows, QuickJS-ng in the native host)
+
+5000 entities, each with `Transform` + `Sprite` + a script component, 200 timed frames
+after 120, best of 3 processes. `idle` is the same scene with no body scheduled.
+
+| body | build | frame CPU | draws | the system alone |
+|---|---|---|---|---|
+| thin | interpreted | 51.06 ms | 1 | 9907 ns/entity |
+| thin | **compiled** | **1.72 ms** | 1 | **18 ns/entity** |
+| script | interpreted | 15.41 ms | 1 | 2777 ns/entity |
+| script | **compiled** | **1.77 ms** | 1 | **27 ns/entity** |
+| heavy | interpreted | 61.99 ms | 4998 | 12093 ns/entity |
+| heavy | **compiled** | **8.73 ms** | 4998 | **1419 ns/entity** |
+| idle | either | 1.52 / 1.63 ms | 1 | — |
+
+**Read the first row as a frame budget.** One system doing three multiply-adds over 5000
+entities costs **51 ms** — the scene runs at 19 fps, missing 60 fps by 3.1x and 30 fps by
+1.5x. Compiled it costs **1.7 ms**, of which 1.5 ms is everything else in the frame. That
+is what this whole road was for, and it is the first time this engine has measured it
+where the constraint holds.
+
+### Three things the numbers say that the JIT numbers could not
+
+**1. The no-JIT penalty on this engine's frame is ~61x.** `thin` interpreted costs 9907
+ns/entity here against **162 ns on V8** (`docs/REARCH_AOT.md` §18, same body, same
+source). Stage 0 measured 154–385x for a bare loop in QuickJS against native C++; on a
+real frame, through the real bridge, it is 61x. Compiled, the two hosts land in the same
+place (18 ns here, 2.1 ns there — both at the floor of what their idle scene can
+resolve), which is the shape AOT should have: the interpreter's speed is the variable
+and the compiled body is not.
+
+**2. A script component is CHEAPER than an engine one here — the opposite of the web.**
+`script` interpreted costs 2777 ns/entity against `thin`'s 9907: **3.6x cheaper** to hand
+a pooled script component to a closure than an engine `Transform`. On V8/wasm the sign is
+reversed (251 ns for script against 162 for thin, script the most expensive row on the
+board). The reason is the boundary: on this host the SDK is given the engine's heap as
+one `ArrayBuffer`, so a script component's bytes are memory JS already has, while an
+engine component's address is a QuickJS→C++ call per entity per frame. **Stage 3's
+conclusions about the row protocol were drawn on the web host and do not transfer
+sign-for-sign to this one.**
+
+**3. `heavy`'s low ratio is not about the compiler.** It writes `transform.position.z`
+per entity, which breaks sprite batching into **4998 draw calls** where every other body
+draws **1**. Most of its 8.73 ms compiled frame is that render, not the system. The body
+was written for a headless harness where nothing renders and the z-write was free; under
+a real renderer it is the dominant cost. `draws` is a column for exactly this reason — a
+cost that lands somewhere the report cannot see reads as the system's.
+
+## What this is and is not
+
+It **is** the shipped iOS/Android interpreter, on a desktop CPU. QuickJS-ng is what
+`native/host/Runtime.cpp` boots on every platform the native host targets.
+
+It is **not** an iPhone number. Two things differ and they pull opposite ways: the CPU is
+a desktop one (optimistic), and iOS's JavaScriptCore in LLInt-only mode is generally
+faster than QuickJS (pessimistic). Stage 4's exit criterion is still a device run.
+
+It also is **not** a measure of a real game's frame. This scene is almost nothing but the
+system: `idle` is 1.5 ms of the 51 ms interpreted frame. A real frame carries physics, UI
+and far more rendering that no compiler touches — `docs/REARCH_AOT.md` §14 measured that
+share, and it is what turns these ratios into a budget.
+
+## How the host is timed
+
+`native/host/Bench.{hpp,cpp}`, driven by the environment so nothing about a shipped game
+changes. Four spans:
+
+- `update` — the `update` call, which only **schedules** the tick: `App.tick` is async and
+ returns at its first await. Measured at ~8 µs of a 51 ms frame. Reported so nobody
+ mistakes it for the tick again.
+- `pump` — the microtask drain that follows, where the systems and the render they drive
+ actually run.
+- `cpu` — the host's whole frame up to `present()`. The number the tables above use.
+- `frame` — including `present()`.
+
+A bench also asks the swapchain to stop waiting for the display
+(`WebGPUDevice::setPresentUncapped`, best effort: Mailbox, then Immediate, then Fifo).
+**Under Fifo a frame cannot be measured at all**: every frame cheaper than the refresh
+interval reads as exactly the refresh interval and every frame dearer than it reads as a
+multiple of one. Measured before the mode was added, the 51 ms interpreted frame and the
+1.7 ms compiled one read as "52 ms" and "16.5 ms" — a 30x difference quantised into a 3x
+one.
+
+The delta is fixed (`ESTELLA_BENCH_DT`, default 1/60) for both the warmup and the timed
+frames. A bench stepped by the wall clock measures the wall clock: two builds would see
+different deltas, move different distances, and have no differential between them.
+
+| env | default | meaning |
+|---|---|---|
+| `BENCH_ENTITIES` | 5000 | entities the startup system spawns |
+| `BENCH_FRAMES` | 300 | timed frames |
+| `BENCH_WARMUP` | 120 | untimed frames first — assets land, pools fill, and a lazily-bound compiled system gets bound before it is timed |
+| `BENCH_REPS` | 3 | processes per configuration; the fastest is kept |
+| `BENCH_BODIES` | `thin` | any of `thin`, `thick`, `heavy`, `script` |
+| `BENCH_IDLE` | off | also run the scene with no body, so a system's own cost can be read off it |
+| `BENCH_MIN_RATIO` | 5 | `--gate` only: the ratio a fallback cannot pass |
+| `BENCH_KEEP` | off | keep the exported apps for poking at |
diff --git a/bench/aot-native/frame-bench.mjs b/bench/aot-native/frame-bench.mjs
new file mode 100644
index 000000000..b31fd41d5
--- /dev/null
+++ b/bench/aot-native/frame-bench.mjs
@@ -0,0 +1,354 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file frame-bench.mjs — what a compiled system buys a frame on a host with NO JIT.
+ *
+ * `bench/aot-frame` measured this engine's frame on V8 and on a phone's Chromium.
+ * Both have a JIT, and its own README says so: "A no-JIT number, and that is the
+ * number AOT exists for." The plan's proxy for that number was a Mac running
+ * Bun/JavaScriptCore.
+ *
+ * The proxy is no longer needed. The desktop native host embeds QuickJS-ng, which
+ * has no JIT — the same constraint iOS puts on JavaScriptCore — and as of the AOT
+ * native road it dispatches to compiled systems. So this runs the REAL host, the
+ * REAL SDK and a REAL exported project, twice from one tree:
+ *
+ * `estella export` the compiled build
+ * `estella export --no-aot` the same project, same tree, interpreted
+ *
+ * and reads the host's own frame clock (native/host/Bench.hpp) off both.
+ *
+ * The project is materialized, not committed: an entity count is a parameter, and
+ * a scene file per count is a file per parameter. Its systems are COPIED from
+ * `bench/aot-frame/project/src/systems.ts` — one source for both benchmarks, so a
+ * ratio measured here and one measured there are about the same code.
+ *
+ * node bench/aot-native/frame-bench.mjs
+ * BENCH_ENTITIES=20000 BENCH_BODIES=thin,heavy node bench/aot-native/frame-bench.mjs
+ */
+import { spawnSync } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { installedTemplateDir } from '../../build-tools/utils/nativeTemplate.js';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+/** The one source both AOT benchmarks measure. */
+const SYSTEMS = path.join(ROOT, 'bench', 'aot-frame', 'project', 'src', 'systems.ts');
+
+/**
+ * `--gate` turns the benchmark into a release criterion.
+ *
+ * The failure this road can have is SILENT: `AotDispatcher.run` returns whether it
+ * took the system, and false sends it back to the interpreter for that frame. That
+ * is deliberate — the no-cliff rule — so a regression that unbinds every system
+ * raises no error and changes no pixel. It only costs time, and nothing was
+ * measuring time. A same-machine ratio is what sees it: an engine that stopped
+ * dispatching reads ~1x, and no absolute millisecond ceiling has to be calibrated
+ * to a machine for that to be true.
+ */
+const GATE = process.argv.includes('--gate');
+const ENTITIES = Number(process.env.BENCH_ENTITIES ?? (GATE ? 2000 : 5000));
+const FRAMES = Number(process.env.BENCH_FRAMES ?? (GATE ? 60 : 300));
+const WARMUP = Number(process.env.BENCH_WARMUP ?? (GATE ? 60 : 120));
+const REPS = Number(process.env.BENCH_REPS ?? (GATE ? 1 : 3));
+const BODIES = (process.env.BENCH_BODIES ?? 'thin').split(',').map((s) => s.trim()).filter(Boolean);
+/** Measured at 29x (5000 entities) and ~23x (2000). The bar is what a fallback
+ * cannot pass, not what today happens to reach. */
+const MIN_RATIO = Number(process.env.BENCH_MIN_RATIO ?? 5);
+/** An idle run of the same scene, so a body's OWN cost can be read off the frame. */
+const IDLE = process.env.BENCH_IDLE === '1';
+const KEEP = process.env.BENCH_KEEP === '1';
+
+/** Which component each body moves, and how to read a position off it. */
+const BODY = {
+ thin: { system: 'thinSystem', comp: 'Transform', read: 'c.position.x + c.position.y + c.position.z' },
+ thick: { system: 'thickSystem', comp: 'Transform', read: 'c.position.x + c.position.y + c.position.z' },
+ heavy: { system: 'heavySystem', comp: 'Transform', read: 'c.position.x + c.position.y + c.position.z' },
+ script: { system: 'scriptSystem', comp: 'Pos', read: 'c.x + c.y + c.z' },
+ idle: { system: null, comp: 'Transform', read: 'c.position.x + c.position.y + c.position.z' },
+};
+
+const os = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : 'linux';
+const version = JSON.parse(spawnSync(process.execPath, ['-p', 'JSON.stringify(require("./package.json"))'],
+ { cwd: ROOT, encoding: 'utf8' }).stdout || '{}').version;
+const template = installedTemplateDir(version, os);
+if (!template || !existsSync(template)) {
+ // Loud, not silent: a bench that skipped without saying so reads as a bench
+ // that ran and found nothing.
+ console.log(`aot native bench: no ${os} runtime template for v${version} — did NOT run.`);
+ console.log(` build one with: node build-tools/cli.js native --target ${os}`);
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------- the project
+
+/** The scene: a camera and nothing else. The entities are a startup system's,
+ * because their number is this benchmark's parameter. */
+const SCENE = JSON.stringify({
+ version: 4,
+ name: 'Main',
+ entities: [{
+ id: 0, name: 'Camera', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 1200, isActive: true, priority: 0 } },
+ ],
+ }],
+}, null, 2);
+
+const TSCONFIG = JSON.stringify({
+ compilerOptions: {
+ target: 'ES2020', module: 'ESNext', moduleResolution: 'bundler', strict: true,
+ esModuleInterop: true, skipLibCheck: true, declaration: false,
+ outDir: './dist', rootDir: '.',
+ paths: { esengine: ['./.esengine/sdk/index.d.ts'], 'esengine/wasm': ['./.esengine/sdk/wasm.d.ts'] },
+ },
+ include: ['src/**/*'], exclude: ['node_modules'],
+}, null, 2);
+
+/**
+ * The project's own source. The scene is built by a startup system from a SEEDED
+ * generator — the same one `bench/aot-frame/measure.mjs` uses — because two builds
+ * with different starting positions have no differential between them, and
+ * `Math.random` would give exactly that.
+ */
+function mainTs(body) {
+ const spec = BODY[body];
+ const schedule = spec.system === null ? '' : `addSystemToSchedule(Schedule.Update, ${spec.system});\n`;
+ return `import {
+ addStartupSystem, addSystemToSchedule, Schedule, defineSystem,
+ Commands, Query, Transform, Sprite,
+} from 'esengine';
+import { Mover, Pos, thinSystem, thickSystem, heavySystem, scriptSystem } from './systems';
+
+// Generated by bench/aot-native/frame-bench.mjs — an entity count is a parameter.
+const ENTITIES = ${ENTITIES};
+const CHECKSUM_AT = ${WARMUP + FRAMES};
+
+/** The generator bench/aot-frame uses, so both benchmarks lay out one scene. */
+function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const setupSystem = defineSystem([Commands()], (cmds) => {
+ const rand = mulberry32(0x1234abcd);
+ for (let i = 0; i < ENTITIES; i++) {
+ cmds.spawn()
+ .insert(Transform, { position: { x: (rand() - 0.5) * 2000, y: (rand() - 0.5) * 2000, z: 0 } })
+ .insert(Mover, { dx: rand() - 0.5, dy: rand() - 0.5, speed: 40 + rand() * 80, boost: rand() < 0.5 ? 1 : 0 })
+ .insert(Pos, { x: 0, y: 0, z: 0 })
+ .insert(Sprite, { size: { x: 4, y: 4 }, color: { r: 1, g: 1, b: 1, a: 1 } });
+ }
+}, { name: 'BenchSetup' });
+
+/**
+ * What the frames actually computed. Printed once, from the frame the timed run
+ * ends on: two builds that disagree here are not two measurements of one thing,
+ * and the ratio between them means nothing.
+ */
+let seen = 0;
+const checksumSystem = defineSystem([Query(${spec.comp})], (query) => {
+ seen++;
+ if (seen !== CHECKSUM_AT) return;
+ let sum = 0;
+ for (const [, c] of query) sum += ${spec.read};
+ console.log('bench checksum: ' + sum.toFixed(4) + ' over ' + ENTITIES + ' entities');
+}, { name: 'BenchChecksum' });
+
+addStartupSystem(setupSystem);
+${schedule}addSystemToSchedule(Schedule.Update, checksumSystem);
+`;
+}
+
+function materialize(dir, body) {
+ mkdirSync(path.join(dir, 'src'), { recursive: true });
+ mkdirSync(path.join(dir, 'assets', 'scenes'), { recursive: true });
+ copyFileSync(SYSTEMS, path.join(dir, 'src', 'systems.ts'));
+ writeFileSync(path.join(dir, 'src', 'main.ts'), mainTs(body));
+ writeFileSync(path.join(dir, 'tsconfig.json'), TSCONFIG);
+ writeFileSync(path.join(dir, 'assets', 'scenes', 'main.esscene'), SCENE);
+ writeFileSync(path.join(dir, 'assets', 'scenes', 'main.esscene.meta'), JSON.stringify({
+ uuid: '7b1f0c8e-4a2d-4f61-9c3a-9d5e2f7a1b04', version: '2.0', type: 'scene',
+ importer: { autoMigrate: true },
+ }, null, 2));
+ writeFileSync(path.join(dir, 'project.esproject'), JSON.stringify({
+ formatVersion: '1', name: `AotNativeBench-${body}`,
+ description: 'Generated by bench/aot-native — what a compiled system buys a no-JIT frame.',
+ version: '0.1.0', defaultScene: 'assets/scenes/main.esscene',
+ designResolution: { width: 800, height: 600 }, spineVersion: 'none',
+ }, null, 2));
+}
+
+// ---------------------------------------------------------------- export + run
+
+function exportApp(project, out, compiled) {
+ const args = [path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', project,
+ '--platform', 'desktop', '--out', out, '--template', template];
+ if (!compiled) args.push('--no-aot');
+ const r = spawnSync(process.execPath, args, { encoding: 'utf8', cwd: ROOT });
+ if (r.status !== 0) {
+ console.error(`✗ the export failed (${compiled ? 'aot' : 'no-aot'})`);
+ console.error((r.stderr || r.stdout || '').trim().slice(-1500));
+ process.exit(1);
+ }
+ const exe = findExecutable(out);
+ if (exe === null) {
+ console.error(`✗ the export assembled no app under ${out}`);
+ process.exit(1);
+ }
+ return exe;
+}
+
+/** The assembled app's executable, wherever the assembler put it. */
+function findExecutable(dir) {
+ const stack = [dir];
+ while (stack.length > 0) {
+ const at = stack.pop();
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
+ const full = path.join(at, entry.name);
+ if (entry.isDirectory()) { stack.push(full); continue; }
+ if (process.platform === 'win32' ? entry.name.endsWith('.exe') : !path.extname(entry.name)) {
+ if (!full.includes(`${path.sep}Content${path.sep}`)) return full;
+ }
+ }
+ }
+ return null;
+}
+
+function run(exe, label) {
+ const r = spawnSync(exe, [], {
+ encoding: 'utf8', cwd: path.dirname(exe),
+ env: {
+ ...process.env,
+ ESTELLA_BENCH_FRAMES: String(FRAMES),
+ ESTELLA_BENCH_WARMUP: String(WARMUP),
+ ESTELLA_BENCH_LABEL: label,
+ ESTELLA_BENCH_DT: String(1 / 60),
+ },
+ });
+ const log = `${r.stdout ?? ''}${r.stderr ?? ''}`;
+ const line = /bench: (\{.*\})/.exec(log);
+ if (line === null) {
+ console.error(`✗ ${label}: the host printed no bench line`);
+ console.error(log.trim().split('\n').slice(-15).join('\n'));
+ process.exit(1);
+ }
+ const checksum = /bench checksum: ([-\d.]+)/.exec(log);
+ return {
+ ...JSON.parse(line[1]),
+ checksum: checksum ? checksum[1] : null,
+ // Installed is not enough: a module can load and never be dispatched to.
+ running: /AOT: (\w+) is running compiled/.exec(log)?.[1] ?? null,
+ };
+}
+
+// ---------------------------------------------------------------------- drive
+
+const out = mkdtempSync(path.join(tmpdir(), 'estella-aot-native-bench-'));
+const rows = [];
+try {
+ const bodies = IDLE ? [...BODIES, 'idle'] : BODIES;
+ for (const body of bodies) {
+ if (!(body in BODY)) { console.error(`✗ unknown body "${body}"`); process.exit(1); }
+ const project = path.join(out, `${body}-project`);
+ materialize(project, body);
+ const built = {};
+ for (const compiled of [false, true]) {
+ const key = compiled ? 'compiled' : 'interpreted';
+ process.stdout.write(` exporting ${body} ${key}...\n`);
+ built[key] = exportApp(project, path.join(out, `${body}-${key}`), compiled);
+ }
+ for (const key of ['interpreted', 'compiled']) {
+ // Every rep in its own process, and the FASTEST kept: noise on a desktop
+ // only ever adds time, so the minimum is the closest thing to the cost.
+ let best = null;
+ for (let rep = 0; rep < REPS; rep++) {
+ const r = run(built[key], `${body} ${key}`);
+ process.stdout.write(` ${body} ${key} rep ${rep + 1}/${REPS}: cpu p50 ${r.cpu.p50.toFixed(3)} ms\n`);
+ if (best === null || r.cpu.p50 < best.cpu.p50) best = r;
+ }
+ rows.push({ body, key, ...best });
+ }
+ }
+} finally {
+ if (!KEEP) rmSync(out, { recursive: true, force: true });
+ else console.log(`\nkept: ${out}`);
+}
+
+// --------------------------------------------------------------------- report
+
+console.log(`\nno-JIT frame — QuickJS-ng in the native host, ${ENTITIES} entities, `
+ + `${FRAMES} frames after ${WARMUP}, best of ${REPS}\n`);
+// `update` is not a column. On this host it only SCHEDULES the App tick — an async
+// function returns at its first await — so the systems, and the render they drive,
+// run in the microtask drain that follows. `tick` below is that drain.
+// `draws` is a column because a BODY can move the render's cost. `heavy` writes
+// `position.z` per entity, which breaks sprite batching into one draw each: its
+// frame then carries ~5000 draw calls that have nothing to do with the system, and
+// the ratio reads low for a reason no timing column can show.
+console.log('body build tick p50 cpu p50 frame p50 draws compiled?');
+for (const r of rows) {
+ console.log(`${r.body.padEnd(9)} ${r.key.padEnd(13)} ${`${r.pump.p50.toFixed(3)} ms`.padStart(10)}`
+ + ` ${`${r.cpu.p50.toFixed(3)} ms`.padStart(10)} ${`${r.frame.p50.toFixed(3)} ms`.padStart(11)}`
+ + ` ${String(r.draws ?? '?').padStart(7)} ${r.running ?? '—'}`);
+}
+
+let bad = 0;
+console.log('');
+// An idle run of the same scene, if one was asked for: the frame minus the system,
+// so the body's OWN cost can be read off a frame that also renders 5000 sprites.
+const idleOf = (key) => rows.find((r) => r.body === 'idle' && r.key === key)?.cpu.p50 ?? null;
+for (const body of [...new Set(rows.map((r) => r.body))]) {
+ const i = rows.find((r) => r.body === body && r.key === 'interpreted');
+ const c = rows.find((r) => r.body === body && r.key === 'compiled');
+ if (!i || !c) continue;
+ // Two worlds that computed different things have no ratio between them.
+ if (i.checksum === null || c.checksum === null) {
+ console.error(`✗ ${body}: a run printed no checksum`);
+ bad++;
+ } else if (i.checksum !== c.checksum) {
+ console.error(`✗ ${body}: the two builds disagree — interpreted ${i.checksum}, compiled ${c.checksum}`);
+ bad++;
+ }
+ if (body !== 'idle' && c.running === null) {
+ console.error(`✗ ${body}: the compiled build never dispatched to a compiled system`);
+ bad++;
+ }
+ if (i.running !== null) {
+ console.error(`✗ ${body}: the --no-aot build dispatched to ${i.running} — it is not the interpreted twin`);
+ bad++;
+ }
+ if (body === 'idle') continue;
+ const ratio = i.cpu.p50 / c.cpu.p50;
+ if (GATE && !(ratio >= MIN_RATIO)) {
+ console.error(`✗ ${body}: the compiled frame is only ${ratio.toFixed(2)}x the interpreted one `
+ + `(needs ${MIN_RATIO}x) — a system is reaching the interpreter`);
+ bad++;
+ }
+ const saved = i.cpu.p50 - c.cpu.p50;
+ console.log(`${body}: the frame's CPU is ${(i.cpu.p50 / c.cpu.p50).toFixed(2)}x — `
+ + `${saved.toFixed(2)} ms of a 16.67 ms frame given back `
+ + `(${i.cpu.p50.toFixed(2)} ms -> ${c.cpu.p50.toFixed(2)} ms)`);
+ const iIdle = idleOf('interpreted');
+ const cIdle = idleOf('compiled');
+ if (iIdle !== null && cIdle !== null) {
+ // The system is the frame minus an idle run of the same scene. Reported in
+ // ns per entity per frame, the unit bench/aot-frame reports, so the two
+ // benchmarks' tables can be read side by side.
+ const iSys = i.cpu.p50 - iIdle;
+ const cSys = c.cpu.p50 - cIdle;
+ const ns = (ms) => (ms * 1e6) / ENTITIES;
+ console.log(`${' '.repeat(body.length)} the system alone: ${ns(iSys).toFixed(0)} ns/entity `
+ + `-> ${ns(cSys).toFixed(0)} ns/entity`
+ + (cSys > 0.05 ? ` (${(iSys / cSys).toFixed(0)}x)` : ' (at the idle floor)'));
+ }
+}
+if (bad > 0) process.exit(1);
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index ac3fd5238..ae11e9cc8 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -312,6 +312,7 @@ if(ESTELLA_QUICKJS_DIR)
host/Runtime.cpp
host/BootLog.cpp
host/Shot.cpp
+ host/Bench.cpp
host/EsnShim.cpp
host/bindings/HeapBindings.cpp
host/bindings/EcsBindings.cpp
diff --git a/native/host/Bench.cpp b/native/host/Bench.cpp
new file mode 100644
index 000000000..9f95383b5
--- /dev/null
+++ b/native/host/Bench.cpp
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Bench.cpp
+ * @brief The frame clock and its report. See Bench.hpp for what and why.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "Bench.hpp"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <string>
+#include <vector>
+
+#include "Runtime.hpp" // ESHOST_LOGI
+
+namespace eshost {
+namespace {
+
+using Clock = std::chrono::steady_clock;
+
+double msSince(const Clock::time_point& t0) {
+ return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
+}
+
+/** A span's samples, and the three numbers worth reading off them. */
+struct Span {
+ std::vector<double> ms;
+ Clock::time_point begun{};
+ void begin() { begun = Clock::now(); }
+ void end() { ms.push_back(msSince(begun)); }
+};
+
+struct BenchState {
+ bool asked = false;
+ bool reported = false;
+ bool quitAfter = true;
+ long warmup = 120;
+ long frames = 0;
+ double dt = 1.0 / 60.0;
+ std::string label;
+ long seen = 0; // frames entered, warmup included
+ Span update, pump, cpu, frame;
+ unsigned draws = 0, sprites = 0;
+};
+
+long envLong(const char* name, long fallback) {
+ const char* v = std::getenv(name);
+ if (v == nullptr || v[0] == '\0') return fallback;
+ const long n = std::strtol(v, nullptr, 10);
+ return n >= 0 ? n : fallback;
+}
+
+BenchState& state() {
+ static BenchState s = [] {
+ BenchState init;
+ const char* frames = std::getenv("ESTELLA_BENCH_FRAMES");
+ init.frames = envLong("ESTELLA_BENCH_FRAMES", 0);
+ init.asked = frames != nullptr && frames[0] != '\0' && init.frames > 0;
+ init.warmup = envLong("ESTELLA_BENCH_WARMUP", 120);
+ if (const char* dt = std::getenv("ESTELLA_BENCH_DT")) {
+ const double v = std::strtod(dt, nullptr);
+ if (v > 0.0) init.dt = v;
+ }
+ if (const char* label = std::getenv("ESTELLA_BENCH_LABEL")) init.label = label;
+ if (const char* quit = std::getenv("ESTELLA_BENCH_QUIT")) init.quitAfter = quit[0] != '0';
+ if (init.asked) {
+ init.update.ms.reserve(static_cast<size_t>(init.frames));
+ init.pump.ms.reserve(static_cast<size_t>(init.frames));
+ init.cpu.ms.reserve(static_cast<size_t>(init.frames));
+ init.frame.ms.reserve(static_cast<size_t>(init.frames));
+ }
+ return init;
+ }();
+ return s;
+}
+
+/** Whether this frame is one of the timed ones. Warmup frames run identically —
+ * they are simply not sampled — so nothing about the loop changes at the seam. */
+bool timing() {
+ const BenchState& s = state();
+ return s.asked && !s.reported && s.seen > s.warmup;
+}
+
+/** Quantile by position on the sorted samples, no interpolation: these are
+ * timings, and the value at a position is one that was actually observed. */
+double at(std::vector<double> v, double q) {
+ if (v.empty()) return 0.0;
+ std::sort(v.begin(), v.end());
+ size_t i = static_cast<size_t>(q * static_cast<double>(v.size() - 1) + 0.5);
+ if (i >= v.size()) i = v.size() - 1;
+ return v[i];
+}
+
+/** One JSON line, because a runner has to parse this and a human has to read it. */
+void report() {
+ BenchState& s = state();
+ s.reported = true;
+ const double p50 = at(s.pump.ms, 0.5);
+ const double c50 = at(s.cpu.ms, 0.5);
+ // The share a compiler can reach, and it is `pump` over `cpu`: `update` only
+ // schedules the tick. Against `cpu`, never against `frame` — a present sleeps
+ // out the rest of the refresh interval, which measures the panel.
+ const double share = c50 > 0.0 ? p50 / c50 : 0.0;
+ ESHOST_LOGI("bench: {\"label\":\"%s\",\"warmup\":%ld,\"frames\":%zu,\"dt\":%.6f,"
+ "\"update\":{\"min\":%.4f,\"p50\":%.4f,\"p90\":%.4f},"
+ "\"pump\":{\"min\":%.4f,\"p50\":%.4f,\"p90\":%.4f},"
+ "\"cpu\":{\"min\":%.4f,\"p50\":%.4f,\"p90\":%.4f},"
+ "\"frame\":{\"min\":%.4f,\"p50\":%.4f,\"p90\":%.4f},"
+ "\"draws\":%u,\"sprites\":%u,\"tickShareOfCpu\":%.4f}",
+ // The FRAME span's count is the authority on how many frames were
+ // sampled: a frame can be abandoned after it began and reach no other span.
+ s.label.c_str(), s.warmup, s.frame.ms.size(), s.dt,
+ at(s.update.ms, 0.0), at(s.update.ms, 0.5), at(s.update.ms, 0.9),
+ at(s.pump.ms, 0.0), p50, at(s.pump.ms, 0.9),
+ at(s.cpu.ms, 0.0), c50, at(s.cpu.ms, 0.9),
+ at(s.frame.ms, 0.0), at(s.frame.ms, 0.5), at(s.frame.ms, 0.9),
+ s.draws, s.sprites, share);
+}
+
+} // namespace
+
+bool benchWanted() { return state().asked; }
+
+double benchDelta(double wall) {
+ const BenchState& s = state();
+ // The fixed step covers the warmup too: a scene that spent its warmup moving at
+ // one rate and its timed frames at another is two scenes.
+ return (s.asked && !s.reported) ? s.dt : wall;
+}
+
+void benchFrameBegin() {
+ BenchState& s = state();
+ if (!s.asked || s.reported) return;
+ ++s.seen;
+ if (timing()) {
+ s.frame.begin();
+ s.cpu.begin();
+ }
+}
+
+void benchUpdateBegin() { if (timing()) state().update.begin(); }
+void benchUpdateEnd() { if (timing()) state().update.end(); }
+void benchPumpBegin() { if (timing()) state().pump.begin(); }
+void benchPumpEnd() { if (timing()) state().pump.end(); }
+void benchBeforePresent() { if (timing()) state().cpu.end(); }
+
+void benchNoteDraws(unsigned draws, unsigned sprites) {
+ if (!timing()) return;
+ state().draws = draws;
+ state().sprites = sprites;
+}
+
+bool benchFrameEnd() {
+ BenchState& s = state();
+ if (!s.asked || s.reported) return false;
+ if (!timing()) return false;
+ s.frame.end();
+ if (static_cast<long>(s.frame.ms.size()) < s.frames) return false;
+ report();
+ return s.quitAfter;
+}
+
+} // namespace eshost
diff --git a/native/host/Bench.hpp b/native/host/Bench.hpp
new file mode 100644
index 000000000..0b305d8cc
--- /dev/null
+++ b/native/host/Bench.hpp
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Bench.hpp
+ * @brief What a frame COSTS on this host — the number AOT exists for, measured
+ * where the constraint AOT exists for actually holds.
+ * @details Every frame number this engine has ever published came from a host with
+ * a JIT: V8 on the desktop, Chromium on the phone (docs/REARCH_AOT.md
+ * §18). But `bench/aot-frame`'s own README says the number the road was
+ * built for is the no-JIT one, and the plan's proxy for it was a Mac
+ * running Bun/JavaScriptCore.
+ *
+ * The proxy stopped being necessary the day this host learned to dispatch
+ * to compiled systems. It embeds QuickJS-ng, which has no JIT — the same
+ * constraint iOS puts on JavaScriptCore — so a desktop build IS a no-JIT
+ * measurement of the real engine, the real SDK and a real exported
+ * project. What was missing was not a harness. It was a clock.
+ *
+ * Four spans, because one number cannot say what it is a share OF:
+ * - `update` — the `update` call itself, which on this host only
+ * SCHEDULES the tick. `App.tick` is async, so it returns at its first
+ * await; measured, this span is ~8us of a 52ms frame. It is reported
+ * so that nobody mistakes it for the tick again.
+ * - `pump` — the microtask drain that follows, where the systems and the
+ * render they drive actually run. THIS is what AOT moves.
+ * - `cpu` — the host's whole frame up to `present()`. Amdahl's
+ * denominator: `pump / cpu` is the fraction a compiler can reach.
+ * - `frame` — including `present()`, for reference.
+ *
+ * A bench also asks the swapchain to stop waiting for the display
+ * (`setPresentUncapped`). Under Fifo every frame cheaper than the refresh
+ * interval reads as exactly the refresh interval and every frame dearer
+ * than it reads as a multiple of one: measured here, a 52ms interpreted
+ * frame and a 1.8ms compiled one both read as "16.67ms" and "52ms" —
+ * a 30x difference quantised into a 3x one.
+ *
+ * Driven by the environment, so nothing about a shipped game changes:
+ * - `ESTELLA_BENCH_FRAMES` timed frames; presence enables the bench.
+ * - `ESTELLA_BENCH_WARMUP` untimed frames first (default 120) — assets
+ * land, pools fill, and a lazily-bound compiled
+ * system gets to be bound before it is timed.
+ * - `ESTELLA_BENCH_DT` fixed delta in seconds (default 1/60). A bench
+ * stepped by the wall clock measures the wall
+ * clock: two builds would see different deltas,
+ * move different distances, and have no
+ * differential between them.
+ * - `ESTELLA_BENCH_LABEL` tag echoed in the result line.
+ * - `ESTELLA_BENCH_QUIT` `0` to keep running after the report; the
+ * default is to exit, which is what a runner
+ * comparing two builds wants.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+namespace eshost {
+
+/** Whether a bench was asked for. */
+bool benchWanted();
+
+/** The delta the frame should use. Returns @p wall untouched unless a bench is
+ * running, in which case every frame gets the same fixed step — see the header. */
+double benchDelta(double wall);
+
+/** Frame boundaries and the span around the SDK tick. All four are no-ops unless
+ * a bench was asked for. */
+void benchFrameBegin();
+void benchUpdateBegin();
+void benchUpdateEnd();
+
+/** The microtask drain the tick's continuation runs in. On this host `update`
+ * only SCHEDULES the App tick — an async function returns at its first await —
+ * so the systems, and the render they drive, are timed here. */
+void benchPumpBegin();
+void benchPumpEnd();
+
+/** Close the frame's CPU span. Call immediately BEFORE `present()`. */
+void benchBeforePresent();
+
+/** What the frame DREW, carried into the report. A body that moves a sprite's z
+ * can break the batching and pay for it in the render rather than in itself, and
+ * a cost that lands somewhere the report cannot see reads as the system's. */
+void benchNoteDraws(unsigned draws, unsigned sprites);
+
+/** Close the frame, and report once the last timed one is in.
+ * @return true when the host was asked to quit and the report is out. */
+bool benchFrameEnd();
+
+} // namespace eshost
diff --git a/native/host/Host.cpp b/native/host/Host.cpp
index 0408510da..f43273e32 100644
--- a/native/host/Host.cpp
+++ b/native/host/Host.cpp
@@ -21,6 +21,7 @@
#include "BootLog.hpp"
#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on
+#include "Bench.hpp"
#include "Shot.hpp"
#if defined(ESTELLA_DESKTOP)
#include "steam/SteamApi.hpp"
@@ -181,6 +182,8 @@ bool bindSurface() {
// Before configureSurface, always: the copy usage is part of the swapchain's
// configuration, so asking afterwards would silently do nothing.
h.gfx->setSurfaceReadback(shotWanted());
+ // A benched frame must not be quantised to the panel's refresh — see Bench.hpp.
+ h.gfx->setPresentUncapped(benchWanted());
if (!h.gfx->configureSurface(h.platform->surface(), w, hh)) {
ESHOST_LOGE("configureSurface failed");
return false;
@@ -288,6 +291,9 @@ void frame() {
h.surfaceSkipReported = false;
ESHOST_LOGI("surface bound again — drawing resumes");
}
+ // Past the point where a frame can be skipped, so what is timed below is a
+ // frame that actually happened (see Bench.hpp).
+ benchFrameBegin();
// A window can change size without being recreated: a rotation, an insets
// change (the system bars leaving on the frame after launch), a layout on
@@ -322,15 +328,22 @@ void frame() {
}
h.lastFrameAt = nowAt;
h.haveLastFrame = true;
+ // A bench steps at a fixed rate, so two builds of the same project move the
+ // same distance and can be held against each other.
+ deltaSeconds = benchDelta(deltaSeconds);
// Booked before the game renders, because the copy is served from inside the
// renderer's own endFrame (see Shot.hpp).
shotBeforeFrame(*h.gfx, h.frame, (u32)h.w, (u32)h.h);
JSValue dt = JS_NewFloat64(h.js, deltaSeconds);
+ benchUpdateBegin();
callJs(h, "update", 1, &dt);
+ benchUpdateEnd();
JS_FreeValue(h.js, dt);
+ benchPumpBegin();
pumpJs(h); // run the App tick's async systems and any timers they set
+ benchPumpEnd();
// Notify JS of voices that ended on their own (the audio thread never touches
// QuickJS; we poll on this thread and push, like touch). onEnd handlers may
@@ -356,8 +369,18 @@ void frame() {
// game is alive and the overlay never opens.
steam().pump();
#endif
+ // Guarded, not just no-op'd: a shipped frame should not pay a lookup for a
+ // measurement it never asked for.
+ if (benchWanted()) {
+ if (auto* benched = h.ctx->tryGet<RenderFrame>()) {
+ const auto& st = benched->stats();
+ benchNoteDraws(st.draw_calls, st.sprites);
+ }
+ }
+ benchBeforePresent();
h.gfx->present();
if (shotAfterPresent(*h.gfx)) h.quitRequested = true;
+ if (benchFrameEnd()) h.quitRequested = true;
// What the frame DREW, not only that one happened: a capture is one flat colour
// whether nothing was submitted or it was submitted into a view nothing is in.
// Reported on a ramp, not only every 120th: the runs worth explaining are the
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index f98074553..bf7a57f47 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -390,6 +390,35 @@ bool WebGPUDevice::surfaceBytesAreBGRA() const {
|| surface_format_ == WGPUTextureFormat_BGRA8UnormSrgb;
}
+/**
+ * The fastest present mode this surface actually advertises.
+ *
+ * Mailbox first: it drops finished frames instead of blocking, so the CPU is
+ * never made to wait and nothing tears. Immediate next — it tears, which is
+ * irrelevant to a measurement. Fifo if the surface offers neither, in which case
+ * the caller gets a throttled frame and the numbers say so.
+ */
+WGPUPresentMode WebGPUDevice::pickUncappedPresentMode() const {
+#if !defined(__EMSCRIPTEN__)
+ if (surface_ && adapter_) {
+ WGPUSurfaceCapabilities caps{};
+ if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success) {
+ WGPUPresentMode chosen = WGPUPresentMode_Fifo;
+ for (size_t i = 0; i < caps.presentModeCount; ++i) {
+ if (caps.presentModes[i] == WGPUPresentMode_Mailbox) {
+ chosen = WGPUPresentMode_Mailbox;
+ break;
+ }
+ if (caps.presentModes[i] == WGPUPresentMode_Immediate) chosen = WGPUPresentMode_Immediate;
+ }
+ wgpuSurfaceCapabilitiesFreeMembers(caps);
+ return chosen;
+ }
+ }
+#endif
+ return WGPUPresentMode_Fifo;
+}
+
bool WebGPUDevice::configureSwapchain(u32 width, u32 height) {
// Anything but the canvas' preferred format costs a full-frame copy per
// present, and only the page can name it (setPreferredSurfaceBGRA). Readback
@@ -433,7 +462,10 @@ bool WebGPUDevice::configureSwapchain(u32 width, u32 height) {
// Adreno on Android only offers Inherit/PreMultiplied) — Configure() rejects
// an unsupported mode outright.
cfg.alphaMode = WGPUCompositeAlphaMode_Auto;
- cfg.presentMode = WGPUPresentMode_Fifo;
+ // Fifo is the only mode every surface must support, and the only one a shipped
+ // game should want. setPresentUncapped asks for a measurable frame instead —
+ // see its comment for why a vsynced one cannot be measured.
+ cfg.presentMode = present_uncapped_ ? pickUncappedPresentMode() : WGPUPresentMode_Fifo;
wgpuSurfaceConfigure(surface_, &cfg);
surface_width_ = width;
surface_height_ = height;
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index aa561980b..01ff310ce 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -276,6 +276,22 @@ public:
*/
void setSurfaceReadback(bool enabled) { surface_readback_ = enabled; }
+ /**
+ * @brief Let the swapchain present as fast as it can, instead of waiting for
+ * the display. Must be set BEFORE the surface is configured.
+ *
+ * Off by default, and a shipped game should leave it off: an uncapped
+ * swapchain burns a core to draw frames nobody sees. It exists for
+ * MEASUREMENT — under Fifo, `getCurrentTexture` blocks until an image frees,
+ * so every frame cheaper than the refresh interval reads as exactly the
+ * refresh interval and every frame dearer than it reads as a multiple. A cost
+ * quantised to the panel is not a cost.
+ *
+ * Best effort: the mode is taken from what the surface advertises (Mailbox,
+ * then Immediate), and a surface offering neither keeps Fifo.
+ */
+ void setPresentUncapped(bool enabled) { present_uncapped_ = enabled; }
+
/**
* @brief Copy the next completed frame's swapchain image into a readback.
*
@@ -434,6 +450,10 @@ private:
bool prefer_surface_bgra_ = false;
/** Whether the surface was configured with CopySrc — see setSurfaceReadback. */
bool surface_readback_ = false;
+ /** Whether the surface should present unthrottled — see setPresentUncapped. */
+ bool present_uncapped_ = false;
+ /** The fastest mode this surface advertises, for setPresentUncapped. */
+ WGPUPresentMode pickUncappedPresentMode() const;
/** The pass being recorded draws to the surface, so a capture rides its encoder. */
bool pass_is_surface_ = false;
/** A booked capture was already copied by a pass; endFrame only maps it. */
diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjs
index 1b5dd6db6..f52fe16f5 100644
--- a/tools/releaseGate.mjs
+++ b/tools/releaseGate.mjs
@@ -102,6 +102,25 @@ export const CRITERIA = [
'sdk/src/ecs/aot/installNativeAot.ts',
],
},
+ {
+ id: 'a-compiled-system-is-cheaper-where-there-is-no-jit',
+ says: 'on a host with no JIT, a compiled system costs a fraction of the interpreted one',
+ // The reason this is a criterion and not a benchmark: the fallback is SILENT.
+ // `AotDispatcher.run` returns whether it took the system, and false sends it
+ // back to the interpreter for that frame — deliberately, so a project never
+ // hits a cliff. An engine that stopped dispatching therefore raises no error
+ // and changes no pixel; it only costs time. The desktop native host embeds
+ // QuickJS-ng, which has no JIT, so this measures the constraint iOS imposes on
+ // the machine that builds. A RATIO, not a millisecond ceiling: one number that
+ // has to be recalibrated per machine is a criterion that fails on the wrong
+ // machines and passes on the wrong code.
+ answeredBy: 'node bench/aot-native/frame-bench.mjs --gate',
+ needs: [
+ 'bench/aot-native/frame-bench.mjs',
+ 'native/host/Bench.cpp',
+ 'bench/aot-frame/project/src/systems.ts',
+ ],
+ },
{
id: 'compiled-systems-compute-what-the-interpreter-computes',
says: 'a packaged compiled system moves the world exactly as the interpreted one does',