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): sync transforms in bulk on device, interpolate in the module

esengine8d34c2b763f7
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f161b2f81..a3f45272a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4513,6 +4513,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -4553,6 +4554,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index de0f93384..40eb9900b 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4661,6 +4661,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -4701,6 +4702,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index dee18a8d2..65622b3c2 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4508,6 +4508,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -4548,6 +4549,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 692903dcb..f28f9ed06 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4723,6 +4723,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -4763,6 +4764,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.md
index b1ec06275..a8bfddba3 100644
--- a/sdk/etc/physics.api.md
+++ b/sdk/etc/physics.api.md
@@ -414,6 +414,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -454,6 +455,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f86a4bc58..e4742f163 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4515,6 +4515,7 @@ _physics_applyAngularImpulse: (entityId: number, impulse: number) => void
_physics_applyForce: (entityId: number, forceX: number, forceY: number) => void
_physics_applyImpulse: (entityId: number, impulseX: number, impulseY: number) => void
_physics_applyTorque: (entityId: number, torque: number) => void
+_physics_capturePoses: () => void
_physics_clearShapes: (entityId: number) => void
_physics_collectEvents: () => void
_physics_createBody: (entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void
@@ -4555,6 +4556,8 @@ _physics_getDynamicBodyTransforms: () => number
_physics_getGravity: () => number
_physics_getHitEventBuffer: () => number
_physics_getHitEventCount: () => number
+_physics_getInterpolatedCount: () => number
+_physics_getInterpolatedTransforms: (alpha: number) => number
_physics_getLinearVelocity: (entityId: number) => number
_physics_getMoveCharacterBuffer: () => number
_physics_getOverlapBuffer: () => number
diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.ts
index 1b1d62ff4..a677dbc4b 100644
--- a/sdk/src/physics/PhysicsModuleLoader.ts
+++ b/sdk/src/physics/PhysicsModuleLoader.ts
@@ -53,6 +53,16 @@ export interface PhysicsWasmModule {
_physics_getDynamicBodyCount(): number;
_physics_getDynamicBodyTransforms(): number;
+ /**
+ * Render interpolation, done by the module. It keeps the two most recent
+ * fixed-step snapshots itself and lerps them, because that loop runs over
+ * every dynamic body every frame — the shape of work the no-JIT budget keeps
+ * off the JS path (docs/REARCH_NATIVE.md §3.2).
+ */
+ _physics_capturePoses(): void;
+ _physics_getInterpolatedCount(): number;
+ _physics_getInterpolatedTransforms(alpha: number): number;
+
_physics_collectEvents(): void;
_physics_getCollisionEnterCount(): number;
_physics_getCollisionEnterBuffer(): number;
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 856ef8a0a..30e269d76 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -41,6 +41,16 @@ import {
type SensorEvent,
} from './PhysicsTypes';
import { withMalloc } from '../wasmScratch';
+import { engineApi, type EngineApi } from '../ecs/engineApi';
+
+/**
+ * The engine surface this file drives. `getTransformPtr` is the web module's own
+ * (it hands back a pointer into wasm memory); a native host answers the batched
+ * entry instead, which is the path every unparented body takes.
+ */
+type PhysicsEngineApi = EngineApi & {
+ getTransformPtr?(registry: unknown, entity: number): number;
+};
// =============================================================================
// Canvas pixelsPerUnit live read
@@ -339,68 +349,36 @@ const syncTransformBuf_ = {
const PHYSICS_BODY_STRIDE = 4; // u32 entity + 3x f32 (x, y, angle)
const PHYSICS_BODY_BYTES = PHYSICS_BODY_STRIDE * 4;
-/** Raw physics-space pose (meters + radians) of one body, for interpolation. */
-interface Pose { x: number; y: number; angle: number; }
-/** The two most recent fixed-step poses, keyed by entity, for render interp. */
-export interface PoseSnapshots { prev: Map<Entity, Pose>; cur: Map<Entity, Pose>; }
-
-// Shortest-arc angle interpolation (radians).
-function lerpAngle(a: number, b: number, t: number): number {
- let d = (b - a) % (2 * Math.PI);
- if (d > Math.PI) d -= 2 * Math.PI;
- else if (d < -Math.PI) d += 2 * Math.PI;
- return a + d * t;
-}
-
-/**
- * Capture post-step body poses for render interpolation: the previous `cur`
- * becomes `prev`, then `cur` is refilled from the batched read-back. A body seen
- * for the first time seeds `prev = cur`, so it doesn't smear on its first frame.
- * @internal exported for testing
- */
-export function capturePhysicsPoses(module: PhysicsWasmModule, snaps: PoseSnapshots): void {
- const tmp = snaps.prev;
- snaps.prev = snaps.cur;
- snaps.cur = tmp;
- snaps.cur.clear();
-
- const count = module._physics_getDynamicBodyCount();
- if (count === 0) return;
- const baseU32 = module._physics_getDynamicBodyTransforms() >> 2;
- const u32 = module.HEAPU32;
- const f32 = module.HEAPF32;
- for (let i = 0; i < count; i++) {
- const o = baseU32 + i * PHYSICS_BODY_STRIDE;
- const e = u32[o] as Entity;
- const x = f32[o + 1], y = f32[o + 2], angle = f32[o + 3];
- snaps.cur.set(e, { x, y, angle });
- if (!snaps.prev.has(e)) snaps.prev.set(e, { x, y, angle });
- }
-}
-
/**
- * Write interpolated body poses into ECS Transforms: each `cur` body is lerped
- * from `prev` by `alpha` (linear position, shortest-arc angle) and applied via
- * the engine's batched sync (or a per-entity path for parented bodies). With
- * `alpha = 1` this reproduces a direct post-step sync.
+ * Write interpolated body poses into ECS Transforms. The snapshot pair and the
+ * lerp itself belong to the physics module (`physics_capturePoses` /
+ * `physics_getInterpolatedTransforms`): they run over every dynamic body every
+ * frame, and the no-JIT budget bars that loop from the JS path
+ * (docs/REARCH_NATIVE.md §3.2). What is left here is routing the finished buffer
+ * to the engine. With `alpha = 1` this reproduces a direct post-step sync.
* @internal exported for testing
*/
export function applyPhysicsTransforms(
app: App,
ppu: number,
parentedBodies: Set<Entity>,
- snaps: PoseSnapshots,
+ module: PhysicsWasmModule,
alpha: number,
): void {
- const cur = snaps.cur;
- const count = cur.size;
+ const count = module._physics_getInterpolatedCount();
if (count === 0) return;
const registry = app.world.getCppRegistry();
if (!registry) return;
- const engineMod = app.world.getWasmModule();
+ // Through engineApi, not app.wasmModule: a device has no wasm module, so
+ // reaching for one left the batched path web-only and every body on a native
+ // host fell back to one addTransform call apiece (see ecs/engineApi.ts).
+ const engineMod = engineApi(app) as PhysicsEngineApi | null;
const hasParented = parentedBodies.size > 0;
+ // Already lerped, in the module's memory: [u32 entity, f32 x, y, angle] (meters).
+ const srcPtr = module._physics_getInterpolatedTransforms(alpha);
+
// Change-tracking boundary (deliberate). Both write paths below sync Transform
// through a raw C++ / ptr fast path and do NOT record a Changed() tick — the one
// intentional exception to the unified write surface (Mut / set / insert / remove /
@@ -408,42 +386,50 @@ export function applyPhysicsTransforms(
// every fixed step, so firing Changed(Transform) here would flood the changed-set
// with ~every moving body and make Changed(Transform) useless as a "gameplay wrote
// this" signal; the batched C++ path also can't record without an O(count) JS loop.
- // To react to physics-driven motion, use the per-step moved set (snaps.cur), not
+ // To react to physics-driven motion, read the module's per-step pose buffer, not
// Changed(Transform).
- // Batched fast path: build [u32 entity, f32 x, y, angle] (meters) interpolated.
- if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {
- withMalloc(engineMod, count * PHYSICS_BODY_BYTES, engineBuf => {
- const u32 = engineMod.HEAPU32;
- const f32 = engineMod.HEAPF32;
- const base = engineBuf >> 2;
- let i = 0;
- for (const [e, c] of cur) {
- const p = snaps.prev.get(e) ?? c;
- const o = base + i * PHYSICS_BODY_STRIDE;
- u32[o] = e as number;
- f32[o + 1] = p.x + (c.x - p.x) * alpha;
- f32[o + 2] = p.y + (c.y - p.y) * alpha;
- f32[o + 3] = lerpAngle(p.angle, c.angle, alpha);
- i++;
- }
- engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);
- });
- return;
+ const batchSync = engineMod?.registry_batchSyncPhysicsTransforms;
+ const engineHeap = engineMod?.HEAPU8;
+ if (!hasParented && batchSync && engineHeap) {
+ // A native host compiles the physics module into the engine's own binary, so
+ // both address one heap and the module's buffer is already an engine pointer.
+ if (engineHeap.buffer === module.HEAPU8.buffer) {
+ batchSync.call(engineMod, registry, srcPtr, count, ppu);
+ return;
+ }
+ // On the web a side module owns separate memory, so it is copied across —
+ // one memcpy, not a per-body loop.
+ if (engineMod?._malloc && engineMod._free) {
+ const bytes = count * PHYSICS_BODY_BYTES;
+ withMalloc(engineMod as Required<Pick<EngineApi, '_malloc' | '_free'>>, bytes, engineBuf => {
+ engineHeap.set(module.HEAPU8.subarray(srcPtr, srcPtr + bytes), engineBuf);
+ batchSync.call(engineMod, registry, engineBuf, count, ppu);
+ });
+ return;
+ }
}
- const getTransformPtr = engineMod?.getTransformPtr
- ? (e: Entity) => engineMod!.getTransformPtr(registry!, e as number)
+ const transformPtrFn = engineMod?.getTransformPtr;
+ const getTransformPtr = transformPtrFn
+ ? (e: Entity) => transformPtrFn.call(engineMod, registry!, e as number)
: null;
const engF32 = engineMod?.HEAPF32;
const addFn = (!getTransformPtr || !engF32) ? registry.addTransform.bind(registry) : null;
const t = syncTransformBuf_;
- for (const [entityId, c] of cur) {
- const p = snaps.prev.get(entityId) ?? c;
- let localX = (p.x + (c.x - p.x) * alpha) * ppu;
- let localY = (p.y + (c.y - p.y) * alpha) * ppu;
- let localAngle = lerpAngle(p.angle, c.angle, alpha);
+ // A parented body's pose has to be expressed in its parent's space, which only
+ // the registry can answer — so these go one at a time, over the same buffer.
+ const srcU32 = module.HEAPU32;
+ const srcF32 = module.HEAPF32;
+ const srcBase = srcPtr >> 2;
+
+ for (let i = 0; i < count; i++) {
+ const o = srcBase + i * PHYSICS_BODY_STRIDE;
+ const entityId = srcU32[o] as Entity;
+ let localX = srcF32[o + 1] * ppu;
+ let localY = srcF32[o + 2] * ppu;
+ let localAngle = srcF32[o + 3];
if (hasParented && parentedBodies.has(entityId)) {
const parentData = app.world.get(entityId, Parent) as ParentData;
@@ -689,9 +675,6 @@ export function registerPhysicsSystem(
const parentedBodies = new Set<Entity>();
const cachedProps = new Map<Entity, CachedBodyProps>();
let lastEntitySyncTick = -1;
- // The two most recent fixed-step poses, for render interpolation (the
- // PostUpdate system lerps prev→cur by Time.fixedAlpha).
- const snaps: PoseSnapshots = { prev: new Map(), cur: new Map() };
// Events accumulated across this frame's fixed steps; published once per frame.
const events: EventAccum = {
collisionEnters: [], collisionExits: [], collisionHits: [], sensorEnters: [], sensorExits: [],
@@ -725,8 +708,9 @@ export function registerPhysicsSystem(
cachedProps.delete(entity);
parentedBodies.delete(entity);
kinematicEntities.delete(entity);
- snaps.prev.delete(entity);
- snaps.cur.delete(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.
}
});
@@ -902,7 +886,7 @@ export function registerPhysicsSystem(
}
collectEvents(module, ppu, events);
- capturePhysicsPoses(module, snaps);
+ module._physics_capturePoses();
// Membership decides batch-vs-parented writeback; a runtime
// reparent of a live body would otherwise stay on the batch path
@@ -941,7 +925,7 @@ export function registerPhysicsSystem(
events.sensorExits = [];
const ppu = readPixelsPerUnit(app);
- applyPhysicsTransforms(app, ppu, parentedBodies, snaps, time.fixedAlpha);
+ applyPhysicsTransforms(app, ppu, parentedBodies, module, time.fixedAlpha);
},
{ name: 'PhysicsInterpolateSystem' }
),
diff --git a/sdk/tests/physicsSyncTransforms.test.ts b/sdk/tests/physicsSyncTransforms.test.ts
index e1c1a838c..a45e682ac 100644
--- a/sdk/tests/physicsSyncTransforms.test.ts
+++ b/sdk/tests/physicsSyncTransforms.test.ts
@@ -5,25 +5,20 @@ import type { Entity } from '../src/types';
import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
import type { TransformData, ParentData } from '../src/component';
import { Transform, Parent } from '../src/component';
-import {
- capturePhysicsPoses,
- applyPhysicsTransforms,
- type PoseSnapshots,
-} from '../src/physics/PhysicsSystem';
+import { applyPhysicsTransforms } from '../src/physics/PhysicsSystem';
import { createMockModule } from './mocks/wasm';
import { World } from '../src/world';
-// Capture the physics buffer into snapshots, then apply with alpha = 1 — which
-// reproduces a direct post-step sync (the old `syncDynamicTransforms` behaviour).
+// Publish the module's pose buffer to Transforms. The lerp itself lives in the
+// physics module (see PhysicsModuleEntry.cpp / physics_interpolation doctests);
+// what these tests cover is the SDK half — routing that buffer to the engine.
function sync(
app: any,
physMod: PhysicsWasmModule,
ppu: number,
parented: Set<Entity>,
): void {
- const snaps: PoseSnapshots = { prev: new Map(), cur: new Map() };
- capturePhysicsPoses(physMod, snaps);
- applyPhysicsTransforms(app, ppu, parented, snaps, 1);
+ applyPhysicsTransforms(app, ppu, parented, physMod, 1);
}
// =============================================================================
@@ -56,10 +51,18 @@ function buildPhysicsBuffer(bodies: Array<{ entity: number; x: number; y: number
return { buffer, HEAPF32: f32, HEAPU32: u32, ptr, count };
}
+/**
+ * Stands in for the module's interpolation: the real one lerps its own snapshot
+ * pair and hands back the result, so a mock that returns a prepared buffer is the
+ * same contract with the arithmetic already settled.
+ */
function createMockPhysicsModule(buf: ReturnType<typeof buildPhysicsBuffer>): PhysicsWasmModule {
return {
_physics_getDynamicBodyCount: () => buf.count,
_physics_getDynamicBodyTransforms: () => buf.ptr,
+ _physics_capturePoses: vi.fn(),
+ _physics_getInterpolatedCount: () => buf.count,
+ _physics_getInterpolatedTransforms: () => buf.ptr,
HEAPF32: buf.HEAPF32,
HEAPU32: buf.HEAPU32,
HEAPU8: new Uint8Array(buf.buffer),
@@ -276,67 +279,60 @@ describe('syncDynamicTransforms — fast path', () => {
});
});
-describe('render interpolation', () => {
+// The lerp itself is the module's (physics_getInterpolatedTransforms); its
+// semantics — midpoint, first-frame seeding, ±π short arc — are covered by the
+// physics_interpolation doctests. What the SDK owes is asking at the right alpha
+// and getting the answer to the engine without a per-body detour.
+describe('interpolation hand-off', () => {
const PPU = 100;
- it('lerps prev→cur by alpha (midpoint at 0.5)', () => {
+ it('asks the module for the pose at this frame\'s alpha', () => {
const app = createTestApp();
const e1 = app.world.spawn();
app.world.insert(e1, Transform, defaultTransform());
- const snaps: PoseSnapshots = { prev: new Map(), cur: new Map() };
- // Step 1: pose A (new body → prev = cur = A).
- capturePhysicsPoses(createMockPhysicsModule(buildPhysicsBuffer([
- { entity: e1 as number, x: 0, y: 0, angle: 0 },
- ])), snaps);
- // Step 2: pose B (prev = A, cur = B).
- capturePhysicsPoses(createMockPhysicsModule(buildPhysicsBuffer([
- { entity: e1 as number, x: 4, y: 8, angle: 0 },
- ])), snaps);
+ const mod = createMockPhysicsModule(buildPhysicsBuffer([
+ { entity: e1 as number, x: 2, y: 4, angle: 0 },
+ ]));
+ const spy = vi.spyOn(mod, '_physics_getInterpolatedTransforms');
- applyPhysicsTransforms(app, PPU, new Set(), snaps, 0.5);
+ applyPhysicsTransforms(app, PPU, new Set(), mod, 0.5);
+ expect(spy).toHaveBeenCalledWith(0.5);
const t = app.world.get(e1, Transform) as TransformData;
- expect(t.position.x).toBeCloseTo(2 * PPU); // halfway 0→4
- expect(t.position.y).toBeCloseTo(4 * PPU); // halfway 0→8
+ expect(t.position.x).toBeCloseTo(2 * PPU);
+ expect(t.position.y).toBeCloseTo(4 * PPU);
});
- it('does not smear a body on its first frame (prev seeded to cur)', () => {
+ it('publishes nothing when the module reports no bodies', () => {
const app = createTestApp();
- const e1 = app.world.spawn();
- app.world.insert(e1, Transform, defaultTransform());
-
- const snaps: PoseSnapshots = { prev: new Map(), cur: new Map() };
- capturePhysicsPoses(createMockPhysicsModule(buildPhysicsBuffer([
- { entity: e1 as number, x: 5, y: 6, angle: 0 },
- ])), snaps);
-
- // Even mid-step (alpha 0.5), a brand-new body sits exactly at its pose.
- applyPhysicsTransforms(app, PPU, new Set(), snaps, 0.5);
-
- const t = app.world.get(e1, Transform) as TransformData;
- expect(t.position.x).toBeCloseTo(5 * PPU);
- expect(t.position.y).toBeCloseTo(6 * PPU);
+ const mod = createMockPhysicsModule(buildPhysicsBuffer([]));
+ expect(() => applyPhysicsTransforms(app, PPU, new Set(), mod, 1)).not.toThrow();
});
- it('interpolates angle the short way across the ±π wrap', () => {
+ it('passes a shared heap straight through instead of re-marshalling it', () => {
+ // A native host compiles physics into the engine's own binary: one heap, so
+ // the module's pointer is already an engine pointer. Copying it there would
+ // be pure waste, and allocating for the copy doubly so.
const app = createTestApp();
const e1 = app.world.spawn();
app.world.insert(e1, Transform, defaultTransform());
- const snaps: PoseSnapshots = { prev: new Map(), cur: new Map() };
- capturePhysicsPoses(createMockPhysicsModule(buildPhysicsBuffer([
- { entity: e1 as number, x: 0, y: 0, angle: Math.PI - 0.1 },
- ])), snaps);
- capturePhysicsPoses(createMockPhysicsModule(buildPhysicsBuffer([
- { entity: e1 as number, x: 0, y: 0, angle: -Math.PI + 0.1 },
- ])), snaps);
+ const buf = buildPhysicsBuffer([{ entity: e1 as number, x: 1, y: 1, angle: 0 }]);
+ const sharedHeap = new Uint8Array(buf.buffer);
+ const mod = createMockPhysicsModule(buf);
+ (mod as any).HEAPU8 = sharedHeap;
- applyPhysicsTransforms(app, PPU, new Set(), snaps, 0.5);
+ const batchSync = vi.fn();
+ const malloc = vi.fn();
+ const engine = app.wasmModule as any;
+ engine.registry_batchSyncPhysicsTransforms = batchSync;
+ engine.HEAPU8 = sharedHeap;
+ engine._malloc = malloc;
- // Short arc from (π-0.1) to (-π+0.1) crosses π → midpoint ≈ ±π, not 0.
- const t = app.world.get(e1, Transform) as TransformData;
- const angle = 2 * Math.atan2(t.rotation.z, t.rotation.w);
- expect(Math.abs(angle)).toBeCloseTo(Math.PI, 2);
+ applyPhysicsTransforms(app, PPU, new Set(), mod, 1);
+
+ expect(batchSync).toHaveBeenCalledWith(expect.anything(), buf.ptr, 1, PPU);
+ expect(malloc).not.toHaveBeenCalled();
});
});
diff --git a/src/esengine/bindings/PhysicsBindings.hpp b/src/esengine/bindings/PhysicsBindings.hpp
index 82da278c7..f469ac71b 100644
--- a/src/esengine/bindings/PhysicsBindings.hpp
+++ b/src/esengine/bindings/PhysicsBindings.hpp
@@ -51,6 +51,13 @@ void physics_setBodyTargetTransform(uint32_t entityId, float x, float y, float a
int physics_getDynamicBodyCount();
// @heapreturn physics_dynamicBodyTransformsBytes()
uintptr_t physics_getDynamicBodyTransforms();
+// Render interpolation. The module keeps the two most recent fixed-step snapshots
+// and does the lerp itself: it touches every dynamic body every frame, and that
+// loop is barred from the JS path by the no-JIT budget (docs/REARCH_NATIVE.md §3.2).
+void physics_capturePoses();
+int physics_getInterpolatedCount();
+// @heapreturn physics_interpolatedTransformsBytes()
+uintptr_t physics_getInterpolatedTransforms(float alpha);
void physics_collectEvents();
int physics_getCollisionEnterCount();
// @heapreturn physics_collisionEnterBytes()
@@ -174,6 +181,7 @@ uintptr_t physics_getMoveCharacterBuffer();
// can say how much is live: a count times an assumed stride would over-read the very
// frame a body was disabled or a query found fewer hits than the last one.
size_t physics_dynamicBodyTransformsBytes();
+size_t physics_interpolatedTransformsBytes();
size_t physics_collisionEnterBytes();
size_t physics_collisionExitBytes();
size_t physics_sensorEnterBytes();
diff --git a/src/esengine/bindings/PhysicsContext.hpp b/src/esengine/bindings/PhysicsContext.hpp
index 53ade5c4c..141256fb3 100644
--- a/src/esengine/bindings/PhysicsContext.hpp
+++ b/src/esengine/bindings/PhysicsContext.hpp
@@ -47,6 +47,18 @@ struct PhysicsContext {
std::vector<float> dynamicTransformBuffer;
+ // Render interpolation, kept here rather than in JS: the two most recent
+ // fixed-step poses and the lerped result, all in the same flat
+ // [entityBits, x, y, angle] layout the readback hands out. A per-body object
+ // graph on the JS side would put a 5000-iteration hot loop on the every-frame
+ // path, which the no-JIT budget forbids (docs/REARCH_NATIVE.md §3.2).
+ std::vector<float> posePrev;
+ std::vector<float> poseCur;
+ std::vector<float> poseInterpolated;
+ // Maps entity -> index into posePrev, built lazily and only when the body set
+ // changed between the two snapshots; steady state matches by position instead.
+ std::unordered_map<uint32_t, uint32_t> posePrevIndex;
+
std::vector<float> collisionEnterBuffer;
std::vector<float> collisionExitBuffer;
std::vector<float> sensorEnterBuffer;
@@ -65,6 +77,10 @@ struct PhysicsContext {
mouseJointId = b2_nullJointId;
dynamicBodyEntities.clear();
dynamicTransformBuffer.clear();
+ posePrev.clear();
+ poseCur.clear();
+ poseInterpolated.clear();
+ posePrevIndex.clear();
collisionEnterBuffer.clear();
collisionExitBuffer.clear();
sensorEnterBuffer.clear();
diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cpp
index 682c42e80..2f3e4cc8b 100644
--- a/src/esengine/bindings/PhysicsModuleEntry.cpp
+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp
@@ -261,6 +261,114 @@ uintptr_t physics_getDynamicBodyTransforms() {
return reinterpret_cast<uintptr_t>(g_ctx.dynamicTransformBuffer.data());
}
+// Render interpolation
+//
+// The snapshot pair and the lerp live here, not in the SDK: interpolation touches
+// every dynamic body every frame, and that is exactly the hot loop the no-JIT
+// budget keeps off the JS path (docs/REARCH_NATIVE.md §3.2). The SDK asks for the
+// finished buffer and hands it straight to the engine's batched Transform sync.
+
+/** The entity id packed into a flat pose buffer at float offset @p offset. */
+static uint32_t poseEntityAt(const std::vector<float>& buf, size_t offset) {
+ uint32_t entityId;
+ std::memcpy(&entityId, &buf[offset], sizeof(uint32_t));
+ return entityId;
+}
+
+/** Shortest-arc angle interpolation (radians), matching the SDK's own lerpAngle. */
+static float lerpAngleShortest(float a, float b, float t) {
+ constexpr float kPi = 3.14159265358979323846f;
+ constexpr float kTwoPi = 2.0f * kPi;
+ float d = std::fmod(b - a, kTwoPi);
+ if (d > kPi) d -= kTwoPi;
+ else if (d < -kPi) d += kTwoPi;
+ return a + d * t;
+}
+
+/**
+ * Promote the current snapshot to `prev` and refill it from the world. Called once
+ * per fixed step, after the step, so the pair always straddles one step.
+ */
+EMSCRIPTEN_KEEPALIVE
+void physics_capturePoses() {
+ g_ctx.posePrev.swap(g_ctx.poseCur);
+ g_ctx.poseCur.clear();
+ g_ctx.posePrevIndex.clear();
+
+ for (uint32_t entityId : g_ctx.dynamicBodyEntities) {
+ auto it = g_ctx.entityToBody.find(entityId);
+ if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) continue;
+ // Same exclusion the readback makes: a disabled body is frozen, and its
+ // stale pose must not be stamped back over a hand-animated Transform.
+ if (!b2Body_IsEnabled(it->second)) continue;
+
+ b2Vec2 pos = b2Body_GetPosition(it->second);
+ float angle = b2Rot_GetAngle(b2Body_GetRotation(it->second));
+
+ pushEntityBits(g_ctx.poseCur, entityId);
+ g_ctx.poseCur.push_back(pos.x);
+ g_ctx.poseCur.push_back(pos.y);
+ g_ctx.poseCur.push_back(angle);
+ }
+}
+
+EMSCRIPTEN_KEEPALIVE
+int physics_getInterpolatedCount() {
+ return static_cast<int>(g_ctx.poseCur.size() / 4);
+}
+
+/**
+ * Interpolate the snapshot pair by @p alpha into a flat [entityBits, x, y, angle]
+ * buffer (physics space) and return it. With alpha = 1 this reproduces a direct
+ * post-step sync.
+ */
+EMSCRIPTEN_KEEPALIVE
+uintptr_t physics_getInterpolatedTransforms(float alpha) {
+ const size_t count = g_ctx.poseCur.size();
+ g_ctx.poseInterpolated.resize(count);
+ if (count == 0) return reinterpret_cast<uintptr_t>(g_ctx.poseInterpolated.data());
+
+ // Steady state (no body created or destroyed since the last step) keeps both
+ // snapshots in the same order, so a body's previous pose sits at its own index
+ // and the whole pass is a linear walk. Only a changed body set pays for a map.
+ const bool sameLayout = g_ctx.posePrev.size() == count;
+ bool indexBuilt = false;
+
+ for (size_t o = 0; o < count; o += 4) {
+ const uint32_t entityId = poseEntityAt(g_ctx.poseCur, o);
+ const float cx = g_ctx.poseCur[o + 1];
+ const float cy = g_ctx.poseCur[o + 2];
+ const float ca = g_ctx.poseCur[o + 3];
+
+ const float* prev = nullptr;
+ if (sameLayout && poseEntityAt(g_ctx.posePrev, o) == entityId) {
+ prev = &g_ctx.posePrev[o];
+ } else if (!g_ctx.posePrev.empty()) {
+ if (!indexBuilt) {
+ for (size_t p = 0; p < g_ctx.posePrev.size(); p += 4) {
+ g_ctx.posePrevIndex[poseEntityAt(g_ctx.posePrev, p)] = static_cast<uint32_t>(p);
+ }
+ indexBuilt = true;
+ }
+ auto it = g_ctx.posePrevIndex.find(entityId);
+ if (it != g_ctx.posePrevIndex.end()) prev = &g_ctx.posePrev[it->second];
+ }
+
+ // A body seen for the first time seeds prev = cur, so it doesn't smear in
+ // from wherever it was spawned.
+ const float px = prev ? prev[1] : cx;
+ const float py = prev ? prev[2] : cy;
+ const float pa = prev ? prev[3] : ca;
+
+ std::memcpy(&g_ctx.poseInterpolated[o], &entityId, sizeof(uint32_t));
+ g_ctx.poseInterpolated[o + 1] = px + (cx - px) * alpha;
+ g_ctx.poseInterpolated[o + 2] = py + (cy - py) * alpha;
+ g_ctx.poseInterpolated[o + 3] = lerpAngleShortest(pa, ca, alpha);
+ }
+
+ return reinterpret_cast<uintptr_t>(g_ctx.poseInterpolated.data());
+}
+
// Collision Events
EMSCRIPTEN_KEEPALIVE
diff --git a/src/esengine/bindings/PhysicsReadback.cpp b/src/esengine/bindings/PhysicsReadback.cpp
index 05ba62789..2bcd9df5f 100644
--- a/src/esengine/bindings/PhysicsReadback.cpp
+++ b/src/esengine/bindings/PhysicsReadback.cpp
@@ -36,6 +36,10 @@ EMSCRIPTEN_KEEPALIVE size_t physics_dynamicBodyTransformsBytes() {
return floatBytes(g_ctx.dynamicTransformBuffer);
}
+EMSCRIPTEN_KEEPALIVE size_t physics_interpolatedTransformsBytes() {
+ return floatBytes(g_ctx.poseInterpolated);
+}
+
EMSCRIPTEN_KEEPALIVE size_t physics_collisionEnterBytes() {
return floatBytes(g_ctx.collisionEnterBuffer);
}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 642c27b29..78b6617ae 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -236,3 +236,25 @@ set(_es_safety_asan $<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>,$<CXX_C
target_compile_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
target_link_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
add_test(NAME test_registry_safety COMMAND test_registry_safety)
+
+# Physics render interpolation. The snapshot pair and the lerp live in the physics
+# module, not the SDK: they touch every dynamic body every frame, which the no-JIT
+# budget keeps off the JS path (docs/REARCH_NATIVE.md §3.2). The whole module is
+# compiled in because its entry TU calls into the shape/joint/query ones.
+if(ES_ENABLE_BOX2D)
+ add_executable(test_physics_interpolation
+ bindings/test_physics_interpolation.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsModuleEntry.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsReadback.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsContext.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsShapes.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsJoints.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/bindings/PhysicsQueries.cpp
+ )
+ target_link_libraries(test_physics_interpolation PRIVATE box2d)
+ target_include_directories(test_physics_interpolation PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/box2d/include
+ )
+ add_test(NAME test_physics_interpolation COMMAND test_physics_interpolation)
+endif()
diff --git a/tests/bindings/test_physics_interpolation.cpp b/tests/bindings/test_physics_interpolation.cpp
new file mode 100644
index 000000000..9575b457b
--- /dev/null
+++ b/tests/bindings/test_physics_interpolation.cpp
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// Render interpolation of physics poses. The snapshot pair and the lerp belong to
+// the module rather than the SDK — they run over every dynamic body every frame,
+// which the no-JIT budget bars from the JS path (docs/REARCH_NATIVE.md §3.2) — so
+// the semantics the SDK used to own are pinned here: the midpoint, a first-frame
+// body that must not smear, the ±π short arc, and matching a body to its previous
+// pose after the body set changed.
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include <doctest.h>
+
+#include "esengine/bindings/PhysicsBindings.hpp"
+#include "esengine/bindings/PhysicsContext.hpp"
+
+#include <cmath>
+#include <cstdint>
+#include <vector>
+
+namespace {
+
+constexpr float kPi = 3.14159265358979323846f;
+
+void resetSnapshots() {
+ g_ctx.posePrev.clear();
+ g_ctx.poseCur.clear();
+ g_ctx.poseInterpolated.clear();
+ g_ctx.posePrevIndex.clear();
+}
+
+void appendPose(std::vector<float>& buf, uint32_t entityId, float x, float y, float angle) {
+ pushEntityBits(buf, entityId);
+ buf.push_back(x);
+ buf.push_back(y);
+ buf.push_back(angle);
+}
+
+const float* interpolate(float alpha) {
+ return reinterpret_cast<const float*>(physics_getInterpolatedTransforms(alpha));
+}
+
+uint32_t entityAt(const float* buf, size_t body) {
+ uint32_t id;
+ std::memcpy(&id, buf + body * 4, sizeof(uint32_t));
+ return id;
+}
+
+} // namespace
+
+TEST_CASE("lerps prev to cur by alpha") {
+ resetSnapshots();
+ appendPose(g_ctx.posePrev, 7, 0.0f, 0.0f, 0.0f);
+ appendPose(g_ctx.poseCur, 7, 4.0f, 8.0f, 0.0f);
+
+ const float* out = interpolate(0.5f);
+ REQUIRE(physics_getInterpolatedCount() == 1);
+ CHECK(entityAt(out, 0) == 7u);
+ CHECK(out[1] == doctest::Approx(2.0f));
+ CHECK(out[2] == doctest::Approx(4.0f));
+}
+
+TEST_CASE("alpha of 1 reproduces a direct post-step sync") {
+ resetSnapshots();
+ appendPose(g_ctx.posePrev, 3, -1.0f, 5.0f, 0.25f);
+ appendPose(g_ctx.poseCur, 3, 2.0f, 9.0f, 1.25f);
+
+ const float* out = interpolate(1.0f);
+ CHECK(out[1] == doctest::Approx(2.0f));
+ CHECK(out[2] == doctest::Approx(9.0f));
+ CHECK(out[3] == doctest::Approx(1.25f));
+}
+
+TEST_CASE("a body on its first frame does not smear") {
+ resetSnapshots();
+ // No previous snapshot at all: the body was created this step.
+ appendPose(g_ctx.poseCur, 11, 5.0f, 6.0f, 0.75f);
+
+ const float* out = interpolate(0.5f);
+ CHECK(out[1] == doctest::Approx(5.0f));
+ CHECK(out[2] == doctest::Approx(6.0f));
+ CHECK(out[3] == doctest::Approx(0.75f));
+}
+
+TEST_CASE("angle takes the short way across the plus-minus pi wrap") {
+ resetSnapshots();
+ appendPose(g_ctx.posePrev, 1, 0.0f, 0.0f, kPi - 0.1f);
+ appendPose(g_ctx.poseCur, 1, 0.0f, 0.0f, -kPi + 0.1f);
+
+ const float* out = interpolate(0.5f);
+ // Crossing pi, not sweeping back through zero.
+ CHECK(std::fabs(out[3]) == doctest::Approx(kPi).epsilon(0.01));
+}
+
+TEST_CASE("a body keeps its own previous pose when the body set changed") {
+ resetSnapshots();
+ // Previous step held two bodies; the first was destroyed, so entity 9 has moved
+ // to index 0 and the fast same-index match no longer lines up.
+ appendPose(g_ctx.posePrev, 4, 100.0f, 100.0f, 0.0f);
+ appendPose(g_ctx.posePrev, 9, 0.0f, 0.0f, 0.0f);
+ appendPose(g_ctx.poseCur, 9, 10.0f, 20.0f, 0.0f);
+
+ const float* out = interpolate(0.5f);
+ REQUIRE(physics_getInterpolatedCount() == 1);
+ CHECK(entityAt(out, 0) == 9u);
+ // Interpolated against entity 9's own previous pose, not entity 4's.
+ CHECK(out[1] == doctest::Approx(5.0f));
+ CHECK(out[2] == doctest::Approx(10.0f));
+}
+
+TEST_CASE("no bodies yields an empty buffer") {
+ resetSnapshots();
+ interpolate(0.5f);
+ CHECK(physics_getInterpolatedCount() == 0);
+}