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): a ceiling on what a frame spends drawing, and a clock that can refuse

esengine1de335aa7c8c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57f26a64c..a602a7da9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -74,6 +74,46 @@ published separately; it ships inside the editor.
and the software rasterizer agree on all four to the byte.
+- **A frame that WAITED is refused, not reported.** Every number the native bench
+ publishes comes from the host's own frame span, and that span can be spent
+ waiting: a frame the compositor throttles reads 16.6 ms whatever the scene
+ holds — 200 entities or 2,000, one draw or none. There was nothing in the
+ report that could tell that from a frame which cost 16.6 ms, and the render
+ pair above then read **1.00x and passed**, having compared two frames that were
+ both the display's.
+
+ The host reports `busy` now: CPU actually burned inside the span, over its
+ wall, from the thread's own clock. Below half, the run is refused with what it
+ measured instead. A throttled run reads 8-11%. Two causes seen here — a covered
+ window, which a benched window now asks not to be (`SDL_WINDOW_ALWAYS_ON_TOP`),
+ and a **virtual display**, where a remote session hands out drawables at its own
+ rate however fast the frame is and the flag does not help.
+
+ The cheapest frame in each comparison trips first, which is the right way
+ round: it is the one a throttle can pin while the other still has work in it.
+
+- **A frame's TIME has a ceiling, and what it bounds is the drawing.** Counts
+ were the only thing holding a frame: `sprite-scale-cost` and its siblings bound
+ draws, meshes and triangles, every one of which a frame can honour while
+ costing twice the CPU it used to. A count says how many sprites were submitted
+ and nothing about what submitting one cost.
+
+ `frame-bench --gate` runs a pair now — one scene twice, differing only in
+ whether its entities carry a `Sprite`. Both halves hold the same entities and
+ run the same schedule, so the machine and the engine's own per-frame cost sit
+ in the denominator and only the numerator carries the drawing; the assertion is
+ the ratio, for the reason the AOT one is a ratio. Measured here, 128,000
+ sprites make the frame 3.7-4.2x the one that only holds them, at 59-61
+ ns/sprite.
+
+ **The entity count is what makes the ratio steady, not what makes it large.**
+ The denominator is the small number and its noise is the ratio's: at 32,000 it
+ read 1.03 and 1.19 ms across runs, the healthy ratio spanned 2.85-3.01, and a
+ sabotage read 3.90 — overlapping. At 128,000 the numerator repeats to 1% and
+ the same sabotage, submitting every sprite twice, takes 59 ns/sprite to 115 and
+ the pair to 6.97x. Red on both sabotaged runs against the ceiling of 5, green
+ on three healthy ones.
+
- **`view.frameCanvas` — "Frame Design Screen" is a command now.** The viewport
has had the button since design mode shipped and nothing behind it, so the
command palette, a keybinding and a driver could all reach every other view
diff --git a/bench/aot-native/README.md b/bench/aot-native/README.md
index 9c96146e7..49086dd3a 100644
--- a/bench/aot-native/README.md
+++ b/bench/aot-native/README.md
@@ -206,4 +206,61 @@ different deltas, move different distances, and have no differential between the
| `BENCH_SPRITES` | on | `0` drops the `Sprite`, which is most of the idle floor — needed to resolve a compiled system at all |
| `BENCH_BYSTANDERS` | 0 | extra entities with only a `Transform`, which no query matches: they grow the world without growing the matched set |
| `BENCH_MIN_RATIO` | 5 | `--gate` only: the ratio a fallback cannot pass |
+| `BENCH_RENDER` | off, on under `--gate` | also run the render pair below |
+| `BENCH_RENDER_ENTITIES` | 128000 | the pair's entity count |
+| `BENCH_RENDER_MAX_RATIO` | 5 | `--gate` only: how much of the frame the drawing may be |
+| `BENCH_MIN_BUSY` | 0.5 | the share of a frame's span that must be CPU for the span to be about the engine |
| `BENCH_KEEP` | off | keep the exported apps for poking at |
+
+## What drawing costs, in time
+
+Counts were the only ceiling a frame had. `sprite-scale-cost` and its siblings hold
+draws, meshes and triangles — and a frame can honour every one of them while costing
+twice the CPU it used to, because a count says how many sprites were submitted and
+nothing says what submitting one cost.
+
+So `--gate` also runs a **pair**: the same scene twice, differing only in whether its
+entities carry a `Sprite`. Both halves hold the same entities and run the same schedule,
+so the machine and the engine's own per-frame cost sit in the denominator, and only the
+numerator carries the drawing. The assertion is the ratio, and the reason is the same one
+the AOT ratio has: a millisecond is a fact about the machine that measured it.
+
+```
+drawing: 128000 sprites make the frame 3.83x the one that only holds them
+ (2.72 ms -> 10.41 ms, 60 ns/sprite, 1 draw(s))
+```
+
+**128,000 because the denominator is the small number**, and its noise is the ratio's.
+The numerator repeats to 1% across runs; the denominator to 16%, and it does not get
+better with more entities — it gets *less of the ratio*. At 32,000 the healthy ratio
+spanned 2.85–3.01 and a sabotage read 3.90, close enough to overlap. At 128,000 healthy
+reads 3.65–4.21 and the same sabotage 6.97.
+
+That sabotage is where the ceiling of 5 comes from: submitting every sprite twice, which
+is the shape of a per-sprite cost that grew. It takes 59 ns/sprite to 115 and the pair
+past the ceiling on both runs, while three healthy runs pass. Both directions, on the
+same machine, on the same tree.
+
+The pair also has to *be* a pair — the half with sprites must draw and the half without
+must not. Two halves that both drew nothing would read 1.0x and pass, having measured
+one scene twice.
+
+## When the clock is not the engine's
+
+Every number here comes from the host's own frame span, and that span can be spent
+**waiting**. A frame the compositor throttles reads 16.6 ms whatever the scene holds —
+200 entities or 2,000, one draw or none — and the pair then reads 1.00x and passes,
+having compared two frames that were both the display's.
+
+So the host reports `busy`: CPU actually burned inside the span, over its wall. A run
+below `BENCH_MIN_BUSY` (default 0.5) is refused rather than reported. Measured, a
+throttled run reads 8-11% busy.
+
+Two causes seen on macOS: a window another app covers, and a **virtual display** — a
+remote-desktop session hands out drawables at its own rate however fast the frame is,
+and `SDL_WINDOW_ALWAYS_ON_TOP` (which a benched window asks for) does not help. Run the
+bench on a machine with its own attached display and nothing over the window.
+
+The DENOMINATOR trips first, and that is by construction: it is the cheapest frame in
+each comparison, so it is the first one a throttle can pin. A pair whose numerator still
+has real work in it will fail on its holding half before its ratio can lie.
diff --git a/bench/aot-native/frame-bench.mjs b/bench/aot-native/frame-bench.mjs
index 2368636e7..f7c35a3ce 100644
--- a/bench/aot-native/frame-bench.mjs
+++ b/bench/aot-native/frame-bench.mjs
@@ -16,21 +16,25 @@
* `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.
+ * and reads the host's own frame clock (native/host/Bench.hpp) off both. It also
+ * reads a COUNT off the host — how many entities each compiled system was paid
+ * over — because the second thing that can go wrong here is not a slower frame
+ * but a frame charged for the whole world (see `--gate`).
*
* 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.
*
- * and reads the host's own frame clock (native/host/Bench.hpp) off both. It also
- * reads a COUNT off the host — how many entities each compiled system was paid
- * over — because the second thing that can go wrong here is not a slower frame
- * but a frame charged for the whole world (see `--gate`).
+ * The same clock answers a second question under `--gate`: what a frame spends
+ * DRAWING. Counts bound how much a frame submits and say nothing about what
+ * submitting it cost, so a pair of scenes differing only in whether they carry a
+ * `Sprite` puts a ceiling on the time — see the README.
*
* node bench/aot-native/frame-bench.mjs
* BENCH_ENTITIES=20000 BENCH_BODIES=thin,heavy node bench/aot-native/frame-bench.mjs
* BENCH_BUILDS=compiled BENCH_BYSTANDERS=95000 node bench/aot-native/frame-bench.mjs
+ * BENCH_BODIES= BENCH_RENDER=1 node bench/aot-native/frame-bench.mjs
*/
import { spawnSync } from 'node:child_process';
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -77,6 +81,29 @@ const KEEP = process.env.BENCH_KEEP === '1';
* never lifts a cheap system clear of it.
*/
const SPRITES = process.env.BENCH_SPRITES !== '0';
+/**
+ * The render pair's scene: one scene twice, differing only in whether its
+ * entities carry a `Sprite`, so only the numerator carries the drawing. 128,000
+ * because the DENOMINATOR is the small number and its noise is the ratio's — the
+ * numerator repeats to 1%, the denominator to 16%, and it does not shrink below.
+ */
+const RENDER_ENTITIES = Number(process.env.BENCH_RENDER_ENTITIES ?? 128000);
+/**
+ * How much of a frame's span has to be CPU for the span to be about the engine.
+ * A window the compositor throttles reads 16.6 ms at 9% busy whatever the scene
+ * holds, and every number in the report is that wait — see MIN_BUSY's uses.
+ */
+const MIN_BUSY = Number(process.env.BENCH_MIN_BUSY ?? 0.5);
+/** Run the pair. Always under `--gate`; opt in with BENCH_RENDER=1 to explore. */
+const RENDER = GATE || process.env.BENCH_RENDER === '1';
+/**
+ * How much of the frame the drawing may be — set from a SABOTAGE, not from
+ * headroom over today. Submitting every sprite twice takes 59 ns/sprite to 109;
+ * healthy runs read 3.65-4.21 and that one 5.94. A ceiling of 4 was tried at
+ * 32,000 entities, where the same sabotage read 3.90 and passed.
+ */
+const RENDER_MAX_RATIO = Number(process.env.BENCH_RENDER_MAX_RATIO ?? 5);
+
/**
* Entities carrying NO component: the size of the WORLD, separated from the size
* of the matched set. Bare is load-bearing — a bystander the engine transforms
@@ -138,7 +165,7 @@ const TSCONFIG = JSON.stringify({
* with different starting positions have no differential between them, and
* `Math.random` would give exactly that.
*/
-function mainTs(body) {
+function mainTs(body, scene) {
const spec = BODY[body];
const schedule = spec.system === null ? '' : `addSystemToSchedule(Schedule.Update, ${spec.system});\n`;
return `import {
@@ -148,8 +175,8 @@ function mainTs(body) {
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 BYSTANDERS = ${BYSTANDERS};
+const ENTITIES = ${scene.entities};
+const BYSTANDERS = ${scene.bystanders};
const CHECKSUM_AT = ${WARMUP + FRAMES};
/** The generator bench/aot-frame uses, so both benchmarks lay out one scene. */
@@ -169,7 +196,7 @@ const setupSystem = defineSystem([Commands()], (cmds) => {
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 })${SPRITES
+ .insert(Pos, { x: 0, y: 0, z: 0 })${scene.sprites
? "\n .insert(Sprite, { size: { x: 4, y: 4 }, color: { r: 1, g: 1, b: 1, a: 1 } })" : ''};
}
// NOTHING on them: they grow the world without growing the matched set, and
@@ -199,11 +226,14 @@ ${schedule}addSystemToSchedule(Schedule.Update, checksumSystem);
`;
}
-function materialize(dir, body) {
+/** What a scene is, as parameters: everything the generated project differs by. */
+const SCENE_DEFAULT = { entities: ENTITIES, bystanders: BYSTANDERS, sprites: SPRITES };
+
+function materialize(dir, body, scene = SCENE_DEFAULT) {
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, 'src', 'main.ts'), mainTs(body, scene));
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({
@@ -211,7 +241,7 @@ function materialize(dir, body) {
importer: { autoMigrate: true },
}, null, 2));
writeFileSync(path.join(dir, 'project.esproject'), JSON.stringify({
- formatVersion: '1', name: `AotNativeBench-${body}`,
+ formatVersion: '1', name: `AotNativeBench-${path.basename(dir)}`,
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',
@@ -269,6 +299,8 @@ function run(exe, label) {
const out = mkdtempSync(path.join(tmpdir(), 'estella-aot-native-bench-'));
const rows = [];
+/** The render pair's two halves, keyed by which one they are. */
+const render = {};
try {
const bodies = IDLE ? [...BODIES, 'idle'] : BODIES;
for (const body of bodies) {
@@ -292,6 +324,30 @@ try {
rows.push({ body, key, ...best });
}
}
+ // The render pair. Compiled only: `idle` schedules no system, so the two
+ // builds of it are the same program, and the interpreted export would cost a
+ // minute to measure nothing.
+ if (RENDER) {
+ const halves = ['drawing', 'holding'];
+ const exe = {};
+ for (const half of halves) {
+ const project = path.join(out, `${half}-project`);
+ materialize(project, 'idle',
+ { entities: RENDER_ENTITIES, bystanders: 0, sprites: half === 'drawing' });
+ process.stdout.write(` exporting ${half} (${RENDER_ENTITIES} entities)...\n`);
+ exe[half] = exportApp(project, path.join(out, `${half}-build`), true);
+ }
+ // Interleaved: run one half's reps and then the other's, and any drift
+ // between the two stretches lands whole in the ratio. Three reps, because
+ // the denominator threw an outlier 12% high in one run of eight.
+ for (let rep = 0, reps = Math.max(REPS, 3); rep < reps; rep++) {
+ for (const half of halves) {
+ const r = run(exe[half], half);
+ process.stdout.write(` ${half} rep ${rep + 1}/${reps}: cpu p50 ${r.cpu.p50.toFixed(3)} ms\n`);
+ if (render[half] === undefined || r.cpu.p50 < render[half].cpu.p50) render[half] = r;
+ }
+ }
+ }
} finally {
if (!KEEP) rmSync(out, { recursive: true, force: true });
else console.log(`\nkept: ${out}`);
@@ -307,17 +363,33 @@ console.log(`\nno-JIT frame — QuickJS-ng in the native host, ${ENTITIES} entit
// `walked` is what a compiled system covered in one frame, `packed` what it had
// to write — zero once the row table is being kept. Counts and not clocks on
// purpose; see the ceiling below.
-console.log('body build tick p50 cpu p50 frame p50 draws walked packed compiled?');
+/** How much of a frame's span was CPU and not waiting; '?' from a host that cannot say. */
+const busyText = (r) => (typeof r.busy === 'number' && r.busy >= 0 ? r.busy.toFixed(2) : '?');
+
+console.log('body build tick p50 cpu p50 frame p50 busy draws walked packed 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)} ${String(r.aotCandidates ?? '?').padStart(9)}`
+ + ` ${busyText(r).padStart(6)} ${String(r.draws ?? '?').padStart(7)} ${String(r.aotCandidates ?? '?').padStart(9)}`
+ ` ${String(r.aotPacked ?? '?').padStart(8)} ${r.running ?? '—'}`);
}
let bad = 0;
console.log('');
+// A frame the compositor throttled spends its span waiting and reads exactly like
+// a frame that cost that much — measured, 16.6 ms whatever the scene held, at 8%
+// busy, and the render pair reading 0.99x and passing. Refuse, do not report.
+for (const r of rows.concat(Object.values(render))) {
+ if (typeof r.busy !== 'number' || r.busy < 0) continue;
+ if (r.busy >= MIN_BUSY) continue;
+ console.error(`✗ ${r.label || 'a run'}: only ${(r.busy * 100).toFixed(0)}% of its frame was CPU`
+ + ` (needs ${(MIN_BUSY * 100).toFixed(0)}%) — it WAITED, so ${r.cpu.p50.toFixed(2)} ms is the`
+ + ' compositor and not the engine. Measured causes: a covered window, and a virtual display'
+ + ' (a remote session), which hands out drawables at its own rate however fast the frame is.');
+ bad++;
+}
+
// ------------------------------------------------------------------ the ceiling
//
// A compiled system is paid over what it MATCHES, not over the world: the host
@@ -417,4 +489,31 @@ for (const body of [...new Set(rows.map((r) => r.body))]) {
+ (cSys > 0.05 ? ` (${(iSys / cSys).toFixed(0)}x)` : ' (at the idle floor)'));
}
}
+
+// ------------------------------------------------------------ what drawing costs
+//
+// The frame's TIME, which nothing else bounds: the count ceilings hold draws,
+// meshes and triangles, every one of which a frame can honour for twice the CPU.
+if (render.drawing && render.holding) {
+ const drawing = render.drawing.cpu.p50;
+ const holding = render.holding.cpu.p50;
+ const ratio = drawing / holding;
+ const nsPerSprite = ((drawing - holding) * 1e6) / RENDER_ENTITIES;
+ console.log(`\ndrawing: ${RENDER_ENTITIES} sprites make the frame ${ratio.toFixed(2)}x the one that `
+ + `only holds them (${holding.toFixed(2)} ms -> ${drawing.toFixed(2)} ms, `
+ + `${nsPerSprite.toFixed(0)} ns/sprite, ${render.drawing.draws} draw(s))`);
+ if (GATE && !(ratio <= RENDER_MAX_RATIO)) {
+ console.error(`✗ drawing: the frame is ${ratio.toFixed(2)}x the one that only holds the same `
+ + `entities, over the ${RENDER_MAX_RATIO}x ceiling — submitting a sprite got dearer`);
+ bad++;
+ }
+ // A half that drew nothing is not a control, it is a broken export: the pair
+ // would read 1.0x and pass, having measured one scene twice.
+ if (!(render.drawing.draws > 0) || render.holding.draws !== 0) {
+ console.error(`✗ drawing: the pair is not a pair — ${render.drawing.draws} draw(s) with sprites, `
+ + `${render.holding.draws} without`);
+ bad++;
+ }
+}
+
if (bad > 0) process.exit(1);
diff --git a/build-tools/utils/desktopApp.js b/build-tools/utils/desktopApp.js
index 6f704aa60..da7eaecec 100644
--- a/build-tools/utils/desktopApp.js
+++ b/build-tools/utils/desktopApp.js
@@ -191,14 +191,11 @@ async function signBundle(bundle, options, nested = []) {
/**
- * The executable inside an assembled app, located through the same table that
- * put it there.
+ * The executable inside an assembled app, from the same table that put it there.
*
- * Two runners searched for it instead, by the shape "a file with no extension".
- * Every signed macOS bundle carries `Contents/_CodeSignature/CodeResources`,
- * which has that shape, and which of the two a directory walk reaches first is
- * decided by directory order — so they launched the signature manifest and then
- * reported that the engine had installed no module and drawn no frame.
+ * Not a search for "a file with no extension": every signed macOS bundle carries
+ * `Contents/_CodeSignature/CodeResources`, which fits that shape, and directory
+ * order decided which one a walk reached first.
*
* @param {string} dir A directory an export wrote an app into, at any depth.
* @param {'macos'|'windows'|'linux'} platform Whose layout to read.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 290ef7872..ae86afddd 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -115,7 +115,7 @@ platform-tools,不是完整 SDK。**注意编译那一半才是被卡住的**
**所以这是一个要你决定的岔路**:装 NDK(Android Studio 的 SDK Manager,或解压一份并
设 `ANDROID_NDK_HOME`),还是把第 2 项挪到别的机器上做。在那之前它开不了。
-## 3. 一帧花了多少**时间**,没有任何东西给它天花板
+## 3. 一帧花了多少**时间**,没有任何东西给它天花板〔已落地 2026-08-27〕
**现状。** 计数天花板有(`sprite-scale-cost` / `mesh-scale-cost` / `shadow-scale-cost`)。
时间的没有:`tools/perf-guard.mjs` 断言的是微基准之间的**比值**(CPU 抵消掉),
@@ -152,6 +152,52 @@ platform-tools,不是完整 SDK。**注意编译那一半才是被卡住的**
`render.shadow.tiles` 的上限,被拿掉了,因为那个场景里没有任何东西能把它推过 8 ——
它由 cascade 数界定,不由 caster 数界定。要预算它得换一个分母。
+### 落地了什么(2026-08-27)
+
+**新准则 `a-frame-pays-for-what-it-draws`**,由 `frame-bench --gate` 回答。形状是一对:
+同一个场景两份,只差实体身上有没有 `Sprite`。两半装着同样的实体、跑同样的调度,所以机器
+和引擎自己那份每帧开销都在分母里,只有分子扛着「画」。实测 128,000 个 sprite 让一帧变成
+「只装着它们」那一帧的 **3.65–4.21x**,59–61 ns/sprite。
+
+**实体数是用来让比值*稳*的,不是用来让它*大*的。** 分母是小的那个数,它的抖动就是比值的
+抖动:32,000 上分母在几次运行间读出 1.03 和 1.19 ms,健康比值散在 2.85–3.01,而破坏读
+3.90 —— **重叠了,天花板 4 抓不住它**。128,000 上分子重复到 1%,同一个破坏(每个 sprite
+提交两次)把 59 ns/sprite 变成 115、比值变成 6.97,对天花板 5 两次都红,三次健康跑全绿。
+
+**开工前先撞了两堵墙,都不在计划里,而且都让「已有的钟」根本没在走。**
+
+1. **三条发布准则在 Mac 上从来跑不了,其中一条还把 runner 的错说成引擎的错。**
+ `verify-aot-native` 和 frame-bench 都靠「找一个没有扩展名的文件」定位刚导出的 app,
+ 而每个签过名的 macOS bundle 都带 `Contents/_CodeSignature/CodeResources` —— 正好是
+ 这个形状,谁先被目录遍历撞上由目录顺序决定。于是两个 runner 跑的都是签名清单。
+ frame-bench 说「宿主没打印 bench 行」,`verify-aot-native` 说「没装模块、没派发到任何
+ 编译系统、一帧都没画」—— 三句话对一个文本文件全是真的。签名自桌面装配器落地起就在
+ darwin 上无条件执行,也就是说这三条准则**从没在它们被写出来的平台上答过一次**。
+
+2. **Metal 上被测的那一帧是显示器的,不是引擎的。** `setPresentUncapped` 挑 Mailbox,
+ 而 Dawn 的 Metal 后端只对 Immediate 清掉 `displaySyncEnabled`(`SwapChainMTL.mm`)——
+ 请求成功了,什么也没改变。**没有任何东西会说出来**,因为被节流的一帧读起来就是
+ 「花了一个刷新间隔」的一帧:200 个实体和 2,000 个、一个 draw 和零个 draw,每个 span
+ 都是 16.6 ms,而 AOT 那两个 build 读出 1.00x —— 门禁把它报成「编译系统退回解释器」。
+ **判定它的是进程自己的两个钟**:6.25 s 墙钟对 0.69 s CPU,也就是说这一帧 89% 的时间在等。
+ 改成 Immediate 优先后同一帧读 3.03 ms,AOT 比值 9.3x。
+
+3. **然后第三堵:一帧可以整段花在*等*上,而报告里没有任何东西能说出来。** 造完天花板去
+ 验它,读到 **1.00x —— 一个会通过的假绿**:两半都被压到 16.6 ms,比的是两帧显示器。
+ 所以宿主现在发 `busy`(span 里真烧掉的 CPU 除以它的墙钟,取自线程自己的钟),低于一半
+ 就**拒绝**而不是报数;被节流的跑读 8–11%。**每次比较里最便宜的那一帧先跳出来**,这个
+ 方向是对的:它正是节流能压住、而另一半还在干活的那个。
+
+ 两个已实测的成因:窗口被盖(benched 窗口现在主动要 `SDL_WINDOW_ALWAYS_ON_TOP`),以及
+ **虚拟显示器**——远程桌面会话按自己的节拍发 drawable,帧再快也没用,置顶标志救不了。
+ **这台机器现在就是第二种**(1920×1080 虚拟屏,`IODisplayWrangler` 不应答),所以
+ `frame-bench --gate` 在这里会拒绝作答。天花板本身的标定是在没被节流的时候取的
+ (drawing 10.3–10.6 / holding 2.45–2.89,破坏 17.0–17.2 / 2.46),数是干净的。
+
+**遗留:`thin` 那条 AOT 比值准则在 `--gate` 下是 `REPS=1`,一个坏样本就定案。** 同一棵树
+上 compiled 侧读到过 0.735 / 1.195 / 2.864 ms,最后那次让准则红了(2.67x,要求 5x)。
+渲染这一对是靠**交错跑 + 3 reps 取最小**解决同一个问题的;`thin` 还没有。
+
## 4. 重读 `rendering` 的判决,顺手解锁 fog / DOF / SSAO
@@ -245,7 +291,7 @@ experimental 对创作者读起来是「大半个引擎没做完」,哪怕其
## 建议的顺序
-**1 → 5 → 4 → 3 → 2。** 〔1、5、6 已关闭;4 的工程那半已落地,定级待拍板;3 的前提被实测推翻,见上;剩 2。〕
+**1 → 5 → 4 → 3 → 2。** 〔1、3、5、6 已关闭;4 的工程那半已落地,定级待拍板;剩 2,卡在 NDK。〕
先把量到的浪费修掉(1),顺手清掉两处假的清单项(5),再做一次定级重读 + FrameConstants
(4,这两个是「读」和「一个成员」,不是工程),然后是时间门禁(3),最后开 Android(2,
diff --git a/native/host/Bench.cpp b/native/host/Bench.cpp
index ec6eda0ec..3c5851a90 100644
--- a/native/host/Bench.cpp
+++ b/native/host/Bench.cpp
@@ -18,6 +18,12 @@
#include <string>
#include <vector>
+#if defined(_WIN32)
+#include <windows.h>
+#else
+#include <ctime>
+#endif
+
#include "Runtime.hpp" // ESHOST_LOGI
namespace eshost {
@@ -29,6 +35,28 @@ double msSince(const Clock::time_point& t0) {
return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
}
+/**
+ * Milliseconds of CPU this thread has actually burned, or -1 where the platform
+ * will not say. A frame that WAITED reads exactly like a frame that worked, and
+ * this is the only thing in the report that tells the two apart.
+ */
+double threadCpuMs() {
+#if defined(_WIN32)
+ FILETIME creation, exit, kernel, user;
+ if (GetThreadTimes(GetCurrentThread(), &creation, &exit, &kernel, &user) == 0) return -1.0;
+ const auto ticks = [](const FILETIME& t) {
+ return (static_cast<unsigned long long>(t.dwHighDateTime) << 32) | t.dwLowDateTime;
+ };
+ return static_cast<double>(ticks(kernel) + ticks(user)) / 1e4; // 100 ns ticks
+#elif defined(CLOCK_THREAD_CPUTIME_ID)
+ timespec ts{};
+ if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) != 0) return -1.0;
+ return static_cast<double>(ts.tv_sec) * 1e3 + static_cast<double>(ts.tv_nsec) / 1e6;
+#else
+ return -1.0;
+#endif
+}
+
/** A span's samples, and the three numbers worth reading off them. */
struct Span {
std::vector<double> ms;
@@ -47,6 +75,10 @@ struct BenchState {
std::string label;
long seen = 0; // frames entered, warmup included
Span update, pump, cpu, frame;
+ /** CPU actually burned inside the timed `cpu` spans, against their wall. A
+ * frame throttled by the compositor spends its span waiting, and every other
+ * number in the report reads that wait as cost. */
+ double busyCpuMs = 0.0, busyWallMs = 0.0, cpuAtSpanBegin = -1.0;
unsigned draws = 0, sprites = 0;
/** This frame's running totals, and the last timed frame's — the same shape
* `draws` has, so the report reads one frame rather than an average that
@@ -113,13 +145,16 @@ void report() {
// 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;
+ // -1, not 0: "the platform would not say" and "the frame did nothing but
+ // wait" are different answers and a consumer has to be able to refuse both.
+ const double busy = s.busyWallMs > 0.0 ? s.busyCpuMs / s.busyWallMs : -1.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,\"aotCandidates\":%u,\"aotPacked\":%u,"
- "\"tickShareOfCpu\":%.4f}",
+ "\"tickShareOfCpu\":%.4f,\"busy\":%.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,
@@ -127,7 +162,7 @@ void report() {
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, s.aotCandidatesFrame, s.aotPackedFrame, share);
+ s.draws, s.sprites, s.aotCandidatesFrame, s.aotPackedFrame, share, busy);
}
} // namespace
@@ -152,6 +187,7 @@ void benchFrameBegin() {
if (timing()) {
s.frame.begin();
s.cpu.begin();
+ s.cpuAtSpanBegin = threadCpuMs();
}
}
@@ -159,7 +195,16 @@ 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 benchBeforePresent() {
+ if (!timing()) return;
+ BenchState& s = state();
+ s.cpu.end();
+ const double now = threadCpuMs();
+ if (s.cpuAtSpanBegin >= 0.0 && now >= 0.0) {
+ s.busyCpuMs += now - s.cpuAtSpanBegin;
+ s.busyWallMs += s.cpu.ms.back();
+ }
+}
void benchNoteDraws(unsigned draws, unsigned sprites) {
if (!timing()) return;
diff --git a/native/host/Bench.hpp b/native/host/Bench.hpp
index 6467754d1..4d197f460 100644
--- a/native/host/Bench.hpp
+++ b/native/host/Bench.hpp
@@ -27,6 +27,11 @@
* denominator: `pump / cpu` is the fraction a compiler can reach.
* - `frame` — including `present()`, for reference.
*
+ * And `busy`: CPU actually burned inside `cpu`, over its wall. A frame
+ * the compositor throttled spends its span WAITING and reads exactly
+ * like a frame that cost that much — measured, 16.6 ms a scene at 11%
+ * busy. Anything consuming these numbers has to be able to refuse that.
+ *
* 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
diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cpp
index 98a64f99f..b8066e191 100644
--- a/native/host/platform/desktop.cpp
+++ b/native/host/platform/desktop.cpp
@@ -30,6 +30,7 @@
#include <string>
#include <vector>
+#include "Bench.hpp"
#include "Host.hpp"
#include "media/text_edit.hpp"
@@ -489,6 +490,10 @@ int main(int argc, char** argv) {
// before any JS, and showing it then is half a second of an empty white rect
// with the game's name on it.
SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN;
+ // A benched window asks not to be covered, because a covered one is not slow,
+ // it is STOPPED: macOS hands an occluded layer drawables at the refresh rate
+ // and no faster, and the frame then reads as the display (see Bench.hpp).
+ if (eshost::benchWanted()) flags |= SDL_WINDOW_ALWAYS_ON_TOP;
#if defined(__APPLE__)
flags |= SDL_WINDOW_METAL;
#elif defined(__linux__)
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index cc4cb29c9..dc76952fa 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -393,14 +393,10 @@ bool WebGPUDevice::surfaceBytesAreBGRA() const {
/**
* The fastest present mode this surface actually advertises.
*
- * Immediate FIRST, and the order is load-bearing rather than a preference: this
- * mode exists so a frame can be timed, and Dawn's Metal backend clears
- * `displaySyncEnabled` for Immediate ALONE (`SwapChainMTL.mm`). A surface that
- * offers both hands back a Mailbox that is still vsynced, so the bench reads the
- * panel — measured here as every span pinned to 16.6 ms while the process sat
- * blocked for 89% of its wall clock. Tearing is what the caller is buying.
- *
- * Fifo is the fallback, and then the caller's frame is throttled.
+ * Immediate FIRST, and the order is load-bearing: Dawn's Metal backend clears
+ * `displaySyncEnabled` for Immediate ALONE (`SwapChainMTL.mm`), so a surface
+ * offering both hands back a Mailbox that is still vsynced — measured, every
+ * span pinned to 16.6 ms. Fifo is the fallback, and then the frame is throttled.
*/
WGPUPresentMode WebGPUDevice::pickUncappedPresentMode() const {
#if !defined(__EMSCRIPTEN__)
diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjs
index 04fc5eca6..3bb8e0e3d 100644
--- a/tools/releaseGate.mjs
+++ b/tools/releaseGate.mjs
@@ -134,6 +134,16 @@ export const CRITERIA = [
needs: ['bench/aot-native/frame-bench.mjs', 'src/esengine/aot/AotHost.hpp',
'native/host/bindings/AotBindings.cpp'],
},
+ {
+ id: 'a-frame-pays-for-what-it-draws',
+ says: 'the CPU a frame spends drawing is bounded, not only the draws it makes',
+ // Counts were the only ceiling a frame had: `sprite-scale-cost` and its
+ // siblings hold draws, meshes and triangles, and a frame can honour all three
+ // while costing twice the CPU. A same-machine ratio, for the reason above.
+ answeredBy: 'node bench/aot-native/frame-bench.mjs --gate',
+ needs: ['bench/aot-native/frame-bench.mjs', 'native/host/Bench.cpp',
+ 'src/esengine/renderer/plugins/SpritePlugin.cpp'],
+ },
{
id: 'compiled-systems-compute-what-the-interpreter-computes',
says: 'a packaged compiled system moves the world exactly as the interpreted one does',