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.

perf(aot): last frame's rows are this frame's rows, when nothing moved

yhhf4ed59e6e956
diff --git a/bench/aot-frame/README.md b/bench/aot-frame/README.md
index 34124f57a..65b17ea79 100644
--- a/bench/aot-frame/README.md
+++ b/bench/aot-frame/README.md
@@ -58,10 +58,21 @@ now a plan built once per system and a flat block written straight through
| script compiled | 81.9 ns | 27.3 ns |
| thin interpreted (control) | 163.2 ns | 162.3 ns |
-**The body is only now becoming visible.** Under 83 ns of plumbing, thin and heavy
-compiled to the same number; under 27 ns, heavy costs about 20% more than thin. That is
-the shape to expect from here: the closer the plumbing gets to zero, the more a ratio
-depends on what the system actually computes.
+**Then the rows stopped being repacked at all.** A row table is a function of which
+entities match and where their components are; both have an authority that answers
+cheaply (the query cache hands back the same array while its answer stands, and
+`Registry::layoutEpoch` sums every pool's own version), so when neither moved, last
+frame's rows are this frame's. Same bench, after that:
+
+| | packed every frame | kept |
+|---|---|---|
+| thin compiled | 27.5 ns | **2.1 ns** |
+| script compiled | 27.3 ns | **2.8 ns** |
+| heavy compiled | 33.8 ns | **9.4 ns** |
+
+**The body is the cost now**, which is the shape AOT should have: heavy is 4x thin
+where under 83 ns of plumbing the two were indistinguishable. Ratios at 5,000 entities
+run 19x (heavy) to 110x (script).
## What this is NOT
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b9a4423a9..7aa9a32f7 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -9300,6 +9300,7 @@ tabIndex: number | undefined
@internal isChangeTracked: (component: AnyComponentDef) => boolean
@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
@internal isIterating: () => boolean
+@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5ca60bf8b..df0bde3b3 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -9493,6 +9493,7 @@ tabIndex: number | undefined
@internal isChangeTracked: (component: AnyComponentDef) => boolean
@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
@internal isIterating: () => boolean
+@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1276e4518..e32d3ff8a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -9295,6 +9295,7 @@ tabIndex: number | undefined
@internal isChangeTracked: (component: AnyComponentDef) => boolean
@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
@internal isIterating: () => boolean
+@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index c0f9a177d..8286848f1 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -9547,6 +9547,7 @@ tabIndex: number | undefined
@internal isChangeTracked: (component: AnyComponentDef) => boolean
@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
@internal isIterating: () => boolean
+@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 97ff99573..9c3b73e9e 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -334,6 +334,7 @@ postprocess_setUniformVec4: (passName: string, uniform: string, x: number, y: nu
postprocess_shutdown: () => void
provideReplacementDevice: (() => boolean) | undefined
recoverDevice: (() => boolean) | undefined
+registryLayoutEpoch: (registry: CppRegistry) => number
registry_batchSyncPhysicsTransforms: (registry: CppRegistry, bufferPtr: number, count: number, ppu: number) => void
registry_getCameraEntities: (registry: CppRegistry) => number[]
registry_getCanvasEntities: ((registry: CppRegistry) => number[]) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index cdb0bd633..f7772d65c 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -9323,6 +9323,7 @@ tabIndex: number | undefined
@internal isChangeTracked: (component: AnyComponentDef) => boolean
@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
@internal isIterating: () => boolean
+@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.ts
index a3f5aebf5..ac8329f59 100644
--- a/sdk/src/ecs/ScriptStorage.ts
+++ b/sdk/src/ecs/ScriptStorage.ts
@@ -34,6 +34,18 @@ export class ScriptStorage {
* linear memory before any component is added, because compiled code cannot
* reach a JS-heap array; a native one leaves the default.
*/
+ /**
+ * Bumped whenever a pooled row is claimed, released, or moved by a growth —
+ * i.e. whenever an address this storage handed out may have stopped meaning
+ * what it meant. The engine's own pools answer the same question through
+ * `Registry::layoutEpoch`; a caller that holds addresses reads both.
+ */
+ get layoutEpoch(): number {
+ return this.layoutEpoch_;
+ }
+
+ private layoutEpoch_ = 0;
+
usePoolMemory(memory: PoolMemory): void {
if (this.pools_.size > 0) {
throw new Error('ScriptPool memory must be chosen before the first pooled component');
@@ -105,6 +117,9 @@ export class ScriptStorage {
const { view, isNew } = pool.put(
entity, component._default as Record<string, unknown>,
filtered as Record<string, unknown> | undefined);
+ // Only a NEW row moves anything: it claims a slot, and claiming may
+ // have grown the pool. Overwriting one leaves every address alone.
+ if (isNew) this.layoutEpoch_++;
storage.set(entity, view);
this.note_(entity, component);
return { value: view as T, isNew };
@@ -146,7 +161,7 @@ export class ScriptStorage {
remove<T>(entity: Entity, component: ComponentDef<T>): void {
const storage = this.tsStorage_.get(component._id);
storage?.delete(entity);
- this.pools_.get(component._id)?.delete(entity);
+ if (this.pools_.get(component._id)?.delete(entity)) this.layoutEpoch_++;
const ids = this.entityComponents_.get(entity);
if (ids) {
ids.delete(component._id);
@@ -177,6 +192,7 @@ export class ScriptStorage {
const { view, isNew } = pool.put(
entity, component._default as Record<string, unknown>,
(data ?? undefined) as Record<string, unknown> | undefined);
+ if (isNew) this.layoutEpoch_++;
storage.set(entity, view);
this.note_(entity, component);
return { isNew };
@@ -216,7 +232,7 @@ export class ScriptStorage {
const removed: symbol[] = [];
for (const id of ids) {
this.tsStorage_.get(id)?.delete(entity);
- this.pools_.get(id)?.delete(entity);
+ if (this.pools_.get(id)?.delete(entity)) this.layoutEpoch_++;
removed.push(id);
}
this.entityComponents_.delete(entity);
diff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.ts
index bb1e7b175..02deebc76 100644
--- a/sdk/src/ecs/aot/AotDispatch.ts
+++ b/sdk/src/ecs/aot/AotDispatch.ts
@@ -22,6 +22,19 @@
* block. The nested `[entity, addr, addr]` arrays this replaced were two
* allocations per entity per frame and then a word-by-word copy of the
* same numbers.
+ *
+ * And then they are KEPT. A row table is a function of two things: which
+ * entities match, and where their components are. Each has an authority
+ * that already answers cheaply — the query cache hands back the very same
+ * array while its answer stands, and `World.layoutEpoch` is one number
+ * over every pool's own version. When neither moved, last frame's rows
+ * are this frame's rows, and packing is the cost that disappears
+ * (bench/aot-frame: 27.5 ns per entity per frame to under 2).
+ *
+ * A world that cannot answer the second question — an engine artifact
+ * with no epoch binding — repacks every frame. Trusting an address
+ * because nobody could tell us it moved is how a compiled system reads
+ * somebody else's bytes.
*/
import type { AnyComponentDef } from '../component';
@@ -33,6 +46,8 @@ import type { AotTwin } from './AotSystems';
/** No `With`/`Without` on a compiled query; the subset has no syntax for one. */
const NO_FILTERS: AnyComponentDef[] = [];
+/** What a query that named an unknown component matches. */
+const EMPTY_ENTITIES: readonly Entity[] = [];
/** What one declared Query needs, resolved once. */
interface QueryPlan {
@@ -63,6 +78,12 @@ interface Plan {
readonly offsets: Uint32Array;
/** How much of `scratch` this call filled. */
rowWords: number;
+ /** The entity array each query was packed from, by identity: the query cache
+ * returns the same one while its answer stands, and a different one the
+ * moment the set or the order changed. */
+ readonly packedFrom: (readonly Entity[] | null)[];
+ /** `World.layoutEpoch` when they were packed; null when it cannot be had. */
+ packedAt: number | null;
}
/**
@@ -78,7 +99,7 @@ export class AotDispatch {
run(twin: AotTwin): void {
const plan = this.planFor_(twin);
- this.packRows_(plan);
+ this.packRows_(plan, this.world.layoutEpoch());
const resources = plan.resources.map((name) => this.runtime.addresses.resourceAt(name) ?? 0);
this.runtime.ctx.build(plan.scratch, plan.rowWords, plan.offsets, plan.counts, resources);
@@ -102,17 +123,32 @@ export class AotDispatch {
* A row whose components cannot all answer is not written: an address of zero
* is a real address, and the compiled code would read somebody else's bytes.
*/
- private packRows_(plan: Plan): void {
+ private packRows_(plan: Plan, epoch: number | null): void {
+ // The whole table or none of it: one query's rows moving says nothing
+ // about another's, but a repack is a walk of both and this way there is
+ // one condition to reason about rather than one per query.
+ let reuse = epoch !== null && epoch === plan.packedAt;
+ const lists: (readonly Entity[])[] = [];
+ for (let k = 0; k < plan.queries.length; k++) {
+ const q = plan.queries[k];
+ const entities = q.resolved
+ ? this.world.queryEntities(q.comps, NO_FILTERS, NO_FILTERS, q.key, undefined, q.depIds)
+ : EMPTY_ENTITIES;
+ lists.push(entities);
+ if (entities !== plan.packedFrom[k]) reuse = false;
+ }
+ if (reuse) return;
+
let at = 0;
for (let k = 0; k < plan.queries.length; k++) {
const q = plan.queries[k];
plan.offsets[k] = at;
+ plan.packedFrom[k] = lists[k]!;
if (!q.resolved) {
plan.counts[k] = 0;
continue;
}
- const entities = this.world.queryEntities(
- q.comps, NO_FILTERS, NO_FILTERS, q.key, undefined, q.depIds);
+ const entities = lists[k]!;
plan.scratch = grow(plan.scratch, at + entities.length * q.width);
const rows = plan.scratch;
const width = q.width;
@@ -135,6 +171,7 @@ export class AotDispatch {
at += n * width;
}
plan.rowWords = at;
+ plan.packedAt = epoch;
}
/**
@@ -185,6 +222,8 @@ export class AotDispatch {
counts: new Uint32Array(queries.length),
offsets: new Uint32Array(queries.length),
rowWords: 0,
+ packedFrom: queries.map(() => null),
+ packedAt: null,
};
this.plans.set(twin, plan);
return plan;
diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.ts
index 5c0ad1674..08f3479af 100644
--- a/sdk/src/ecs/bridge/BuiltinBridge.ts
+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts
@@ -546,6 +546,20 @@ export class BuiltinBridge {
return this.builtinMethodCache_;
}
+ /**
+ * Every engine pool's version in one number, or null where this build cannot
+ * be asked (no registry, or an artifact older than the binding). Null means
+ * "assume everything moved": a holder of addresses must re-resolve rather
+ * than trust a number it could not read.
+ */
+ layoutEpoch(): number | null {
+ const registry = this.cppRegistry_;
+ if (!registry) return null;
+ const fn = (this.module_ as unknown as Record<string, unknown> | null)?.['registryLayoutEpoch'];
+ if (typeof fn !== 'function') return null;
+ return (fn as (r: CppRegistry) => number)(registry);
+ }
+
getEntitySet(cppName: string): Set<Entity> | undefined {
return this.builtinEntitySets_.get(cppName);
}
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index 04343b05f..954a77795 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -1185,6 +1185,19 @@ export class World {
return this.addressResolver(component)(entity);
}
+ /**
+ * @internal One number for "could any component have moved since you last
+ * asked": the engine's pools (`Registry::layoutEpoch`) plus this SDK's own (a
+ * claimed, released or grown script row). Null where the engine cannot be
+ * asked, which means re-resolve. It says nothing about which entities MATCH;
+ * that is the query cache's answer, and a caller needing both asks both.
+ */
+ layoutEpoch(): number | null {
+ const engine = this.builtin_.layoutEpoch();
+ if (engine === null && this.builtin_.hasCpp) return null;
+ return (engine ?? 0) + this.scripts_.layoutEpoch;
+ }
+
/**
* @internal The same answer as a function, for a caller with a whole column
* to walk: the lookup above is per entity, and a loop that pays it per row is
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index fdcb2a05a..f3756717e 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -571,6 +571,14 @@ export interface ESEngineModule {
anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
+ /**
+ * Every component pool's version, summed (`Registry::layoutEpoch`). Equal
+ * across two reads means no stored component changed address between them —
+ * which is what a holder of raw addresses (the AOT row table) asks before
+ * trusting them for another frame.
+ */
+ registryLayoutEpoch(registry: CppRegistry): number;
+
// Pointer-based component access
getTransformPtr(registry: CppRegistry, entity: number): number;
getSpritePtr(registry: CppRegistry, entity: number): number;
diff --git a/sdk/tests/aot-row-cache.test.ts b/sdk/tests/aot-row-cache.test.ts
new file mode 100644
index 000000000..f31b3e4ac
--- /dev/null
+++ b/sdk/tests/aot-row-cache.test.ts
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file aot-row-cache.test.ts
+ * @brief When last frame's rows are this frame's rows, and when they are not.
+ *
+ * @details The row table a compiled system reads is a function of two things:
+ * which entities match, and where their components are. Keeping it
+ * across frames is the difference between 27 ns per entity per frame
+ * and under 2 (bench/aot-frame) — and the way it goes wrong is silent.
+ * A stale address is not an error; it is somebody else's bytes.
+ *
+ * So each half is tested against the thing only IT can see. The query
+ * cache answers "which entities", and hands back a different array the
+ * moment the set or the order changed. `World.layoutEpoch` answers
+ * "where", including the moves this SDK never hears about — a C++
+ * system inserting a component reallocates that pool with no JS call
+ * anywhere in it.
+ *
+ * Addresses here come from an injected MemoryProvider and the epoch
+ * from a stub binding, because both of those are what a real engine
+ * would move and neither can be moved on demand.
+ */
+import { describe, it, expect } from 'vitest';
+
+import { World } from '../src/ecs/world';
+import { Transform } from '../src/ecs/component';
+import type { AnyComponentDef } from '../src/ecs/component';
+import { defineSystem, SystemRunner } from '../src/ecs/system';
+import { ResourceStorage } from '../src/ecs/resource';
+import { WasmPoolMemory, type WasmHeap } from '../src/ecs/WasmPoolMemory';
+import { AotContext, SYSCTX_WORDS } from '../src/ecs/aot/AotContext';
+import { AotDispatch } from '../src/ecs/aot/AotDispatch';
+import { AotSystems, type AotManifest } from '../src/ecs/aot/AotSystems';
+import type { AotRuntime } from '../src/ecs/aot/AotRuntime';
+import type { ComponentHeap, MemoryProvider } from '../src/ecs/bridge/memoryProvider';
+import { engineAbiDigest, projectShapeDigest } from '../src/ecs/aot/abiDigest';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import type { Entity } from '../src/types';
+
+const N = 8;
+const STRIDE = 64;
+
+/** A linear memory and a bump allocator: the engine, as far as an arena cares. */
+class Heap implements WasmHeap {
+ readonly memory = new WebAssembly.Memory({ initial: 4, maximum: 4 });
+ HEAPU8 = new Uint8Array(this.memory.buffer);
+ private next = 4096;
+ _malloc(size: number): number {
+ const at = this.next;
+ this.next += (size + 15) & ~15;
+ return at;
+ }
+ _free(): void { /* a bump allocator frees nothing */ }
+}
+
+/**
+ * Enough of a CppRegistry for `insert` to go through: the bridge refuses a
+ * builtin component whose four methods are not there. What they do is nobody's
+ * business here — the addresses come from the injected provider below.
+ */
+let nextEntity = 0;
+const REGISTRY = {
+ create: () => ++nextEntity,
+ addTransform: () => {},
+ getTransform: () => ({}),
+ hasTransform: () => true,
+ removeTransform: () => {},
+} as unknown as CppRegistry;
+
+/**
+ * A world whose `Transform` addresses this test can move, and whose engine can
+ * be asked — or not asked — for its layout epoch.
+ */
+function harness(options: { epochBinding?: boolean } = {}) {
+ const heap = new Heap();
+ const memory = new WasmPoolMemory(heap);
+ const world = new World();
+ world.useScriptPoolMemory(memory);
+
+ const live = new Set<number>();
+ const state = { base: 1 << 16, epoch: 0, resolved: 0 };
+ const provider: MemoryProvider = {
+ resolveComponentHeap: (name: string) => (name === 'Transform'
+ ? (entity: Entity, out: ComponentHeap): boolean => {
+ const id = entity as unknown as number;
+ if (!live.has(id)) return false;
+ state.resolved++;
+ out.f32 = new Float32Array(heap.memory.buffer);
+ out.u32 = new Uint32Array(heap.memory.buffer);
+ out.u8 = heap.HEAPU8;
+ out.ptr = state.base + id * STRIDE;
+ return true;
+ }
+ : null),
+ };
+ const module = {
+ ...(options.epochBinding === false ? {} : { registryLayoutEpoch: () => state.epoch }),
+ } as unknown as ESEngineModule;
+ world.connectCpp(REGISTRY, module, { memory: provider });
+
+ const runner = new SystemRunner(world, new ResourceStorage());
+ const system = defineSystem([], () => { /* the closure never runs here */ },
+ { name: 'Move' });
+
+ // The twin: it records the rows it was handed rather than reading them, which
+ // is the only thing this test is about.
+ const seen: number[][] = [];
+ const ctx = new AotContext(memory);
+ const systems = new AotSystems();
+ systems.install(
+ {
+ engineAbi: engineAbiDigest(4),
+ projectShapes: projectShapeDigest([]),
+ systems: [{
+ name: 'Move', symbol: 'es_sys_Move',
+ queries: [[{ comp: 'Transform', mut: false }]], resources: [],
+ }],
+ } satisfies AotManifest,
+ { es_sys_Move: (at: number) => seen.push(rowsAt(heap, at)) },
+ (name) => (name === 'Transform' ? Transform as unknown as AnyComponentDef : undefined),
+ );
+ const runtime: AotRuntime = {
+ systems,
+ addresses: { componentNamed: () => Transform as unknown as AnyComponentDef, resourceAt: () => undefined },
+ ctx,
+ };
+ runner.useAot(runtime);
+ void new AotDispatch(world, runtime);
+
+ const spawn = (): Entity => {
+ const entity = world.spawn();
+ live.add(entity as unknown as number);
+ world.insert(entity, Transform as unknown as AnyComponentDef, {});
+ return entity;
+ };
+ return { world, runner, system, state, seen, spawn, live };
+}
+
+/** The addresses in the first query's rows, read out of the arena. */
+function rowsAt(heap: Heap, ctx: number): number[] {
+ const words = new Uint32Array(heap.memory.buffer);
+ const queries = words[(ctx >> 2) + 0]!;
+ const rows = words[(queries >> 2) + 0]!;
+ const count = words[(queries >> 2) + 1]!;
+ const out: number[] = [];
+ for (let i = 0; i < count; i++) out.push(words[(rows >> 2) + i * 2 + 1]!);
+ return out;
+}
+
+describe('the rows a compiled system reads, kept across frames', () => {
+ it('resolves an address once, not once a frame', () => {
+ const h = harness();
+ for (let i = 0; i < N; i++) h.spawn();
+
+ h.runner.run(h.system);
+ const first = h.state.resolved;
+ expect(first).toBe(N);
+
+ for (let f = 0; f < 5; f++) h.runner.run(h.system);
+ // Nothing moved and nothing joined, so there was nothing to ask again.
+ expect(h.state.resolved).toBe(first);
+ expect(h.seen.length).toBe(6);
+ expect(h.seen[5]).toEqual(h.seen[0]);
+ });
+
+ it('follows the addresses when the engine says its pools moved', () => {
+ const h = harness();
+ for (let i = 0; i < N; i++) h.spawn();
+ h.runner.run(h.system);
+ const before = h.seen[0]!;
+
+ // What a C++ system's insert does to a pool: every component of that type
+ // is somewhere else, and nothing in JS was called.
+ h.state.base += 1 << 20;
+ h.state.epoch++;
+ h.runner.run(h.system);
+
+ const after = h.seen[1]!;
+ expect(after).not.toEqual(before);
+ expect(after).toEqual(before.map((a) => a + (1 << 20)));
+ });
+
+ it('follows the entity set without needing the epoch to say so', () => {
+ const h = harness();
+ for (let i = 0; i < N; i++) h.spawn();
+ h.runner.run(h.system);
+ expect(h.seen[0]!.length).toBe(N);
+
+ h.spawn();
+ h.runner.run(h.system);
+ expect(h.seen[1]!.length).toBe(N + 1);
+ });
+
+ it('follows a reorder, which moves neither the count nor the epoch', () => {
+ const h = harness();
+ const entities = [];
+ for (let i = 0; i < N; i++) entities.push(h.spawn());
+ h.runner.run(h.system);
+ const before = h.seen[0]!;
+
+ // The same entities the other way round: a cache that only counted rows
+ // would hand the compiled code last frame's order, and the closure it must
+ // agree with iterates the new one.
+ h.world.applyEntityOrder([...entities].reverse());
+ h.runner.run(h.system);
+
+ expect(h.seen[1]).toEqual([...before].reverse());
+ });
+
+ it('re-resolves every frame when the engine cannot be asked', () => {
+ const h = harness({ epochBinding: false });
+ for (let i = 0; i < N; i++) h.spawn();
+
+ h.runner.run(h.system);
+ h.runner.run(h.system);
+ h.runner.run(h.system);
+ // An artifact with no epoch binding is one that cannot promise anything
+ // stayed put, so the rows are rebuilt — the same cost as before this
+ // cache existed, which is the point: it degrades, it does not guess.
+ expect(h.state.resolved).toBe(3 * N);
+ });
+
+ it('lays out a SysCtx whichever way the rows came', () => {
+ const h = harness();
+ for (let i = 0; i < N; i++) h.spawn();
+ h.runner.run(h.system);
+ // The arena's shape is the ABI's, not the cache's: rows begin after the
+ // SysCtx and one QueryRows record, cached or freshly packed.
+ expect(h.seen[0]!.length).toBe(N);
+ expect(SYSCTX_WORDS).toBe(6);
+ });
+});
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 63aaac264..7c51e146e 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -387,6 +387,12 @@ int getTransformPtr(ecs::Registry& r, u32 e) {
return static_cast<int>(reinterpret_cast<uintptr_t>(t));
}
+// Every pool's version in one number: what a holder of raw component addresses
+// asks before trusting them for another frame (Registry::layoutEpoch).
+double registryLayoutEpoch(ecs::Registry& r) {
+ return r.layoutEpoch();
+}
+
int getSpritePtr(ecs::Registry& r, u32 e) {
auto* s = r.tryGet<ecs::Sprite>(Entity::fromRaw(e));
if (!s) return 0;
@@ -427,6 +433,7 @@ int getCircleCollider2DPtr(ecs::Registry& r, u32 e) {
EMSCRIPTEN_BINDINGS(esengine_ptr_access) {
emscripten::function("getTransformPtr", &esengine::getTransformPtr);
+ emscripten::function("registryLayoutEpoch", &esengine::registryLayoutEpoch);
emscripten::function("getSpritePtr", &esengine::getSpritePtr);
emscripten::function("getVelocityPtr", &esengine::getVelocityPtr);
emscripten::function("getCameraPtr", &esengine::getCameraPtr);
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 5bceda58d..51e4f4cd9 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -513,6 +513,23 @@ public:
return rank;
}
+ /**
+ * @brief Sum of every pool's version — one number for "did anything move"
+ * @return Equal across two reads ⇒ no stored component changed address
+ *
+ * @details A holder of RAW ADDRESSES (the AOT row table) needs one cheap
+ * question, and one that covers pools it never asked about: a C++
+ * insert moves that pool with no JS call in it. u64 so it cannot
+ * wrap onto a value already seen; double because JS takes that.
+ */
+ double layoutEpoch() const {
+ u64 sum = 0;
+ for (const auto& pool : pools_) {
+ if (pool) sum += pool->version();
+ }
+ return static_cast<double>(sum);
+ }
+
/** @brief Reorders every component pool by a rank table from buildEntityRank. */
void applyEntityRank(const std::vector<u32>& rank) {
for (auto& pool : pools_) {