A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(aot): a compiled game packages and boots, and the frame says which
yhhf0182d9c9c00
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 363c3b161..5a83c77e2 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -454,6 +454,14 @@ jobs:- uses: ./.github/actions/editor-host+ # A golden project marks a system @compiled, so packaging one now runs the+ # AOT step — and a promise the build cannot keep fails the export rather+ # than falling back. This job packages, so this job needs the toolchain.+ - name: Setup Emscripten+ uses: mymindstorm/setup-emsdk@v16+ with:+ version: 5.0.0+# The golden corpus, packaged and opened the way a player opens it, then held# against the editor's own frame of the same game. Exporting was checked and# the engine was checked; the package never was — and "it launched" is not the@@ -463,6 +471,14 @@ jobs:ELECTRON_DISABLE_SANDBOX: '1'run: xvfb-run -a node tools/verify-golden.mjs --tier pr+ # The same game packaged twice from one tree, compiled and interpreted, and+ # the two frames held against each other — the only check that sees what a+ # compiled system does to a PIXEL.+ - name: Compare a compiled game's frame to an interpreted one (PR tier)+ env:+ ELECTRON_DISABLE_SANDBOX: '1'+ run: xvfb-run -a node tools/verify-aot-parity.mjs+# Projects as they were RELEASED, opened by the editor of today. The golden# corpus is re-saved by whoever last touched it, so it can only say that this# version opens its own files; a person's project is not re-saved by anybody.diff --git a/examples/space-shooter/src/systems/effects.ts b/examples/space-shooter/src/systems/effects.tsindex bbe85cbfd..e1c29ba2b 100644--- a/examples/space-shooter/src/systems/effects.ts+++ b/examples/space-shooter/src/systems/effects.ts@@ -5,6 +5,13 @@ import {import { Explosion, Star, Bullet, Enemy } from '../components';import { HALF_HEIGHT, HALF_WIDTH, DESTROY_Y, SPAWN_Y } from '../resources';+/**+ * Carries every live bullet along its own axis.+ *+ * @compiled+ * The frame this moves is what verify-aot-parity holds against an interpreted+ * one: a twin reading the wrong offset puts the bullets somewhere visible.+ */export const bulletMoveSystem = defineSystem([Res(Time), Query(Mut(Transform), Bullet)],(time, query) => {diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 9a0fe279a..42ecd2748 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -28,6 +28,8 @@ const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options--json <file> also write the result here, for a caller that reads it back--enforce-budget fail (exit 1) when the package is over a size limit--minify minify the bundled scripts, as a shipping build does+ --no-aot package without compiling the systems marked @compiled, so+ the same project runs both ways and the frames are compared--steam-sdk <dir> desktop: a Steamworks SDK whose redistributable ships in the app--steam-appid <id> desktop: also write the Steam depot scripts for this app id@@ -51,7 +53,7 @@ The panorama itself is not shipped — a light references the \`.esenv\`.`;/** Options take a value; these do not — without the distinction a trailing flag* swallows nothing, ends the loop, and a CI job silently gets no gate. */-const FLAGS = new Set(['enforce-budget', 'minify']);+const FLAGS = new Set(['enforce-budget', 'minify', 'no-aot']);function parseArgs(argv) {const [command, projectDir, ...rest] = argv;@@ -401,6 +403,9 @@ try {iosSources: platform === 'ios' && templateDir ? iosTemplateSources(templateDir) : null,androidOutput: opts.output === 'project' ? 'project' : undefined,minify: opts.minify,+ // `dev` is what the AOT step calls "do not compile" — the editor's preview+ // mode, reused here so there is one word for it (docs/REARCH_AOT.md §9).+ ...(opts['no-aot'] ? { aotMode: 'dev' } : {}),sizeBudgetBytes,});const report = { ...result, outDir };diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 2cbeaa85b..a41191aa6 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -56,7 +56,7 @@ import { measureBuild, type BuildSizeReport } from './sizeReport';import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';import { collectSubsystems, subsystemGapWarnings, targetGaps, type Subsystem } from '../project/targetSupport';import { scanSideModuleIds, sideModuleFiles, shipsSideModule } from '../bundle/sideModuleScan';-import { buildCompiledSystems } from '../bundle/buildCompiledSystems';+import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';import { resolveEmcc, runEmcc } from '../bundle/emccPath';export type { ExportPlatform };@@ -360,6 +360,14 @@ export interface ExportGameOptions {* the repo's own submodule; a project that promised nothing never needs one.*/emcc?: string | null;+ /**+ * Whether this export compiles what the project marked `@compiled`.+ *+ * Default `release`: it compiles, and a promise the subset cannot keep fails+ * the build. `dev` skips the step, which is how one project is packaged twice+ * for the differential that proves the two frames agree (REARCH_AOT.md §8.2).+ */+ aotMode?: BuildMode;/** Shipping config: minify the bundles, no sourcemap. Default off (dev). */minify?: boolean;sourcemap?: boolean;@@ -517,6 +525,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>runtime,minify: opts.minify,emcc: opts.emcc,+ aotMode: opts.aotMode,contentAddressed: opts.contentAddressed,compressTextures: opts.compressTextures,compressAudio: opts.compressAudio,@@ -541,6 +550,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>runtime,minify: opts.minify,emcc: opts.emcc,+ aotMode: opts.aotMode,contentAddressed: opts.contentAddressed,compressTextures: opts.compressTextures,compressAudio: opts.compressAudio,@@ -708,7 +718,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>// promise someone is collecting on, so a promise the subset cannot keep// fails the build rather than quietly falling back to the interpreter.const built = await buildCompiledSystems(opts.root, {- mode: 'release', emcc: resolveEmcc(opts.emcc), run: runEmcc,+ mode: opts.aotMode ?? 'release', emcc: resolveEmcc(opts.emcc), run: runEmcc,});if (!built.ok) {errors.push(...built.errors);diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex 3934572f1..745032626 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -44,7 +44,7 @@ import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnosimport { scanSideModuleIds, sideModuleFiles } from '../bundle/sideModuleScan';import { OPEN_DATA_DIR } from './miniGameExportProfile';import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';-import { buildCompiledSystems } from '../bundle/buildCompiledSystems';+import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';import { resolveEmcc, runEmcc } from '../bundle/emccPath';import type { MiniGameExportProfile, MiniGameVendor } from './miniGameExportProfile';@@ -164,6 +164,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {* promised nothing never needs one.*/emcc?: string | null;+ /** Whether this export compiles `@compiled` systems; see exportGame. */+ aotMode?: BuildMode;/** Emit content-addressed asset filenames (<hash><ext>) for dedup + immutable caching. */contentAddressed?: boolean;/** Encode raster textures to GPU-compressed KTX2 at cook time. */@@ -325,7 +327,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// the target AOT exists for (docs/REARCH_AOT.md §1.1: iOS mini-games have no// JIT). A PATH, because WXWebAssembly cannot compile bytes.const built = await buildCompiledSystems(opts.root, {- mode: 'release', emcc: resolveEmcc(opts.emcc), run: runEmcc,+ mode: opts.aotMode ?? 'release', emcc: resolveEmcc(opts.emcc), run: runEmcc,});if (!built.ok) {errors.push(...built.errors);diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjsindex 9620ef7fa..74a5b281b 100644--- a/tools/releaseGate.mjs+++ b/tools/releaseGate.mjs@@ -89,6 +89,15 @@ export const CRITERIA = ['pipeline/tests/hotupdate-verify-fixture.test.ts',],},+ {+ id: 'compiled-game-packages-and-draws',+ says: 'a game whose systems were compiled packages, boots and draws the game it drew interpreted',+ // Not "the same pixels": the loop is wall-clock, so two launches of ONE+ // package already differ by more than a wrong field offset does (the file+ // carries the measurement). This settles black, dead, or a different game.+ answeredBy: 'node tools/verify-aot-parity.mjs',+ needs: ['tools/verify-aot-parity.mjs', 'examples/space-shooter/src/systems/effects.ts'],+ },{id: 'old-projects-open',says: 'projects released by older versions still open, with nothing dropped',diff --git a/tools/verify-aot-parity.mjs b/tools/verify-aot-parity.mjsnew file mode 100644index 000000000..ef9e5d81c--- /dev/null+++ b/tools/verify-aot-parity.mjs@@ -0,0 +1,191 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file verify-aot-parity.mjs — a compiled game packages, boots and draws its game.+ *+ * One example packaged twice from one tree — once compiled, once with+ * `--no-aot` — both opened the way a player does, and the frames compared+ * (docs/REARCH_AOT.md §8.2, the pixel half).+ *+ * WHAT IT CANNOT SEE, measured rather than assumed. The loop runs on wall-clock+ * time, so two launches settle at different points in the animation: on+ * ecs-basics the most-changed cell reads 0.52 between two CORRECT runs, and+ * 0.57 when the compiled module is sabotaged to read one field four bytes off.+ * The signal is under the phase noise, both for the mean and for the cell max.+ * A frame comparison here therefore catches the coarse class — a compiled build+ * that is black, dead, or drawing a different game — and NOT a twin that reads+ * the wrong offset. That one needs the same displacement over the same fixed+ * steps, which needs a deterministic step in the packaged host.+ *+ * node tools/verify-aot-parity.mjs+ * node tools/verify-aot-parity.mjs --only space-shooter --shots out/+ */+import { spawnSync } from 'node:child_process';+import { mkdirSync, rmSync, readFileSync, existsSync, readdirSync, statSync } from 'node:fs';+import path from 'node:path';+import { GOLDEN, projectDir, parityFor, launchTimeoutFor, ROOT } from './goldenProjects.mjs';+import { frameDistance } from './frameCompare.mjs';+import { retryOnDeadGpu, deadGpuVerdict } from './lib/deadGpu.mjs';+import { runTool } from './lib/runTool.mjs';+import { requireCurrentEngine } from './lib/engineBuild.mjs';++const argv = process.argv.slice(2);+const flag = (n, d) => {+ const i = argv.indexOf(`--${n}`);+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d;+};++const ONLY = flag('only', '');+const SHOTS = flag('shots', '');+const WORK = flag('work', path.join(ROOT, '.golden'));+const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'launch-export.mjs');+const ENGINE = { dir: path.join(ROOT, 'desktop', 'public', 'wasm'), variant: 'web' };+/** The surface both runs open at. One number, so a difference is the game's. */+const SURFACE = { w: 820, h: 461 };++if (SHOTS) mkdirSync(SHOTS, { recursive: true });++/** Which of a project's files mark a system `@compiled` — the same text the AOT+ * build step looks for, over the same `src/` tree it lowers. */+function promises(id) {+ const found = [];+ const walk = (dir) => {+ if (!existsSync(dir)) return;+ for (const name of readdirSync(dir)) {+ const p = path.join(dir, name);+ if (statSync(p).isDirectory()) walk(p);+ else if (p.endsWith('.ts') && !p.endsWith('.d.ts') && readFileSync(p, 'utf8').includes('@compiled')) found.push(p);+ }+ };+ walk(path.join(projectDir(id), 'src'));+ return found;+}++/**+ * Every example that promises compilation, not only the golden ones.+ *+ * A golden project can promise compilation in a system that runs only once the+ * player fires, and then both frames agree because the compiled code touched no+ * entity at all — green over an empty query. So the marker picks the corpus.+ */+const EXAMPLES = path.join(ROOT, 'examples');+const only = ONLY ? new Set(ONLY.split(',').map((s) => s.trim())) : null;+const subjects = readdirSync(EXAMPLES)+ .filter((id) => (!only || only.has(id)) && promises(id).length > 0)+ .map((id) => GOLDEN.find((g) => g.id === id) ?? { id, targets: ['web'] });++// A differential over nothing is the failure this file exists to prevent: it+// would report green on a compiler that emits garbage, having compiled none.+if (subjects.length === 0) {+ console.error('aot parity: no example marks a system @compiled');+ console.error(' this gate would pass having compiled nothing — mark a per-frame system that');+ console.error(' MOVES something, or remove the release criterion that names this file');+ process.exit(1);+}++console.log(`aot parity: ${subjects.length} project(s)`);+requireCurrentEngine(ROOT, ENGINE.dir, process.argv, ENGINE.variant);++/** Package one project, with or without its compiled systems. */+function exportOnce(id, out, compiled) {+ rmSync(out, { recursive: true, force: true });+ return spawnSync(process.execPath, [+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', projectDir(id),+ '--platform', 'web', '--out', out, ...(compiled ? [] : ['--no-aot']),+ ], { encoding: 'utf8', cwd: ROOT });+}++/** What a package says it carries: the module file, and the config naming it. */+function carriesModule(out) {+ let named = false;+ try {+ named = Boolean(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).aot);+ } catch { named = false; }+ return { file: existsSync(path.join(out, 'aot', 'systems.wasm')), named };+}++/** Open a package and write its frame, once more past a dead GPU. */+function launch(id, out, png, timeoutMs) {+ const run = retryOnDeadGpu(+ () => {+ const r = runTool('pnpm', ['exec', 'electron', LAUNCHER,+ '--dir', out, '--out', png, '--w', String(SURFACE.w), '--h', String(SURFACE.h),+ ...(timeoutMs ? ['--timeout', String(timeoutMs)] : []),+ ], { encoding: 'utf8', cwd: ROOT });+ const verdict = (r.stdout || '').split('\n').find((l) => l.startsWith('✓') || l.startsWith('✗'));+ return { ok: r.status === 0, output: `${r.stdout ?? ''}${r.stderr ?? ''}`, measured: Boolean(verdict), r };+ },+ () => console.log(`↻ ${id} — the GPU process died before it drew; launching again`),+ );+ return { ...run.r, gpuDied: Boolean(run.gpuDied) };+}++const results = [];+for (const g of subjects) {+ const id = g.id;+ const marked = promises(id).map((p) => path.relative(ROOT, p));+ console.log(`\n${id} — marked: ${marked.join(', ')}`);++ const dirs = { aot: path.join(WORK, `${id}-aot`), interp: path.join(WORK, `${id}-interp`) };+ let broke = false;+ for (const kind of ['aot', 'interp']) {+ const r = exportOnce(id, dirs[kind], kind === 'aot');+ if (r.status !== 0) {+ results.push({ id, stage: `package-${kind}`, ok: false, why: (r.stderr || r.stdout || '').trim().slice(-300) });+ console.log(`✗ ${id} — the ${kind} package failed`);+ broke = true;+ }+ }+ if (broke) continue;++ // Both halves have to be what they claim, or this compares two identical+ // interpreted packages and passes without a compiled line having run.+ const withAot = carriesModule(dirs.aot);+ const without = carriesModule(dirs.interp);+ const claims = [];+ if (!withAot.file) claims.push('the compiled package carries no aot/systems.wasm');+ if (!withAot.named) claims.push('the compiled package does not name a module in game.config.json');+ if (without.file) claims.push('the --no-aot package carries a module anyway');+ if (without.named) claims.push('the --no-aot package names a module in game.config.json');+ if (claims.length > 0) {+ results.push({ id, stage: 'packages-differ', ok: false, why: claims.join('; ') });+ console.log(`✗ ${id} — the two packages are not the two things being compared`);+ for (const c of claims) console.log(` ${c}`);+ continue;+ }+ results.push({ id, stage: 'packages-differ', ok: true, why: '' });+ console.log(`✓ ${id} — one package compiled, one interpreted`);++ const timeoutMs = launchTimeoutFor(g);+ const shots = {};+ for (const kind of ['aot', 'interp']) {+ const png = SHOTS ? path.join(SHOTS, `${id}-${kind}.png`) : path.join(WORK, `${id}-${kind}.png`);+ const r = launch(id, dirs[kind], png, timeoutMs);+ const line = (r.stdout || '').split('\n').find((l) => l.startsWith('✓') || l.startsWith('✗')) ?? '';+ if (r.status !== 0 || !existsSync(png)) {+ const why = r.gpuDied+ ? `${deadGpuVerdict(`the ${kind} package`)} (${line || 'no frame'})`+ : line || 'launch failed';+ results.push({ id, stage: `launch-${kind}`, ok: false, why });+ console.log(`✗ ${id} ${kind} — ${why}`);+ broke = true;+ break;+ }+ shots[kind] = png;+ }+ if (broke) continue;++ const tol = parityFor(g) ?? 0.06;+ const d = frameDistance(readFileSync(shots.aot), readFileSync(shots.interp));+ const ok = d <= tol;+ results.push({+ id, stage: 'frame', ok,+ why: ok ? '' : `the compiled frame sits ${d.toFixed(3)} from the interpreted one (tolerance ${tol})`,+ });+ console.log(`${ok ? '✓' : '✗'} ${id} — frame distance ${d.toFixed(3)} against ${tol}`);+}++const bad = results.filter((r) => !r.ok);+console.log(`\naot parity: ${results.length - bad.length}/${results.length} ok`);+for (const r of bad) console.log(` ✗ ${r.id} ${r.stage} — ${r.why}`);+process.exit(bad.length > 0 ? 1 : 0);