Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add live physics runtime system over an engine adapter (part of #771)

Nguyen Xuan An50af7f3511de
diff --git a/README.md b/README.md
index 43a5cca3..149908e6 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline |
| Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
+| Live games | `67js/addons/physics-runtime` | [Live physics](docs/physics-runtime.md): a physics world stepped in the game loop, contact and sensor events, ray, shape and overlap queries |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --git a/changes/771.md b/changes/771.md
new file mode 100644
index 00000000..b3e1bbfe
--- /dev/null
+++ b/changes/771.md
@@ -0,0 +1 @@
+- `67js/addons/physics-runtime` adds `createPhysicsSystem`, live physics as a runtime system over an engine adapter (Rapier first): stepped in `fixedUpdate`, contact and sensor events, kinematic control, ray, shape-cast and overlap queries, and interpolated part matrices (part of #771)
diff --git a/docs/physics-runtime.md b/docs/physics-runtime.md
new file mode 100644
index 00000000..a89169d2
--- /dev/null
+++ b/docs/physics-runtime.md
@@ -0,0 +1,88 @@
+# Live physics
+
+`67js/addons/physics-runtime` steps a physics world inside the [game loop](runtime.md). The recorded bake in [physics.md](physics.md) renders a film; this is for a browser game, where code pushes bodies, reads contacts and casts rays every frame. Both paths build the world with the same function, so a scene behaves the same on either.
+
+```js
+import { Renderer67 } from '67js';
+import { createRuntime } from '67js/addons/runtime';
+import { createPhysicsSystem } from '67js/addons/physics-runtime';
+
+const physics = await createPhysicsSystem({
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'crate', translation: [0, 3, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10] },
+ { name: 'crate', body: 'crate', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ ],
+});
+physics.bind('crate', cratePart);
+physics.on('contact', event => event.started && playThud(event.bodyA, event.bodyB));
+
+const runtime = createRuntime(renderer, { fixedStepSeconds: physics.timestep, systems: [physics] });
+runtime.start();
+```
+
+The definition is the one `createPhysicsScene` takes, without `events` (a live game has no tick script; call the methods below instead). Joints, force fields, sensors, collision groups and masks work as in [physics.md](physics.md).
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `adapter` | `rapierAdapter` | The engine, see below |
+| `timestep` | `1/60` | Seconds per step. The runtime's `fixedStepSeconds` must equal it; a mismatch throws and says which value to pass. |
+| `bindings` | `[]` | `[{ body, part }]`, same as `physics.bind` |
+| `name` | `'physics'` | The runtime system name |
+| `solverIterations`, `maxBodies`, `maxColliders`, `maxJoints` | as in physics.md | Bounds and solver quality |
+
+Put the system after input and before animation and game code in `systems`.
+
+## Control
+
+- `setKinematicPose(body, { translation, rotation })` moves a `kinematic` body; the world sees the move in the next step, and dynamic bodies resting on it are carried.
+- `applyImpulse(body, impulse, point?)` and `setLinearVelocity(body, velocity)` act on a `dynamic` body.
+- `getPose(body)` returns `{ translation, rotation }` as of the last step.
+- `bind(body, part)` writes the body's pose to `part.matrix` (a retained `Float32Array(16)`, scale is kept). In `'both'` mode the pose is interpolated with `context.alpha`, so a 30 Hz simulation looks smooth on a 144 Hz screen.
+
+## Events
+
+`physics.on('contact', listener)` and `physics.on('sensor', listener)` return an unsubscribe function. After each step the listeners get, per pair:
+
+```js
+{ step, kind: 'contact' | 'sensor', started, colliderA, colliderB, bodyA, bodyB }
+```
+
+`started` is `true` when two colliders begin touching and `false` when they stop. A pair with a sensor collider is `'sensor'`. Within a pair `colliderA` is the lower collider index, and a step's events are sorted by `(colliderA, colliderB, started first)`, so every adapter fires the same sequence. `physics.events` holds the last step's events; `physics.eventsTruncated` is set if more than `maxContactEvents` (4096) arrived in one step.
+
+## Queries
+
+They read the world as the last step left it. Every query takes optional `{ mask, excludeBody, includeSensors }`: `mask` is a collision-group mask (0 to 65535), `excludeBody` skips one body (for example the player), and sensors are skipped unless `includeSensors` is `true`.
+
+- `raycast(origin, direction, { maxDistance = 1000 })` returns the first hit or `null`: `{ body, collider, distance, point, normal }`. The direction need not be a unit vector.
+- `shapeCast(shape, translation, direction, { maxDistance, rotation })` sweeps a shape and returns the first hit in the same form; `distance` is how far the shape's centre travelled.
+- `overlap(shape, translation, { rotation })` returns the sorted names of the bodies that touch the shape.
+
+A shape is `{ type: 'ball', radius }`, `{ type: 'cuboid', halfExtents }` or `{ type: 'capsule', halfHeight, radius }`.
+
+## Engines
+
+An adapter is `{ name, load?(), createWorld(prepared) }`. `prepared` is the validated scene (bodies, colliders, joints, fields, gravity). `createWorld` returns:
+
+```js
+{
+ step(stepSeconds, elapsedSeconds), readPose(bodyIndex, out7), free(),
+ setKinematicPose(bodyIndex, translation, rotation), setLinearVelocity(bodyIndex, velocity), applyImpulse(bodyIndex, impulse, point),
+ drainEvents(callback(colliderIndexA, colliderIndexB, started)),
+ raycast(origin, unitDirection, maxDistance, filter), shapeCast(shape, translation, rotation, unitDirection, maxDistance, filter),
+ overlap(shape, translation, rotation, filter),
+}
+```
+
+Bodies and colliders are addressed by their index in the definition; the system maps indices to names, validates every argument and orders events. `rapierAdapter` (Rapier, already a dependency of the physics addon) is the one adapter shipped today. The tests run the system over a scripted adapter to prove it reads nothing else.
+
+## Limits
+
+At most 64 listeners per kind, 4096 bound parts, 1024 overlap results and a query distance up to 1,000,000. Counts of bodies, colliders and joints follow physics.md. `dispose()` (the runtime calls it) frees the world.
+
+Measured on one machine, 500 dynamic boxes settling on a floor with Rapier: about 3 ms per step (`tests/physics-runtime.test.js` prints the figure). Other engines are not shipped yet.
diff --git a/docs/runtime.md b/docs/runtime.md
index f76e3cd4..e4fb1f72 100644
--- a/docs/runtime.md
+++ b/docs/runtime.md
@@ -58,7 +58,7 @@ The first argument is any object with `render(frame)`, such as `Renderer67`.
## System interface
-Physics, input, player, animation graph, audio and game code plug in as systems. A system is a plain object. Only `name` is required; leave out any hook it does not need.
+Physics ([live physics](physics-runtime.md)), input ([input](input.md)), player, animation graph, audio and game code plug in as systems. A system is a plain object. Only `name` is required; leave out any hook it does not need.
```js
const system = {
diff --git a/package.json b/package.json
index 3a073c50..69817da6 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"docs/physics.md",
"docs/runtime.md",
"docs/input.md",
+ "docs/physics-runtime.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -120,6 +121,7 @@
"./addons/cloth": "./build/cloth.js",
"./addons/runtime": "./build/runtime.js",
"./addons/input": "./build/input.js",
+ "./addons/physics-runtime": "./build/physics-runtime.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index c1736dd8..3b90ba6d 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -53,7 +53,7 @@ const sourceDocuments = [
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'runtime.md', 'input.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
+ 'runtime.md', 'input.md', 'physics-runtime.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/src/docs-live.js b/src/docs-live.js
index d98ebc38..62a28728 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -64,6 +64,7 @@ const addonLoaders = import.meta.glob([
'./cloth.js',
'./runtime.js',
'./input.js',
+ './physics-runtime.js',
'./update-part-vertices.js',
]);
const moduleCache = new Map();
diff --git a/src/physics-runtime.js b/src/physics-runtime.js
new file mode 100644
index 00000000..f6c0d9ae
--- /dev/null
+++ b/src/physics-runtime.js
@@ -0,0 +1,421 @@
+// Live physics as a runtime system. One small interface (bodies, colliders, joints, forces, ray, shape and overlap
+// queries, contact and sensor events) sits over a physics engine adapter, and the system steps it in fixedUpdate and
+// writes the body poses to scene parts. The Rapier adapter wraps the world builder the recorded bake in physics.js uses,
+// so the bake path and the live path share one adapter. Another engine plugs in as an object with the same shape as
+// `rapierAdapter`; see docs/physics-runtime.md. Nothing here touches the film path.
+import { mat4, quat } from 'gl-matrix';
+import { applyForceFieldImpulses, createRapierWorld, loadPhysicsEngine, prepareLivePhysics, requireRapier } from './physics.js';
+
+export const PHYSICS_RUNTIME_LIMITS = Object.freeze({
+ maximumListeners: 64,
+ maximumBindings: 4096,
+ maximumOverlaps: 1024,
+ maximumQueryDistance: 1e6,
+});
+
+const SHAPE_TYPES = ['ball', 'cuboid', 'capsule'];
+const MAX_GROUP_BITS = 0xffff;
+const STEP_TOLERANCE = 1e-9;
+const POSE_STRIDE = 7;
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function finiteVector(value, length, label) {
+ if (!(Array.isArray(value) || ArrayBuffer.isView(value)) || value.length !== length || !Array.from(value).every(Number.isFinite)) {
+ throw new TypeError(`${label} must be an array of ${length} finite numbers, got ${Array.isArray(value) ? JSON.stringify(value) : describe(value)}.`);
+ }
+ return Array.from(value);
+}
+
+function unitDirection(value, label) {
+ const direction = finiteVector(value, 3, label);
+ const length = Math.hypot(...direction);
+ if (!(length > 0)) throw new RangeError(`${label} must not be the zero vector; pass a direction such as [0, -1, 0].`);
+ return direction.map(component => component / length);
+}
+
+function queryDistance(value, label) {
+ if (typeof value !== 'number' || !(value > 0) || value > PHYSICS_RUNTIME_LIMITS.maximumQueryDistance) {
+ throw new RangeError(`${label} must be a number above 0 and up to ${PHYSICS_RUNTIME_LIMITS.maximumQueryDistance}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function positiveNumber(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
+ throw new RangeError(`${label} must be a number above 0, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function validateShape(shape, label) {
+ if (shape === null || typeof shape !== 'object' || !SHAPE_TYPES.includes(shape.type)) {
+ const got = shape === null || typeof shape !== 'object' ? describe(shape) : String(shape.type);
+ throw new TypeError(`${label} must be { type: ${SHAPE_TYPES.map(type => `"${type}"`).join(' | ')}, ... }, got ${got}.`);
+ }
+ if (shape.type === 'ball') return { type: 'ball', radius: positiveNumber(shape.radius, `${label}.radius`) };
+ if (shape.type === 'capsule') {
+ return { type: 'capsule', halfHeight: positiveNumber(shape.halfHeight, `${label}.halfHeight`), radius: positiveNumber(shape.radius, `${label}.radius`) };
+ }
+ const halfExtents = finiteVector(shape.halfExtents, 3, `${label}.halfExtents`);
+ halfExtents.forEach((extent, axis) => positiveNumber(extent, `${label}.halfExtents[${axis}]`));
+ return { type: 'cuboid', halfExtents };
+}
+
+function validateRotation(value, label) {
+ if (value === undefined) return [0, 0, 0, 1];
+ const rotation = finiteVector(value, 4, label);
+ const length = Math.hypot(...rotation);
+ if (!(length > 0)) throw new RangeError(`${label} must not be the zero quaternion; pass [x, y, z, w] such as [0, 0, 0, 1].`);
+ return rotation.map(component => component / length);
+}
+
+const xyz = array => ({ x: array[0], y: array[1], z: array[2] });
+const xyzw = array => ({ ...xyz(array), w: array[3] });
+
+/** The Rapier adapter: a world built by the same function the recorded bake uses. */
+export const rapierAdapter = Object.freeze({
+ name: 'rapier',
+ load: loadPhysicsEngine,
+ createWorld(prepared) {
+ const rapier = requireRapier();
+ const { world, bodies, colliderIndices } = createRapierWorld(rapier, prepared);
+ const eventQueue = new rapier.EventQueue(true);
+
+ function queryFilter(filter) {
+ const flags = filter.includeSensors ? undefined : rapier.QueryFilterFlags.EXCLUDE_SENSORS;
+ const groups = ((MAX_GROUP_BITS << 16) | filter.mask) >>> 0;
+ const excludedBody = filter.excludeBody === undefined ? undefined : bodies[filter.excludeBody];
+ return [flags, groups, undefined, excludedBody];
+ }
+
+ function rapierShape(shape) {
+ if (shape.type === 'ball') return new rapier.Ball(shape.radius);
+ if (shape.type === 'capsule') return new rapier.Capsule(shape.halfHeight, shape.radius);
+ return new rapier.Cuboid(...shape.halfExtents);
+ }
+
+ return {
+ step(stepSeconds, elapsedSeconds) {
+ world.timestep = stepSeconds;
+ if (prepared.fields.length) applyForceFieldImpulses({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);
+ world.step(eventQueue);
+ },
+ readPose(bodyIndex, output) {
+ const position = bodies[bodyIndex].translation();
+ const rotation = bodies[bodyIndex].rotation();
+ output[0] = position.x;
+ output[1] = position.y;
+ output[2] = position.z;
+ output[3] = rotation.x;
+ output[4] = rotation.y;
+ output[5] = rotation.z;
+ output[6] = rotation.w;
+ },
+ setKinematicPose(bodyIndex, translation, rotation) {
+ if (translation) bodies[bodyIndex].setNextKinematicTranslation(xyz(translation));
+ if (rotation) bodies[bodyIndex].setNextKinematicRotation(xyzw(rotation));
+ },
+ setLinearVelocity(bodyIndex, velocity) {
+ bodies[bodyIndex].setLinvel(xyz(velocity), true);
+ },
+ applyImpulse(bodyIndex, impulse, point) {
+ if (point) bodies[bodyIndex].applyImpulseAtPoint(xyz(impulse), xyz(point), true);
+ else bodies[bodyIndex].applyImpulse(xyz(impulse), true);
+ },
+ drainEvents(callback) {
+ eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
+ callback(colliderIndices.get(firstHandle), colliderIndices.get(secondHandle), started);
+ });
+ },
+ raycast(origin, direction, maxDistance, filter) {
+ const ray = new rapier.Ray(xyz(origin), xyz(direction));
+ const hit = world.castRayAndGetNormal(ray, maxDistance, true, ...queryFilter(filter));
+ if (!hit) return null;
+ return { collider: colliderIndices.get(hit.collider.handle), distance: hit.timeOfImpact, normal: [hit.normal.x, hit.normal.y, hit.normal.z] };
+ },
+ shapeCast(shape, translation, rotation, direction, maxDistance, filter) {
+ const hit = world.castShape(xyz(translation), xyzw(rotation), xyz(direction), rapierShape(shape), 0, maxDistance, true, ...queryFilter(filter));
+ if (!hit) return null;
+ return { collider: colliderIndices.get(hit.collider.handle), distance: hit.time_of_impact, normal: [hit.normal1.x, hit.normal1.y, hit.normal1.z] };
+ },
+ overlap(shape, translation, rotation, filter) {
+ const found = [];
+ world.intersectionsWithShape(xyz(translation), xyzw(rotation), rapierShape(shape), collider => {
+ found.push(colliderIndices.get(collider.handle));
+ return found.length < PHYSICS_RUNTIME_LIMITS.maximumOverlaps;
+ }, ...queryFilter(filter));
+ return found;
+ },
+ free() {
+ eventQueue.free();
+ world.free();
+ },
+ };
+ },
+});
+
+function validateAdapter(adapter) {
+ if (adapter === null || typeof adapter !== 'object' || typeof adapter.createWorld !== 'function' || typeof adapter.name !== 'string') {
+ throw new TypeError('createPhysicsSystem adapter must be an object like { name, load?(), createWorld(prepared) }, such as rapierAdapter.');
+ }
+ return adapter;
+}
+
+function validateFilter(filter, bodyIndices) {
+ if (filter === null || typeof filter !== 'object') throw new TypeError('A physics query options value must be an object like { mask, excludeBody, includeSensors } or left out.');
+ const mask = filter.mask ?? MAX_GROUP_BITS;
+ if (!Number.isInteger(mask) || mask < 0 || mask > MAX_GROUP_BITS) {
+ throw new RangeError(`A physics query mask must be an integer from 0 to ${MAX_GROUP_BITS}, got ${String(filter.mask)}.`);
+ }
+ let excludeBody;
+ if (filter.excludeBody !== undefined) {
+ excludeBody = bodyIndices.get(filter.excludeBody);
+ if (excludeBody === undefined) throw new RangeError(`A physics query excludeBody names no body: "${String(filter.excludeBody)}". Present: ${[...bodyIndices.keys()].join(', ')}.`);
+ }
+ return { mask, excludeBody, includeSensors: filter.includeSensors === true };
+}
+
+function partScale(matrix) {
+ return [Math.hypot(matrix[0], matrix[1], matrix[2]), Math.hypot(matrix[4], matrix[5], matrix[6]), Math.hypot(matrix[8], matrix[9], matrix[10])];
+}
+
+/**
+ * Build a live physics system for a runtime. Await it: the adapter may load a wasm engine first.
+ * `definition` is the recorded-physics definition without tick events (docs/physics.md). Options: adapter (default
+ * rapierAdapter), timestep (default 1/60; give the runtime the same fixedStepSeconds), name, bindings, solverIterations.
+ */
+export async function createPhysicsSystem(definition, options = {}) {
+ if (options === null || typeof options !== 'object') throw new TypeError('createPhysicsSystem options must be an object or left out.');
+ const { adapter: requestedAdapter, name, bindings: initialBindings, ...engineOptions } = options;
+ const adapter = validateAdapter(requestedAdapter ?? rapierAdapter);
+ const timestep = engineOptions.timestep ?? 1 / 60;
+ const prepared = prepareLivePhysics(definition, { ...engineOptions, timestep });
+ await adapter.load?.();
+ const world = adapter.createWorld(prepared);
+
+ const bodyNames = Object.freeze(prepared.bodies.map(body => body.name));
+ const bodyIndices = new Map(bodyNames.map((bodyName, index) => [bodyName, index]));
+ let previousPoses = new Float32Array(bodyNames.length * POSE_STRIDE);
+ let currentPoses = new Float32Array(bodyNames.length * POSE_STRIDE);
+ const bindings = [];
+ const listeners = { contact: new Set(), sensor: new Set() };
+ let stepEvents = [];
+ let eventsTruncated = false;
+ let stepCount = 0;
+ let disposed = false;
+
+ function readPoses() {
+ for (let bodyIndex = 0; bodyIndex < bodyNames.length; bodyIndex++) {
+ world.readPose(bodyIndex, currentPoses.subarray(bodyIndex * POSE_STRIDE, (bodyIndex + 1) * POSE_STRIDE));
+ }
+ }
+ readPoses();
+ previousPoses.set(currentPoses);
+
+ function assertAlive() {
+ if (disposed) throw new Error('This physics system was disposed. Call createPhysicsSystem again.');
+ }
+
+ function bodyIndexOf(bodyName, action) {
+ const index = bodyIndices.get(bodyName);
+ if (index === undefined) throw new RangeError(`${action} names no body: "${String(bodyName)}". Present: ${bodyNames.join(', ')}.`);
+ return index;
+ }
+
+ function requireBodyType(bodyName, action, type) {
+ const index = bodyIndexOf(bodyName, action);
+ const actual = prepared.bodies[index].type;
+ if (actual !== type) throw new TypeError(`${action} needs a ${type} body; "${bodyName}" is ${actual}.`);
+ return index;
+ }
+
+ const colliderBodyName = colliderIndex => bodyNames[prepared.colliders[colliderIndex].body];
+
+ function describeHit(hit, origin, unit) {
+ return {
+ body: colliderBodyName(hit.collider),
+ collider: prepared.colliders[hit.collider].name,
+ distance: hit.distance,
+ point: origin.map((component, axis) => component + unit[axis] * hit.distance),
+ normal: hit.normal,
+ };
+ }
+
+ function collectEvents() {
+ const collected = [];
+ eventsTruncated = false;
+ world.drainEvents((first, second, started) => {
+ if (collected.length >= prepared.maxContactEvents) {
+ eventsTruncated = true;
+ return;
+ }
+ const [colliderA, colliderB] = first < second ? [first, second] : [second, first];
+ const sensor = prepared.colliders[colliderA].sensor || prepared.colliders[colliderB].sensor;
+ collected.push(Object.freeze({
+ step: stepCount,
+ kind: sensor ? 'sensor' : 'contact',
+ started,
+ colliderA,
+ colliderB,
+ bodyA: colliderBodyName(colliderA),
+ bodyB: colliderBodyName(colliderB),
+ }));
+ });
+ // Engines report events in their own order; sorting makes every adapter fire the same sequence.
+ collected.sort((first, second) => first.colliderA - second.colliderA || first.colliderB - second.colliderB || Number(second.started) - Number(first.started));
+ return collected;
+ }
+
+ function writeBindings(alpha) {
+ for (const binding of bindings) {
+ const offset = binding.index * POSE_STRIDE;
+ for (let axis = 0; axis < 3; axis++) {
+ binding.position[axis] = previousPoses[offset + axis] + (currentPoses[offset + axis] - previousPoses[offset + axis]) * alpha;
+ }
+ for (let component = 0; component < 4; component++) {
+ binding.start[component] = previousPoses[offset + 3 + component];
+ binding.end[component] = currentPoses[offset + 3 + component];
+ }
+ quat.slerp(binding.rotation, binding.start, binding.end, alpha);
+ mat4.fromRotationTranslationScale(binding.part.matrix, binding.rotation, binding.position, binding.scale);
+ }
+ }
+
+ function bind(bodyName, part) {
+ assertAlive();
+ const index = bodyIndexOf(bodyName, 'bind');
+ const matrix = part?.matrix;
+ if (!(matrix instanceof Float32Array) || matrix.length !== 16) {
+ throw new TypeError(`bind("${bodyName}") needs a part with a retained Float32Array(16) matrix, got ${describe(matrix)}.`);
+ }
+ if (bindings.length >= PHYSICS_RUNTIME_LIMITS.maximumBindings) {
+ throw new RangeError(`A physics system binds at most ${PHYSICS_RUNTIME_LIMITS.maximumBindings} parts.`);
+ }
+ if (bindings.some(binding => binding.part.matrix === matrix)) throw new RangeError(`bind("${bodyName}") got a part whose matrix is already bound.`);
+ const scale = partScale(matrix);
+ if (!scale.every(size => size > 0 && Number.isFinite(size))) {
+ throw new RangeError(`bind("${bodyName}") needs a part matrix with a positive scale, such as the identity matrix.`);
+ }
+ bindings.push({ part, index, scale, position: new Float32Array(3), rotation: quat.create(), start: quat.create(), end: quat.create() });
+ writeBindings(1);
+ return system;
+ }
+
+ function on(kind, listener) {
+ assertAlive();
+ if (!(kind in listeners)) throw new RangeError(`on() kind must be "contact" or "sensor", got ${String(kind)}.`);
+ if (typeof listener !== 'function') throw new TypeError(`on("${kind}") needs a listener function, got ${describe(listener)}.`);
+ if (listeners[kind].size >= PHYSICS_RUNTIME_LIMITS.maximumListeners) {
+ throw new RangeError(`A physics system holds at most ${PHYSICS_RUNTIME_LIMITS.maximumListeners} listeners per kind.`);
+ }
+ listeners[kind].add(listener);
+ return () => listeners[kind].delete(listener);
+ }
+
+ const system = {
+ name: name ?? 'physics',
+ adapter: adapter.name,
+ timestep,
+ bodyNames,
+ get stepCount() { return stepCount; },
+ /** The contact and sensor events of the last step, sorted by collider pair. */
+ get events() { return stepEvents; },
+ get eventsTruncated() { return eventsTruncated; },
+ on,
+ bind,
+
+ // Runtime hooks.
+ fixedUpdate(stepSeconds, context) {
+ assertAlive();
+ if (Math.abs(stepSeconds - timestep) > STEP_TOLERANCE * Math.max(1, timestep)) {
+ throw new RangeError(`The runtime fixed step is ${stepSeconds} s but this physics system was built with timestep ${timestep} s. Create the runtime with fixedStepSeconds: physics.timestep, or pass timestep: ${stepSeconds} to createPhysicsSystem.`);
+ }
+ world.step(stepSeconds, stepCount * stepSeconds);
+ stepCount += 1;
+ [previousPoses, currentPoses] = [currentPoses, previousPoses];
+ readPoses();
+ stepEvents = collectEvents();
+ // In 'both' mode update() writes the interpolated pose; otherwise this step is the only writer.
+ if (context?.mode !== 'both') writeBindings(1);
+ for (const event of stepEvents) {
+ for (const listener of listeners[event.kind]) listener(event);
+ }
+ },
+ update(_delta, context) {
+ if (context?.mode === 'both') writeBindings(context.alpha);
+ },
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ world.free();
+ bindings.length = 0;
+ },
+
+ // Control. Kinematic bodies are driven by code; dynamic bodies take impulses and velocities.
+ setKinematicPose(bodyName, pose) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'setKinematicPose', 'kinematic');
+ if (pose === null || typeof pose !== 'object' || (pose.translation === undefined && pose.rotation === undefined)) {
+ throw new TypeError('setKinematicPose needs { translation, rotation } with at least one of them.');
+ }
+ const translation = pose.translation === undefined ? undefined : finiteVector(pose.translation, 3, 'setKinematicPose translation');
+ const rotation = pose.rotation === undefined ? undefined : validateRotation(pose.rotation, 'setKinematicPose rotation');
+ world.setKinematicPose(index, translation, rotation);
+ return system;
+ },
+ setLinearVelocity(bodyName, velocity) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'setLinearVelocity', 'dynamic');
+ world.setLinearVelocity(index, finiteVector(velocity, 3, 'setLinearVelocity velocity'));
+ return system;
+ },
+ applyImpulse(bodyName, impulse, point) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'applyImpulse', 'dynamic');
+ world.applyImpulse(index, finiteVector(impulse, 3, 'applyImpulse impulse'), point === undefined ? undefined : finiteVector(point, 3, 'applyImpulse point'));
+ return system;
+ },
+ /** Pose of a body after the last step: { translation, rotation }. */
+ getPose(bodyName) {
+ assertAlive();
+ const offset = bodyIndexOf(bodyName, 'getPose') * POSE_STRIDE;
+ return { translation: Array.from(currentPoses.subarray(offset, offset + 3)), rotation: Array.from(currentPoses.subarray(offset + 3, offset + POSE_STRIDE)) };
+ },
+
+ // Queries read the world as the last step left it.
+ /** First hit along a ray, or null: { body, collider, distance, point, normal }. */
+ raycast(origin, direction, queryOptions = {}) {
+ assertAlive();
+ const start = finiteVector(origin, 3, 'raycast origin');
+ const unit = unitDirection(direction, 'raycast direction');
+ const maximumDistance = queryDistance(queryOptions.maxDistance ?? 1000, 'raycast maxDistance');
+ const hit = world.raycast(start, unit, maximumDistance, validateFilter(queryOptions, bodyIndices));
+ return hit ? describeHit(hit, start, unit) : null;
+ },
+ /** Sweep a ball, cuboid or capsule along a direction and return the first hit, or null: { body, collider, distance, point, normal }. */
+ shapeCast(shape, translation, direction, queryOptions = {}) {
+ assertAlive();
+ const validShape = validateShape(shape, 'shapeCast shape');
+ const start = finiteVector(translation, 3, 'shapeCast translation');
+ const unit = unitDirection(direction, 'shapeCast direction');
+ const maximumDistance = queryDistance(queryOptions.maxDistance ?? 1000, 'shapeCast maxDistance');
+ const rotation = validateRotation(queryOptions.rotation, 'shapeCast rotation');
+ const hit = world.shapeCast(validShape, start, rotation, unit, maximumDistance, validateFilter(queryOptions, bodyIndices));
+ return hit ? describeHit(hit, start, unit) : null;
+ },
+ /** Names of the bodies whose colliders touch a ball, cuboid or capsule placed in the world, sorted. */
+ overlap(shape, translation, queryOptions = {}) {
+ assertAlive();
+ const validShape = validateShape(shape, 'overlap shape');
+ const start = finiteVector(translation, 3, 'overlap translation');
+ const rotation = validateRotation(queryOptions.rotation, 'overlap rotation');
+ const found = world.overlap(validShape, start, rotation, validateFilter(queryOptions, bodyIndices));
+ return [...new Set(found.map(colliderBodyName))].sort();
+ },
+ };
+ for (const binding of initialBindings ?? []) bind(binding.body, binding.part);
+ return system;
+}
diff --git a/src/physics.js b/src/physics.js
index ae656bef..7c221910 100644
--- a/src/physics.js
+++ b/src/physics.js
@@ -329,6 +329,7 @@ function prepare(definition, options) {
throw new TypeError('sensor must be boolean');
}
const common = {
+ name: collider.name,
body,
translation: vector(collider.translation, 3, 'collider translation', ZERO),
rotation: rotation(collider.rotation, 'collider rotation'),
@@ -757,15 +758,10 @@ function colliderDescriptor(rapier, collider) {
return descriptor;
}
-function bakePrepared(preparedScene) {
- const rapier = rapierEngine;
+/** Build the Rapier world for a prepared scene. Shared by the recorded bake and the live runtime. Frees itself on failure. */
+export function createRapierWorld(rapier, preparedScene) {
const world = new rapier.World(xyz(preparedScene.gravity));
- const eventQueue = new rapier.EventQueue(true);
- const contactEvents = [];
const colliderIndices = new Map();
- const lastMovingFrames = new Int32Array(preparedScene.bodies.length).fill(-1);
- let contactEventsTruncated = false;
- let timeline;
try {
world.timestep = preparedScene.timestep;
world.numSolverIterations = preparedScene.solverIterations;
@@ -814,6 +810,38 @@ function bakePrepared(preparedScene) {
if (joint.motor !== undefined) applyJointMotor(rapier, created, joint.motor);
return created;
});
+ return { world, bodies, joints, colliderIndices };
+ } catch (error) {
+ world.free();
+ throw error;
+ }
+}
+
+/** Push every dynamic body by the force fields at `fieldTime`, as one impulse over a step. */
+export function applyForceFieldImpulses(preparedScene, bodies, fieldTime) {
+ const fieldAccel = [0, 0, 0];
+ for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {
+ if (preparedScene.bodies[bodyIndex].type !== 'dynamic') continue;
+ const body = bodies[bodyIndex];
+ const pos = body.translation();
+ const vel = body.linvel();
+ evaluateForceFields(preparedScene.fields, [pos.x, pos.y, pos.z], [vel.x, vel.y, vel.z], fieldTime, fieldAccel);
+ const scale = body.mass() * preparedScene.timestep;
+ if (fieldAccel[0] || fieldAccel[1] || fieldAccel[2]) {
+ body.applyImpulse({ x: fieldAccel[0] * scale, y: fieldAccel[1] * scale, z: fieldAccel[2] * scale }, true);
+ }
+ }
+}
+
+function bakePrepared(preparedScene) {
+ const rapier = rapierEngine;
+ const { world, bodies, joints, colliderIndices } = createRapierWorld(rapier, preparedScene);
+ const eventQueue = new rapier.EventQueue(true);
+ const contactEvents = [];
+ const lastMovingFrames = new Int32Array(preparedScene.bodies.length).fill(-1);
+ let contactEventsTruncated = false;
+ let timeline;
+ try {
timeline = new Float32Array(preparedScene.memoryPlan.timelineBytes / 4);
let eventIndex = 0;
for (let frame = 0; frame < preparedScene.frameCount; frame++) {
@@ -846,21 +874,7 @@ function bakePrepared(preparedScene) {
}
}
}
- if (preparedScene.fields.length) {
- const fieldTime = (frame - 1) * preparedScene.timestep;
- const fieldAccel = [0, 0, 0];
- for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {
- if (preparedScene.bodies[bodyIndex].type !== 'dynamic') continue;
- const body = bodies[bodyIndex];
- const pos = body.translation();
- const vel = body.linvel();
- evaluateForceFields(preparedScene.fields, [pos.x, pos.y, pos.z], [vel.x, vel.y, vel.z], fieldTime, fieldAccel);
- const scale = body.mass() * preparedScene.timestep;
- if (fieldAccel[0] || fieldAccel[1] || fieldAccel[2]) {
- body.applyImpulse({ x: fieldAccel[0] * scale, y: fieldAccel[1] * scale, z: fieldAccel[2] * scale }, true);
- }
- }
- }
+ if (preparedScene.fields.length) applyForceFieldImpulses(preparedScene, bodies, (frame - 1) * preparedScene.timestep);
world.step(eventQueue);
eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
if (contactEvents.length >= preparedScene.maxContactEvents) {
@@ -1099,3 +1113,18 @@ function recordedScene(preparedScene, timeline, recording) {
},
});
}
+
+/** Validate a definition for the live runtime. There is no timeline, so the frame count is 1 and tick events are not accepted. */
+export function prepareLivePhysics(definition, options = {}) {
+ if (definition && definition.events !== undefined && definition.events.length) {
+ throw new TypeError('a live physics definition takes no events; call applyImpulse, setKinematicPose or setLinearVelocity on the system instead');
+ }
+ const prepared = prepare({ ...definition, events: [] }, { ...options, frameCount: 1 });
+ return prepared;
+}
+
+/** The loaded Rapier module, or throws when loadPhysicsEngine has not resolved. */
+export function requireRapier() {
+ if (!rapierEngine) throw new Error('Physics engine is not loaded. Await loadPhysicsEngine() first.');
+ return rapierEngine;
+}
diff --git a/tests/physics-runtime.test.js b/tests/physics-runtime.test.js
new file mode 100644
index 00000000..107bb880
--- /dev/null
+++ b/tests/physics-runtime.test.js
@@ -0,0 +1,194 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createPhysicsSystem, rapierAdapter } from '../src/physics-runtime.js';
+import { createRuntime } from '../src/runtime.js';
+
+const STEP = 1 / 60;
+
+function worldDefinition() {
+ return {
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'box', translation: [0, 2, 0] },
+ { name: 'zone', type: 'fixed', translation: [4, 1, 0] },
+ { name: 'platform', type: 'kinematic', translation: [-4, 1, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10] },
+ { name: 'crate', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ { name: 'trigger', body: 'zone', shape: 'cuboid', halfExtents: [1, 1, 1], sensor: true },
+ { name: 'lift', body: 'platform', shape: 'cuboid', halfExtents: [1, 0.1, 1] },
+ ],
+ };
+}
+
+function stepMany(system, count) {
+ for (let step = 0; step < count; step++) system.fixedUpdate(STEP, { mode: 'fixed' });
+}
+
+test('a live world steps in fixedUpdate and a box falls onto the floor', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ assert.equal(physics.adapter, 'rapier');
+ stepMany(physics, 120);
+ const { translation } = physics.getPose('box');
+ assert.ok(Math.abs(translation[1] - 0.5) < 0.05, `box rests on the floor, y = ${translation[1]}`);
+ assert.equal(physics.stepCount, 120);
+ physics.dispose();
+});
+
+test('contact events fire once on start, sorted, with body names', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const heard = [];
+ physics.on('contact', event => heard.push(event));
+ stepMany(physics, 120);
+ const started = heard.filter(event => event.started);
+ assert.equal(started.length, 1);
+ assert.deepEqual([started[0].bodyA, started[0].bodyB], ['floor', 'box']);
+ assert.equal(started[0].kind, 'contact');
+ assert.ok(started[0].step > 0 && started[0].step < 60);
+ physics.dispose();
+});
+
+test('sensor events report a body entering and leaving a trigger', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const heard = [];
+ physics.on('sensor', event => heard.push(`${event.started ? 'enter' : 'exit'} ${event.bodyA}/${event.bodyB}`));
+ physics.applyImpulse('box', [4, 0, 0]);
+ stepMany(physics, 60);
+ assert.ok(heard.includes('enter box/zone') || heard.includes('enter zone/box'), heard.join(', '));
+ physics.setLinearVelocity('box', [-6, 0, 0]);
+ stepMany(physics, 60);
+ assert.ok(heard.some(entry => entry.startsWith('exit')), heard.join(', '));
+ physics.dispose();
+});
+
+test('a kinematic body follows setKinematicPose and carries the world', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ physics.setKinematicPose('platform', { translation: [-4, 3, 0] });
+ stepMany(physics, 2);
+ assert.ok(Math.abs(physics.getPose('platform').translation[1] - 3) < 1e-4);
+ assert.throws(() => physics.setKinematicPose('box', { translation: [0, 0, 0] }), /needs a kinematic body; "box" is dynamic/);
+ physics.dispose();
+});
+
+test('raycast, shapeCast and overlap read the world', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ stepMany(physics, 120);
+ const ray = physics.raycast([0, 5, 0], [0, -1, 0]);
+ assert.equal(ray.body, 'box');
+ assert.equal(ray.collider, 'crate');
+ assert.ok(Math.abs(ray.distance - 4) < 0.05, `distance ${ray.distance}`);
+ assert.ok(Math.abs(ray.normal[1] - 1) < 1e-4);
+ assert.ok(Math.abs(ray.point[1] - 1) < 0.05);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { excludeBody: 'box' }).body, 'floor');
+ assert.equal(physics.raycast([0, 5, 0], [0, 1, 0]), null);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { maxDistance: 1 }), null);
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0]).body, 'floor', 'a ray ignores sensors by default');
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0], { includeSensors: true }).body, 'zone');
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { mask: 0 }), null);
+
+ const sweep = physics.shapeCast({ type: 'ball', radius: 0.25 }, [0, 5, 0], [0, -1, 0]);
+ assert.equal(sweep.body, 'box');
+ assert.ok(Math.abs(sweep.distance - 3.75) < 0.05, `sweep ${sweep.distance}`);
+
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 1 }, [0, 0.5, 0]), ['box', 'floor']);
+ assert.deepEqual(physics.overlap({ type: 'cuboid', halfExtents: [0.2, 0.2, 0.2] }, [0, 8, 0]), []);
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 0.5 }, [-9, 0, 0]), ['floor']);
+ physics.dispose();
+});
+
+test('errors name the field and what to pass', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ assert.throws(() => physics.raycast([0, 0], [0, -1, 0]), /raycast origin must be an array of 3 finite numbers/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, 0, 0]), /raycast direction must not be the zero vector/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, -1, 0], { maxDistance: -1 }), /raycast maxDistance must be a number above 0/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, -1, 0], { excludeBody: 'nope' }), /excludeBody names no body: "nope"/);
+ assert.throws(() => physics.overlap({ type: 'sphere' }, [0, 0, 0]), /overlap shape must be \{ type: "ball"/);
+ assert.throws(() => physics.applyImpulse('floor', [0, 1, 0]), /needs a dynamic body; "floor" is fixed/);
+ assert.throws(() => physics.getPose('ghost'), /getPose names no body: "ghost"\. Present: floor, box/);
+ assert.throws(() => physics.on('bump', () => {}), /kind must be "contact" or "sensor"/);
+ assert.throws(() => physics.fixedUpdate(1 / 30, { mode: 'fixed' }), /fixedStepSeconds: physics\.timestep/);
+ physics.dispose();
+ assert.throws(() => physics.getPose('box'), /disposed/);
+ await assert.rejects(createPhysicsSystem({ ...worldDefinition(), events: [{ tick: 0, type: 'impulse', body: 'box', impulse: [1, 0, 0] }] }), /takes no events/);
+ await assert.rejects(createPhysicsSystem(worldDefinition(), { adapter: {} }), /adapter must be an object/);
+});
+
+test('the system runs inside the runtime and writes interpolated part matrices', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const part = { matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) };
+ physics.bind('box', part);
+ const runtime = createRuntime({ render() {} }, {
+ systems: [physics],
+ fixedStepSeconds: physics.timestep,
+ mode: 'both',
+ scheduler: { request: () => 1, cancel() {} },
+ clock: () => 0,
+ visibility: { hidden: false, subscribe: () => () => {} },
+ });
+ runtime.step(1000 / 60 * 0.5);
+ assert.equal(physics.stepCount, 0);
+ for (let frame = 0; frame < 10; frame++) runtime.step(100);
+ assert.ok(physics.stepCount >= 59);
+ assert.ok(part.matrix[13] < 2 && part.matrix[13] > 0.4, `box y ${part.matrix[13]}`);
+ runtime.dispose();
+ assert.throws(() => physics.getPose('box'), /disposed/);
+});
+
+test('a 500-box scene runs live and records the step time', async () => {
+ const bodies = [{ name: 'floor', type: 'fixed', translation: [0, -0.5, 0] }];
+ const colliders = [{ name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [20, 0.5, 20] }];
+ for (let index = 0; index < 500; index++) {
+ const name = `box${index}`;
+ const column = index % 10;
+ const row = Math.floor(index / 10) % 10;
+ const layer = Math.floor(index / 100);
+ bodies.push({ name, translation: [(column - 4.5) * 1.2, 0.5 + layer * 1.1, (row - 4.5) * 1.2] });
+ colliders.push({ name, body: name, shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 });
+ }
+ const physics = await createPhysicsSystem({ bodies, colliders }, { maxBodies: 512, maxColliders: 512 });
+ stepMany(physics, 10);
+ const steps = 120;
+ const start = performance.now();
+ stepMany(physics, steps);
+ const millisecondsPerStep = (performance.now() - start) / steps;
+ console.log(`physics-runtime 500 boxes (${physics.adapter}): ${millisecondsPerStep.toFixed(2)} ms per step`);
+ assert.equal(physics.bodyNames.length, 501);
+ assert.ok(Math.abs(physics.getPose('box0').translation[1] - 0.5) < 0.1);
+ physics.dispose();
+});
+
+// A scripted engine with no physics: it proves the system reads only the adapter interface.
+test('another adapter plugs in and its events are normalised the same way', async () => {
+ const calls = [];
+ const scripted = {
+ name: 'scripted',
+ createWorld(prepared) {
+ assert.equal(prepared.bodies.length, 4);
+ return {
+ step(stepSeconds, elapsedSeconds) { calls.push(['step', stepSeconds, elapsedSeconds]); },
+ readPose(index, output) { output.set([index, 0, 0, 0, 0, 0, 1]); },
+ drainEvents(callback) { callback(3, 1, true); callback(2, 1, false); callback(0, 1, true); },
+ raycast: () => ({ collider: 1, distance: 2, normal: [0, 1, 0] }),
+ free() { calls.push(['free']); },
+ };
+ },
+ };
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: scripted });
+ assert.equal(physics.adapter, 'scripted');
+ physics.fixedUpdate(STEP, { mode: 'fixed' });
+ assert.deepEqual(physics.events.map(event => [event.kind, event.started, event.bodyA, event.bodyB]), [
+ ['contact', true, 'floor', 'box'],
+ ['sensor', false, 'box', 'zone'],
+ ['contact', true, 'box', 'platform'],
+ ]);
+ assert.deepEqual(physics.getPose('zone').translation, [2, 0, 0]);
+ assert.equal(physics.raycast([0, 0, 0], [0, 1, 0]).body, 'box');
+ physics.dispose();
+ assert.deepEqual(calls.at(-1), ['free']);
+});
+
+test('the rapier adapter is frozen and named', () => {
+ assert.equal(rapierAdapter.name, 'rapier');
+ assert.ok(Object.isFrozen(rapierAdapter));
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 80d48ff3..5bb2d35e 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -107,6 +107,7 @@ export default defineConfig({
cloth: 'src/cloth.js',
runtime: 'src/runtime.js',
input: 'src/input.js',
+ 'physics-runtime': 'src/physics-runtime.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.