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
perf(physics): reuse mutation checkpoints after pause
yhh22574f6abe27
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a91527171..8a46d5a54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,7 @@ published separately; it ships inside the editor.### Fixed-- **Physics reconciliation follows component mutation cursors.** Body, collider and activity edits reconcile affected World-owned entities, including native hierarchy changes and edits between fixed steps in one frame. Paused and disconnected consumers release their readers. Full refreshes compare shared collision-definition snapshots to retain unchanged shapes and contacts; native reset epochs distinguish registry resets from history overflow so overflow recovery preserves solver velocity. Static poses and one-way platform updates follow affected entities, while older cores retain the full-reconcile path.+- **Physics reconciliation follows component mutation cursors.** Body, collider and activity edits reconcile affected World-owned entities, including native hierarchy changes and edits between fixed steps in one frame. Paused and disconnected consumers release their readers; component stamps survive without retained history and skip unchanged body definitions on resume. Full refreshes compare shared collision-definition snapshots to retain unchanged shapes and contacts; native reset epochs distinguish registry resets from history overflow so overflow recovery preserves solver velocity. Static poses and one-way platform updates follow affected entities, while older cores retain the full-reconcile path.## [0.89.1] - 2026-10-16diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 53fd26f0d..eaaae4751 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -10055,6 +10055,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationRevision: (component: AnyComponentDef, kind: "write" | "topology") => number@internal mutationSequence: (kind: "write" | "topology") => number@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]@internal onCoreDisconnect: (dispose: () => void) => () => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex eb675dd4b..3242b0b4f 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -10268,6 +10268,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationRevision: (component: AnyComponentDef, kind: "write" | "topology") => number@internal mutationSequence: (kind: "write" | "topology") => number@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]@internal onCoreDisconnect: (dispose: () => void) => () => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 756b3cb70..cc0652cdb 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -10050,6 +10050,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationRevision: (component: AnyComponentDef, kind: "write" | "topology") => number@internal mutationSequence: (kind: "write" | "topology") => number@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]@internal onCoreDisconnect: (dispose: () => void) => () => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 29e5302d5..c757ce83f 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -10349,6 +10349,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationRevision: (component: AnyComponentDef, kind: "write" | "topology") => number@internal mutationSequence: (kind: "write" | "topology") => number@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]@internal onCoreDisconnect: (dispose: () => void) => () => voiddiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex b23a35314..d06e82f9f 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -405,6 +405,7 @@ provideReplacementDevice: (() => boolean) | undefinedrecoverDevice: (() => boolean) | undefinedregistryLayoutEpoch: (registry: CppRegistry) => numberregistry_batchSyncPhysicsTransforms: (registry: CppRegistry, bufferPtr: number, count: number, ppu: number) => void+registry_componentMutationRevision: ((registry: CppRegistry, component: number, topology: boolean) => number) | undefinedregistry_entityChangeResetEpoch: ((registry: CppRegistry) => number) | undefinedregistry_entityChangeSequence: ((registry: CppRegistry) => number) | undefinedregistry_getCameraEntities: (registry: CppRegistry) => number[]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0af6577c3..579c21544 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -10081,6 +10081,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationRevision: (component: AnyComponentDef, kind: "write" | "topology") => number@internal mutationSequence: (kind: "write" | "topology") => number@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]@internal onCoreDisconnect: (dispose: () => void) => () => voiddiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex ec0841441..b7c523248 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -169,6 +169,8 @@ export class ChangeTracker {private componentAddedSequences_ = new Map<symbol, ComponentSequences>();private componentChangedSequences_ = new Map<symbol, ComponentSequences>();private changeSequence_ = 0;+ private revision_ = 0;+ private readonly revisions_ = new Map<symbol, [number, number]>();private readonly removals_ = new ReaderOwnedJournal(true);/** Membership moves, independent of ordinary change tracking. */private readonly topology_ = new ReaderOwnedJournal(true);@@ -306,6 +308,17 @@ export class ChangeTracker {return kind === 'write' ? this.writes_ : this.topology_;}+ mutationRevision(component: AnyComponentDef, kind: 'write' | 'topology'): number {+ let revisions = this.revisions_.get(component._id);+ if (!revisions) { revisions = [0, 0]; this.revisions_.set(component._id, revisions); }+ return revisions[kind === 'write' ? 0 : 1];+ }++ private recordRevision_(componentId: symbol, topology: boolean): void {+ const revisions = this.revisions_.get(componentId);+ if (revisions) revisions[topology ? 1 : 0] = ++this.revision_;+ }+registerTopologyReaderFrom(component: AnyComponentDef, retainFromTick: number): number {const id = this.nextReaderId_++;this.topology_.register(component._id, id, retainFromTick);@@ -412,6 +425,7 @@ export class ChangeTracker {}recordAdded(component: AnyComponentDef, entity: Entity): void {+ this.recordRevision_(component._id, true);this.componentIncarnations_.get(component._id)?.set(entity, this.nextIncarnation_++);// BEFORE the tracking gate: a membership journal is what lets a consumer// follow arrivals and departures WITHOUT enrolling the component in@@ -443,6 +457,7 @@ export class ChangeTracker {}recordChanged(component: AnyComponentDef, entity: Entity): void {+ this.recordRevision_(component._id, false);// Before the tracking gate, like the other two journals: a consumer that// enumerates writes should not have to enrol the component in `Changed`// tracking, whose per-entity map it cannot enumerate cheaply anyway.@@ -484,6 +499,7 @@ export class ChangeTracker {* recorded for one kind and dropped for the other.*/recordRemovedById(componentId: symbol, entity: Entity): void {+ this.recordRevision_(componentId, true);this.componentIncarnations_.get(componentId)?.delete(entity);// Same reason as `recordAdded`: first, and gated on its own readers.if (this.topology_.hasReaders(componentId)) {diff --git a/sdk/src/ecs/ComponentMutationReader.ts b/sdk/src/ecs/ComponentMutationReader.tsindex 8e4710b50..66c3cb6a9 100644--- a/sdk/src/ecs/ComponentMutationReader.ts+++ b/sdk/src/ecs/ComponentMutationReader.ts@@ -12,12 +12,14 @@ import { ENTITY_CHANGE_CAPACITY, ENTITY_CHANGE_WORDS, ENTITY_CHANGE_SUBTREE,export interface ComponentMutationBatch {readonly full: boolean;readonly reset: boolean;+ readonly refreshPoses: boolean;readonly entities: Set<Entity>;readonly changed: Map<AnyComponentDef, Set<Entity>>;readonly nativeSequence: number;readonly resetEpoch: number;readonly writeSequence: number;readonly topologySequence: number;+ readonly checkpoint: readonly number[];}/** Projects SDK and native mutation cursors onto World-owned entities. Readers@@ -30,6 +32,7 @@ export class ComponentMutationReader {private first = true;private bindingReset = false;private disposed = false;+ private checkpoint: readonly number[] | null = null;private resetEpoch: number | null = null;private lastRegistry: CppRegistry | null = null;private readonly nativeTypes = new Map<number, AnyComponentDef>();@@ -55,7 +58,8 @@ export class ComponentMutationReader {if (this.lease !== null) return true;const api = worldEngineApi(this.world), registry = this.world.getCppRegistry();if (!registry?.componentTypeId || !api?.registry_watchEntityChanges || !api.registry_unwatchEntityChanges- || !api.registry_entityChangeSequence || !api.registry_entityChangeResetEpoch || !api.registry_readEntityChanges+ || !api.registry_entityChangeSequence || !api.registry_entityChangeResetEpoch || !api.registry_componentMutationRevision+ || !api.registry_readEntityChanges|| !api._malloc || !api._free || !api.HEAPU32) return false;for (const component of this.members) {if (!isBuiltinComponent(component)) continue;@@ -79,6 +83,12 @@ export class ComponentMutationReader {const world = this.world, api = this.api!, registry = this.registry!;const nativeSequence = api.registry_entityChangeSequence!(registry);const resetEpoch = api.registry_entityChangeResetEpoch!(registry);+ const checkpoint = [api.registry_componentMutationRevision!(registry, ENTITY_CHANGE_NO_COMPONENT, false)];+ for (const component of this.values) checkpoint.push(world.mutationRevision(component, 'write'));+ for (const component of this.members) checkpoint.push(world.mutationRevision(component, 'topology'));+ for (const [id, component] of this.nativeTypes) {+ checkpoint.push(api.registry_componentMutationRevision!(registry, id, !this.values.has(component)));+ }const writeSequence = world.mutationSequence('write'), topologySequence = world.mutationSequence('topology');const entities = new Set<Entity>(), roots = new Set<Entity>();const changed = new Map<AnyComponentDef, Set<Entity>>();@@ -96,21 +106,31 @@ export class ComponentMutationReader {for (const entity of world.mutationsForCursor(component, 'topology', reader)) note(component, entity, true);}let reset = this.bindingReset || resetEpoch < 0 || resetEpoch !== this.resetEpoch;- let full = this.first || reset;- if (nativeSequence !== this.cursor) {+ const unchanged = this.checkpoint !== null && checkpoint.every((value, index) => value >= 0 && value === this.checkpoint![index]);+ let full = reset || this.first && !unchanged;+ let refreshPoses = false;+ if (nativeSequence !== this.cursor && !(this.first && unchanged && !reset)) {withMalloc({ _malloc: api._malloc!.bind(api), _free: api._free!.bind(api) },ENTITY_CHANGE_CAPACITY * ENTITY_CHANGE_WORDS * 4, ptr => {- if (!ptr) { full = true; return; }+ if (!ptr) { full ||= !unchanged; refreshPoses = true; return; }const count = api.registry_readEntityChanges!(registry, this.cursor, ptr, ENTITY_CHANGE_CAPACITY);- if (count < 0) { full = true; return; }+ if (count < 0) { full ||= !unchanged; refreshPoses = true; return; }if (!Number.isInteger(count) || count > ENTITY_CHANGE_CAPACITY) throw new Error('Invalid native mutation batch length');const heap = api.HEAPU32!;for (let i = 0; i < count; ++i) {const at = (ptr >>> 2) + i * ENTITY_CHANGE_WORDS;const entity = heap[at] as Entity, flags = heap[at + 1], type = heap[at + 2];- if (flags & ENTITY_CHANGE_RESET) { full = true; reset = true; continue; }+ if (flags & ENTITY_CHANGE_RESET) { full = true; refreshPoses = true; continue; }if (flags & ENTITY_CHANGE_SUBTREE) roots.add(entity);- if (type === ENTITY_CHANGE_NO_COMPONENT) entities.add(entity);+ if (type === ENTITY_CHANGE_NO_COMPONENT) {+ entities.add(entity);+ if (!(flags & ENTITY_CHANGE_SUBTREE)) {+ for (const component of this.nativeTypes.values()) {+ note(component, entity, true);+ world.refreshBuiltinMembership(entity, component);+ }+ }+ }const component = this.nativeTypes.get(type);if (!component) continue;const membership = !(flags & ENTITY_CHANGE_REPLACED);@@ -134,16 +154,15 @@ export class ComponentMutationReader {if (hasChildren?.(entity)) for (const child of world.get(entity, Children).entities) pending.push(child);}}- if (roots.size) world.invalidateTransformComposition();- // Native Transform replacement is a value write, independent of body membership.- if (changed.has(Transform)) world.invalidateTransformComposition();- return { full, reset, entities, changed, nativeSequence, resetEpoch, writeSequence, topologySequence };+ if (full || refreshPoses || roots.size || changed.has(Transform)) world.invalidateTransformComposition();+ return { full, reset, refreshPoses, entities, changed, nativeSequence, resetEpoch, writeSequence, topologySequence, checkpoint };}commit(batch: ComponentMutationBatch): void {this.cursor = batch.nativeSequence; this.first = false;this.bindingReset = false;this.resetEpoch = batch.resetEpoch;+ this.checkpoint = batch.checkpoint;for (const [component, reader] of this.writes) this.world.advanceMutationCursor(component, 'write', reader, batch.writeSequence);for (const [component, reader] of this.topology) this.world.advanceMutationCursor(component, 'topology', reader, batch.topologySequence);}diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 9089bcf8c..1683a0dc7 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -123,6 +123,7 @@ export interface NativeEngineApi {probe_volume_create?(resX: number, resY: number, resZ: number, shPtr: number): number;probe_volume_release?(volumeHandle: number): void;registry_batchSyncPhysicsTransforms?(registry: unknown, bufferPtr: number, count: number, ppu: number): void;+ registry_componentMutationRevision?(registry: unknown, component: number, topology: boolean): number;registry_entityChangeResetEpoch?(registry: unknown): number;registry_entityChangeSequence?(registry: unknown): number;registry_getCanvasEntity?(registry: unknown): number;@@ -420,6 +421,7 @@ export function createNativeEngineApi(bind('probe_volume_create', 'es_probe_volume_create', false);bind('probe_volume_release', 'es_probe_volume_release', false);bind('registry_batchSyncPhysicsTransforms', 'es_registry_batchSyncPhysicsTransforms', true);+ bind('registry_componentMutationRevision', 'es_registry_componentMutationRevision', true);bind('registry_entityChangeResetEpoch', 'es_registry_entityChangeResetEpoch', true);bind('registry_entityChangeSequence', 'es_registry_entityChangeSequence', true);bind('registry_getCanvasEntity', 'es_registry_getCanvasEntity', true);diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex ff3c0e3e8..344eddc82 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -1513,6 +1513,11 @@ export class World {/** @internal Current boundary to acknowledge after a successful read. */mutationSequence(kind: 'write' | 'topology'): number { return this.changes_.mutationSequence(kind); }+ /** @internal Component stamps survive released mutation-history readers. */+ mutationRevision(component: AnyComponentDef, kind: 'write' | 'topology'): number {+ return this.changes_.mutationRevision(component, kind);+ }+/** @internal Unacknowledged component mutations for this reader. */mutationsForCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number): Entity[] {return this.changes_.mutationsForCursor(component, kind, reader);diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex 02fee354b..0d360eab3 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -945,7 +945,8 @@ export function registerPhysics2DSystem(lastStructuralVersion = structuralVersion;} // end if (needReconcile)- staticPoses.sync(module, ppu, mutationBatch?.full ?? needReconcile, entity => !!cachedProps.get(entity)?.enabled);+ staticPoses.sync(module, ppu, mutationBatch ? mutationBatch.full || mutationBatch.refreshPoses : needReconcile,+ entity => !!cachedProps.get(entity)?.enabled);// Kinematic bodies are driven by their Transform (changed via gameplay,// not tracked as a physics edit) — push every step, even when thediff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex fcc408d86..3006fb050 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -689,6 +689,7 @@ export interface ESEngineModule {registry_unwatchEntityChanges?(registry: CppRegistry, reader: number): void;registry_entityChangeSequence?(registry: CppRegistry): number;registry_entityChangeResetEpoch?(registry: CppRegistry): number;+ registry_componentMutationRevision?(registry: CppRegistry, component: number, topology: boolean): number;registry_readEntityChanges?(registry: CppRegistry, after: number, outputPtr: number, capacity: number): number;registry_batchSyncPhysicsTransforms(registry: CppRegistry, bufferPtr: number, count: number, ppu: number): void;registry_readWorldPoses2D?(registry: CppRegistry, entitiesPtr: number, count: number, outputPtr: number): number;diff --git a/sdk/tests/component-mutation-cursor.test.ts b/sdk/tests/component-mutation-cursor.test.tsindex 1a1f9d1e1..434da9bd5 100644--- a/sdk/tests/component-mutation-cursor.test.ts+++ b/sdk/tests/component-mutation-cursor.test.ts@@ -75,3 +75,18 @@ it('continues disconnect cleanup when another native observer fails', () => {first(); second();expect(world.getStorageSizes().coreDisconnectCallbacks).toBe(0);});++it('keeps component stamps without retaining write or topology history', () => {+ const world = new World(), component = defineComponent('MutationStamp', { value: 0 });+ expect(world.mutationRevision(component, 'write')).toBe(0);+ expect(world.mutationRevision(component, 'topology')).toBe(0);+ const entity = world.spawn(); world.insert(entity, component);+ const write = world.mutationRevision(component, 'write'), topology = world.mutationRevision(component, 'topology');+ world.update(entity, component, value => { value.value++; });+ expect(world.mutationRevision(component, 'write')).toBeGreaterThan(write);+ expect(world.mutationRevision(component, 'topology')).toBe(topology);+ world.remove(entity, component);+ expect(world.mutationRevision(component, 'topology')).toBeGreaterThan(topology);+ expect(world.bufferedWriteRows(component)).toBe(0);+ expect(world.writeReaderCount(component)).toBe(0); expect(world.topologyReaderCount(component)).toBe(0);+});diff --git a/sdk/tests/physics-mutation-reconcile-wasm.test.ts b/sdk/tests/physics-mutation-reconcile-wasm.test.tsindex f129d5846..e4d66eae6 100644--- a/sdk/tests/physics-mutation-reconcile-wasm.test.ts+++ b/sdk/tests/physics-mutation-reconcile-wasm.test.ts@@ -189,4 +189,52 @@ describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('component-driven physicreader.dispose(); world.disconnectCpp(); first.delete(); second.delete();}});++ it('resumes without reading body definitions after unrelated paused native churn', async () => {+ const { app, registry, unrelated, bodyReads, clear } = await scene();+ const lease = core.registry_watchEntityChanges!(registry);+ try {+ app.getResource(Time).scale = 0; await app.tick(1 / 60);+ for (let i = 0; i <= ENTITY_CHANGE_CAPACITY; ++i) {+ registry.addVelocity(unrelated, { linear: { x: i, y: 0, z: 0 }, angular: { x: 0, y: 0, z: 0 } });+ }+ app.getResource(Time).scale = 1; await app.tick(1 / 60);+ expect(bodyReads()).toEqual([]); expect(clear).not.toHaveBeenCalled();+ } finally { core.registry_unwatchEntityChanges!(registry, lease); }+ });++ it('retains a same-tick edit made after the last physics sample across pause', async () => {+ const { app, world, bodies, clear, hit } = await scene();+ let once = true;+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem([], () => {+ if (once) world.update(bodies[0], BoxCollider2D, value => { value.halfExtents.x = .06; });+ }, { name: 'EditBeforePhysicsSample' }));+ app.addSystemToSchedule(Schedule.FixedPostUpdate, defineSystem([], () => {+ if (!once) return; once = false;+ world.update(bodies[0], BoxCollider2D, value => { value.halfExtents.x = .11; });+ app.getResource(Time).scale = 0;+ }, { name: 'EditAndPauseAfterPhysics' }));+ await app.tick(1 / 60);+ expect(clear).toHaveBeenCalledOnce(); expect(hit()).toBeCloseTo(-6, 3);+ app.getResource(Time).scale = 1; await app.tick(1 / 60);+ expect(clear).toHaveBeenCalledTimes(2); expect(hit()).toBeCloseTo(-11, 3);+ });++ it('refreshes poses after unrelated native overflow without reading body definitions', async () => {+ const { app, registry, unrelated, bodies, bodyReads, hit } = await scene();+ for (let i = 0; i <= ENTITY_CHANGE_CAPACITY; ++i) {+ registry.addVelocity(unrelated, { linear: { x: i, y: 0, z: 0 }, angular: { x: 0, y: 0, z: 0 } });+ }+ const transform = registry.getTransform(bodies[0]); transform.position.x = 20;+ registry.addTransform(bodies[0], transform); await app.tick(1 / 60);+ expect(bodyReads()).toEqual([]); expect(hit()).toBeCloseTo(15, 3);+ });++ it('removes a solver body after its owned native entity is destroyed', async () => {+ const { app, world, registry, module, bodies, hit } = await scene();+ registry.destroy(bodies[0]); await app.tick(1 / 60);+ expect(module._physics_getBodyCount()).toBe(255);+ expect(world.has(bodies[0], RigidBody2D)).toBe(false);+ expect(hit()).toBeUndefined();+ });});diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 7f2b9198f..b584ea88d 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -1219,6 +1219,9 @@ u32 registry_watchEntityChanges(ecs::Registry& registry) { return registry.watchvoid registry_unwatchEntityChanges(ecs::Registry& registry, u32 reader) { registry.unwatchEntityChanges(reader); }double registry_entityChangeSequence(ecs::Registry& registry) { return registry.entityChangeSequence(); }double registry_entityChangeResetEpoch(ecs::Registry& registry) { return registry.entityChangeResetEpoch(); }+double registry_componentMutationRevision(ecs::Registry& registry, u32 component, bool topology) {+ return registry.componentMutationRevision(component, topology);+}int registry_readEntityChanges(ecs::Registry& registry, double after, uintptr_t outputPtr, int capacity) {if (capacity < 0 || capacity > static_cast<int>(ecs::ENTITY_CHANGE_CAPACITY)|| outputPtr % alignof(ecs::EntityChangeRow)) return -1;diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 428fd341f..03451e0e5 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -323,6 +323,7 @@ u32 registry_watchEntityChanges(ecs::Registry& registry);void registry_unwatchEntityChanges(ecs::Registry& registry, u32 reader);double registry_entityChangeSequence(ecs::Registry& registry);double registry_entityChangeResetEpoch(ecs::Registry& registry);+double registry_componentMutationRevision(ecs::Registry& registry, u32 component, bool topology);// Output contains entity/flags/component-type rows. Returns -1 when the cursor or capacity// cannot cover the retained history; the caller must perform a full refresh.int registry_readEntityChanges(ecs::Registry& registry, double after, uintptr_t outputPtr, int capacity);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 279bf51f3..63b3fff1c 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -786,6 +786,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("registry_unwatchEntityChanges", &esengine::registry_unwatchEntityChanges);emscripten::function("registry_entityChangeSequence", &esengine::registry_entityChangeSequence);emscripten::function("registry_entityChangeResetEpoch", &esengine::registry_entityChangeResetEpoch);+ emscripten::function("registry_componentMutationRevision", &esengine::registry_componentMutationRevision);emscripten::function("registry_readEntityChanges", &esengine::registry_readEntityChanges);emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);diff --git a/src/esengine/ecs/EntityChangeJournal.hpp b/src/esengine/ecs/EntityChangeJournal.hppindex 4bcf597ab..7c5de54ba 100644--- a/src/esengine/ecs/EntityChangeJournal.hpp+++ b/src/esengine/ecs/EntityChangeJournal.hpp@@ -4,6 +4,7 @@#include "../core/Types.hpp"#include "../core/Reflection.hpp"#include <algorithm>+#include <array>#include <cmath>#include <span>#include <unordered_set>@@ -29,8 +30,9 @@ struct EntityChangeRow { u32 entity; u32 flags; u32 component; };static_assert(sizeof(EntityChangeRow) == ENTITY_CHANGE_WORDS * sizeof(u32));/** Independent cursors share bounded history. Exhausted or invalid cursors must- * rescan; reading never consumes another observer's rows. No readers means no- * retained storage or writes. Raw component references require an explicit record. */+ * rescan; reading never consumes another observer's rows. History exists only+ * while observed; component stamps persist across unobserved periods. Raw+ * component references require an explicit record. */class EntityChangeJournal {public:u32 watch() {@@ -49,10 +51,20 @@ public:}double sequence() const { return static_cast<double>(sequence_); }double resetEpoch() const { return reset_epoch_ == MAX_SEQUENCE ? -1 : static_cast<double>(reset_epoch_); }+ double componentRevision(u32 component, bool topology) const {+ const auto value = component == ENTITY_CHANGE_NO_COMPONENT ? entity_revisions_[topology ? 1 : 0]+ : component < revisions_.size() ? revisions_[component][topology ? 1 : 0] : 0;+ return value == MAX_SEQUENCE ? -1 : static_cast<double>(value);+ }usize readerCount() const { return readers_.size(); }usize retainedRows() const { return rows_.empty() ? 0 : std::min<u64>(sequence_, ENTITY_CHANGE_CAPACITY); }void record(u32 entity, u32 flags = 0, u32 component = ENTITY_CHANGE_NO_COMPONENT) {+ if (revision_ < MAX_SEQUENCE) ++revision_;+ if (component != ENTITY_CHANGE_NO_COMPONENT && component >= revisions_.size()) revisions_.resize(component + 1);+ auto& revisions = component == ENTITY_CHANGE_NO_COMPONENT ? entity_revisions_ : revisions_[component];+ revisions[0] = revision_;+ if (!(flags & ENTITY_CHANGE_REPLACED)) revisions[1] = revision_;if ((flags & ENTITY_CHANGE_RESET) && reset_epoch_ < MAX_SEQUENCE) ++reset_epoch_;if (readers_.empty()) return;// Saturation preserves the JS number contract by requiring a rescan.@@ -77,6 +89,9 @@ private:std::unordered_set<u32> readers_;u64 sequence_ = 0;u64 reset_epoch_ = 0;+ u64 revision_ = 0;+ std::vector<std::array<u64, 2>> revisions_;+ std::array<u64, 2> entity_revisions_{};u32 next_reader_ = 0;bool exhausted_ = false;};diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex abc4f6b04..456a1ccae 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -125,7 +125,12 @@ public:u32 watchEntityChanges() { return entity_changes_.watch(); }void unwatchEntityChanges(u32 reader) { entity_changes_.unwatch(reader); }double entityChangeSequence() const { return entity_changes_.sequence(); }- double entityChangeResetEpoch() const { return entity_changes_.resetEpoch(); }+ double entityChangeResetEpoch() const {+ return entity_reset_epoch_ == RESET_EPOCH_LIMIT ? -1 : static_cast<double>(entity_reset_epoch_);+ }+ double componentMutationRevision(u32 component, bool topology) const {+ return entity_changes_.componentRevision(component, topology);+ }i32 readEntityChanges(double after, std::span<EntityChangeRow> output) const {return entity_changes_.read(after, output);}@@ -543,6 +548,7 @@ public:* @details Resets the registry to its initial empty state.*/void clear() {+ if (entity_reset_epoch_ < RESET_EPOCH_LIMIT) ++entity_reset_epoch_;recordEntityChange(INVALID_ENTITY, ENTITY_CHANGE_RESET);for (auto& pool : pools_) {if (pool) {@@ -819,6 +825,8 @@ private:std::vector<u8> entityValid_;EntityChangeJournal entity_changes_;+ static constexpr u64 RESET_EPOCH_LIMIT = (u64{1} << 53) - 1;+ u64 entity_reset_epoch_ = 0;template<typename T>void recordComponentChange(Entity entity, u32 flags = 0) {diff --git a/tests/ecs/test_entity_activity.cpp b/tests/ecs/test_entity_activity.cppindex dde9ce5df..7a5017cce 100644--- a/tests/ecs/test_entity_activity.cpp+++ b/tests/ecs/test_entity_activity.cpp@@ -142,6 +142,21 @@ TEST_CASE("entity change overflow and invalid cursors refuse partial histories")CHECK(journal.read(journal.sequence(), {}) == 0);}+TEST_CASE("component revisions survive without retaining native mutation rows") {+ EntityChangeJournal journal;+ journal.record(1, 0, 5);+ const auto initial = journal.componentRevision(5, false), membership = journal.componentRevision(5, true);+ CHECK(initial > 0); CHECK(membership > 0);+ journal.record(1, ENTITY_CHANGE_REPLACED, 5);+ CHECK(journal.componentRevision(5, false) > initial);+ CHECK(journal.componentRevision(5, true) == membership);+ CHECK(journal.componentRevision(6, false) == 0);+ CHECK(journal.retainedRows() == 0);+ const auto reader = journal.watch(); journal.unwatch(reader);+ CHECK(journal.componentRevision(5, false) > initial);+ CHECK(journal.retainedRows() == 0);+}+TEST_CASE("registry history covers component lifetime and explicit native writes") {using namespace esengine::ecs;Registry registry;@@ -168,9 +183,11 @@ TEST_CASE("registry history covers component lifetime and explicit native writesCHECK(rows[3].component == componentTypeId<Sample>());CHECK(rows[5].component == componentTypeId<JournalPosition>());const auto cursor = registry.entityChangeSequence();+ registry.invalidateActivityHierarchy();+ CHECK(registry.entityChangeResetEpoch() == 0);registry.clear();CHECK(registry.entityChangeResetEpoch() == 1);- REQUIRE(registry.readEntityChanges(cursor, rows) == 1);+ REQUIRE(registry.readEntityChanges(cursor, rows) == 2);CHECK(rows[0].flags == ENTITY_CHANGE_RESET);registry.unwatchEntityChanges(reader);}diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex c4c661ab6..9df5b9d68 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'perf(physics): reuse mutation checkpoints after pause':+ { note: 'Physics reconciliation follows component mutation cursors.' },'fix(ecs): invalidate projections when the core changes':{ note: 'Physics reconciliation follows component mutation cursors.' },'perf(physics): reconcile only changed body definitions':