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(aot): one source, interpreted and compiled, frame for frame
esenginecc524c4e05d2
diff --git a/compiler/src/abi.ts b/compiler/src/abi.tsindex 16daae0b7..d98e99182 100644--- a/compiler/src/abi.ts+++ b/compiler/src/abi.ts@@ -614,3 +614,4 @@ export function packLayout(shapes: ReadonlyMap<string, CompShape>): AbiLayout {* declarations, so this list has no second author to drift from.*/const RESOURCES = new Set(resourceNames());+diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.tsindex a72c6ee83..b9255560b 100644--- a/compiler/src/codegen.ts+++ b/compiler/src/codegen.ts@@ -36,7 +36,7 @@ import {} from './abi';import {BOOL, F64,- type EirFn, type EirModule, type EirSystem, type EirType, type Expr, type Local,+ type CompShape, type EirFn, type EirModule, type EirSystem, type EirType, type Expr, type Local,type LeafEnc, type MathFn, type Place, type Stmt,} from './eir';@@ -1000,3 +1000,45 @@ function calledFns(module: EirModule, systems: readonly EirSystem[]): string[] {// Declaration order, so a helper that calls a helper is defined first.return [...module.fns.keys()].filter((n) => want.has(n));}+++/**+ * What a module DECLARES, as a host or a runtime reads it — one mapping, where+ * there were two. Structurally typed rather than against the SDK's+ * `AotSystemDecl`: naming that type would pull the whole runtime in here.+ */+export interface ModuleDeclaration {+ readonly name: string;+ readonly symbol: string;+ readonly queries: { comp: string; mut: boolean }[][];+ readonly resources: { name: string; mut: boolean; fields?: string[] }[];+ readonly readers: { slot: number; event: string; fields: string[] }[];+ readonly writers: { slot: number; event: string; fields: string[] }[];+}++export function moduleDeclarations(+ module: EirModule,+ systems: readonly EirSystem[],+): ModuleDeclaration[] {+ const fieldsOf = (table: ReadonlyMap<string, CompShape>, name: string): string[] =>+ [...(table.get(name)?.fields.keys() ?? [])];+ return systems.map((sys) => {+ const plan = planFor(sys);+ return {+ name: sys.name,+ symbol: cSymbol(sys.name),+ queries: plan.queries.map((q) => q.map((a) => ({ comp: a.comp, mut: a.mut }))),+ // An ENGINE resource's shape is `engineAbi`'s; only a project's own+ // travels here, because only the build knows its field order.+ resources: plan.resources.map((r) => (module.userResources.has(r.name)+ ? { name: r.name, mut: r.mut, fields: fieldsOf(module.comps, r.name) }+ : { name: r.name, mut: r.mut })),+ readers: plan.readers.map((r) => ({+ slot: r.slot, event: r.event, fields: fieldsOf(module.events, r.event),+ })),+ writers: plan.writers.map((w) => ({+ slot: w.slot, event: w.event, fields: fieldsOf(module.events, w.event),+ })),+ };+ });+}diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.tsindex 6a5e84345..1eda664d0 100644--- a/pipeline/src/bundle/buildCompiledSystems.ts+++ b/pipeline/src/bundle/buildCompiledSystems.ts@@ -27,8 +27,8 @@ import { brokenPromises, lowerProgram } from '../../../compiler/src/frontend';import { verifySystem } from '../../../compiler/src/verify';import { inlineSystem } from '../../../compiler/src/inline';import { builtinShapes } from '../../../compiler/src/builtins';-import { packLayout, planFor } from '../../../compiler/src/abi';-import { CFLAGS, WASM_LINK_FLAGS, cSymbol, emitC } from '../../../compiler/src/codegen';+import { packLayout } from '../../../compiler/src/abi';+import { CFLAGS, WASM_LINK_FLAGS, emitC, moduleDeclarations } from '../../../compiler/src/codegen';import { nativeLinkFlags, nativeModuleExt } from '../../../compiler/src/hostCC';import { AOT_MANIFEST, AOT_WASM } from './aotArtifacts';@@ -138,17 +138,7 @@ export interface BuildCompiledResult {notes: string[];}-/** A project resource's fields in LAYOUT order, as the code reads them. */-function fieldsOfShape(module: { comps: ReadonlyMap<string, { fields: ReadonlyMap<string, unknown> }> },- name: string): string[] {- return [...(module.comps.get(name)?.fields.keys() ?? [])];-}-/** A payload's fields in LAYOUT order, which is the order the code reads them. */-function fieldsOf(module: { events: ReadonlyMap<string, { fields: ReadonlyMap<string, unknown> }> },- event: string): string[] {- return [...(module.events.get(event)?.fields.keys() ?? [])];-}/** Every `.ts` under `src/`, which is the unit a project's program is. */function sources(root: string): string[] {@@ -297,25 +287,10 @@ export async function buildCompiledSystems(engineAbi: c.handshake.engineAbi,projectShapes: c.handshake.projectShapes,moduleContract: c.handshake.moduleContract,- systems: inlined.map((sys) => {- const plan = planFor(sys);- return {- name: sys.name,- symbol: cSymbol(sys.name),- queries: plan.queries.map((q) => q.map((a) => ({ comp: a.comp, mut: a.mut }))),- resources: plan.resources.map((r) => (lowered.module.userResources.has(r.name)- ? { name: r.name, mut: r.mut, fields: fieldsOfShape(lowered.module, r.name) }- : { name: r.name, mut: r.mut })),- // The payload layout travels with the manifest: the runtime flattens an- // object into it, and the compiled code reads at those offsets.- readers: plan.readers.map((r) => ({- slot: r.slot, event: r.event, fields: fieldsOf(lowered.module, r.event),- })),- writers: plan.writers.map((w) => ({- slot: w.slot, event: w.event, fields: fieldsOf(lowered.module, w.event),- })),- };- }),+ // The one mapping from plans to declarations, shared with whatever else+ // installs a module it just compiled — this was a second copy of the C+ // table the artifact carries.+ systems: moduleDeclarations(lowered.module, inlined),};writeFileSync(path.join(dir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);return { ok: true, modulePath, manifest, errors: [], notes };diff --git a/sdk/tests/aot-conformance.test.ts b/sdk/tests/aot-conformance.test.tsnew file mode 100644index 000000000..d8e83d62b--- /dev/null+++ b/sdk/tests/aot-conformance.test.ts@@ -0,0 +1,145 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file aot-conformance.test.ts+ * @brief One source on two roads, frame for frame.+ *+ * @details The compiler holds its emitted C against its OWN interpreter, and+ * this suite held hand-written C against expectations. Neither asks+ * the question a player asks: does the module the compiler makes of a+ * system do what the author's closure does, in the App that runs it?+ *+ * So the same file is read twice — as closures, and as the artifact a+ * real build produces — and the worlds are compared after every frame.+ * Loud skip without emsdk: a differential that never compiled anything+ * agrees with itself.+ */+import { describe, it, expect } from 'vitest';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { lowerProgram, brokenPromises } from '../../compiler/src/frontend';+import { builtinShapes } from '../../compiler/src/builtins';+import { inlineSystem } from '../../compiler/src/inline';+import { packLayout } from '../../compiler/src/abi';+import { emitC, moduleDeclarations, WASM_LINK_FLAGS } from '../../compiler/src/codegen';+import { emccPath } from '../../build-tools/utils/emscripten.js';++import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { createMockModule } from './mocks/wasm';+import { FakeEngine } from './fakeEngine';+import { useBytesPlatform } from './helpers/aotFade';+import { Schedule } from '../src/ecs/system';+import type { AotManifest } from '../src/ecs/aot/AotSystems';+import type { Entity } from '../src/types';++const EMCC = emccPath();+const FIXTURE = path.resolve(__dirname, 'fixtures/conformance-systems.ts');+const FRAMES = 12;+const DT = 1 / 60;++/** The artifact a build makes of the fixture: the module, and what it declares. */+function compileFixture(emcc: string): { wasm: Uint8Array; manifest: AotManifest } {+ const lowered = lowerProgram([FIXTURE], builtinShapes());+ expect(brokenPromises(lowered), 'the fixture must compile').toEqual([]);+ const inlined = lowered.module.systems.map((s) => inlineSystem(s, lowered.module.fns));+ const c = emitC(lowered.module, packLayout(lowered.module.comps), inlined, 4);++ const dir = mkdtempSync(path.join(tmpdir(), 'estella-conf-'));+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, 'estella_abi.h'), c.header);+ writeFileSync(path.join(dir, 'estella_offsets.h'), c.offsets);+ writeFileSync(path.join(dir, 'sys.c'), c.source);+ const out = path.join(dir, 'sys.wasm');+ const built = spawnSync(emcc, [+ '-std=c11', '-O2', '-ffp-contract=off', '-Wall', '-Wextra',+ ...WASM_LINK_FLAGS, `-sEXPORTED_FUNCTIONS=${c.symbols.map((s) => `_${s}`).join(',')}`,+ '-o', out, path.join(dir, 'sys.c'),+ ], { encoding: 'utf8', cwd: dir, shell: process.platform === 'win32' });+ if (built.status !== 0) throw new Error(`emcc failed:\n${built.stderr}`);++ return {+ wasm: readFileSync(out),+ manifest: {+ engineAbi: c.handshake.engineAbi,+ projectShapes: c.handshake.projectShapes,+ moduleContract: c.handshake.moduleContract,+ systems: moduleDeclarations(lowered.module, inlined),+ },+ };+}++/** The world the fixture's systems touch, after each frame. */+type Trace = number[][][];++async function play(compiled: { wasm: Uint8Array; manifest: AotManifest } | null): Promise<{+ trace: Trace; calls: number;+}> {+ // One context for both roads on purpose: the fixture's `defineComponent`+ // runs once, at import, and a road that reset the registry under it would+ // hand the runtime a project with no components at all.+ useBytesPlatform();+ const app = App.new();+ const module = createMockModule();+ app.connectCpp(module.getRegistry(), module);+ const fixture = await import('./fixtures/conformance-systems');+ app.addSystemToSchedule(Schedule.Update, fixture.driftSystem);+ app.addSystemToSchedule(Schedule.Update, fixture.clampSystem);++ // Before the first pooled component: a pool cannot move to other memory+ // once it has rows, and the module addresses only the heap it was given.+ let runtime = null as { systems: { calls: number } } | null;+ if (compiled) {+ await app.useCompiledSystems({+ host: new FakeEngine(), manifest: compiled.manifest, wasm: compiled.wasm,+ });+ runtime = (app as unknown as { aot_: { systems: { calls: number } } }).aot_;+ }++ const seeds: [number, number][] = [[0, 120], [9.5, 60], [-9.5, -60], [3, -300]];+ const entities: Entity[] = seeds.map(([x, speed]) => {+ const e = app.world.spawn();+ app.world.insert(e, fixture.Mover, { x, speed, bounces: 0 });+ return e;+ });++ const trace: Trace = [];+ for (let f = 0; f < FRAMES; f++) {+ await app.tick(DT);+ trace.push(entities.map((e) => {+ const m = app.world.get(e, fixture.Mover) as { x: number; speed: number; bounces: number };+ return [m.x, m.speed, m.bounces];+ }));+ }+ return { trace, calls: runtime?.systems.calls ?? 0 };+}++describe.skipIf(!EMCC)('one source, interpreted and compiled', () => {+ it('answers the same world after every frame', async () => {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const artifact = compileFixture(EMCC!);+ const interpreted = await play(null);+ const twins = await play(artifact);++ // Installed is not the same question as ran, and a differential cannot+ // tell them apart — the closure that would have run produces the same+ // numbers. Two systems, every frame.+ expect(twins.calls).toBe(FRAMES * 2);+ expect(interpreted.calls).toBe(0);++ // Frame for frame, so a divergence names the frame it began on rather+ // than only the state it ended in.+ for (let f = 0; f < FRAMES; f++) {+ expect([f, twins.trace[f]]).toEqual([f, interpreted.trace[f]]);+ }+ // And the run went somewhere: a fixture whose systems do nothing agrees+ // on every road.+ expect(interpreted.trace[FRAMES - 1]).not.toEqual(interpreted.trace[0]);+ });+});diff --git a/sdk/tests/fixtures/conformance-systems.ts b/sdk/tests/fixtures/conformance-systems.tsnew file mode 100644index 000000000..b5b160cc0--- /dev/null+++ b/sdk/tests/fixtures/conformance-systems.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file conformance-systems.ts+ * @brief One source, read twice: as closures, and as the module the compiler+ * makes of it.+ *+ * @details Imported by relative path rather than through `esengine`, because+ * the same file has to be importable by the suite AND lowerable by the+ * compiler — which matches `defineSystem` by name, not by where it+ * came from.+ */+import { defineComponent } from '../../src/ecs/component';+import { defineSystem } from '../../src/ecs/system';+import { Query, Mut } from '../../src/ecs/query';+import { Res, Time } from '../../src/ecs/resource';++export const Mover = defineComponent('ConfMover', { x: 0, speed: 0, bounces: 0 });++/**+ * @compiled+ */+export const driftSystem = defineSystem(+ [Query(Mut(Mover)), Res(Time)],+ (query, time) => {+ for (const [, m] of query) {+ m.x = m.x + m.speed * time.delta;+ }+ },+ { name: 'ConfDrift' },+);++/**+ * @compiled+ */+export const clampSystem = defineSystem(+ [Query(Mut(Mover))],+ (query) => {+ for (const [, m] of query) {+ if (m.x > 10) {+ m.x = 10;+ m.speed = -m.speed;+ m.bounces = m.bounces + 1;+ } else if (m.x < -10) {+ m.x = -10;+ m.speed = -m.speed;+ m.bounces = m.bounces + 1;+ }+ }+ },+ { name: 'ConfClamp' },+);