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(physics): reconcile only changed body definitions

yhhae1fd1c52dad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eee18f0da..a91527171 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ published separately; it ships inside the editor.
## [Unreleased]
+### 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.
+
## [0.89.1] - 2026-10-16
### Fixed
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 233d811b5..02fee354b 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -13,7 +13,7 @@
import type { App } from '../app/app';
import type { Entity } from '../types';
import type { TransformData, ParentData, CanvasData } from '../ecs/component';
-import { Transform, Parent, Canvas } from '../ecs/component';
+import { Transform, Parent, Children, Disabled, Canvas } from '../ecs/component';
import { Res, Time, type TimeData } from '../ecs/resource';
import { Schedule, defineSystem } from '../ecs/system';
import { playModeOnly } from '../ecs/env';
@@ -45,6 +45,7 @@ import {
import { withMalloc } from '../wasm/wasmScratch';
import { engineApi, type EngineApi } from '../ecs/bridge/engineApi';
import { StaticBodyPoses2D } from './StaticBodyPoses2D';
+import { ComponentMutationReader } from '../ecs/ComponentMutationReader';
import { ENTITY_POSE_2D_WORDS } from '../wasm/constants.generated';
/**
@@ -336,10 +337,14 @@ function syncOneWayPlatforms(
module: PhysicsWasmModule,
trackedEntities: Set<Entity>,
trackedOneWay: Set<Entity>,
+ candidates?: Iterable<Entity>,
): void {
- const seen = new Set<Entity>();
- for (const entity of world.getEntitiesWithComponents([OneWayPlatform2D, RigidBody2D])) {
- if (!trackedEntities.has(entity)) continue;
+ const selected = candidates ?? new Set([...world.getEntitiesWithComponents([OneWayPlatform2D, RigidBody2D]), ...trackedOneWay]);
+ for (const entity of selected) {
+ if (!trackedEntities.has(entity) || !world.isEntityActive(entity) || !world.has(entity, OneWayPlatform2D)) {
+ if (trackedOneWay.delete(entity)) module._physics_setOneWayPlatform(entity, 0, 0, 0);
+ continue;
+ }
const ow = world.get(entity, OneWayPlatform2D) as OneWayPlatform2DData;
if (ow.localSpace) {
module._physics_setOneWayPlatformLocal(entity, ow.normal.x, ow.normal.y, ow.enabled ? 1 : 0);
@@ -347,13 +352,6 @@ function syncOneWayPlatforms(
module._physics_setOneWayPlatform(entity, ow.normal.x, ow.normal.y, ow.enabled ? 1 : 0);
}
trackedOneWay.add(entity);
- seen.add(entity);
- }
- for (const entity of [...trackedOneWay]) {
- if (!seen.has(entity)) {
- module._physics_setOneWayPlatform(entity, 0, 0, 0);
- trackedOneWay.delete(entity);
- }
}
}
@@ -616,6 +614,7 @@ interface CachedBodyProps {
enabled: boolean;
/** Bitmask of present collider components — drives shape rebuild on change. */
colliderSig: number;
+ colliderState: string;
/** Last sync of this body; inactive entities retain edits until reactivation. */
syncedTick: number;
}
@@ -638,6 +637,10 @@ export function colliderSignature(world: App['world'], entity: Entity): number {
return sig;
}
+function colliderState(world: App['world'], entity: Entity): string {
+ return JSON.stringify(COLLIDER_TYPES.map(component => activeCollider(world, entity, component)));
+}
+
/** True if any present collider component changed since `sinceTick`. @internal */
export function collidersChangedSince(world: App['world'], entity: Entity, sinceTick: number): boolean {
for (const C of COLLIDER_TYPES) {
@@ -692,6 +695,18 @@ export function registerPhysics2DSystem(
const trackedOneWay = new Set<Entity>();
const parentedBodies = new Set<Entity>();
const cachedProps = new Map<Entity, CachedBodyProps>();
+ // Equal authored shapes share one snapshot; unchanged full refreshes retain contacts.
+ const colliderStates = new Map<string, { value: string; references: number }>();
+ const retainState = (value: string): string => {
+ let state = colliderStates.get(value);
+ if (!state) { state = { value, references: 0 }; colliderStates.set(value, state); }
+ state.references++;
+ return state.value;
+ };
+ const releaseState = (value: string) => {
+ const state = colliderStates.get(value);
+ if (state && --state.references === 0) colliderStates.delete(value);
+ };
let lastEntitySyncTick = -1;
// Events accumulated across this frame's fixed steps; published once per frame.
const events: EventAccum = {
@@ -699,11 +714,8 @@ export function registerPhysics2DSystem(
};
const fixedDt = config.fixedTimestep;
- // Change-driven reconcile: track physics components so a value edit is an O(1)
- // signal, letting the per-step reconcile skip the full entity scan in steady
- // state (no structural change + no physics-component edit). Kinematic bodies
- // are driven by their Transform, so they're tracked separately and pushed every
- // step regardless of whether the reconcile ran.
+ // Mutation cursors select authoring edits. Change stamps gate full scans on
+ // older hosts. Kinematic targets remain driven every fixed step.
const physicsComponents = [RigidBody2D, ...COLLIDER_TYPES, ...JOINT_TYPES, OneWayPlatform2D];
for (const c of physicsComponents) app.world.enableChangeTracking(c);
const kinematicEntities = new Set<Entity>();
@@ -712,6 +724,14 @@ export function registerPhysics2DSystem(
const world = app.world;
world.enableChangeTracking(Transform);
+ const mutations = new ComponentMutationReader(world, physicsComponents, [Transform, Children], [Parent, Disabled]);
+
+ const destroyBody = (entity: Entity) => {
+ if (!trackedEntities.delete(entity)) return;
+ module._physics_destroyBody(entity);
+ releaseState(cachedProps.get(entity)!.colliderState);
+ cachedProps.delete(entity); parentedBodies.delete(entity); kinematicEntities.delete(entity); staticPoses.delete(entity);
+ };
const offDespawn = world.onDespawn((entity: Entity) => {
if (trackedJoints.has(entity)) {
@@ -723,12 +743,7 @@ export function registerPhysics2DSystem(
trackedOneWay.delete(entity);
}
if (trackedEntities.has(entity)) {
- module._physics_destroyBody(entity);
- trackedEntities.delete(entity);
- cachedProps.delete(entity);
- parentedBodies.delete(entity);
- kinematicEntities.delete(entity);
- staticPoses.delete(entity);
+ destroyBody(entity);
// The module's pose snapshots need no cleanup: destroying the body drops
// it from the dynamic set the next capture rebuilds from, and the lerp is
// driven by the current snapshot, so a stale `prev` entry is never read.
@@ -754,13 +769,13 @@ export function registerPhysics2DSystem(
// Keep the query API's default scale in sync with the live Canvas,
// so raycast/overlap that omit `ppu` aren't silently scaled to 100.
if (app.hasResource(Physics2D)) app.getResource(Physics2D).setPixelsPerUnit(ppu);
- // Steady-state fast path: skip the full entity reconcile unless
- // something structural changed (spawn/despawn/add-remove component →
- // structuralVersion) OR a physics component was edited (O(1) gate).
- // Otherwise the bodies are simulated by Box2D + read back in bulk.
+ // Native and SDK mutations share the sparse path; structural and
+ // component stamps retain the full-scan fallback for older hosts.
const structuralVersion = world.getWorldVersion();
+ const mutationBatch = mutations.read();
let needReconcile = structuralVersion !== lastStructuralVersion;
- if (!needReconcile) {
+ if (mutationBatch) needReconcile = mutationBatch.full || mutationBatch.entities.size > 0;
+ else if (!needReconcile) {
for (let i = 0; i < physicsComponents.length; i++) {
if (world.anyChangedSince(physicsComponents[i], lastEntitySyncTick)) {
needReconcile = true;
@@ -768,9 +783,19 @@ export function registerPhysics2DSystem(
}
}
}
+ if (mutationBatch) {
+ for (const entity of mutationBatch.changed.get(Transform) ?? []) staticPoses.invalidate(entity);
+ if (mutationBatch.reset) {
+ for (const entity of trackedJoints) module._physics_destroyJoint(entity);
+ trackedJoints.clear();
+ for (const entity of trackedOneWay) module._physics_setOneWayPlatform(entity, 0, 0, 0);
+ trackedOneWay.clear();
+ for (const entity of trackedEntities) destroyBody(entity);
+ }
+ }
if (needReconcile) {
world.ensureTransformsComposed();
- const entities = world.getEntitiesWithComponents([RigidBody2D, Transform]);
+ const entities = mutationBatch?.entities ?? world.getEntitiesWithComponents([RigidBody2D, Transform]);
const currentEntities = new Set<Entity>();
// ── Unified body + collider reconcile ───────────────────────
@@ -779,6 +804,8 @@ export function registerPhysics2DSystem(
// (enable/disable, props, shapes) with minimal in-place ops that
// preserve simulation state — never destroy-and-rebuild.
for (const entity of entities) {
+ if (mutationBatch && (!world.valid(entity) || !world.has(entity, RigidBody2D)
+ || !world.has(entity, Transform) || !world.isEntityActive(entity))) continue;
currentEntities.add(entity);
const rb = world.get(entity, RigidBody2D) as RigidBody2DData;
@@ -808,6 +835,7 @@ export function registerPhysics2DSystem(
bullet: rb.bullet,
enabled: true,
colliderSig: colliderSignature(world, entity),
+ colliderState: retainState(colliderState(world, entity)),
syncedTick: world.getWorldTick(),
});
if (rb.bodyType === BodyType.Kinematic) kinematicEntities.add(entity);
@@ -819,21 +847,22 @@ export function registerPhysics2DSystem(
}
const cached = cachedProps.get(entity)!;
+ const reenabled = rb.enabled && !cached.enabled;
// 1. enabled toggle — in place (keeps shapes/velocity/joints).
if (rb.enabled !== cached.enabled) {
module._physics_setBodyEnabled(entity, rb.enabled ? 1 : 0);
cached.enabled = rb.enabled;
+ if (rb.enabled) staticPoses.invalidate(entity);
}
// 2. body properties.
- if (world.isChangedSince(entity, RigidBody2D, cached.syncedTick) &&
- (cached.bodyType !== rb.bodyType ||
+ if (cached.bodyType !== rb.bodyType ||
cached.gravityScale !== rb.gravityScale ||
cached.linearDamping !== rb.linearDamping ||
cached.angularDamping !== rb.angularDamping ||
cached.fixedRotation !== rb.fixedRotation ||
- cached.bullet !== rb.bullet)) {
+ cached.bullet !== rb.bullet) {
module._physics_updateBodyProperties(
entity, rb.bodyType,
rb.gravityScale, rb.linearDamping, rb.angularDamping,
@@ -851,9 +880,15 @@ export function registerPhysics2DSystem(
// or any collider's fields change (body + velocity preserved).
const sig = colliderSignature(world, entity);
if (sig !== cached.colliderSig ||
- collidersChangedSince(world, entity, cached.syncedTick)) {
- module._physics_clearShapes(entity);
- addShapeForEntity(world, module, entity, config.collisionLayerMasks);
+ (mutationBatch ? reenabled || mutationBatch.full || COLLIDER_TYPES.some(component => mutationBatch.changed.get(component)?.has(entity))
+ : collidersChangedSince(world, entity, cached.syncedTick))) {
+ const state = colliderState(world, entity);
+ if (state !== cached.colliderState) {
+ module._physics_clearShapes(entity);
+ addShapeForEntity(world, module, entity, config.collisionLayerMasks);
+ releaseState(cached.colliderState);
+ cached.colliderState = retainState(state);
+ }
cached.colliderSig = sig;
}
@@ -866,14 +901,18 @@ export function registerPhysics2DSystem(
const parent = world.has(entity, Parent) ? world.get(entity, Parent).entity : null;
staticPoses.track(entity, parent);
parentedBodies.delete(entity);
- } else staticPoses.delete(entity);
+ } else {
+ staticPoses.delete(entity);
+ if (world.has(entity, Parent)) parentedBodies.add(entity); else parentedBodies.delete(entity);
+ }
cached.syncedTick = world.getWorldTick();
}
// Activity filtering removes descendants from the query too.
// Freeze those bodies in place so reactivation keeps velocity,
// shapes and joints; only component removal destroys the body.
- for (const entity of trackedEntities) {
+ for (const entity of mutationBatch?.entities ?? trackedEntities) {
+ if (!trackedEntities.has(entity)) continue;
if (!currentEntities.has(entity)) {
if (world.has(entity, RigidBody2D) && world.has(entity, Transform)) {
const cached = cachedProps.get(entity)!;
@@ -883,12 +922,7 @@ export function registerPhysics2DSystem(
}
continue;
}
- module._physics_destroyBody(entity);
- trackedEntities.delete(entity);
- cachedProps.delete(entity);
- parentedBodies.delete(entity);
- kinematicEntities.delete(entity);
- staticPoses.delete(entity);
+ destroyBody(entity);
}
}
@@ -896,20 +930,22 @@ export function registerPhysics2DSystem(
// Destroy joints whose definition changed or whose component was
// removed; createPendingJoints re-adds present+enabled ones.
for (const entity of [...trackedJoints]) {
- if (jointChangedOrGone(world, entity, lastEntitySyncTick)
+ if (!trackedEntities.has(entity) || mutationBatch?.full
+ || JOINT_TYPES.some(component => mutationBatch?.changed.get(component)?.has(entity))
+ || jointChangedOrGone(world, entity, lastEntitySyncTick)
|| jointPartnerGone(world, entity, trackedEntities)) {
module._physics_destroyJoint(entity);
trackedJoints.delete(entity);
}
}
createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);
- syncOneWayPlatforms(world, module, trackedEntities, trackedOneWay);
+ syncOneWayPlatforms(world, module, trackedEntities, trackedOneWay, mutationBatch?.entities);
lastEntitySyncTick = world.getWorldTick();
lastStructuralVersion = structuralVersion;
} // end if (needReconcile)
- staticPoses.sync(module, ppu, needReconcile, entity => !!cachedProps.get(entity)?.enabled);
+ staticPoses.sync(module, ppu, mutationBatch?.full ?? 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 the
@@ -917,6 +953,7 @@ export function registerPhysics2DSystem(
// fixed step so Box2D derives their velocity from the delta: that
// velocity is what carries/pushes resting dynamic bodies (a plain
// teleport reports zero velocity, so platforms wouldn't move riders).
+ if (kinematicEntities.size) world.ensureTransformsComposed();
for (const entity of kinematicEntities) {
if (!cachedProps.get(entity)?.enabled) continue;
const wt = world.get(entity, Transform) as TransformData;
@@ -935,20 +972,8 @@ export function registerPhysics2DSystem(
collectEvents(module, ppu, events);
module._physics_capturePoses();
- // Membership decides batch-vs-parented writeback; a runtime
- // reparent of a live body would otherwise stay on the batch path
- // and get its world pose written as a local one. Only gaining or
- // losing a Parent changes the answer, and that is a structural
- // edit, so this rides the reconcile gate rather than walking
- // every body every step.
- if (needReconcile) {
- for (const entity of trackedEntities) {
- if (cachedProps.get(entity)?.bodyType !== BodyType.Static && world.has(entity, Parent)) {
- parentedBodies.add(entity);
- }
- else parentedBodies.delete(entity);
- }
- }
+ // Acknowledge the sampled boundaries; later same-frame writes remain pending.
+ if (mutationBatch) mutations.commit(mutationBatch);
},
{ name: 'PhysicsStepSystem' }
),
@@ -985,7 +1010,12 @@ export function registerPhysics2DSystem(
{ runIf: playModeOnly, profileDomain: 'physics' }
);
const offFrameEnd = app.onFrameEnd(() => {
- if (app.isPaused() || !playModeOnly() || app.getResource(Time).scale <= 0) staticPoses.pause();
+ if (app.isPaused() || !playModeOnly() || app.getResource(Time).scale <= 0) {
+ staticPoses.pause(); mutations.pause();
+ }
});
- return () => { offFrameEnd(); offDespawn(); staticPoses.dispose(); };
+ return () => {
+ offFrameEnd(); offDespawn(); staticPoses.dispose(); mutations.dispose();
+ colliderStates.clear(); cachedProps.clear();
+ };
}
diff --git a/sdk/src/physics/StaticBodyPoses2D.ts b/sdk/src/physics/StaticBodyPoses2D.ts
index ba8ef9575..936d213d6 100644
--- a/sdk/src/physics/StaticBodyPoses2D.ts
+++ b/sdk/src/physics/StaticBodyPoses2D.ts
@@ -17,9 +17,9 @@ export class StaticBodyPoses2D {
private parents = new Map<Entity, number[]>();
private reader: number | null = null;
private epoch = -1;
- private tick = -1;
private ppu = -1;
private legacyStale = false;
+ private readonly dirty = new Set<Entity>();
constructor(private readonly world: World) {}
@@ -37,8 +37,11 @@ export class StaticBodyPoses2D {
const previous = this.poses.get(entity);
if (previous?.parent === parent) return;
this.set(entity, previous ? { ...previous, parent } : { x: NaN, y: NaN, angle: NaN, parent });
+ this.invalidate(entity);
}
+ invalidate(entity: Entity): void { if (this.poses.has(entity)) this.dirty.add(entity); }
+
delete(entity: Entity): void {
const parent = this.poses.get(entity)?.parent;
if (parent != null) {
@@ -47,11 +50,12 @@ export class StaticBodyPoses2D {
if (!group?.size) { this.groups.delete(parent); this.parents.delete(parent); }
}
this.poses.delete(entity);
+ this.dirty.delete(entity);
}
/** A stopped simulation owes a full pose refresh, but retains no write history. */
pause(): void {
- if (this.reader !== null) this.world.disposeWriteReader(Transform, this.reader);
+ if (this.reader !== null) this.world.disposeMutationCursor(Transform, 'write', this.reader);
this.reader = null;
this.epoch = -1;
}
@@ -60,9 +64,10 @@ export class StaticBodyPoses2D {
const world = this.world;
if (!this.poses.size) { this.pause(); return; }
const first = this.reader === null;
- if (first) this.reader = world.registerWriteReaderFrom(Transform, world.getWorldTick());
+ if (first) this.reader = world.registerMutationCursor(Transform, 'write');
+ const through = world.mutationSequence('write');
const epoch = world.transformEpoch();
- if (first || reconcile || epoch < 0 || epoch !== this.epoch || ppu !== this.ppu) {
+ if (first || reconcile || this.dirty.size || epoch < 0 || epoch !== this.epoch || ppu !== this.ppu) {
world.ensureTransformsComposed();
const all = first || reconcile || epoch < 0 || ppu !== this.ppu;
const changedParents = new Set<Entity>();
@@ -78,17 +83,18 @@ export class StaticBodyPoses2D {
} else this.parents.delete(parent);
if (!all && changed) changedParents.add(parent);
}
- const selected: Entity[] = [];
- if (all) for (const entity of this.poses.keys()) selected.push(entity);
+ const selected = new Set<Entity>();
+ if (all) for (const entity of this.poses.keys()) selected.add(entity);
else {
- for (const parent of changedParents) for (const entity of this.groups.get(parent)!) selected.push(entity);
- const written = new Set(world.getWrittenEntitiesSince(Transform, this.tick));
+ for (const parent of changedParents) for (const entity of this.groups.get(parent)!) selected.add(entity);
+ for (const entity of this.dirty) selected.add(entity);
+ const written = new Set(world.mutationsForCursor(Transform, 'write', this.reader!));
for (const entity of written) {
const pose = this.poses.get(entity);
- if (pose && (pose.parent === null || !changedParents.has(pose.parent))) selected.push(entity);
+ if (pose && (pose.parent === null || !changedParents.has(pose.parent))) selected.add(entity);
}
}
- if (batchStaticPoses2D(world, module, selected, ppu, enabled)) this.legacyStale = true;
+ if (batchStaticPoses2D(world, module, [...selected], ppu, enabled)) this.legacyStale = true;
else {
if (this.legacyStale) {
for (const pose of this.poses.values()) pose.x = NaN;
@@ -111,9 +117,9 @@ export class StaticBodyPoses2D {
}
}
this.epoch = world.transformEpoch();
- this.tick = world.getWorldTick() - 1;
+ this.dirty.clear();
this.ppu = ppu;
- world.advanceWriteReader(Transform, this.reader!, this.tick);
+ world.advanceMutationCursor(Transform, 'write', this.reader!, through);
}
dispose(): void {
diff --git a/sdk/tests/physics-mutation-reconcile-wasm.test.ts b/sdk/tests/physics-mutation-reconcile-wasm.test.ts
new file mode 100644
index 000000000..bd1dbeda3
--- /dev/null
+++ b/sdk/tests/physics-mutation-reconcile-wasm.test.ts
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { Transform, Disabled } from '../src/ecs/component';
+import { Time } from '../src/ecs/resource';
+import { Schedule, defineSystem } from '../src/ecs/system';
+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';
+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';
+import { Physics2D } from '../src/physics/Physics2D';
+import { RigidBody2D, BoxCollider2D, BodyType } from '../src/physics/PhysicsComponents';
+import type { ESEngineModule } from '../src/wasm';
+import type { Entity } from '../src/types';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';
+import { ENTITY_CHANGE_CAPACITY } from '../src/wasm/constants.generated';
+
+let core: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });
+
+async function scene() {
+ core.setActiveContext(null);
+ const app = App.new(); apps.push(app);
+ const registry = new core.Registry(); app.connectCpp(registry, core, { ownedRegistry: true });
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ const clear = vi.spyOn(module, "_physics_clearShapes");
+ const properties = vi.spyOn(module, "_physics_updateBodyProperties");
+ vi.spyOn(module, "_physics_setBodyTransforms"); const poses = vi.mocked(module._physics_setBodyTransforms!);
+ const plugin = new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module);
+ app.addPlugin(plugin); await app.getResource(Physics2DRuntime).initPromise;
+ const world = app.world, root = world.spawn(), unrelated = world.spawn(), bodies: Entity[] = [];
+ world.insert(root, Transform); world.insert(unrelated, Transform); world.insert(unrelated, Disabled);
+ for (let i = 0; i < 256; ++i) {
+ const entity = world.spawn(); bodies.push(entity);
+ world.insert(entity, Transform, { position: { x: i * 40, y: 0, z: 0 } });
+ world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
+ world.insert(entity, BoxCollider2D, { halfExtents: { x: .05, y: .05 }, radius: 0 });
+ world.setParent(entity, root);
+ }
+ await app.stepFrames(3, 1 / 60);
+ clear.mockClear(); properties.mockClear(); poses.mockClear();
+ const get = vi.spyOn(world, 'get');
+ const bodyReads = () => get.mock.calls.filter(([, component]) => component === RigidBody2D).map(([entity]) => entity);
+ const hit = (entity = bodies[0]) => app.getResource(Physics2D).raycast({ x: -50, y: 0 }, { x: 1, y: 0 }, 300)
+ .find(value => value.entity === entity)?.point.x;
+ return { app, world, registry, module, plugin, root, unrelated, bodies, get, clear, properties, poses, bodyReads, hit };
+}
+
+describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('component-driven physical body reconciliation', () => {
+ beforeAll(async () => { core = await loadWasmModule(); });
+
+ it('reconciles one collider edit without reading or resubmitting the other bodies', async () => {
+ const { app, world, bodies, bodyReads, clear, poses, hit } = await scene();
+ world.update(bodies[0], BoxCollider2D, value => { value.halfExtents.x = .1; });
+ await app.tick(1 / 60);
+ expect(bodyReads()).toEqual([bodies[0]]);
+ expect(clear).toHaveBeenCalledOnce(); expect(clear).toHaveBeenCalledWith(bodies[0]);
+ expect(poses).not.toHaveBeenCalled();
+ expect(hit()).toBeCloseTo(-10, 3);
+ });
+
+ it('ignores unrelated structural changes even when the world has inactive UI', async () => {
+ const { app, world, bodies, root, bodyReads, clear } = await scene();
+ const entity = world.spawn(); world.insert(entity, Transform); world.setParent(entity, root);
+ await app.tick(1 / 60); world.despawn(entity); await app.tick(1 / 60);
+ expect(bodyReads()).toEqual([]); expect(clear).not.toHaveBeenCalled();
+ const parent = world.spawn(); world.insert(parent, Transform, { position: { x: 25, y: 0, z: 0 } });
+ world.setParent(bodies[0], parent); await app.tick(1 / 60);
+ expect(bodyReads()).toEqual([bodies[0]]);
+ });
+
+ it('observes native collider and body replacements without SDK write notifications', async () => {
+ const { app, registry, bodies, bodyReads, clear, properties, hit } = await scene();
+ const collider = registry.getBoxCollider2D(bodies[0]); collider.halfExtents.x = .2;
+ registry.addBoxCollider2D(bodies[0], collider);
+ const body = registry.getRigidBody2D(bodies[0]); body.linearDamping = .7;
+ registry.addRigidBody2D(bodies[0], body);
+ await app.tick(1 / 60);
+ expect(bodyReads()).toEqual([bodies[0]]); expect(clear).toHaveBeenCalledOnce(); expect(clear).toHaveBeenCalledWith(bodies[0]);
+ expect(properties).toHaveBeenCalledOnce(); expect(hit()).toBeCloseTo(-20, 3);
+ });
+
+ it('refreshes native body membership and recreates the missing solver body', async () => {
+ const { app, world, registry, module, bodies } = await scene();
+ const entity = bodies[0], body = registry.getRigidBody2D(entity);
+ registry.removeRigidBody2D(entity); await app.tick(1 / 60);
+ expect(module._physics_getBodyCount()).toBe(255);
+ expect(world.has(entity, RigidBody2D)).toBe(false);
+ registry.addRigidBody2D(entity, body); await app.tick(1 / 60);
+ expect(module._physics_getBodyCount()).toBe(256);
+ expect(world.getEntitiesWithComponents([RigidBody2D, Transform])).toContain(entity);
+ });
+
+ it('refreshes an edited hidden collider when its native ancestor is re-enabled', async () => {
+ const { app, world, registry, module, root, bodies, hit, clear } = await scene();
+ registry.setEntityEnabled!(root, false); await app.tick(1 / 60);
+ world.update(bodies[0], BoxCollider2D, value => { value.halfExtents.x = .15; });
+ await app.tick(1 / 60); expect(hit()).toBeUndefined();
+ registry.setEntityEnabled!(root, true); await app.tick(1 / 60);
+ expect(module._physics_getBodyCount()).toBe(256);
+ expect(clear).toHaveBeenCalledOnce(); expect(clear).toHaveBeenCalledWith(bodies[0]);
+ expect(hit()).toBeCloseTo(-15, 3);
+ });
+
+ it('releases stopped readers and compares collider snapshots on resume', async () => {
+ const { app, world, registry, bodies, clear, hit } = await scene();
+ app.getResource(Time).scale = 0; await app.tick(1 / 60);
+ expect(world.writeReaderCount(RigidBody2D)).toBe(0);
+ expect(world.topologyReaderCount(RigidBody2D)).toBe(0);
+ expect(world.writeReaderCount(Transform)).toBe(0);
+ const collider = registry.getBoxCollider2D(bodies[0]); collider.halfExtents.x = .12;
+ registry.addBoxCollider2D(bodies[0], collider);
+ app.getResource(Time).scale = 1; await app.tick(1 / 60);
+ expect(clear).toHaveBeenCalledOnce(); expect(clear).toHaveBeenCalledWith(bodies[0]);
+ expect(hit()).toBeCloseTo(-12, 3);
+ });
+
+ it('applies two collider edits in two fixed steps of the same world tick', async () => {
+ const { app, world, bodies, clear, hit } = await scene();
+ let edits = 0; const hits: number[] = [];
+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem([], () => {
+ world.update(bodies[0], BoxCollider2D, value => { value.halfExtents.x = ++edits === 1 ? .1 : .15; });
+ }, { name: 'EditColliderEachFixedStep' }));
+ app.addSystemToSchedule(Schedule.FixedPostUpdate, defineSystem([], () => { hits.push(hit()!); }, { name: 'ReadEditedShape' }));
+ vi.spyOn(performance, 'now').mockReturnValue(0);
+ await app.tick(2 / 60);
+ expect(edits).toBe(2); expect(clear).toHaveBeenCalledTimes(2);
+ expect(hits[0]).toBeCloseTo(-10, 3); expect(hits[1]).toBeCloseTo(-15, 3);
+ });
+
+ it('observes native Transform replacement without reconciling body definitions', async () => {
+ const { app, registry, bodies, bodyReads, poses, hit } = await scene();
+ const transform = registry.getTransform(bodies[0]); transform.position.x = 20;
+ registry.addTransform(bodies[0], transform); await app.tick(1 / 60);
+ expect(bodyReads()).toEqual([]); expect(poses).toHaveBeenCalledOnce();
+ expect(poses.mock.calls[0][1]).toBe(1); expect(hit()).toBeCloseTo(15, 3);
+ });
+
+ it('refreshes after native history overflow while preserving solver velocity and unchanged shapes', async () => {
+ const { app, world, registry, module, unrelated, bodies, clear } = await scene();
+ const entity = bodies[0];
+ world.update(entity, RigidBody2D, value => { value.bodyType = BodyType.Dynamic; });
+ await app.tick(1 / 60); module._physics_setLinearVelocity(entity, 1, 0);
+ 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 collider = registry.getBoxCollider2D(entity); collider.halfExtents.x = .08;
+ registry.addBoxCollider2D(entity, collider); await app.tick(1 / 60);
+ expect(module._physics_getBodyCount()).toBe(256);
+ expect(clear).toHaveBeenCalledOnce(); expect(clear).toHaveBeenCalledWith(entity);
+ expect(module.HEAPF32[module._physics_getLinearVelocity(entity) >>> 2]).toBeCloseTo(1, 5);
+ });
+
+ it('releases its native lease before disconnect and removes the lifecycle observer on cleanup', async () => {
+ const { app, world, registry, plugin } = await scene();
+ const unwatch = vi.spyOn(core, 'registry_unwatchEntityChanges');
+ expect(world.getStorageSizes().coreDisconnectCallbacks).toBe(1);
+ world.disconnectCpp();
+ expect(unwatch).toHaveBeenCalledOnce();
+ expect(world.writeReaderCount(RigidBody2D)).toBe(0);
+ expect(core.registry_readEntityChanges!(registry, 0, 0, 0)).toBe(-1);
+ plugin.cleanup(app);
+ expect(world.getStorageSizes().coreDisconnectCallbacks).toBe(0);
+ expect(world.writeReaderCount(Transform)).toBe(0);
+ expect(unwatch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 18505c298..afddf67e3 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): reconcile only changed body definitions':
+ { note: 'Physics reconciliation follows component mutation cursors.' },
'refactor(ecs): unify SDK and native mutation cursors':
{ internal: 'Provides same-tick SDK mutation cursors, generated host component IDs, native reset epochs and owned core-disconnect leases for shared sparse runtime synchronization.' },
'refactor(ecs): expose bounded native entity change history':