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(ecs): world transforms have an authority, and it is not the renderer
esengine83e62dc6cef6
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex cd024c2ec..69f2604ac 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -9513,6 +9513,7 @@ tabIndex: number | undefined@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void+@internal ensureTransformsComposed: () => void@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStats@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@@ -9523,6 +9524,7 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@@ -9549,6 +9551,7 @@ tabIndex: number | undefined@internal setQueryCostEnabled: (enabled: boolean) => void@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number+@internal transformEpoch: () => number@internal useScriptPoolMemory: (memory: PoolMemory) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 15a9fd397..50ccf9be1 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -9706,6 +9706,7 @@ tabIndex: number | undefined@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void+@internal ensureTransformsComposed: () => void@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStats@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@@ -9716,6 +9717,7 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@@ -9742,6 +9744,7 @@ tabIndex: number | undefined@internal setQueryCostEnabled: (enabled: boolean) => void@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number+@internal transformEpoch: () => number@internal useScriptPoolMemory: (memory: PoolMemory) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 70dedbcac..302563a7c 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -9508,6 +9508,7 @@ tabIndex: number | undefined@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void+@internal ensureTransformsComposed: () => void@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStats@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@@ -9518,6 +9519,7 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@@ -9544,6 +9546,7 @@ tabIndex: number | undefined@internal setQueryCostEnabled: (enabled: boolean) => void@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number+@internal transformEpoch: () => number@internal useScriptPoolMemory: (memory: PoolMemory) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 807cbfa77..9cf4031ee 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -9760,6 +9760,7 @@ tabIndex: number | undefined@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void+@internal ensureTransformsComposed: () => void@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStats@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@@ -9770,6 +9771,7 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@@ -9796,6 +9798,7 @@ tabIndex: number | undefined@internal setQueryCostEnabled: (enabled: boolean) => void@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number+@internal transformEpoch: () => number@internal useScriptPoolMemory: (memory: PoolMemory) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voiddiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 37618985f..2bef30215 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -423,6 +423,8 @@ tilemap_setTile: ((entity: number, x: number, y: number, tileId: number) => voidtilemap_setTiles: ((entity: number, tilesPtr: number, count: number) => void) | undefinedtrail_clear: ((registry: CppRegistry, entity: number) => void) | undefinedtrail_update: ((registry: CppRegistry, dt: number) => void) | undefined+transform_ensureComposed: ((registry: CppRegistry) => void) | undefined+transform_epochAddress: (() => number) | undefinedtransform_update: (registry: CppRegistry) => voiduiHitTest_getHitEntity: () => numberuiHitTest_pick: ((registry: CppRegistry, worldX: number, worldY: number) => number) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 6025e3419..f2b10b1c9 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -9536,6 +9536,7 @@ tabIndex: number | undefined@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void+@internal ensureTransformsComposed: () => void@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStats@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@@ -9546,6 +9547,7 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@@ -9572,6 +9574,7 @@ tabIndex: number | undefined@internal setQueryCostEnabled: (enabled: boolean) => void@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number+@internal transformEpoch: () => number@internal useScriptPoolMemory: (memory: PoolMemory) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voiddiff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.tsindex 310c83721..3d242ef31 100644--- a/sdk/src/ecs/aot/AotDispatch.ts+++ b/sdk/src/ecs/aot/AotDispatch.ts@@ -113,6 +113,9 @@ function resolverFor(world: World, def: AnyComponentDef): (entity: Entity) => nureturn isTagDef(def) ? () => 0 : world.addressResolver(def);}+/** Components whose value feeds the world-transform composition. */+const COMPOSITION_INPUTS = new Set(['Transform', 'Parent', 'Children']);+export class AotDispatch {private readonly plans = new Map<AotTwin, Plan>();@@ -244,6 +247,15 @@ export class AotDispatch {const q = plan.queries[k];const n = plan.counts[k];if (q.mutated.length === 0 || n === 0) continue;+ // NOT an observation, so it must not inherit `isChangeTracked`'s+ // opt-in: a server with no `Changed(Transform)` consumer would+ // otherwise move transforms nobody recomposes.+ for (const def of q.mutated) {+ if (COMPOSITION_INPUTS.has(def._name)) {+ this.world.invalidateTransformComposition();+ break;+ }+ }for (const def of q.mutated) {if (!this.world.isChangeTracked(def)) continue;const base = plan.offsets[k];diff --git a/sdk/src/ecs/aot/installNativeAot.ts b/sdk/src/ecs/aot/installNativeAot.tsindex d81ad297f..cea4432ef 100644--- a/sdk/src/ecs/aot/installNativeAot.ts+++ b/sdk/src/ecs/aot/installNativeAot.ts@@ -199,6 +199,9 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nu* may have moved, and the Changed ticks are marked. The call itself is one* number crossing the boundary.*/+/** Components whose value feeds the world-transform composition. */+const COMPOSITION_INPUTS = new Set(['Transform', 'Parent', 'Children']);+class NativeAotDispatch implements AotDispatcher {/** The epoch the pools were last reported at. Null means never. */private reportedAt_: number | null | undefined = undefined;@@ -287,6 +290,14 @@ class NativeAotDispatch implements AotDispatcher {*/private markChanged_(twin: AotTwin): void {for (let k = 0; k < twin.decl.queries.length; k++) {+ // Before the tracking filter below: composition staleness is not an+ // observation and must not inherit its opt-in.+ for (const def of twin.mutated[k] ?? []) {+ if (COMPOSITION_INPUTS.has(def._name)) {+ this.world.invalidateTransformComposition();+ break;+ }+ }const mutated = (twin.mutated[k] ?? []).filter((def) => this.world.isChangeTracked(def));if (mutated.length === 0) continue;const comps = twin.decl.queries[k]!diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.tsindex 433b9c2f5..178273a55 100644--- a/sdk/src/ecs/bridge/BuiltinBridge.ts+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts@@ -340,6 +340,7 @@ function formatBridgeDiagnostic(v: BridgeVerification): string {export class BuiltinBridge {private cppRegistry_: CppRegistry | null = null;private module_: ESEngineModule | null = null;+ private transformEpochWord_ = -1;private memory_: MemoryProvider | null = null;private builtinMethodCache_ = new Map<string, BuiltinMethods>();private builtinEntitySets_ = new Map<string, Set<Entity>>();@@ -364,6 +365,12 @@ export class BuiltinBridge {): void {this.cppRegistry_ = cppRegistry;this.module_ = module ?? null;+ // The ADDRESS is stable; the view over it is not. Emscripten replaces+ // every HEAP view when memory grows, and a cached one writes nowhere+ // while looking like it worked — so only the word offset is kept.+ this.transformEpochWord_ = module?.transform_epochAddress+ ? module.transform_epochAddress() >>> 2+ : -1;// Web derives a wasm-HEAP backend from the module; the native runtime// injects its own (es_<Component>_buffer). No module and no override => no// fast path (resolvePtr* return null), exactly as before.@@ -402,6 +409,31 @@ export class BuiltinBridge {this.builtinEntitySets_.clear();}+ /**+ * Say that composed world transforms are stale. Called for a write to a+ * local transform field or to the hierarchy — never for `worldPosition` and+ * friends, which are the composition's own output.+ */+ invalidateTransformComposition(): void {+ if (this.transformEpochWord_ < 0) return;+ const heap = this.module_?.HEAPU32;+ if (!heap) return;+ heap[this.transformEpochWord_] = (heap[this.transformEpochWord_] + 1) >>> 0;+ }++ /** Compose if any producer invalidated since the last one; O(1) otherwise. */+ ensureTransformsComposed(): void {+ if (!this.cppRegistry_) return;+ this.module_?.transform_ensureComposed?.(this.cppRegistry_);+ }++ /** @internal What the staleness counter reads, for the fixtures that assert+ * a producer notified. */+ transformEpoch(): number {+ const heap = this.module_?.HEAPU32;+ return this.transformEpochWord_ < 0 || !heap ? -1 : heap[this.transformEpochWord_];+ }+get hasCpp(): boolean {return this.cppRegistry_ !== null;}diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex aa61baf4f..6c7cc2956 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -115,6 +115,10 @@ export interface QueryFilter {// World// =============================================================================+/** Components whose value feeds the world-transform composition. Hierarchy is+ * in here too: a reparent moves a subtree without touching its transforms. */+const COMPOSITION_INPUTS = new Set(['Transform', 'Parent', 'Children']);+/*** The entity store, as `GetWorld()` hands it to a system — the escape hatch for* work the declared parameters cannot express. Prefer `Query`/`Res`/`Commands`:@@ -610,13 +614,13 @@ export class World {parents.add(child);this.changes_.recordAdded(Parent, child);}- this.changes_.recordChanged(Parent, child);+ this.recordComponentWrite_(child, Parent);if (!children.has(parent)) {children.add(parent);this.changes_.recordAdded(Children, parent);}- this.changes_.recordChanged(Children, parent);+ this.recordComponentWrite_(parent, Children);}this.queries_.markStructuralChange();@@ -680,7 +684,7 @@ export class World {handleWasmError(e, `set(${component._name}, entity=${entity})`);}}- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);notifyBridge('onComponentChanged', entity, component._name);return;}@@ -694,7 +698,7 @@ export class World {this.changes_.recordAdded(component, entity);notifyBridge('onComponentAdded', entity, component._name);}- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);if ((component as ComponentDef<any>)._id === Name._id) {this.names_.update(entity, (data as { value: string }).value);}@@ -737,7 +741,7 @@ export class World {} finally {// A throwing `edit` has already written to the live object, so the// change is reported before the error escapes.- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);if ((component as ComponentDef<any>)._id === Name._id) {this.names_.update(entity, (draft as { value: string }).value);}@@ -838,7 +842,7 @@ export class World {this.changes_.recordAdded(component, entity);notifyBridge('onComponentAdded', entity, component._name);}- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);notifyBridge('onComponentChanged', entity, component._name);return merged;}@@ -855,7 +859,7 @@ export class World {this.changes_.recordAdded(component, entity);notifyBridge('onComponentAdded', entity, component._name);}- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);if (component._id === Name._id) {this.names_.update(entity, (value as { value: string }).value);}@@ -1275,9 +1279,39 @@ export class World {return this.changes_.writeReaderCount(component);}+ /**+ * @internal One place for "this component was written".+ *+ * The composition epoch hangs off the LOGICAL mutation contract, not off the+ * storage path: `set`, `insert`, `update` and a `Mut` write-back all arrive+ * here whether or not the fast pointer setter moved the bytes.+ */+ private recordComponentWrite_(entity: Entity, component: AnyComponentDef): void {+ if (COMPOSITION_INPUTS.has(component._name)) {+ this.builtin_.invalidateTransformComposition();+ }+ this.changes_.recordChanged(component, entity);+ }++ /** @internal Say composed world transforms are stale, for a producer that+ * wrote the bytes without going through the mutation seam. */+ invalidateTransformComposition(): void {+ this.builtin_.invalidateTransformComposition();+ }++ /** @internal Compose world transforms if a producer invalidated them. */+ ensureTransformsComposed(): void {+ this.builtin_.ensureTransformsComposed();+ }++ /** @internal What the composition staleness counter reads. */+ transformEpoch(): number {+ return this.builtin_.transformEpoch();+ }+/** @internal Mark component as changed without writing data (for in-place Mut query) */markChanged(entity: Entity, component: AnyComponentDef): void {- this.changes_.recordChanged(component, entity);+ this.recordComponentWrite_(entity, component);}/** @internal Whether any query is asking about `component`'s changes. */diff --git a/sdk/src/net/replication/interest.ts b/sdk/src/net/replication/interest.tsindex 27dc1aedb..4eeef663d 100644--- a/sdk/src/net/replication/interest.ts+++ b/sdk/src/net/replication/interest.ts@@ -143,11 +143,18 @@ export function radiusInterest(radius: number, options: RadiusInterestOptions =};}+/**+ * WORLD space, as the option documents: `position` is authoring input relative+ * to the parent, so two children of different parents sharing an offset would+ * otherwise occupy the same point. The server composes before it samples.+ */function defaultPosition(world: World, entity: Entity): InterestPoint | null {const Transform = getComponent('Transform');if (!Transform || !world.has(entity, Transform)) return null;- const t = world.tryGet(entity, Transform) as { position?: { x: number; y: number; z?: number } } | null;- return t?.position ? { x: t.position.x, y: t.position.y, z: t.position.z ?? 0 } : null;+ const t = world.tryGet(entity, Transform) as+ { worldPosition?: { x: number; y: number; z?: number } } | null;+ const p = t?.worldPosition;+ return p ? { x: p.x, y: p.y, z: p.z ?? 0 } : null;}/**diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex b1169781d..33f426619 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -628,6 +628,10 @@ export class ReplicationServer {* other O(population) the policy shape forces.*/private resolveVisibility_(): (connectionId: number) => Set<Entity> {+ // Relevance is decided in world space, so the composition has to be+ // current before a snapshot is taken — here rather than inside a position+ // reader, so a caller's own reader sees the same composed fact.+ this.world_.ensureTransformsComposed();const source = this.interest_;if (!source) {const all = [...this.known_];diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 24fd8b206..840ee2fbe 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -423,6 +423,11 @@ export interface ESEngineModule {renderer_resize(width: number, height: number): void;renderer_beginFrame(elapsedSec: number): void;renderer_updateTransforms(registry: CppRegistry): void;+ /** Address of the transform composition's staleness counter, so a producer+ * stores into linear memory rather than calling across it. */+ transform_epochAddress?(): number;+ /** Compose world transforms if a producer said the inputs moved; O(1) if not. */+ transform_ensureComposed?(registry: CppRegistry): void;/** Permute component storage to the given entity order — see World.applyEntityOrder.* Optional: an older core still answers every other renderer entry point. */renderer_setEntityDrawOrder?(registry: CppRegistry, entitiesPtr: number, count: number): void;diff --git a/sdk/tests/world-transform-authority.test.ts b/sdk/tests/world-transform-authority.test.tsnew file mode 100644index 000000000..d43743cb0--- /dev/null+++ b/sdk/tests/world-transform-authority.test.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Who decides when world transforms are recomposed.+ *+ * A staleness epoch that producers advance and consumers wait on. A render+ * frame is not a mutation: a server with no frames still recomposes, and two+ * fixed steps inside one frame each get their own answer.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { App } from '../src/app/app';+import { Transform } from '../src/ecs/component';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('world transform authority', () => {+ let module: ESEngineModule;+ beforeAll(async () => { module = await loadWasmModule(); });++ /** A parent at 100 and a child 5 to its right, on a server with no renderer. */+ function parented() {+ const app = App.new();+ app.connectCpp(new module.Registry() as unknown as CppRegistry, module);+ const world = app.world;+ const parent = world.spawn('parent');+ world.insert(parent, Transform, { position: { x: 100, y: 0, z: 0 } });+ const child = world.spawn('child');+ world.insert(child, Transform, { position: { x: 5, y: 0, z: 0 } });+ world.setParent(child, parent);+ const worldX = () => (world.get(child, Transform) as { worldPosition: { x: number } })+ .worldPosition.x;+ return { app, world, parent, child, worldX };+ }++ it('composes for a server that has no renderer at all', () => {+ const { world, worldX } = parented();+ world.ensureTransformsComposed();+ expect(worldX()).toBe(105);+ });++ it('recomposes for each of two steps inside one frame', () => {+ const { world, parent, worldX } = parented();+ world.update(parent, Transform, (t) => { (t as { position: { x: number } }).position.x = 10; });+ world.ensureTransformsComposed();+ expect(worldX()).toBe(15);++ // No frame boundary between these: replication samples on every fixed+ // step, and a frame may run several.+ world.update(parent, Transform, (t) => { (t as { position: { x: number } }).position.x = 20; });+ world.ensureTransformsComposed();+ expect(worldX()).toBe(25);+ });++ it('composes once for any number of consumers in one generation', () => {+ const { world, parent, worldX } = parented();+ world.update(parent, Transform, (t) => { (t as { position: { x: number } }).position.x = 7; });+ const epoch = world.transformEpoch();++ world.ensureTransformsComposed();+ world.ensureTransformsComposed();+ world.ensureTransformsComposed();++ expect(worldX()).toBe(12);+ // Composing does not itself count as a mutation: writing the world+ // fields must not advance the epoch, or every compose is stale again.+ expect(world.transformEpoch()).toBe(epoch);+ });++ it('a render frame is not a mutation', () => {+ const { world } = parented();+ world.ensureTransformsComposed();+ const epoch = world.transformEpoch();+ module.renderer_beginFrame(0);+ expect(world.transformEpoch()).toBe(epoch);+ });++ it('every legal write path advances the epoch', () => {+ const { world, parent } = parented();+ const advances = (fn: () => void): boolean => {+ const before = world.transformEpoch();+ fn();+ return world.transformEpoch() !== before;+ };+ expect(advances(() => world.update(parent, Transform, (t) => {+ (t as { position: { x: number } }).position.x += 1;+ }))).toBe(true);+ expect(advances(() => world.set(parent, Transform,+ world.get(parent, Transform)))).toBe(true);+ expect(advances(() => world.markChanged(parent, Transform))).toBe(true);+ // Hierarchy moves a subtree without touching a single transform.+ const other = world.spawn('other');+ world.insert(other, Transform, { position: { x: 0, y: 0, z: 0 } });+ expect(advances(() => world.setParent(other, parent))).toBe(true);+ });++ it('survives the wasm heap growing under the notifier', () => {+ const { world, parent, worldX } = parented();+ world.ensureTransformsComposed();++ // A cached typed-array view detaches when Emscripten replaces the heap,+ // and writes to it go nowhere while looking like they worked.+ const before = module.HEAPU32.buffer;+ const blocks: number[] = [];+ for (let i = 0; i < 64 && module.HEAPU32.buffer === before; i++) {+ blocks.push((module as unknown as { _malloc(n: number): number })._malloc(8 << 20));+ }+ expect(blocks.length).toBeGreaterThan(0);++ world.update(parent, Transform, (t) => { (t as { position: { x: number } }).position.x = 400; });+ world.ensureTransformsComposed();+ expect(worldX()).toBe(405);+ });++ it('keeps two worlds apart even at the same epoch value', () => {+ const a = parented();+ a.world.ensureTransformsComposed();+ expect(a.worldX()).toBe(105);++ // A second registry, composed at whatever number the shared epoch holds:+ // having composed the first world says nothing about this one.+ const b = parented();+ b.world.ensureTransformsComposed();+ expect(b.worldX()).toBe(105);+ });++ it('composes a chain built after the first compose', () => {+ const app = App.new();+ app.connectCpp(new module.Registry() as unknown as CppRegistry, module);+ const world = app.world;+ world.ensureTransformsComposed();+ const p = world.spawn();+ world.insert(p, Transform, { position: { x: 3, y: 0, z: 0 } });+ const c = world.spawn();+ world.insert(c, Transform, { position: { x: 4, y: 0, z: 0 } });+ world.setParent(c, p);+ world.ensureTransformsComposed();+ expect((world.get(c, Transform) as { worldPosition: { x: number } }).worldPosition.x).toBe(7);+ world.disconnectCpp();+ });+});++describe('a compiled system that moves transforms', () => {+ let module: ESEngineModule;+ beforeAll(async () => { module = await loadWasmModule(); });++ it('invalidates composition with no Changed consumer anywhere', () => {+ const app = App.new();+ app.connectCpp(new module.Registry() as unknown as CppRegistry, module);+ const world = app.world;+ const parent = world.spawn();+ world.insert(parent, Transform, { position: { x: 100, y: 0, z: 0 } });+ const child = world.spawn();+ world.insert(child, Transform, { position: { x: 5, y: 0, z: 0 } });+ world.setParent(child, parent);+ world.ensureTransformsComposed();++ // Nothing tracks Transform: no Changed() filter, no replication, no+ // write reader. Composition staleness must not depend on any of them —+ // the AOT dispatcher reports it before the tracking filter, not inside.+ expect(world.isChangeTracked(Transform)).toBe(false);++ const before = world.transformEpoch();+ world.invalidateTransformComposition();+ expect(world.transformEpoch()).not.toBe(before);++ world.update(parent, Transform, (t) => { (t as { position: { x: number } }).position.x = 200; });+ world.ensureTransformsComposed();+ expect((world.get(child, Transform) as { worldPosition: { x: number } }).worldPosition.x)+ .toBe(205);+ world.disconnectCpp();+ });+});diff --git a/src/esengine/animation/TweenSystem.cpp b/src/esengine/animation/TweenSystem.cppindex b26218819..bca37edf2 100644--- a/src/esengine/animation/TweenSystem.cpp+++ b/src/esengine/animation/TweenSystem.cpp@@ -1,5 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#include "../ecs/TransformSystem.hpp"#include "TweenSystem.hpp"#include "EasingFunctions.hpp"#include "../ecs/components/Transform.hpp"@@ -161,6 +162,10 @@ static void markUIAnimOverride(ecs::Registry& registry, Entity entity, u8 flag,static void applyTweenValue(ecs::Registry& registry, Entity entity, TweenTarget target, f32 value,std::vector<Entity>& flagged) {+ // Position, scale and rotation targets write local Transform fields.+ // Notifying for colour targets too costs one recompose that changes+ // nothing, where missing one leaves the world reading a stale transform.+ ecs::invalidateTransformComposition();switch (target) {case TweenTarget::PositionX:if (auto* c = registry.tryGet<ecs::Transform>(entity)) {diff --git a/src/esengine/bindings/EngineState.hpp b/src/esengine/bindings/EngineState.hppindex 813a59776..2552ded1b 100644--- a/src/esengine/bindings/EngineState.hpp+++ b/src/esengine/bindings/EngineState.hpp@@ -22,7 +22,6 @@ struct EngineState {u32 viewport_height = 720;glm::vec4 clear_color{0.0f, 0.0f, 0.0f, 1.0f};glm::mat4 current_view_projection{1.0f};- bool transforms_updated = false;};} // namespace esenginediff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 8f21a7cf8..db42d4722 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -410,7 +410,10 @@ void renderer_resize(u32 width, u32 height) {}void renderer_beginFrame(f32 elapsedSec) {- ctx().state().transforms_updated = false;+ // A render frame is not a mutation: composition is invalidated by the+ // producers that write transform inputs. A server has no frames, and one+ // frame may run several fixed steps.+if (auto* rc = ctx().tryGet<RenderContext>()) {rc->setFrameTime(elapsedSec, g_viewportWidth, g_viewportHeight);}@@ -448,12 +451,10 @@ void renderer_end() {checkGLErrors("renderer_end");}+/** Compose if a producer said the inputs moved. The renderer is a consumer of+ * world transforms, not the authority over when they are computed. */static void ensureTransformsUpdated(ecs::Registry& registry) {- if (!ctx().state().transforms_updated && g_transformSystem) {- esengine::World w{registry, ctx().services(), 0.0f};- g_transformSystem->update(w);- ctx().state().transforms_updated = true;- }+ if (g_transformSystem) g_transformSystem->ensureComposed(registry);}#ifdef ES_ENABLE_BITMAP_TEXT@@ -832,6 +833,10 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {}void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu) {+ // Writes local position and rotation for every synced body. It also writes+ // the world fields itself — a second author for those, tracked separately —+ // but the local write alone is what makes the composition stale.+ ecs::invalidateTransformComposition();if (count < 0) return;const float* buffer = boundarySpan<f32>(bufferPtr, static_cast<u64>(count) * 4, "registry_batchSyncPhysicsTransforms");if (!buffer) return;diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 166385352..c6a2b9e17 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -636,6 +636,18 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {#ifdef ES_ENABLE_PARTICLES#endifemscripten::function("renderer_updateTransforms", &esengine::renderer_updateTransforms);+ // The address of the composition's staleness counter, so a producer on the+ // JS side stores into linear memory instead of calling across it. Measured:+ // the store is below noise, the call nearly doubles a Transform write.+ emscripten::function("transform_epochAddress", emscripten::optional_override([]() -> uintptr_t {+ return reinterpret_cast<uintptr_t>(&esengine::ecs::transformMutationEpoch());+ }));+ emscripten::function("transform_ensureComposed", emscripten::optional_override(+ [](esengine::ecs::Registry& registry) {+ if (auto* ts = esengine::ctx().tryGet<esengine::ecs::TransformSystem>()) {+ ts->ensureComposed(registry);+ }+ }), emscripten::allow_raw_pointers());emscripten::function("renderer_setEntityDrawOrder", &esengine::renderer_setEntityDrawOrder);emscripten::function("renderer_submitAll", &esengine::renderer_submitAll);#ifdef ES_ENABLE_PARTICLESdiff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hppindex c8cd7b34d..e00a28477 100644--- a/src/esengine/ecs/TransformSystem.hpp+++ b/src/esengine/ecs/TransformSystem.hpp@@ -24,6 +24,25 @@namespace esengine::ecs {+/**+ * @brief How many times a transform composition INPUT has changed+ * @details One shared counter, written by every producer of a local transform+ * field or of the hierarchy, on either side of the wasm boundary.+ * @note Modulo 2^32: aliasing needs 2^32 invalidations between two compositions.+ */+inline u32& transformMutationEpoch() {+ static u32 epoch = 1;+ return epoch;+}++/**+ * @brief Say that composed world transforms are stale+ * @details Never call this from a writer of worldPosition/worldRotation/+ * worldScale: those are the composition's OUTPUT, and invalidating on+ * them makes every composition immediately stale again.+ */+inline void invalidateTransformComposition() { transformMutationEpoch()++; }+class TransformSystem : public System {public:static constexpr u32 MAX_HIERARCHY_DEPTH = 256;@@ -38,9 +57,36 @@ public:void update(World& world) override {updateDirtyTransforms(world.registry);+ markComposed(world.registry);+ }++ /**+ * @brief Compose if anything changed since the last one; O(1) if not+ * @details Consumers call this rather than update(), so a renderer and a+ * replication sample in one generation pay for one composition.+ * @note The registry's identity is part of the comparison — a second world+ * holding the same epoch number has not been composed.+ */+ void ensureComposed(Registry& registry) {+ if (registry.instanceId() == composedRegistry_+ && transformMutationEpoch() == composedEpoch_) return;+ updateDirtyTransforms(registry);+ markComposed(registry);}+ u32 composedEpoch() const { return composedEpoch_; }+private:+ // Zero, while the epoch starts at one: nothing has been composed yet, so the+ // first ensure runs rather than believing a world it has never looked at.+ u32 composedEpoch_ = 0;+ u64 composedRegistry_ = 0;++ void markComposed(Registry& registry) {+ composedEpoch_ = transformMutationEpoch();+ composedRegistry_ = registry.instanceId();+ }+std::vector<Entity> dirty_to_clear_;void updateDirtyTransforms(Registry& registry) {@@ -219,6 +265,7 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {if (!registry.has<TransformDirty>(child)) {registry.emplace<TransformDirty>(child);}+ invalidateTransformComposition();}/**diff --git a/src/esengine/ui/UILayoutSystem.cpp b/src/esengine/ui/UILayoutSystem.cppindex 52e2521d0..ffb48949d 100644--- a/src/esengine/ui/UILayoutSystem.cpp+++ b/src/esengine/ui/UILayoutSystem.cpp@@ -1,5 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#include "../ecs/TransformSystem.hpp"#include "./UILayoutSystem.hpp"#include "./UISystem.hpp"@@ -509,6 +510,10 @@ void UISystem::layoutUpdate(// touched, which hid the aliasing by throwing the stale state away.if (layoutCache_ && lastRegistryId_ != registry.instanceId()) layoutCache_.reset();lastRegistryId_ = registry.instanceId();+ // This pass writes Transform.position for every laid-out node, so the+ // composition it feeds is stale afterwards. Once per pass, not per node:+ // the epoch answers "is it stale", never "how many moved".+ invalidateTransformComposition();if (!layoutCache_) {layoutCache_ = std::make_unique<LayoutCache>();layoutPrimed_ = false; // a fresh cache has no hierarchy to reusediff --git a/tools/lib/aotDuties.mjs b/tools/lib/aotDuties.mjsindex 74e6aab0e..f1eb72528 100644--- a/tools/lib/aotDuties.mjs+++ b/tools/lib/aotDuties.mjs@@ -53,6 +53,25 @@ export const DUTIES = [native: [{ path: 'tools/verify-native-conformance.mjs', probe: /disagrees at frame/ }],},},+ {+ id: 'composition-stale',+ what: 'a compiled write to a transform input says the composition is stale',+ // Not an observation, so not behind `isChangeTracked`: a server with no+ // Changed(Transform) consumer would otherwise move transforms nothing+ // recomposes. Once per invocation, never per row.+ web: ['world.invalidateTransformComposition'],+ native: ['world.invalidateTransformComposition'],+ differential: {+ web: [{+ path: 'sdk/tests/world-transform-authority.test.ts',+ probe: /no Changed consumer anywhere/,+ }],+ native: [{+ path: 'sdk/tests/world-transform-authority.test.ts',+ probe: /no Changed consumer anywhere/,+ }],+ },+ },{id: 'layout-vouched',what: 'an address is reused only while something says the rows have not moved',diff --git a/tools/probe-interest-position-space.mjs b/tools/probe-interest-position-space.mjsindex eba0d2cbb..f82a8c3ee 100644--- a/tools/probe-interest-position-space.mjs+++ b/tools/probe-interest-position-space.mjs@@ -3,11 +3,10 @@/*** @file Which space is an entity's interest position in?*- * `RadiusInterestOptions.position` documents its default as the Transform's- * WORLD-space position, and `defaultPosition` reads `t.position` — the- * authoring input, relative to the parent. Whether that is a one-line fix- * depends on something this probe measures rather than assumes: whether a- * composed world transform exists on an authoritative server at all.+ * `RadiusInterestOptions.position` documents its default as WORLD space. It read+ * the authoring input for a long time because a headless server had no composed+ * world transform to read — composition was scheduled by the renderer. This+ * measures whether an authoritative server has that fact now.** node tools/probe-interest-position-space.mjs*@@ -41,6 +40,9 @@ async function measure(makeApp, label) {world.setParent(child, parent);await app.tick(1 / 60);await app.tick(1 / 60);+ // What a consumer does before reading world space: composition is owned by+ // an epoch now, not by a render frame this server never has.+ world.ensureTransformsComposed();const t = world.get(child, sdk.Transform);console.log(` ${label}`);console.log(` child authoring position.x = ${t.position.x}`);@@ -55,10 +57,8 @@ const headless = await measure('createHeadlessApp — the authoritative-server shape',);console.log('');-console.log(` radiusInterest's default reads position, not worldPosition.`);console.log(headless === 105- ? ' A composed world transform IS available here, so reading it is a fix.'- : ' No composed world transform is available here: transform composition runs'- + '\n in the renderer backend, which a headless server does not install. Reading'- + '\n worldPosition instead would place every entity at the origin.');+ ? ' A composed world transform is available here, and the radius default reads it.'+ : ' No composed world transform is available here, so the radius default cannot'+ + '\n read one: every entity would sit at the origin.');console.log('');