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
fix(physics): preserve unchanged joint projections
yhh5b73e046ad23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e428f2cce..ce9efed4f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Fixed++- **Unchanged 2D joints retain their solver state.** Paused collision edits, full mutation-history refreshes and identical joint writes preserve existing constraints instead of destroying and recreating them. Missing solver joints recover on reconciliation, changes to the live Canvas scale rebuild joint dimensions, and older cores observe joint writes after a previous physics run in the same tick. All six joint types retain their enabled and partner-lifetime behavior.+## [0.89.2] - 2026-10-16### Fixeddiff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex 0d360eab3..5c48171dc 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -205,7 +205,7 @@ function createPendingJoints(world: App['world'],module: PhysicsWasmModule,trackedEntities: Set<Entity>,- trackedJoints: Set<Entity>,+ trackedJoints: Map<Entity, string>,invPpu: number,): void {const jointEntities = world.getEntitiesWithComponents([HingeJoint2D, RigidBody2D]);@@ -224,7 +224,7 @@ function createPendingJoints(joint.enableLimit ? 1 : 0, joint.lowerAngle, joint.upperAngle,joint.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}for (const entity of world.getEntitiesWithComponents([DistanceJoint2D, RigidBody2D])) {@@ -244,7 +244,7 @@ function createPendingJoints(j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,j.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}for (const entity of world.getEntitiesWithComponents([SliderJoint2D, RigidBody2D])) {@@ -264,7 +264,7 @@ function createPendingJoints(j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,j.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}for (const entity of world.getEntitiesWithComponents([FixedJoint2D, RigidBody2D])) {@@ -282,7 +282,7 @@ function createPendingJoints(j.linearDampingRatio, j.angularDampingRatio,j.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}for (const entity of world.getEntitiesWithComponents([WheelJoint2D, RigidBody2D])) {@@ -302,7 +302,7 @@ function createPendingJoints(j.enableMotor ? 1 : 0, j.maxMotorTorque, j.motorSpeed,j.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}for (const entity of world.getEntitiesWithComponents([MotorJoint2D, RigidBody2D])) {@@ -320,7 +320,7 @@ function createPendingJoints(j.angularHertz, j.angularDampingRatio, j.maxSpringTorque,j.collideConnected ? 1 : 0,);- trackedJoints.add(entity);+ if (module._physics_hasJoint(entity)) trackedJoints.set(entity, jointState(world, entity, invPpu)!);}}@@ -628,6 +628,14 @@ const COLLIDER_TYPES = [const JOINT_TYPES = [HingeJoint2D, DistanceJoint2D, SliderJoint2D, FixedJoint2D, WheelJoint2D, MotorJoint2D] as const;+function jointState(world: App['world'], entity: Entity, invPpu: number): string | null {+ for (let i = 0; i < JOINT_TYPES.length; ++i) {+ const component = JOINT_TYPES[i];+ if (world.has(entity, component)) return JSON.stringify([i, invPpu, world.get(entity, component)]);+ }+ return null;+}+/** Bitmask of which collider components an entity currently has. @internal */export function colliderSignature(world: App['world'], entity: Entity): number {let sig = 0;@@ -691,7 +699,7 @@ export function registerPhysics2DSystem(config: ResolvedPhysics2DConfig,): () => void {const trackedEntities = new Set<Entity>();- const trackedJoints = new Set<Entity>();+ const trackedJoints = new Map<Entity, string>();const trackedOneWay = new Set<Entity>();const parentedBodies = new Set<Entity>();const cachedProps = new Map<Entity, CachedBodyProps>();@@ -708,6 +716,8 @@ export function registerPhysics2DSystem(if (state && --state.references === 0) colliderStates.delete(value);};let lastEntitySyncTick = -1;+ let lastJointInvPpu = NaN;+ let lastJointWriteRevisions: number[] = [];// Events accumulated across this frame's fixed steps; published once per frame.const events: EventAccum = {collisionEnters: [], collisionExits: [], collisionHits: [], sensorEnters: [], sensorExits: [],@@ -766,6 +776,7 @@ export function registerPhysics2DSystem(// value captured when the wasm module first loaded.const ppu = readPixelsPerUnit(app);const invPpu = 1 / ppu;+ const jointScaleChanged = invPpu !== lastJointInvPpu;// 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);@@ -773,6 +784,10 @@ export function registerPhysics2DSystem(// component stamps retain the full-scan fallback for older hosts.const structuralVersion = world.getWorldVersion();const mutationBatch = mutations.read();+ const jointWriteRevisions = mutationBatch ? null+ : JOINT_TYPES.map(component => world.mutationRevision(component, 'write'));+ const jointWritesChanged = !!jointWriteRevisions+ && jointWriteRevisions.some((revision, i) => revision !== lastJointWriteRevisions[i]);let needReconcile = structuralVersion !== lastStructuralVersion;if (mutationBatch) needReconcile = mutationBatch.full || mutationBatch.entities.size > 0;else if (!needReconcile) {@@ -783,10 +798,11 @@ export function registerPhysics2DSystem(}}}+ needReconcile ||= jointScaleChanged || jointWritesChanged;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);+ for (const entity of trackedJoints.keys()) module._physics_destroyJoint(entity);trackedJoints.clear();for (const entity of trackedOneWay) module._physics_setOneWayPlatform(entity, 0, 0, 0);trackedOneWay.clear();@@ -927,12 +943,14 @@ export function registerPhysics2DSystem(}// ── Joint reconcile ─────────────────────────────────────────- // Destroy joints whose definition changed or whose component was- // removed; createPendingJoints re-adds present+enabled ones.- for (const entity of [...trackedJoints]) {- if (!trackedEntities.has(entity) || mutationBatch?.full- || JOINT_TYPES.some(component => mutationBatch?.changed.get(component)?.has(entity))- || jointChangedOrGone(world, entity, lastEntitySyncTick)+ // Definition snapshots preserve solver state across full refreshes+ // and identical writes. Missing solver joints must be recreated.+ for (const [entity, state] of trackedJoints) {+ const changed = jointScaleChanged || (mutationBatch ? mutationBatch.full+ || JOINT_TYPES.some(component => mutationBatch.changed.get(component)?.has(entity))+ : jointWritesChanged || jointChangedOrGone(world, entity, lastEntitySyncTick));+ if (!trackedEntities.has(entity) || !module._physics_hasJoint(entity)+ || (changed && jointState(world, entity, invPpu) !== state)|| jointPartnerGone(world, entity, trackedEntities)) {module._physics_destroyJoint(entity);trackedJoints.delete(entity);@@ -942,6 +960,8 @@ export function registerPhysics2DSystem(syncOneWayPlatforms(world, module, trackedEntities, trackedOneWay, mutationBatch?.entities);lastEntitySyncTick = world.getWorldTick();+ lastJointInvPpu = invPpu;+ if (jointWriteRevisions) lastJointWriteRevisions = jointWriteRevisions;lastStructuralVersion = structuralVersion;} // end if (needReconcile)@@ -1017,6 +1037,6 @@ export function registerPhysics2DSystem(});return () => {offFrameEnd(); offDespawn(); staticPoses.dispose(); mutations.dispose();- colliderStates.clear(); cachedProps.clear();+ colliderStates.clear(); cachedProps.clear(); trackedJoints.clear();};}diff --git a/sdk/tests/physics-joint-reconcile-wasm.test.ts b/sdk/tests/physics-joint-reconcile-wasm.test.tsnew file mode 100644index 000000000..66689ff50--- /dev/null+++ b/sdk/tests/physics-joint-reconcile-wasm.test.ts@@ -0,0 +1,156 @@+// 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, Canvas } from '../src/ecs/component';+import { Time } from '../src/ecs/resource';+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';+import {+ RigidBody2D, BoxCollider2D, BodyType, DistanceJoint2D,+ HingeJoint2D, SliderJoint2D, FixedJoint2D, WheelJoint2D, MotorJoint2D,+} from '../src/physics/PhysicsComponents';+import type { ESEngineModule } from '../src/wasm';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });++async function scene(legacy = false) {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app);+ const registry = new core.Registry(); app.connectCpp(registry, core, { ownedRegistry: true });+ if (legacy) registry.componentTypeId = undefined;+ const module = await loadSideModule<PhysicsWasmModule>('physics');+ const create = vi.spyOn(module, '_physics_createDistanceJoint');+ const destroy = vi.spyOn(module, '_physics_destroyJoint');+ const otherCreates = [+ vi.spyOn(module, '_physics_createRevoluteJoint'), vi.spyOn(module, '_physics_createPrismaticJoint'),+ vi.spyOn(module, '_physics_createWeldJoint'), vi.spyOn(module, '_physics_createWheelJoint'),+ vi.spyOn(module, '_physics_createMotorJoint'),+ ];+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module));+ await app.getResource(Physics2DRuntime).initPromise;+ const world = app.world, anchor = world.spawn(), owner = world.spawn(), other = world.spawn();+ for (const entity of [anchor, owner, other]) {+ world.insert(entity, Transform, { position: { x: entity === owner ? 40 : 0, y: 0, z: 0 } });+ world.insert(entity, RigidBody2D, { bodyType: entity === owner ? BodyType.Dynamic : BodyType.Static });+ world.insert(entity, BoxCollider2D, { halfExtents: { x: .01, y: .01 }, radius: 0 });+ }+ world.insert(owner, DistanceJoint2D, { connectedEntity: anchor, length: 40 });+ await app.stepFrames(3, 1 / 60);+ expect(module._physics_getJointCount()).toBe(1);+ create.mockClear(); destroy.mockClear();+ return { app, world, registry, module, anchor, owner, other, create, destroy, otherCreates };+}++describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('joint projection reconciliation', () => {+ beforeAll(async () => { core = await loadWasmModule(); });++ it('retains the live joint when a different collider is edited while paused', async () => {+ const { app, world, module, owner, other, create, destroy } = await scene();+ module._physics_setDistanceJointLength(owner, .75);+ app.getResource(Time).scale = 0; await app.tick(1 / 60);+ world.update(other, BoxCollider2D, value => { value.halfExtents.x = .02; });+ app.getResource(Time).scale = 1; await app.tick(1 / 60);+ expect(destroy).not.toHaveBeenCalled(); expect(create).not.toHaveBeenCalled();+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.75);+ expect(module._physics_getJointCount()).toBe(1);+ });++ it('retains a native joint when the authored definition is replaced identically', async () => {+ const { app, world, module, owner, create, destroy } = await scene();+ module._physics_setDistanceJointLength(owner, .75);+ world.insert(owner, DistanceJoint2D, world.get(owner, DistanceJoint2D));+ await app.tick(1 / 60);+ expect(destroy).not.toHaveBeenCalled(); expect(create).not.toHaveBeenCalled();+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.75);+ });++ it('applies a joint definition change once', async () => {+ const { app, world, module, owner, create, destroy } = await scene();+ world.update(owner, DistanceJoint2D, joint => { joint.length = 60; }); await app.tick(1 / 60);+ expect(destroy).toHaveBeenCalledOnce(); expect(create).toHaveBeenCalledOnce();+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.6);+ await app.tick(1 / 60); expect(create).toHaveBeenCalledOnce();+ });++ it('recovers a solver joint lost before an unrelated authoring edit', async () => {+ const { app, world, module, owner, other, create } = await scene();+ module._physics_destroyJoint(owner);+ expect(module._physics_hasJoint(owner)).toBe(0);+ world.update(other, BoxCollider2D, value => { value.halfExtents.x = .02; });+ await app.tick(1 / 60);+ expect(create).toHaveBeenCalledOnce(); expect(module._physics_hasJoint(owner)).toBe(1);+ expect(module._physics_getJointCount()).toBe(1);+ });++ it('rescales joint lengths when only the live Canvas scale changes', async () => {+ const { app, world, module, owner, create, destroy } = await scene();+ const canvas = world.spawn(); world.insert(canvas, Canvas, { pixelsPerUnit: 200 });+ await app.tick(1 / 60);+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.2);+ expect(destroy).toHaveBeenCalledOnce(); expect(create).toHaveBeenCalledOnce();+ world.update(canvas, Canvas, value => { value.pixelsPerUnit = 400; });+ await app.tick(1 / 60);+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.1);+ expect(create).toHaveBeenCalledTimes(2);+ });++ it.each([HingeJoint2D, DistanceJoint2D, SliderJoint2D, FixedJoint2D, WheelJoint2D, MotorJoint2D])(+ 'retains $name through a paused full refresh and respects enabled edits', async component => {+ const { app, world, module, owner, anchor, other, create, destroy, otherCreates } = await scene();+ world.remove(owner, DistanceJoint2D);+ world.insert(owner, component, { connectedEntity: anchor });+ await app.tick(1 / 60); expect(module._physics_getJointCount()).toBe(1);+ for (const spy of [create, destroy, ...otherCreates]) spy.mockClear();+ app.getResource(Time).scale = 0; await app.tick(1 / 60);+ world.update(other, BoxCollider2D, value => { value.halfExtents.x = .03; });+ app.getResource(Time).scale = 1; await app.tick(1 / 60);+ for (const spy of [create, destroy, ...otherCreates]) expect(spy).not.toHaveBeenCalled();+ world.update(owner, component, value => { value.enabled = false; }); await app.tick(1 / 60);+ expect(module._physics_getJointCount()).toBe(0);+ world.update(owner, component, value => { value.enabled = true; }); await app.tick(1 / 60);+ expect(module._physics_getJointCount()).toBe(1);+ },+ );++ it('recreates a joint after its partner body disappears and returns', async () => {+ const { app, world, module, anchor, owner, create } = await scene();+ const body = { ...world.get(anchor, RigidBody2D) };+ world.remove(anchor, RigidBody2D); await app.tick(1 / 60);+ expect(module._physics_getJointCount()).toBe(0);+ world.insert(anchor, RigidBody2D, body); await app.tick(1 / 60);+ expect(module._physics_hasJoint(owner)).toBe(1); expect(create).toHaveBeenCalledOnce();+ });++ it('keeps identical authored writes stable with an older core', async () => {+ const { app, world, module, owner, create, destroy } = await scene(true);+ module._physics_setDistanceJointLength(owner, .8);+ world.insert(owner, DistanceJoint2D, world.get(owner, DistanceJoint2D));+ await app.tick(1 / 60);+ expect(destroy).not.toHaveBeenCalled(); expect(create).not.toHaveBeenCalled();+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.8);+ world.update(owner, DistanceJoint2D, value => { value.length = 90; }); await app.tick(1 / 60);+ expect(module._physics_getDistanceJointLength(owner)).toBeCloseTo(.9);+ });++ it('retains a dense constraint set when one unrelated collider changes during pause', async () => {+ const { app, world, module, anchor, other, create, destroy } = await scene();+ for (let i = 0; i < 128; ++i) {+ const entity = world.spawn();+ world.insert(entity, Transform, { position: { x: 100, y: 0, z: 0 } });+ world.insert(entity, RigidBody2D, { bodyType: BodyType.Dynamic });+ world.insert(entity, DistanceJoint2D, { connectedEntity: anchor, length: 100 });+ }+ await app.tick(1 / 60); expect(module._physics_getJointCount()).toBe(129);+ create.mockClear(); destroy.mockClear();+ app.getResource(Time).scale = 0; await app.tick(1 / 60);+ world.update(other, BoxCollider2D, value => { value.halfExtents.x = .04; });+ app.getResource(Time).scale = 1; await app.tick(1 / 60);+ expect(create).not.toHaveBeenCalled(); expect(destroy).not.toHaveBeenCalled();+ expect(module._physics_getJointCount()).toBe(129);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 77452a0e1..bc5512145 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 = {+ 'fix(physics): preserve unchanged joint projections':+ { note: 'Unchanged 2D joints retain their solver state.' },'fix(ecs): scope native mutations to world ownership':{ note: 'Physics reconciliation follows component mutation cursors.' },'perf(physics): reuse mutation checkpoints after pause':