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
test(ui): measure WASM layout and await integration frames (#89)
YHHc6c8d508f8b4
diff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.mdindex 52145f4b6..3c5ebcd2c 100644--- a/examples/ui-localization-debug/README.md+++ b/examples/ui-localization-debug/README.md@@ -153,3 +153,14 @@ exact submitted geometry outside timing and exposes raw paired samples andenvironment metadata. Statistics describe ten batch-average frame times, notindividual-frame P95. A representative run is saved in`cache-cpu-web-2026-10-09.json`; timings vary with JIT and background load.++For the real Yoga/WASM layout comparison, run `node tools/ui-layout-cpu-benchmark.mjs`+and open `http://127.0.0.1:5197/__layout-cpu-benchmark`. It serves the existing+editor WASM build and records its SHA-256. The fixture has one Canvas, twenty+Flex rows and four hundred controls. It compares a correct manual dirty signal+with forced property refresh; both retain Yoga nodes. Timings include component+writes and one layout call, excluding App scheduling, Transform pass, text and+GPU. Four update ratios and both width states compare all 421 nodes' local+positions and computed dimensions. Raw paired data is in+`layout-cpu-web-2026-10-09.json`. This does not benchmark a fresh Yoga rebuild;+the incremental-layout SDK regression separately compares against fresh registries.diff --git a/examples/ui-localization-debug/VALIDATION.md b/examples/ui-localization-debug/VALIDATION.mdindex 5904dfde9..3d3900234 100644--- a/examples/ui-localization-debug/VALIDATION.md+++ b/examples/ui-localization-debug/VALIDATION.md@@ -430,3 +430,29 @@ snapshot; live-game-only dialogs and scripts need runtime acceptance separately.complex shaping and target devices remain unmeasured. Warm-up/JIT/backgroundload affect results; do not convert these ratios into a game FPS claim.RM-009 remains In Progress. No local Electron/native runner launched.++## Actual WASM layout measurement and test lifetime — 2026-10-09++- A browser-only fixture loads the existing editor engine WASM (SHA-256 in the+ raw report). One Canvas, twenty flex rows, four hundred controls: all 421+ nodes' local positions and dimensions agree for 0/1/10/100% updates and both+ changed width states. Changed widths are checked explicitly to reject no-ops.+- Ten paired batches of twenty layout calls alternate normal manual dirty+ signals and forced property refresh. Both retain Yoga nodes; this is not a+ fresh-node rebuild or historical before/after benchmark. Timing includes+ UINode writes and uiLayout_update, excluding App scheduling, Transform, text,+ rendering and GPU. Browser-generated layout-cpu-web-2026-10-09.json preserves+ every sample and the loaded WASM build hash.+- Median batch-average update milliseconds, forced → normal: static+ 0.060 → 0.015; 1% changes 0.125 → 0.125; 10% 0.505 → 0.495;+ 100% 4.290 → 4.390. Dirty layouts show no extra benefit against a forced+ property refresh, since both perform that work. P95 describes batch averages.+- Running the existing integration suite exposed three async not.toThrow+ assertions that did not await tick before deleting the registry; they logged+ deleted-Registry errors while reporting success. Await the actual tick Promise,+ verify root dimensions after one/sixty ticks, and fail on logged system errors+ (App can catch them without rejecting tick). Seventeen real-WASM integration+ and incremental-versus-fresh-registry tests now pass without system errors.+- No runtime optimization is claimed. End-to-end frame timing, changed-subtree+ scope optimization, shaping and device acceptance remain open; RM-009 remains+ In Progress. No local Electron/native runner launched.diff --git a/examples/ui-localization-debug/layout-cpu-web-2026-10-09.json b/examples/ui-localization-debug/layout-cpu-web-2026-10-09.jsonnew file mode 100644index 000000000..0904a20fd--- /dev/null+++ b/examples/ui-localization-debug/layout-cpu-web-2026-10-09.json@@ -0,0 +1,150 @@+{+ "schema": 1,+ "controls": 400,+ "nodes": 421,+ "rounds": 10,+ "frames": 20,+ "date": "2026-10-10T02:03:23.080Z",+ "build": {+ "wasmSha256": "e39668b95b3d5a7ed899906843f06d21531da0083e9c0b17d5ce6c1426f29125",+ "wasmBytes": 1910267+ },+ "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",+ "dpr": 1.25,+ "statistic": "median/nearest-rank P95 of batch-average update times",+ "results": [+ {+ "rate": 0,+ "changed": 0,+ "samples": {+ "normal": [+ 0.010000002384185792,+ 0.015000003576278686,+ 0.009999996423721314,+ 0.015000003576278686,+ 0.010000002384185792,+ 0.01499999761581421,+ 0.015000003576278686,+ 0.020000004768371583,+ 0.010000002384185792,+ 0.015000003576278686+ ],+ "forced": [+ 0.10499999523162842,+ 0.0550000011920929,+ 0.06500000357627869,+ 0.06499999761581421,+ 0.06499999761581421,+ 0.0550000011920929,+ 0.05499999523162842,+ 0.06499999761581421,+ 0.059999996423721315,+ 0.059999996423721315+ ]+ },+ "normalMedian": 0.01499999761581421,+ "forcedMedian": 0.059999996423721315,+ "maxDifference": 0+ },+ {+ "rate": 0.01,+ "changed": 4,+ "samples": {+ "normal": [+ 0.1350000023841858,+ 0.1300000011920929,+ 0.11499999761581421,+ 0.1350000023841858,+ 0.1600000023841858,+ 0.1300000011920929,+ 0.1199999988079071,+ 0.125,+ 0.11499999761581421,+ 0.125+ ],+ "forced": [+ 0.1449999988079071,+ 0.125,+ 0.1350000023841858,+ 0.1449999988079071,+ 0.2199999988079071,+ 0.1199999988079071,+ 0.1199999988079071,+ 0.1100000023841858,+ 0.125,+ 0.1550000011920929+ ]+ },+ "normalMedian": 0.125,+ "forcedMedian": 0.125,+ "maxDifference": 0+ },+ {+ "rate": 0.1,+ "changed": 40,+ "samples": {+ "normal": [+ 0.5100000023841857,+ 0.5399999976158142,+ 0.5350000023841858,+ 0.4949999988079071,+ 0.4850000023841858,+ 0.4899999976158142,+ 0.4849999964237213,+ 0.4949999988079071,+ 0.4949999988079071,+ 0.4849999964237213+ ],+ "forced": [+ 0.5550000011920929,+ 0.5100000023841857,+ 0.5449999988079071,+ 0.5050000011920929,+ 0.5049999952316284,+ 0.4900000035762787,+ 0.5050000011920929,+ 0.5600000023841858,+ 0.4899999976158142,+ 0.6900000035762787+ ]+ },+ "normalMedian": 0.4949999988079071,+ "forcedMedian": 0.5050000011920929,+ "maxDifference": 0+ },+ {+ "rate": 1,+ "changed": 400,+ "samples": {+ "normal": [+ 4.215000003576279,+ 4.194999998807907,+ 4.475,+ 4.394999998807907,+ 5.044999998807907,+ 4.375,+ 4.314999997615814,+ 4.475,+ 4.3900000035762785,+ 4.585000002384186+ ],+ "forced": [+ 4.309999996423722,+ 4.275,+ 4.284999996423721,+ 4.289999997615814,+ 4.525,+ 4.254999995231628,+ 4.285000002384185,+ 4.554999995231628,+ 4.784999996423721,+ 4.689999997615814+ ]+ },+ "normalMedian": 4.3900000035762785,+ "forcedMedian": 4.289999997615814,+ "maxDifference": 0+ }+ ],+ "scope": "actual WASM layout update + UINode writes; retained Yoga nodes in both; no full App/Transform/text/GPU; not historical before/after"+}diff --git a/sdk/tests/ui-layout-integration.test.ts b/sdk/tests/ui-layout-integration.test.tsindex 7e65ae42c..976ded476 100644--- a/sdk/tests/ui-layout-integration.test.ts+++ b/sdk/tests/ui-layout-integration.test.ts@@ -8,7 +8,8 @@* Requires pre-built WASM at build/wasm/web/esengine.wasm.* Run `node build-tools/cli.js build -t web` first if missing.*/-import { describe, it, expect, beforeAll } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import { log } from '../src/util/logger';import { App } from '../src/app/app';import { UINode, type UINodeData } from '../src/ui/core/ui-node';import { FlexContainer, type FlexContainerData } from '../src/ui/layout/flex';@@ -92,6 +93,14 @@ function makeSprite(w = 100, h = 100) {describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () => {let module: ESEngineModule;+ beforeEach(() => { vi.spyOn(log, 'error'); });+ afterEach(() => {+ // App reports system errors rather than rejecting tick; they must fail+ // this integration suite even when a Promise resolves successfully.+ try { expect(log.error).not.toHaveBeenCalled(); }+ finally { vi.restoreAllMocks(); }+ });+beforeAll(async () => {module = await loadWasmModule();});@@ -158,7 +167,9 @@ describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () =>setCanvasRect(app, -400, -300, 400, 300);- await expect(async () => await app.tick(1 / 60)).not.toThrow();+ await expect(app.tick(1 / 60)).resolves.toBeUndefined();+ expect(nodeW(registry, root)).toBeCloseTo(800, 3);+ expect(nodeH(registry, root)).toBeCloseTo(600, 3);disposeApp(app, registry);});@@ -267,8 +278,10 @@ describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () =>setCanvasRect(app, -400, -300, 400, 300);for (let i = 0; i < 60; i++) {- await expect(async () => await app.tick(1 / 60)).not.toThrow();+ await expect(app.tick(1 / 60)).resolves.toBeUndefined();}+ expect(nodeW(registry, root)).toBeCloseTo(800, 3);+ expect(nodeH(registry, root)).toBeCloseTo(600, 3);disposeApp(app, registry);});@@ -285,7 +298,7 @@ describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () =>const cam = app.getResource(UICameraInfo);cam.valid = false;- await expect(async () => await app.tick(1 / 60)).not.toThrow();+ await expect(app.tick(1 / 60)).resolves.toBeUndefined();expect(nodeW(registry, root)).toBe(0);diff --git a/tools/ui-layout-cpu-benchmark.mjs b/tools/ui-layout-cpu-benchmark.mjsnew file mode 100644index 000000000..f11368b0c--- /dev/null+++ b/tools/ui-layout-cpu-benchmark.mjs@@ -0,0 +1,31 @@+// SPDX-License-Identifier: Apache-2.0+// Serves the existing editor WASM build; never launches Electron.+import fs from 'node:fs';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { fileURLToPath, pathToFileURL } from 'node:url';+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const wasmDir = path.join(root, 'desktop/public/wasm');+const wasm = fs.readFileSync(path.join(wasmDir, 'esengine.wasm'));+const metadata = { wasmSha256: createHash('sha256').update(wasm).digest('hex'), wasmBytes: wasm.length };+const { createServer } = await import(pathToFileURL(path.join(root, 'desktop/node_modules/vite/dist/node/index.js')).href);+const server = await createServer({ configFile: false, root,+ optimizeDeps: { noDiscovery: true, entries: [] },+ server: { host: '127.0.0.1', port: 5197, strictPort: true },+ plugins: [{ name: 'layout-cpu-benchmark', configureServer(server) {+ server.middlewares.use((req, res, next) => {+ const url = new URL(req.url, 'http://127.0.0.1');+ if (url.pathname === '/__layout-build.json') {+ res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(metadata));+ } else if (['/__layout-wasm/esengine.js', '/__layout-wasm/esengine.wasm'].includes(url.pathname)) {+ res.setHeader('Content-Type', url.pathname.endsWith('.wasm') ? 'application/wasm' : 'application/javascript');+ res.end(fs.readFileSync(path.join(wasmDir, path.basename(url.pathname))));+ } else if (url.pathname === '/__layout-cpu-benchmark') {+ server.transformIndexHtml(req.url, '<html lang="zh"><head><meta charset="utf-8"><title>2D 布局 CPU 对照</title></head><body><main id="root"></main><script type="module" src="/tools/ui-layout-cpu-benchmark.ts"></script></body></html>')+ .then(html => { res.setHeader('Content-Type', 'text/html'); res.end(html); });+ } else next();+ });+ } }],+});+await server.listen();+console.log('Layout CPU benchmark: http://127.0.0.1:5197/__layout-cpu-benchmark');diff --git a/tools/ui-layout-cpu-benchmark.ts b/tools/ui-layout-cpu-benchmark.tsnew file mode 100644index 000000000..4239109e8--- /dev/null+++ b/tools/ui-layout-cpu-benchmark.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+import { App } from '../sdk/src/app/app';+import { Canvas, Transform } from '../sdk/src/ecs/component';+import { UINode } from '../sdk/src/ui/core/ui-node';+import { FlexContainer } from '../sdk/src/ui/layout/flex';+import { UILayoutPlugin } from '../sdk/src/ui/layout/layout';+import { px } from '../sdk/src/ui/core/dimension';+import type { CppRegistry, ESEngineModule } from '../sdk/src/wasm';++document.getElementById('root')!.innerHTML = `<style>+body{background:#15181e;color:#e3e8ef;font:14px system-ui;margin:0}main{max-width:1080px;margin:auto;padding:28px}+h1{font-size:22px}p{color:#bac3d1;line-height:1.7}button{padding:9px 18px;border:0;border-radius:6px;background:#307ed4;color:white}button:disabled{opacity:.5}+table{width:100%;border-collapse:collapse;margin:24px 0}th,td{padding:12px;text-align:left;border-bottom:1px solid #333d4d}pre{white-space:pre-wrap;word-break:break-all;font-size:11px}+</style><h1>2D 布局 · WASM CPU 对照</h1>+<p>1 个 Canvas、20 个 Flex 行、400 个控件。比较正常 dirty 信号和每次强制属性刷新;两者都保留 Yoga 节点。+计时包括控件写入和一次 uiLayout_update,不含完整 App 帧、Transform pass、文字、渲染或 GPU。+10 轮 × 20 次更新,交替顺序。中位/P95 来自批次平均更新耗时,非单帧尾延迟。</p>+<button id="run">运行对照</button><p id="status" role="status">等待运行</p>+<table><thead><tr><th>更新比例</th><th>强制刷新 中位/P95 ms</th><th>正常 dirty 中位/P95 ms</th><th>全部节点布局</th></tr></thead><tbody id="rows"></tbody></table>+<details><summary>原始数据与 WASM 版本</summary><pre id="raw"></pre></details>`;+const run = document.getElementById('run') as HTMLButtonElement;+const status = document.getElementById('status')!;+const tick = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+const percentile = (values: number[], p: number) => [...values].sort((a, b) => a - b)[Math.ceil(values.length * p) - 1];+const rounds = 10, frames = 20, controls = 400;++run.onclick = async () => {+ run.disabled = true;+ document.getElementById('rows')!.replaceChildren();+ document.getElementById('raw')!.textContent = '';+ let app: App | null = null, registry: CppRegistry | null = null;+ try {+ status.textContent = '加载真实 WASM…';+ const wasmEntry = '/__layout-wasm/esengine.js';+ const { default: factory } = await import(/* @vite-ignore */ wasmEntry);+ const module = await factory() as ESEngineModule;+ const build = await (await fetch('/__layout-build.json')).json();+ app = App.new(); registry = new module.Registry() as unknown as CppRegistry;+ app.connectCpp(registry, module); app.addPlugin(new UILayoutPlugin());+ const world = app.world;+ const all: number[] = [], leaves: number[] = [];+ const spawn = (parent: number | null, data: Record<string, unknown>) => {+ const e = world.spawn(); all.push(e);+ world.insert(e, Transform, {}); world.insert(e, UINode, data);+ if (parent !== null) world.setParent(e, parent);+ return e;+ };+ const root = spawn(null, { position: 1, width: px(800), height: px(600) });+ world.insert(root, Canvas, {}); world.insert(root, FlexContainer, { direction: 1 });+ for (let row = 0; row < 20; row++) {+ const parent = spawn(root, { width: px(760), height: px(26), flexShrink: 0 });+ world.insert(parent, FlexContainer, { direction: 0, gap: { x: 6, y: 0 } });+ for (let column = 0; column < 20; column++) leaves.push(spawn(parent, { width: px(20), height: px(20), flexShrink: 0 }));+ }+ const solve = (changed: number, frame: number, force: boolean) => {+ for (let i = 0; i < changed; i++) world.insert(leaves[i], UINode, {+ ...world.get(leaves[i], UINode), width: px(frame % 2 ? 22 : 20),+ });+ module.uiLayout_update!(registry!, -400, -300, 400, 300, force || changed > 0);+ };+ const read = () => all.map(e => {+ const t = registry!.getTransform(e);+ return { w: module.getUINodeComputedWidth!(registry!, e), h: module.getUINodeComputedHeight!(registry!, e),+ x: t.position.x, y: t.position.y };+ });+ const results: unknown[] = [];+ for (const rate of [0, .01, .1, 1]) {+ status.textContent = `正在测量 ${rate * 100}% 控件更新…`;+ const changed = Math.round(controls * rate);+ for (let f = 0; f < 20; f++) { solve(changed, f, false); solve(changed, f, true); }+ const samples = { normal: [] as number[], forced: [] as number[] };+ for (let round = 0; round < rounds; round++) {+ await tick();+ for (const mode of round % 2 ? ['normal', 'forced'] as const : ['forced', 'normal'] as const) {+ const start = performance.now();+ for (let frame = 0; frame < frames; frame++) solve(changed, frame, mode === 'forced');+ samples[mode].push((performance.now() - start) / frames);+ }+ }+ let maxDifference = 0;+ // Both variants must agree for every node, not only the edited leaves.+ for (const frame of [0, 1]) {+ solve(changed, frame, false); const normal = read();+ solve(changed, frame, true); const forced = read();+ for (let i = 0; i < all.length; i++) for (const key of ['w', 'h', 'x', 'y'] as const)+ maxDifference = Math.max(maxDifference, Math.abs(normal[i][key] - forced[i][key]));+ if (changed && Math.abs(normal[all.indexOf(leaves[0])].w - (frame % 2 ? 22 : 20)) > .001)+ throw Error('Changed width did not apply');+ }+ if (!Number.isFinite(maxDifference) || maxDifference > .001) throw Error('Layout comparison failed');+ const n = percentile(samples.normal, .5), f = percentile(samples.forced, .5);+ results.push({ rate, changed, samples, normalMedian: n, forcedMedian: f, maxDifference });+ const row = document.createElement('tr');+ row.innerHTML = `<td>${rate * 100}% (${changed}/${controls})</td><td>${f.toFixed(3)} / ${percentile(samples.forced, .95).toFixed(3)}</td><td>${n.toFixed(3)} / ${percentile(samples.normal, .95).toFixed(3)}</td><td>${all.length} 节点一致</td>`;+ document.getElementById('rows')!.append(row);+ }+ document.getElementById('raw')!.textContent = JSON.stringify({ schema: 1, controls, nodes: all.length, rounds, frames,+ date: new Date().toISOString(), build, userAgent: navigator.userAgent, dpr: devicePixelRatio,+ statistic: 'median/nearest-rank P95 of batch-average update times', results,+ scope: 'actual WASM layout update + UINode writes; retained Yoga nodes in both; no full App/Transform/text/GPU; not historical before/after' }, null, 2);+ status.textContent = '完成:四种更新比例、两个尺寸状态的全部节点布局一致。';+ } catch (error) { status.textContent = `失败:${String(error)}`; }+ finally {+ if (app && registry) { for (const e of app.world.getAllEntities()) app.world.despawn(e);+ app.world.disconnectCpp(); (registry as unknown as { delete(): void }).delete(); }+ run.disabled = false;+ }+};