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 project's own resource compiles, without the engine learning it
esengine4c7fa4056f0f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1dde4e368..c13c29f77 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,6 +45,13 @@ published separately; it ships inside the editor.`UICameraInfo.viewProjection` is deliberately not in it, since a member has tohave a fixed width.+ A resource the PROJECT declares compiles as well, with no engine change per+ resource: `defineResource({ value: 0 }, 'Score')` has literal defaults, so the+ build derives the layout from the declaration the same way it does for a+ component, and carries it in the manifest. The runtime lays the block out at+ that layout and refuses a module whose field ORDER no longer matches, because+ a moved field is not an error — it is a read of a different one.+Events compile too, both directions. `EventWriter(E)` and `EventReader(E)` areparameters a compiled system may declare: `writer.send({ … })` flattens thepayload into the fields the event declares and appends one record, anddiff --git a/compiler/src/abi.ts b/compiler/src/abi.tsindex ecc556eab..ce890abd0 100644--- a/compiler/src/abi.ts+++ b/compiler/src/abi.ts@@ -497,6 +497,10 @@ export function abiHandshake(// component to a project must not invalidate a module that never reads it.const named = new Set<string>();for (const p of plans) for (const q of p.queries) for (const a of q) named.add(a.comp);+ // A project's own RESOURCE is a project shape; the ENGINE's is not, being+ // covered by `engineAbi`. Counting one twice puts it in a digest the+ // runtime computes without it.+ for (const p of plans) for (const r of p.resources) if (!RESOURCES.has(r.name)) named.add(r.name);const shapes: ShapeDigestInput[] = [];for (const name of named) {diff --git a/compiler/src/eir.ts b/compiler/src/eir.tsindex 758d613bc..55bf26800 100644--- a/compiler/src/eir.ts+++ b/compiler/src/eir.ts@@ -226,6 +226,9 @@ export interface EirModule {/** Event payloads, by declared name. A separate namespace from components:* a program may name one of each the same thing without meaning one. */readonly events: ReadonlyMap<string, CompShape>;+ /** Resources the PROJECT declared, as opposed to the engine's own. Their+ * layout is derived from the declaration, so nothing adapts to each one. */+ readonly userResources: ReadonlySet<string>;}// =============================================================================diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.tsindex 801d7b223..334d2a4c8 100644--- a/compiler/src/frontend.ts+++ b/compiler/src/frontend.ts@@ -897,6 +897,28 @@ function eventLeaf(t: ts.TypeNode): FieldSpec | null {return null;}+/**+ * `defineResource<T>({ value: 0 }, 'Score')` -> a shape. The same rule a+ * component's defaults meet, for the same reason: every field is one f64, and+ * anything else has no fixed width.+ */+function resourceShapeOf(call: ts.CallExpression, name: string): CompShape | null {+ const defaults = call.arguments[0];+ if (!defaults || !ts.isObjectLiteralExpression(defaults)) return null;+ const fields = new Map<string, FieldSpec>();+ for (const prop of defaults.properties) {+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) return null;+ const init = ts.isPrefixUnaryExpression(prop.initializer)+ && prop.initializer.operator === ts.SyntaxKind.MinusToken+ ? prop.initializer.operand : prop.initializer;+ if (ts.isNumericLiteral(init)) fields.set(prop.name.text, { type: F64, enc: HOST_ENC, offset: null });+ else if (init.kind === ts.SyntaxKind.TrueKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {+ fields.set(prop.name.text, { type: BOOL, enc: HOST_ENC, offset: null });+ } else return null;+ }+ return fields.size === 0 ? null : { name, storage: 'host', fields };+}+/** Two declarations of one name are the same component only if every field matches. */function sameShape(a: CompShape, b: CompShape): boolean {if (a.fields.size !== b.fields.size) return false;@@ -942,6 +964,8 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str/** Event payloads, by declared name — a second namespace from components. */const events = new Map<string, CompShape>();const eventBindings = new Map<string, string>();+ /** Resources the PROJECT declared, whose layout travels in the manifest. */+ const userResources = new Set<string>();const consts = new Map<string, ConstValue>();const fns = new Map<string, EirFn>();// Why a function could not be lowered, reported at the CALL SITE rather than@@ -999,6 +1023,26 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<strfor (const sf of sources) {walkTop(sf, (node, binding) => {if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) return;+ if (node.expression.text === 'defineResource') {+ // A project's own resource is a shape like any other: its+ // DEFAULTS are a literal, so nothing here has to be taught+ // about it the way an engine service does.+ const named = node.arguments[1];+ if (!named || !ts.isStringLiteral(named)) return;+ const shape = resourceShapeOf(node, named.text);+ if (!shape) {+ diagnostics.push({+ file: sf.fileName, line: lineOf(sf, node), kind: 'permanent', severity: 'note',+ message: `defineResource('${named.text}') has a default that is not a literal `+ + 'number or boolean',+ });+ return;+ }+ comps.set(shape.name, shape);+ userResources.add(shape.name);+ if (binding) bindings.set(binding, shape.name);+ return;+ }if (node.expression.text === 'defineEvent') {const shape = eventShape(node, interfaces);if (!shape) {@@ -1108,7 +1152,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str});}- return { module: { systems, comps, fns, events }, diagnostics, seen, systemBindings, required };+ return { module: { systems, comps, fns, events, userResources }, diagnostics, seen, systemBindings, required };}/** `{ name: 'MoveSystem' }` if given, else the const it is assigned to. */diff --git a/compiler/tests/conformance.test.ts b/compiler/tests/conformance.test.tsindex 3fe4dc73a..0b3a4e8a2 100644--- a/compiler/tests/conformance.test.ts+++ b/compiler/tests/conformance.test.ts@@ -276,7 +276,7 @@ describe('conformance — an event out of memory and back into it', () => {}runSystem(ping!, world);const sent = (world.sent?.get('FixturePinged') ?? []) as (readonly number[])[];- (world as { events?: Map<string, Row[]> }).events =+ (world as unknown as { events?: Map<string, Row[]> }).events =new Map([['FixturePinged', sent.map((args) => ({ by: args[0]! }))]]);world.sent?.clear();runSystem(pong!, world);diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.tsindex e9b0436c0..3ca9ca535 100644--- a/compiler/tests/coverage.test.ts+++ b/compiler/tests/coverage.test.ts@@ -50,7 +50,7 @@ import { builtinShapes } from '../src/builtins';const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));/** Per-frame systems only. See the file header before lowering these. */-const FRAME_FLOOR = 14;+const FRAME_FLOOR = 15;/** Per-frame systems the contract could take once the pending work is done. */const CEILING_FLOOR = 84;diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.tsindex 01999459b..791e5c5bd 100644--- a/pipeline/src/bundle/buildCompiledSystems.ts+++ b/pipeline/src/bundle/buildCompiledSystems.ts@@ -44,9 +44,13 @@ export interface CompiledSystemInfo {symbol: string;/** One entry per declared Query: its components, in the order it names them. */queries: { comp: string; mut: boolean }[][];- /** One per declared Res/ResMut, in declaration order. `mut` is what makes the- * runtime write a mirrored resource back after the call. */- resources: { name: string; mut: boolean }[];+ /**+ * One per declared Res/ResMut, in declaration order. `mut` is what makes the+ * runtime write a mirrored resource back after the call; `fields` is present+ * for a resource the PROJECT declared, because its layout is not something+ * the engine knows — it was derived from the declaration.+ */+ resources: { name: string; mut: boolean; fields?: string[] }[];/** Event readers and writers, with the payload layout each one uses. */readers: { slot: number; event: string; fields: string[] }[];writers: { slot: number; event: string; fields: string[] }[];@@ -79,6 +83,12 @@ 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[] {@@ -235,7 +245,9 @@ export async function buildCompiledSystems(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) => ({ name: r.name, mut: r.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) => ({diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 17fde38b9..3f8fab584 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -522,7 +522,7 @@ systems: readonly AotSystemDecl[]name: stringqueries: readonly (readonly { comp: string; mut: boolean; }[])[]readers: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined-resources: readonly { name: string; mut: boolean; }[]+resources: readonly { name: string; mut: boolean; fields?: readonly string[]; }[]symbol: stringwriters: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 6e19d228a..07bd00d8a 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -522,7 +522,7 @@ systems: readonly AotSystemDecl[]name: stringqueries: readonly (readonly { comp: string; mut: boolean; }[])[]readers: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined-resources: readonly { name: string; mut: boolean; }[]+resources: readonly { name: string; mut: boolean; fields?: readonly string[]; }[]symbol: stringwriters: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 04551e4b6..332e4e529 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -517,7 +517,7 @@ systems: readonly AotSystemDecl[]name: stringqueries: readonly (readonly { comp: string; mut: boolean; }[])[]readers: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined-resources: readonly { name: string; mut: boolean; }[]+resources: readonly { name: string; mut: boolean; fields?: readonly string[]; }[]symbol: stringwriters: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f588e5734..9d0902a00 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -517,7 +517,7 @@ systems: readonly AotSystemDecl[]name: stringqueries: readonly (readonly { comp: string; mut: boolean; }[])[]readers: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined-resources: readonly { name: string; mut: boolean; }[]+resources: readonly { name: string; mut: boolean; fields?: readonly string[]; }[]symbol: stringwriters: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 38ba1a2dc..53f547ec7 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -517,7 +517,7 @@ systems: readonly AotSystemDecl[]name: stringqueries: readonly (readonly { comp: string; mut: boolean; }[])[]readers: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined-resources: readonly { name: string; mut: boolean; }[]+resources: readonly { name: string; mut: boolean; fields?: readonly string[]; }[]symbol: stringwriters: readonly { slot: number; event: string; fields: readonly string[]; }[] | undefined```diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex 92b9e4d4b..e96b30571 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -631,7 +631,12 @@ export class App {host: opts.host,manifest: opts.manifest,wasm: opts.wasm,- knowsResource: (name) => builtinResource(name) !== undefined,+ resourceFields: (name) => {+ const def = builtinResource(name) ?? this.resources_.getByName(name);+ if (def === undefined) return undefined;+ const value = this.resources_.get(def);+ return typeof value === 'object' && value !== null ? Object.keys(value) : [];+ },// A manifest carries event NAMES; the registry answers for the ones// some system has asked for a reader or a writer of.events: (name) => {@@ -644,7 +649,9 @@ export class App {return { read: () => bus.getReadBuffer(), send: (payload) => bus.send(payload) };},resources: (name) => {- const def = builtinResource(name);+ // The engine's own by name, and the PROJECT's through the+ // storage's own name registry — a compiled system reads either.+ const def = builtinResource(name) ?? this.resources_.getByName(name);// `get`, not `has` then `get`: a slot holding a materialised// default is what an INTERPRETED system reads, and a twin has to// see the same world or the two stop being the same program.diff --git a/sdk/src/ecs/aot/AotResources.ts b/sdk/src/ecs/aot/AotResources.tsindex 7c73e1889..e0682df45 100644--- a/sdk/src/ecs/aot/AotResources.ts+++ b/sdk/src/ecs/aot/AotResources.ts@@ -20,7 +20,9 @@*/import { POOL_SLOT_BYTES, type PoolBlock, type PoolMemory } from '../ScriptPool';-import { resourceBitSource, resourceBlockBytes, resourceLayout } from '../resourceShapes';+import {+ resourceBitSource, resourceBlockBytes, resourceLayout, type ResourceMember,+} from '../resourceShapes';/** Reads the live value of a named resource, or undefined if the world has none. */export type ResourceReader = (name: string) => Readonly<Record<string, unknown>> | undefined;@@ -34,21 +36,46 @@ export class AotResources {private readonly blocks = new Map<string, PoolBlock>();private readonly views = new Map<string, Uint8Array>();- constructor(private readonly memory: PoolMemory, private readonly read: ResourceReader) {}+ constructor(+ private readonly memory: PoolMemory,+ private readonly read: ResourceReader,+ /**+ * Layouts for the resources the PROJECT declared, from the manifest.+ * The engine's own come from `resourceShapes.ts`; a project's cannot,+ * and a build is the only thing that knows the order it compiled for.+ */+ private readonly declared: ReadonlyMap<string, readonly string[]> = new Map(),+ ) {}++ /** `name`'s members, from the engine's table or from what the build said. */+ private layoutOf(name: string): readonly ResourceMember[] | null {+ const engine = resourceLayout(name);+ if (engine) return engine;+ const fields = this.declared.get(name);+ return fields+ ? fields.map((field, i) => ({ kind: 'scalar', name: field, offset: i * POOL_SLOT_BYTES }))+ : null;+ }++ /** Bytes `name`'s block needs, by whichever layout answers for it. */+ private bytesOf(name: string): number {+ const declared = this.declared.get(name);+ return declared ? declared.length * POOL_SLOT_BYTES : resourceBlockBytes(name);+ }/*** The address of `name`'s bytes, with this frame's values in them, or* undefined when the resource has no layout or the world has no value.*/addressOf(name: string): number | undefined {- const layout = resourceLayout(name);+ const layout = this.layoutOf(name);if (!layout) return undefined;const value = this.read(name);if (!value) return undefined;let block = this.blocks.get(name);if (!block) {- block = this.memory.alloc(resourceBlockBytes(name));+ block = this.memory.alloc(this.bytesOf(name));this.blocks.set(name, block);}// Re-viewed rather than held: allocating anything may have grown the@@ -56,7 +83,7 @@ export class AotResources {const buffer = this.memory.current?.(block) ?? block.buffer;let view = this.views.get(name);if (!view || view.buffer !== buffer) {- view = new Uint8Array(buffer, block.byteOffset, resourceBlockBytes(name));+ view = new Uint8Array(buffer, block.byteOffset, this.bytesOf(name));this.views.set(name, view);}const f64 = new Float64Array(view.buffer, view.byteOffset, view.byteLength / POOL_SLOT_BYTES);@@ -101,7 +128,7 @@ export class AotResources {* skipped, because the block never carried it.*/writeBack(name: string): void {- const layout = resourceLayout(name);+ const layout = this.layoutOf(name);const view = this.views.get(name);const value = this.read(name) as Record<string, unknown> | undefined;if (!layout || !view || !value) return;diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.tsindex d3f1b0a26..ace07c91e 100644--- a/sdk/src/ecs/aot/AotSystems.ts+++ b/sdk/src/ecs/aot/AotSystems.ts@@ -26,7 +26,7 @@ export interface AotSystemDecl {readonly queries: readonly (readonly { comp: string; mut: boolean }[])[];/** One per declared Res/ResMut. `mut` is what makes a host write the mirror* back after the call — without it the write is silently dropped. */- readonly resources: readonly { name: string; mut: boolean }[];+ readonly resources: readonly { name: string; mut: boolean; fields?: readonly string[] }[];/*** Event readers, and the query slot each one's payloads go into. `fields`* is the payload's layout, in the order the compiled code reads it — the@@ -99,7 +99,12 @@ export class AotSystems {manifest: AotManifest,exports: Readonly<Record<string, unknown>>,resolve: (name: string) => AnyComponentDef | undefined,- hasResource: (name: string) => boolean = () => true,+ /**+ * The fields this runtime's copy of a resource has, in ITS order, or+ * undefined when there is no such resource. Asked rather than taken+ * from the manifest: a manifest compared against itself always agrees.+ */+ resourceFields: (name: string) => readonly string[] | undefined = () => [],): void {// Two questions with two fixes, so two answers rather than one that can// only say "something moved".@@ -110,7 +115,7 @@ export class AotSystems {+ 'Rebuild the module against this engine — a wrong offset reads a different '+ 'field rather than failing.');}- const shapes = projectShapeDigest(scriptShapes(manifest, resolve));+ const shapes = projectShapeDigest(scriptShapes(manifest, resolve, resourceFields));if (manifest.projectShapes !== shapes) {throw new Error(`AOT module refused: built for components ${manifest.projectShapes}, this project `@@ -120,7 +125,7 @@ export class AotSystems {for (const r of decl.resources) {// A resource with no address is not a slow path: the ctx would// carry 0 and the compiled code would read whatever is there.- if (!hasResource(r.name)) {+ if (!resourceFields(r.name)) {throw new Error(`AOT module refused: '${decl.name}' reads resource `+ `'${r.name}', which this runtime does not have`);}@@ -157,10 +162,21 @@ export class AotSystems {function scriptShapes(manifest: AotManifest,resolve: (name: string) => AnyComponentDef | undefined,+ resourceFields: (name: string) => readonly string[] | undefined,): ShapeDigestInput[] {const seen = new Set<string>();const out: ShapeDigestInput[] = [];for (const decl of manifest.systems) {+ // A resource the project declared is a project shape: its fields are+ // what the code reads at each offset, so a change has to refuse a+ // module built before it.+ for (const r of decl.resources) {+ if (!r.fields || seen.has(r.name)) continue;+ seen.add(r.name);+ // As the RUNTIME has it: the module baked in an order, and this is+ // what says whether that order is still the one here.+ out.push({ name: r.name, fields: [...(resourceFields(r.name) ?? [])] });+ }for (const query of decl.queries) {for (const arg of query) {if (seen.has(arg.comp)) continue;diff --git a/sdk/src/ecs/aot/installAot.ts b/sdk/src/ecs/aot/installAot.tsindex f69e6e71e..c742f6f57 100644--- a/sdk/src/ecs/aot/installAot.ts+++ b/sdk/src/ecs/aot/installAot.ts@@ -53,11 +53,12 @@ export interface InstallAotOptions {/** The live value of a named resource, for the mirror to copy in. */readonly resources: ResourceReader;/**- * Whether this runtime HAS such a resource, asked once at install. Distinct- * from `resources`, which asks for a value: a resource the engine creates on- * its first frame has no value yet and is not missing.+ * The fields this runtime's `name` has, in its own order, or undefined when+ * there is no such resource. Two questions at once, and both are asked at+ * install: whether it exists, and whether it still looks the way the module+ * was built against.*/- readonly knowsResource?: (name: string) => boolean;+ readonly resourceFields?: (name: string) => readonly string[] | undefined;/** The bus a manifest's event NAME refers to, for reading and for sending. */readonly events?: EventBusAccess;}@@ -93,11 +94,15 @@ export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promiconst systems = new AotSystems();systems.install(opts.manifest, exports, componentNamed,- opts.knowsResource ?? ((name) => opts.resources(name) !== undefined));+ opts.resourceFields ?? ((name) => {+ const value = opts.resources(name);+ return value === undefined ? undefined : Object.keys(value);+ }));return {systems,- addresses: worldAddresses(new AotResources(memory, opts.resources),+ addresses: worldAddresses(+ new AotResources(memory, opts.resources, declaredLayouts(opts.manifest)),new AotEvents(memory, opts.events ?? (() => undefined))),ctx: new AotContext(memory),};@@ -113,6 +118,15 @@ function wasmSource(wasm: string | BufferSource): string | ArrayBuffer {return wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength) as ArrayBuffer;}+/** Layouts the BUILD derived for the project's own resources, by name. */+function declaredLayouts(manifest: AotManifest): Map<string, readonly string[]> {+ const out = new Map<string, readonly string[]>();+ for (const decl of manifest.systems) {+ for (const r of decl.resources) if (r.fields) out.set(r.name, r.fields);+ }+ return out;+}+/** What a manifest's component NAME means in this runtime. */function componentNamed(name: string): AnyComponentDef | undefined {return getComponent(name);diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.tsindex b2db130aa..58b43d64a 100644--- a/sdk/tests/aot-app.test.ts+++ b/sdk/tests/aot-app.test.ts@@ -14,13 +14,13 @@ import { bootMockApp } from './helpers/mockApp';import {buildAotModule, buildFadeModule, eventManifest, fadeManifest, fadeTaggedManifest,keyProbeC, keyProbeManifest, EVENT_C,- timeScaleManifest, FADE_TAGGED_C,+ timeScaleManifest, userResManifest, FADE_TAGGED_C, USER_RES_C,FADE_PROBE_ALPHA, FADE_PROBE_C, TIME_SCALE_C,} from './helpers/aotFade';import { FakeEngine } from './fakeEngine';import { emccPath } from '../../build-tools/utils/emscripten.js';import { defineComponent, defineTag } from '../src/ecs/component';-import { Time } from '../src/ecs/resource';+import { defineResource, ResMut, Time } from '../src/ecs/resource';import { defineEvent, EventReader, EventWriter } from '../src/ecs/event';import { Input } from '../src/input/input';import { defineSystem, Schedule } from '../src/ecs/system';@@ -244,6 +244,37 @@ describe('an App told to run its compiled twins', () => {expect(seen).toEqual(entities.map((_, i) => (i + 1) * 0.1));});+ it.skipIf(!EMCC)("reads a resource the PROJECT declared, at the layout the build derived", async () => {+ const wasm = buildAotModule(EMCC!, USER_RES_C, 'es_sys_Tally');+ const { app } = bootMockApp();+ // Declared by the project, not by the engine: nothing in the SDK knows+ // these fields, so the only description of them is the manifest's.+ const Score = defineResource({ step: 3, total: 0 }, 'Score');+ app.insertResource(Score, { step: 3, total: 0 });+ app.addSystemToSchedule(Schedule.Update, defineSystem([ResMut(Score)], () => {+ /* the twin is the point */+ }, { name: 'Tally' }));+ await app.useCompiledSystems({+ host: new FakeEngine(), manifest: userResManifest(['step', 'total']), wasm,+ });++ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(app.getResource(Score)).toEqual({ step: 3, total: 6 });+ });++ it.skipIf(!EMCC)('and refuses a module built for a different field order', async () => {+ const { app } = bootMockApp();+ const Score = defineResource({ step: 3, total: 0 }, 'Score');+ app.insertResource(Score, { step: 3, total: 0 });+ // Swapped: same fields, and every one of them at the wrong offset. This+ // is the failure a digest exists for — not an error, a different field.+ await expect(app.useCompiledSystems({+ host: new FakeEngine(), manifest: userResManifest(['total', 'step']),+ wasm: buildAotModule(EMCC!, USER_RES_C, 'es_sys_Tally'),+ })).rejects.toThrow(/Rebuild the project/);+ });+it.skipIf(!EMCC)('refuses a module built for other shapes, and the App keeps interpreting', async () => {const { app, Fade } = fadeApp();await expect(app.useCompiledSystems({diff --git a/sdk/tests/helpers/aotFade.ts b/sdk/tests/helpers/aotFade.tsindex e2e09cdf4..86ea2a80e 100644--- a/sdk/tests/helpers/aotFade.ts+++ b/sdk/tests/helpers/aotFade.ts@@ -186,6 +186,39 @@ void es_sys_Emit(es_addr_t ctx) {}`;+/**+ * A system over a resource the PROJECT declared: `score.value += 1`. Nothing in+ * the engine knows this resource's layout — the build derived it from the+ * declaration and put it in the manifest, which is the point of the fixture.+ */+export const USER_RES_C = `#include <stdint.h>+#include <string.h>+typedef uint32_t es_addr_t;+#define ES_PTR(a) ((unsigned char *)(a))+typedef struct { es_addr_t queries, resources, cmdBuf, cmdCap, cmdCount, events; } EsSysCtx;+static double ld(const unsigned char *p) { double v; memcpy(&v, p, 8); return v; }+static void st(unsigned char *p, double v) { memcpy(p, &v, 8); }++void es_sys_Tally(es_addr_t ctx) {+ const EsSysCtx *c = (const EsSysCtx *)ES_PTR(ctx);+ const es_addr_t *res = (const es_addr_t *)ES_PTR(c->resources);+ unsigned char *score = ES_PTR(res[0]);+ st(score + 8u, ld(score + 8u) + ld(score)); /* total += step, slot 1 += slot 0 */+}+`;++/** What a build writes for it: the field ORDER is the layout, and it travels. */+export function userResManifest(fields: readonly string[]): AotManifest {+ return {+ engineAbi: engineAbiDigest(4),+ projectShapes: projectShapeDigest([{ name: 'Score', fields: [...fields] }]),+ systems: [{+ name: 'Tally', symbol: 'es_sys_Tally', queries: [],+ resources: [{ name: 'Score', mut: true, fields: [...fields] }],+ }],+ };+}+/** The manifest for whichever half is being run. */export function eventManifest(which: 'Absorb' | 'Emit'): AotManifest {const shapes = projectShapeDigest([{ name: 'Fade', fields: FADE_FIELDS }]);