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.

feat(physics): FixedUpdate determinism + render interpolation (P1) + audit doc

esengineb1cf164f4e61
diff --git a/docs/REARCH_PHYSICS.md b/docs/REARCH_PHYSICS.md
new file mode 100644
index 000000000..fe8362dab
--- /dev/null
+++ b/docs/REARCH_PHYSICS.md
@@ -0,0 +1,94 @@
+# Physics Architecture — Audit & Rearchitecture
+
+**Status (2026-06-21):** audit complete; **P1 in progress** (FixedUpdate determinism +
+render interpolation). Physics core = **Box2D 3.2.0** (the v3 rewrite) in a side wasm
+module (`third_party/box2d`, C++ bindings `src/esengine/bindings/Physics*.cpp`), wrapped
+by the TS SDK (`sdk/src/physics/*`).
+
+## Verdict
+
+**The engine choice is state-of-the-art (Box2D v3.2 = the SOTA 2D physics, a peer of
+Rapier2D). The integration has modern foundations but three real gaps keep it below
+top-tier (Bevy+rapier / Unity DOTS Physics).** No engine swap is warranted — the work is
+in the integration layer.
+
+### Already modern — do not churn
+
+- v3 C-handle API (`b2WorldId`/`b2BodyId`/`b2ShapeId`/`b2JointId`); no v2 pointers.
+- Buffered event model: `b2World_GetContactEvents` / `b2World_GetSensorEvents` — the v2
+ `b2ContactListener` pattern is fully absent.
+- Frame-based joint defs (`base.localFrameA/B`) for all five joints; v3 motion locks
+ (not v2 `fixedRotation`); per-body `isBullet` continuous.
+- Sub-stepping wired (`b2World_Step(dt, subStepCount)`, default 4 substeps).
+- Native broadphase queries (`CastRay`/`OverlapShape`/`CastShape`/`OverlapAABB`) — no
+ manual AABB walking.
+- **Batched transform read-back** through a shared HEAP buffer
+ `[u32 entity, f32 x, y, angle]` + a single `registry_batchSyncPhysicsTransforms`
+ apply — the #1 thing wasm physics bridges get wrong, done right here.
+- Data-only ECS components keyed by entity id (no wasm handles in components —
+ Bevy/DOTS-correct); generation-safe handles (`b2*_IsValid`); clean lifecycle/teardown;
+ `playModeOnly` gating; entity↔body via `b2Body_SetUserData`.
+
+## The three gaps that matter (ranked)
+
+1. **Determinism defect.** Physics steps in `Schedule.PostUpdate` on a *variable* wall-clock
+ `time.delta`, not on the fixed-step schedule. There are two accumulators: a dead TS one
+ (`app.ts:581-592` `FixedUpdate` — zero SDK registrations) and the live C++ one
+ (`PhysicsModuleEntry.cpp:106-117`). Substep *count* per frame varies with framerate
+ (144 Hz vs 60 Hz) → not frame/replay-deterministic.
+2. **No render interpolation (the "looks naive" tell).** The C++ accumulator remainder is
+ trapped; no prev+current pose, no lerp. Default physics 30 Hz vs a 60/144 Hz display →
+ visible stutter.
+3. **Colliders / joints / `RigidBody.enabled` are create-only.** Shapes are built once
+ (`PhysicsSystem.ts:555`); editing a collider at runtime does nothing (no
+ change-detection, no shape rebuild). Blocks the editor's live-edit story.
+
+### Secondary gaps
+
+- Ignores `b2World_GetBodyEvents` (moved-only read-back) — re-reads every dynamic body,
+ including sleeping ones, each frame.
+- No contact *hit* events (`enableHitEvents` / `hitEventThreshold` unused) — no impact speed.
+- Chatty *writeback* (per-body `_physics_setBodyTransform` / `updateBodyProperties`); only
+ the read-back is batched.
+- Identity leaks: joints keyed by `entityB` (silent overwrite, `PhysicsJoints.cpp:35`);
+ chain `b2ChainId` discarded (`PhysicsShapes.cpp:174`).
+- World toggles hardcoded to `b2DefaultWorldDef()` (sleeping / continuous / restitution
+ threshold / warm-starting / max linear speed not surfaced) — **overlaps the deferred
+ physics project-settings work** (the settings UI needs these knobs to exist).
+- Query `ppu` defaulted to 100 per-call instead of the live `Canvas.pixelsPerUnit`
+ (silent wrong-scale footgun, `Physics.ts:145`).
+- `enableContactEvents = true` on every shape; single-threaded (`workerCount` unused — fine
+ for the wasm target today).
+
+## Phased plan
+
+- **P1 — FixedUpdate determinism + render interpolation (together).** Highest correctness +
+ visible-quality win. SDK-only (no wasm rebuild). See below.
+- **P2 — runtime collider/joint/`enabled` mutability.** Unblocks editor live-edit and the
+ physics project-settings.
+- **P3 — `b2World_GetBodyEvents` + contact hit events + world-toggle config surface** (the
+ config surface feeds the project-settings flow). Touches C++.
+- **P4 — batched writeback + identity-leak fixes + query `ppu` from live Canvas.**
+
+## P1 — design (SDK-only)
+
+The engine already has a correct fixed-step accumulator (`app.ts:581-592`,
+`fixedTimestep_ = 1/60`); after the fixed loop, `fixedAccumulator_` is the interpolation
+remainder. P1 puts physics on that seam and interpolates the render pose — no C++ change.
+
+1. **Expose the seam on `Time`.** Add `fixedDelta` (= `fixedTimestep_`) and `fixedAlpha`
+ (= `fixedAccumulator_ / fixedTimestep_`, 0..1, set after the fixed loop) to the `Time`
+ resource, plus an `app.getFixedTimestep()` getter.
+2. **Align cadences.** The physics fixed timestep is set to the engine's
+ (`getFixedTimestep()`) so one `FixedUpdate` tick = exactly one `b2World_Step`, and
+ `fixedAlpha` is the true fraction within a single physics step.
+3. **Step in `FixedUpdate`.** A step system (`Schedule.FixedUpdate`, `playModeOnly`)
+ reconciles bodies, pushes pending writes, `_physics_step(fixedDelta)` (one C++ step),
+ collects events, then captures pose snapshots: `prev = last cur`, `cur = read-back`.
+4. **Interpolate in `PostUpdate`.** A sync system lerps `prev → cur` by `Time.fixedAlpha`
+ (linear x/y, shortest-arc angle) into a buffer applied via the existing batched
+ `registry_batchSyncPhysicsTransforms` (+ the parented-body path). New bodies seed
+ `prev = cur` (no first-frame smear); teleports snap.
+
+**Result:** framerate-independent substep count (deterministic) + smooth render at any
+display rate. Lands the integration layer at "modern" to match the SOTA core.
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index b93056d20..86f9e2fc7 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -337,6 +337,11 @@ export class App {
return this;
}
+ /** The fixed-update timestep (seconds) — the FixedUpdate / physics cadence. */
+ getFixedTimestep(): number {
+ return this.fixedTimestep_;
+ }
+
setMaxDeltaTime(v: number): this {
this.maxDeltaTime_ = v;
return this;
@@ -469,7 +474,7 @@ export class App {
this.runner_.setTimingEnabled(true);
}
if (!this.resources_.has(Time)) {
- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
+ this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0, fixedDelta: this.fixedTimestep_, fixedAlpha: 0 });
}
this.finishPlugins_();
}
@@ -490,7 +495,7 @@ export class App {
this.runner_.setTimingEnabled(true);
}
if (!this.resources_.has(Time)) {
- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
+ this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0, fixedDelta: this.fixedTimestep_, fixedAlpha: 0 });
}
this.finishPlugins_();
}
@@ -590,6 +595,10 @@ export class App {
if (fixedSteps >= this.maxFixedSteps_) {
this.fixedAccumulator_ = this.fixedTimestep_;
}
+ // Remainder fraction into the current fixed step — render-time systems
+ // (physics interpolation) lerp prev→current by this for smooth motion.
+ this.resources_.get(Time).fixedAlpha =
+ this.fixedTimestep_ > 0 ? this.fixedAccumulator_ / this.fixedTimestep_ : 0;
await this.runSchedule(Schedule.PreUpdate);
await this.runSchedule(Schedule.Update);
@@ -841,6 +850,7 @@ export class App {
time.delta = delta;
time.elapsed += delta;
time.frameCount++;
+ time.fixedDelta = this.fixedTimestep_;
}
}
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index dc5e6cc7a..b3d62cc7c 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -285,34 +285,84 @@ const syncTransformBuf_ = {
const PHYSICS_BODY_STRIDE = 4; // u32 entity + 3x f32 (x, y, angle)
const PHYSICS_BODY_BYTES = PHYSICS_BODY_STRIDE * 4;
-/** @internal exported for testing */
-export function syncDynamicTransforms(
+/** 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.
+ * @internal exported for testing
+ */
+export function applyPhysicsTransforms(
app: App,
- module: PhysicsWasmModule,
ppu: number,
parentedBodies: Set<Entity>,
+ snaps: PoseSnapshots,
+ alpha: number,
): void {
- const count = module._physics_getDynamicBodyCount();
+ const cur = snaps.cur;
+ const count = cur.size;
if (count === 0) return;
- const ptr = module._physics_getDynamicBodyTransforms();
- const baseU32 = ptr >> 2;
- const physU32 = module.HEAPU32;
- const physF32 = module.HEAPF32;
-
const registry = app.world.getCppRegistry();
if (!registry) return;
-
const engineMod = app.world.getWasmModule();
const hasParented = parentedBodies.size > 0;
+ // Batched fast path: build [u32 entity, f32 x, y, angle] (meters) interpolated.
if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {
- const byteLen = count * PHYSICS_BODY_BYTES;
- withMalloc(engineMod, byteLen, engineBuf => {
- engineMod.HEAPU8.set(
- new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),
- engineBuf,
- );
+ 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;
@@ -322,28 +372,22 @@ export function syncDynamicTransforms(
? (e: Entity) => engineMod!.getTransformPtr(registry!, e as number)
: null;
const engF32 = engineMod?.HEAPF32;
- const addFn = (!getTransformPtr || !engF32)
- ? registry.addTransform.bind(registry)
- : null;
-
+ const addFn = (!getTransformPtr || !engF32) ? registry.addTransform.bind(registry) : null;
const t = syncTransformBuf_;
- for (let i = 0; i < count; i++) {
- const offset = baseU32 + i * PHYSICS_BODY_STRIDE;
- const entityId = physU32[offset] as Entity;
- let localX = physF32[offset + 1] * ppu;
- let localY = physF32[offset + 2] * ppu;
- let localAngle = physF32[offset + 3];
+ 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);
if (hasParented && parentedBodies.has(entityId)) {
const parentData = app.world.get(entityId, Parent) as ParentData;
if (parentData && app.world.valid(parentData.entity) && app.world.has(parentData.entity, Transform)) {
const pwt = app.world.get(parentData.entity, Transform) as TransformData;
const parentAngleZ = quatToAngleZ(pwt.worldRotation);
- const worldX = localX;
- const worldY = localY;
- const dx = worldX - pwt.worldPosition.x;
- const dy = worldY - pwt.worldPosition.y;
+ const dx = localX - pwt.worldPosition.x;
+ const dy = localY - pwt.worldPosition.y;
const cos = Math.cos(-parentAngleZ);
const sin = Math.sin(-parentAngleZ);
const sx = pwt.worldScale.x !== 0 ? pwt.worldScale.x : 1;
@@ -407,16 +451,27 @@ export function syncDynamicTransforms(
// Collision event drain
// =============================================================================
-function collectEvents(app: App, module: PhysicsWasmModule, ppu: number): void {
+interface EventAccum {
+ collisionEnters: CollisionEnterEvent[];
+ collisionExits: Array<{ entityA: Entity; entityB: Entity }>;
+ sensorEnters: SensorEvent[];
+ sensorExits: SensorEvent[];
+}
+
+/**
+ * Drain this fixed step's events into the per-frame accumulator. Physics may step
+ * several times per rendered frame; accumulating (rather than overwriting) keeps
+ * every collision — the interpolation system publishes + clears once per frame.
+ */
+function collectEvents(module: PhysicsWasmModule, ppu: number, accum: EventAccum): void {
module._physics_collectEvents();
- const collisionEnters: CollisionEnterEvent[] = [];
const enterCount = module._physics_getCollisionEnterCount();
if (enterCount > 0) {
const enterPtr = module._physics_getCollisionEnterBuffer() >> 2;
for (let i = 0; i < enterCount; i++) {
const base = enterPtr + i * COLLISION_EVENT_STRIDE;
- collisionEnters.push({
+ accum.collisionEnters.push({
entityA: module.HEAPU32[base] as Entity,
entityB: module.HEAPU32[base + 1] as Entity,
normalX: module.HEAPF32[base + 2],
@@ -427,51 +482,41 @@ function collectEvents(app: App, module: PhysicsWasmModule, ppu: number): void {
}
}
- const collisionExits: Array<{ entityA: Entity; entityB: Entity }> = [];
const exitCount = module._physics_getCollisionExitCount();
if (exitCount > 0) {
const exitPtr = module._physics_getCollisionExitBuffer() >> 2;
for (let i = 0; i < exitCount; i++) {
const base = exitPtr + i * 2;
- collisionExits.push({
+ accum.collisionExits.push({
entityA: module.HEAPU32[base] as Entity,
entityB: module.HEAPU32[base + 1] as Entity,
});
}
}
- const sensorEnters: SensorEvent[] = [];
const sensorEnterCount = module._physics_getSensorEnterCount();
if (sensorEnterCount > 0) {
const sensorEnterPtr = module._physics_getSensorEnterBuffer() >> 2;
for (let i = 0; i < sensorEnterCount; i++) {
const base = sensorEnterPtr + i * 2;
- sensorEnters.push({
+ accum.sensorEnters.push({
sensorEntity: module.HEAPU32[base] as Entity,
visitorEntity: module.HEAPU32[base + 1] as Entity,
});
}
}
- const sensorExits: SensorEvent[] = [];
const sensorExitCount = module._physics_getSensorExitCount();
if (sensorExitCount > 0) {
const sensorExitPtr = module._physics_getSensorExitBuffer() >> 2;
for (let i = 0; i < sensorExitCount; i++) {
const base = sensorExitPtr + i * 2;
- sensorExits.push({
+ accum.sensorExits.push({
sensorEntity: module.HEAPU32[base] as Entity,
visitorEntity: module.HEAPU32[base + 1] as Entity,
});
}
}
-
- app.insertResource(PhysicsEvents, {
- collisionEnters,
- collisionExits,
- sensorEnters,
- sensorExits
- });
}
// =============================================================================
@@ -502,6 +547,12 @@ 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: [], sensorEnters: [], sensorExits: [] };
+ const fixedDt = config.fixedTimestep;
const world = app.world;
@@ -515,14 +566,19 @@ export function registerPhysicsSystem(
trackedEntities.delete(entity);
cachedProps.delete(entity);
parentedBodies.delete(entity);
+ snaps.prev.delete(entity);
+ snaps.cur.delete(entity);
}
});
+ // ── Step + capture (fixed cadence) ──────────────────────────────────────
+ // Runs in FixedUpdate (fixed dt, framerate-independent → deterministic step
+ // count). Reconciles bodies, steps Box2D once, drains events, snapshots poses.
app.addSystemToSchedule(
- Schedule.PostUpdate,
+ Schedule.FixedUpdate,
defineSystem(
- [Res(Time)],
- (time: TimeData) => {
+ [],
+ () => {
// Read pixelsPerUnit live each tick so a Canvas property
// change at runtime (editor: user edits Canvas.pixelsPerUnit)
// propagates to physics transforms instead of staying at the
@@ -615,14 +671,42 @@ export function registerPhysicsSystem(
createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);
- if (trackedEntities.size > 0 && time.delta > 0) {
- module._physics_step(time.delta);
+ if (trackedEntities.size > 0) {
+ module._physics_step(fixedDt);
}
- syncDynamicTransforms(app, module, ppu, parentedBodies);
- collectEvents(app, module, ppu);
+ collectEvents(module, ppu, events);
+ capturePhysicsPoses(module, snaps);
+ },
+ { name: 'PhysicsStepSystem' }
+ ),
+ { runIf: playModeOnly }
+ );
+
+ // ── Interpolate + publish (render cadence) ──────────────────────────────
+ // Runs once per rendered frame in PostUpdate: publishes the frame's events,
+ // then writes interpolated (prev→cur by Time.fixedAlpha) poses to Transforms.
+ app.addSystemToSchedule(
+ Schedule.PostUpdate,
+ defineSystem(
+ [Res(Time)],
+ (time: TimeData) => {
+ app.insertResource(PhysicsEvents, {
+ collisionEnters: events.collisionEnters,
+ collisionExits: events.collisionExits,
+ sensorEnters: events.sensorEnters,
+ sensorExits: events.sensorExits,
+ });
+ // Fresh arrays for next frame; the published ones stay live on the resource.
+ events.collisionEnters = [];
+ events.collisionExits = [];
+ events.sensorEnters = [];
+ events.sensorExits = [];
+
+ const ppu = readPixelsPerUnit(app);
+ applyPhysicsTransforms(app, ppu, parentedBodies, snaps, time.fixedAlpha);
},
- { name: 'PhysicsSystem' }
+ { name: 'PhysicsInterpolateSystem' }
),
{ runIf: playModeOnly }
);
diff --git a/sdk/src/resource.ts b/sdk/src/resource.ts
index 777245566..b8f9408db 100644
--- a/sdk/src/resource.ts
+++ b/sdk/src/resource.ts
@@ -156,11 +156,22 @@ export interface TimeData {
delta: number;
elapsed: number;
frameCount: number;
+ /** Fixed-update timestep in seconds — the FixedUpdate / physics cadence. */
+ fixedDelta: number;
+ /**
+ * Interpolation factor in [0, 1) into the current fixed step
+ * (fixedAccumulator / fixedDelta), set after the fixed-update loop each
+ * frame. Render-time systems lerp prev→current state by this to smooth
+ * fixed-step simulation (e.g. physics) onto the variable render rate.
+ */
+ fixedAlpha: number;
}
export const Time = defineResource<TimeData>({
delta: 0,
elapsed: 0,
- frameCount: 0
+ frameCount: 0,
+ fixedDelta: 1 / 60,
+ fixedAlpha: 0,
}, 'Time');
diff --git a/sdk/tests/physicsSyncTransforms.test.ts b/sdk/tests/physicsSyncTransforms.test.ts
index 27d80b301..ae0415a51 100644
--- a/sdk/tests/physicsSyncTransforms.test.ts
+++ b/sdk/tests/physicsSyncTransforms.test.ts
@@ -3,10 +3,27 @@ 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 { syncDynamicTransforms } from '../src/physics/PhysicsSystem';
+import {
+ capturePhysicsPoses,
+ applyPhysicsTransforms,
+ type PoseSnapshots,
+} 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).
+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);
+}
+
// =============================================================================
// Helpers
// =============================================================================
@@ -89,7 +106,7 @@ describe('syncDynamicTransforms', () => {
const physMod = createMockPhysicsModule(buf);
const parentedBodies = new Set<Entity>();
- syncDynamicTransforms(app, physMod, PPU, parentedBodies);
+ sync(app, physMod, PPU, parentedBodies);
const t = app.world.get(e1, Transform) as TransformData;
expect(t.position.x).toBeCloseTo(350);
@@ -107,7 +124,7 @@ describe('syncDynamicTransforms', () => {
]);
const physMod = createMockPhysicsModule(buf);
- syncDynamicTransforms(app, physMod, PPU, new Set());
+ sync(app, physMod, PPU, new Set());
const t = app.world.get(e1, Transform) as TransformData;
const half = angle * 0.5;
@@ -133,7 +150,7 @@ describe('syncDynamicTransforms', () => {
]);
const physMod = createMockPhysicsModule(buf);
- syncDynamicTransforms(app, physMod, PPU, new Set());
+ sync(app, physMod, PPU, new Set());
expect((app.world.get(e1, Transform) as TransformData).position.x).toBeCloseTo(100);
expect((app.world.get(e2, Transform) as TransformData).position.x).toBeCloseTo(300);
@@ -151,7 +168,7 @@ describe('syncDynamicTransforms', () => {
]);
const physMod = createMockPhysicsModule(buf);
- syncDynamicTransforms(app, physMod, PPU, new Set());
+ sync(app, physMod, PPU, new Set());
const t = app.world.get(e1, Transform) as TransformData;
expect(t.position.x).toBeCloseTo(500);
@@ -166,7 +183,7 @@ describe('syncDynamicTransforms', () => {
const buf = buildPhysicsBuffer([]);
const physMod = createMockPhysicsModule(buf);
- syncDynamicTransforms(app, physMod, PPU, new Set());
+ sync(app, physMod, PPU, new Set());
const t = app.world.get(e1, Transform) as TransformData;
expect(t.position.x).toBeCloseTo(42);
@@ -193,7 +210,7 @@ describe('syncDynamicTransforms', () => {
const buf = buildPhysicsBuffer(bodies);
const physMod = createMockPhysicsModule(buf);
- syncDynamicTransforms(app, physMod, PPU, new Set());
+ sync(app, physMod, PPU, new Set());
const t0 = app.world.get(entities[0], Transform) as TransformData;
expect(t0.position.x).toBeCloseTo(0);
@@ -225,7 +242,7 @@ describe('syncDynamicTransforms — fast path', () => {
}
const buf = buildPhysicsBuffer(bodies.map((b, i) => ({ entity: entities[i] as number, ...b })));
- syncDynamicTransforms(app, createMockPhysicsModule(buf), PPU, new Set());
+ sync(app, createMockPhysicsModule(buf), PPU, new Set());
for (let i = 0; i < bodies.length; i++) {
const t = app.world.get(entities[i], Transform) as TransformData;
@@ -249,10 +266,75 @@ describe('syncDynamicTransforms — fast path', () => {
const physMod = createMockPhysicsModule(buf);
const parentedBodies = new Set<Entity>([e1]);
- syncDynamicTransforms(app, physMod, PPU, parentedBodies);
+ sync(app, physMod, PPU, parentedBodies);
const t = app.world.get(e1, Transform) as TransformData;
expect(t.position.x).toBeCloseTo(200);
expect(t.position.y).toBeCloseTo(300);
});
});
+
+describe('render interpolation', () => {
+ const PPU = 100;
+
+ it('lerps prev→cur by alpha (midpoint at 0.5)', () => {
+ 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);
+
+ applyPhysicsTransforms(app, PPU, new Set(), snaps, 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
+ });
+
+ it('does not smear a body on its first frame (prev seeded to cur)', () => {
+ 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);
+ });
+
+ it('interpolates angle the short way across the ±π wrap', () => {
+ 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);
+
+ applyPhysicsTransforms(app, PPU, new Set(), snaps, 0.5);
+
+ // 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);
+ });
+});