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.

refactor(physics): split PhysicsPlugin.ts (1105 lines) into four files

esengine02407930da78
diff --git a/sdk/benchmarks/physics.bench.ts b/sdk/benchmarks/physics.bench.ts
index 7761d444f..5936c403b 100644
--- a/sdk/benchmarks/physics.bench.ts
+++ b/sdk/benchmarks/physics.bench.ts
@@ -4,7 +4,7 @@ import { World } from '../src/world';
import { defineBuiltin } from '../src/component';
import type { CppRegistry, ESEngineModule } from '../src/wasm';
import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
-import { syncDynamicTransforms } from '../src/physics/PhysicsPlugin';
+import { syncDynamicTransforms } from '../src/physics/PhysicsSystem';
import type { Entity } from '../src/types';
let wasmModule: ESEngineModule;
diff --git a/sdk/src/physics/Physics.ts b/sdk/src/physics/Physics.ts
new file mode 100644
index 000000000..e887bcf1f
--- /dev/null
+++ b/sdk/src/physics/Physics.ts
@@ -0,0 +1,417 @@
+/**
+ * @file Physics.ts
+ * @brief User-facing physics API + PhysicsAPI resource
+ *
+ * `Physics` is the ergonomic wrapper game code uses to drive bodies
+ * (forces, impulses, joints, raycasts). It is published as the
+ * `PhysicsAPI` resource once `PhysicsPlugin` finishes loading the
+ * wasm module; instantiation before that throws.
+ */
+
+import type { App } from '../app';
+import type { Entity, Vec2 } from '../types';
+import { defineResource } from '../resource';
+import type { PhysicsWasmModule } from './PhysicsModuleLoader';
+import { PhysicsRuntime } from './PhysicsRuntime';
+import { PhysicsDebugDraw, type PhysicsDebugDrawConfig } from './PhysicsDebugDraw';
+import {
+ CAST_HIT_STRIDE,
+ type RaycastHit,
+ type ShapeCastHit,
+ type MassData,
+} from './PhysicsTypes';
+
+// =============================================================================
+// Physics API Helper
+// =============================================================================
+
+export class Physics {
+ private module_: PhysicsWasmModule;
+
+ constructor(app: App) {
+ const module = app.hasResource(PhysicsRuntime)
+ ? app.getResource(PhysicsRuntime).module
+ : null;
+ if (!module) {
+ throw new Error('Physics module not loaded. Ensure PhysicsPlugin init is complete.');
+ }
+ this.module_ = module;
+ }
+
+ /** @internal */
+ static _fromModule(module: PhysicsWasmModule): Physics {
+ const instance = Object.create(Physics.prototype) as Physics;
+ instance.module_ = module;
+ return instance;
+ }
+
+ applyForce(entity: Entity, force: Vec2): void {
+ this.module_._physics_applyForce(entity, force.x, force.y);
+ }
+
+ applyImpulse(entity: Entity, impulse: Vec2): void {
+ this.module_._physics_applyImpulse(entity, impulse.x, impulse.y);
+ }
+
+ setLinearVelocity(entity: Entity, velocity: Vec2): void {
+ this.module_._physics_setLinearVelocity(entity, velocity.x, velocity.y);
+ }
+
+ getLinearVelocity(entity: Entity): Vec2 {
+ const ptr = this.module_._physics_getLinearVelocity(entity);
+ const base = ptr >> 2;
+ return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
+ }
+
+ setGravity(gravity: Vec2): void {
+ this.module_._physics_setGravity(gravity.x, gravity.y);
+ }
+
+ getGravity(): Vec2 {
+ const ptr = this.module_._physics_getGravity();
+ const base = ptr >> 2;
+ return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
+ }
+
+ setAngularVelocity(entity: Entity, omega: number): void {
+ this.module_._physics_setAngularVelocity(entity, omega);
+ }
+
+ getAngularVelocity(entity: Entity): number {
+ return this.module_._physics_getAngularVelocity(entity);
+ }
+
+ applyTorque(entity: Entity, torque: number): void {
+ this.module_._physics_applyTorque(entity, torque);
+ }
+
+ applyAngularImpulse(entity: Entity, impulse: number): void {
+ this.module_._physics_applyAngularImpulse(entity, impulse);
+ }
+
+ createRevoluteJoint(
+ entityA: Entity, entityB: Entity,
+ anchorA: Vec2, anchorB: Vec2,
+ options?: {
+ enableMotor?: boolean; motorSpeed?: number; maxMotorTorque?: number;
+ enableLimit?: boolean; lowerAngle?: number; upperAngle?: number;
+ collideConnected?: boolean;
+ }
+ ): boolean {
+ const o = options ?? {};
+ return this.module_._physics_createRevoluteJoint(
+ entityA, entityB,
+ anchorA.x, anchorA.y, anchorB.x, anchorB.y,
+ o.enableMotor ? 1 : 0, o.motorSpeed ?? 0, o.maxMotorTorque ?? 0,
+ o.enableLimit ? 1 : 0, o.lowerAngle ?? 0, o.upperAngle ?? 0,
+ o.collideConnected ? 1 : 0,
+ ) !== 0;
+ }
+
+ destroyJoint(entity: Entity): void {
+ this.module_._physics_destroyJoint(entity);
+ }
+
+ setRevoluteMotorSpeed(entity: Entity, speed: number): void {
+ this.module_._physics_setRevoluteMotorSpeed(entity, speed);
+ }
+
+ setRevoluteMaxMotorTorque(entity: Entity, torque: number): void {
+ this.module_._physics_setRevoluteMaxMotorTorque(entity, torque);
+ }
+
+ enableRevoluteMotor(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableRevoluteMotor(entity, enable ? 1 : 0);
+ }
+
+ enableRevoluteLimit(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableRevoluteLimit(entity, enable ? 1 : 0);
+ }
+
+ setRevoluteLimits(entity: Entity, lower: number, upper: number): void {
+ this.module_._physics_setRevoluteLimits(entity, lower, upper);
+ }
+
+ getRevoluteAngle(entity: Entity): number {
+ return this.module_._physics_getRevoluteAngle(entity);
+ }
+
+ getRevoluteMotorTorque(entity: Entity): number {
+ return this.module_._physics_getRevoluteMotorTorque(entity);
+ }
+
+ raycast(
+ origin: Vec2, direction: Vec2, maxDistance: number,
+ maskBits = 0xFFFF, ppu = 100,
+ ): RaycastHit[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_raycast(
+ origin.x * invPpu, origin.y * invPpu,
+ direction.x, direction.y,
+ maxDistance * invPpu, maskBits,
+ );
+ if (count === 0) return [];
+
+ const ptr = this.module_._physics_getRaycastBuffer() >> 2;
+ const results: RaycastHit[] = [];
+ for (let i = 0; i < count; i++) {
+ const base = ptr + i * CAST_HIT_STRIDE;
+ results.push({
+ entity: this.module_.HEAPU32[base] as Entity,
+ point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
+ normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
+ fraction: this.module_.HEAPF32[base + 5],
+ });
+ }
+ results.sort((a, b) => a.fraction - b.fraction);
+ return results;
+ }
+
+ overlapCircle(center: Vec2, radius: number, maskBits = 0xFFFF, ppu = 100): Entity[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_overlapCircle(
+ center.x * invPpu, center.y * invPpu,
+ radius * invPpu, maskBits,
+ );
+ return this.readUniqueEntityBuffer_(count);
+ }
+
+ setAwake(entity: Entity, awake: boolean): void {
+ this.module_._physics_setAwake(entity, awake ? 1 : 0);
+ }
+
+ isAwake(entity: Entity): boolean {
+ return this.module_._physics_isAwake(entity) !== 0;
+ }
+
+ shapeCastCircle(
+ center: Vec2, radius: number, translation: Vec2,
+ maskBits = 0xFFFF, ppu = 100,
+ ): ShapeCastHit[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_shapeCastCircle(
+ center.x * invPpu, center.y * invPpu, radius * invPpu,
+ translation.x * invPpu, translation.y * invPpu, maskBits,
+ );
+ return this.readShapeCastBuffer_(count, ppu);
+ }
+
+ shapeCastBox(
+ center: Vec2, halfExtents: Vec2, angle: number, translation: Vec2,
+ maskBits = 0xFFFF, ppu = 100,
+ ): ShapeCastHit[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_shapeCastBox(
+ center.x * invPpu, center.y * invPpu,
+ halfExtents.x * invPpu, halfExtents.y * invPpu, angle,
+ translation.x * invPpu, translation.y * invPpu, maskBits,
+ );
+ return this.readShapeCastBuffer_(count, ppu);
+ }
+
+ shapeCastCapsule(
+ center1: Vec2, center2: Vec2, radius: number, translation: Vec2,
+ maskBits = 0xFFFF, ppu = 100,
+ ): ShapeCastHit[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_shapeCastCapsule(
+ center1.x * invPpu, center1.y * invPpu,
+ center2.x * invPpu, center2.y * invPpu,
+ radius * invPpu,
+ translation.x * invPpu, translation.y * invPpu, maskBits,
+ );
+ return this.readShapeCastBuffer_(count, ppu);
+ }
+
+ overlapAABB(min: Vec2, max: Vec2, maskBits = 0xFFFF, ppu = 100): Entity[] {
+ const invPpu = 1 / ppu;
+ const count = this.module_._physics_overlapAABB(
+ min.x * invPpu, min.y * invPpu,
+ max.x * invPpu, max.y * invPpu, maskBits,
+ );
+ return this.readUniqueEntityBuffer_(count);
+ }
+
+ getMass(entity: Entity): number {
+ return this.module_._physics_getBodyMass(entity);
+ }
+
+ getInertia(entity: Entity): number {
+ return this.module_._physics_getBodyInertia(entity);
+ }
+
+ getCenterOfMass(entity: Entity, ppu = 100): Vec2 {
+ const ptr = this.module_._physics_getBodyCenterOfMass(entity);
+ const base = ptr >> 2;
+ return {
+ x: this.module_.HEAPF32[base] * ppu,
+ y: this.module_.HEAPF32[base + 1] * ppu,
+ };
+ }
+
+ getMassData(entity: Entity, ppu = 100): MassData {
+ return {
+ mass: this.getMass(entity),
+ inertia: this.getInertia(entity),
+ centerOfMass: this.getCenterOfMass(entity, ppu),
+ };
+ }
+
+ getDistanceJointLength(entity: Entity, ppu = 100): number {
+ return this.module_._physics_getDistanceJointLength(entity) * ppu;
+ }
+
+ getDistanceJointCurrentLength(entity: Entity, ppu = 100): number {
+ return this.module_._physics_getDistanceJointCurrentLength(entity) * ppu;
+ }
+
+ setDistanceJointLength(entity: Entity, length: number, ppu = 100): void {
+ this.module_._physics_setDistanceJointLength(entity, length / ppu);
+ }
+
+ enableDistanceJointSpring(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableDistanceJointSpring(entity, enable ? 1 : 0);
+ }
+
+ enableDistanceJointLimit(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableDistanceJointLimit(entity, enable ? 1 : 0);
+ }
+
+ setDistanceJointLimits(entity: Entity, minLength: number, maxLength: number, ppu = 100): void {
+ this.module_._physics_setDistanceJointLimits(entity, minLength / ppu, maxLength / ppu);
+ }
+
+ enableDistanceJointMotor(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableDistanceJointMotor(entity, enable ? 1 : 0);
+ }
+
+ setDistanceJointMotorSpeed(entity: Entity, speed: number): void {
+ this.module_._physics_setDistanceJointMotorSpeed(entity, speed);
+ }
+
+ setDistanceJointMaxMotorForce(entity: Entity, force: number): void {
+ this.module_._physics_setDistanceJointMaxMotorForce(entity, force);
+ }
+
+ getDistanceJointMotorForce(entity: Entity): number {
+ return this.module_._physics_getDistanceJointMotorForce(entity);
+ }
+
+ getPrismaticJointTranslation(entity: Entity, ppu = 100): number {
+ return this.module_._physics_getPrismaticJointTranslation(entity) * ppu;
+ }
+
+ getPrismaticJointSpeed(entity: Entity, ppu = 100): number {
+ return this.module_._physics_getPrismaticJointSpeed(entity) * ppu;
+ }
+
+ enablePrismaticJointSpring(entity: Entity, enable: boolean): void {
+ this.module_._physics_enablePrismaticJointSpring(entity, enable ? 1 : 0);
+ }
+
+ enablePrismaticJointLimit(entity: Entity, enable: boolean): void {
+ this.module_._physics_enablePrismaticJointLimit(entity, enable ? 1 : 0);
+ }
+
+ setPrismaticJointLimits(entity: Entity, lower: number, upper: number, ppu = 100): void {
+ this.module_._physics_setPrismaticJointLimits(entity, lower / ppu, upper / ppu);
+ }
+
+ enablePrismaticJointMotor(entity: Entity, enable: boolean): void {
+ this.module_._physics_enablePrismaticJointMotor(entity, enable ? 1 : 0);
+ }
+
+ setPrismaticJointMotorSpeed(entity: Entity, speed: number): void {
+ this.module_._physics_setPrismaticJointMotorSpeed(entity, speed);
+ }
+
+ setPrismaticJointMaxMotorForce(entity: Entity, force: number): void {
+ this.module_._physics_setPrismaticJointMaxMotorForce(entity, force);
+ }
+
+ getPrismaticJointMotorForce(entity: Entity): number {
+ return this.module_._physics_getPrismaticJointMotorForce(entity);
+ }
+
+ enableWheelJointSpring(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableWheelJointSpring(entity, enable ? 1 : 0);
+ }
+
+ enableWheelJointLimit(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableWheelJointLimit(entity, enable ? 1 : 0);
+ }
+
+ setWheelJointLimits(entity: Entity, lower: number, upper: number, ppu = 100): void {
+ this.module_._physics_setWheelJointLimits(entity, lower / ppu, upper / ppu);
+ }
+
+ enableWheelJointMotor(entity: Entity, enable: boolean): void {
+ this.module_._physics_enableWheelJointMotor(entity, enable ? 1 : 0);
+ }
+
+ setWheelJointMotorSpeed(entity: Entity, speed: number): void {
+ this.module_._physics_setWheelJointMotorSpeed(entity, speed);
+ }
+
+ setWheelJointMaxMotorTorque(entity: Entity, torque: number): void {
+ this.module_._physics_setWheelJointMaxMotorTorque(entity, torque);
+ }
+
+ getWheelJointMotorTorque(entity: Entity): number {
+ return this.module_._physics_getWheelJointMotorTorque(entity);
+ }
+
+ private readUniqueEntityBuffer_(count: number): Entity[] {
+ if (count === 0) return [];
+ const ptr = this.module_._physics_getOverlapBuffer() >> 2;
+ const results: Entity[] = [];
+ const seen = new Set<number>();
+ for (let i = 0; i < count; i++) {
+ const entityId = this.module_.HEAPU32[ptr + i] as Entity;
+ if (!seen.has(entityId)) {
+ seen.add(entityId);
+ results.push(entityId);
+ }
+ }
+ return results;
+ }
+
+ private readShapeCastBuffer_(count: number, ppu: number): ShapeCastHit[] {
+ if (count === 0) return [];
+ const ptr = this.module_._physics_getShapeCastBuffer() >> 2;
+ const results: ShapeCastHit[] = [];
+ for (let i = 0; i < count; i++) {
+ const base = ptr + i * CAST_HIT_STRIDE;
+ results.push({
+ entity: this.module_.HEAPU32[base] as Entity,
+ point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
+ normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
+ fraction: this.module_.HEAPF32[base + 5],
+ });
+ }
+ results.sort((a, b) => a.fraction - b.fraction);
+ return results;
+ }
+
+ static setDebugDraw(app: App, enabled: boolean): void {
+ const config = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
+ if (config) {
+ config.enabled = enabled;
+ app.insertResource(PhysicsDebugDraw, config);
+ }
+ }
+
+ static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void {
+ const current = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
+ if (current) {
+ app.insertResource(PhysicsDebugDraw, { ...current, ...config });
+ }
+ }
+}
+
+/**
+ * Resource published by `PhysicsPlugin` once the wasm module is ready.
+ * Game code reads it as `app.getResource(PhysicsAPI)` to call forces,
+ * impulses, joint helpers, raycasts, etc.
+ */
+export const PhysicsAPI = defineResource<Physics>(null!, 'PhysicsAPI');
diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.ts
index ae463f55c..c7b7d9a75 100644
--- a/sdk/src/physics/PhysicsPlugin.ts
+++ b/sdk/src/physics/PhysicsPlugin.ts
@@ -1,146 +1,78 @@
/**
* @file PhysicsPlugin.ts
- * @brief Physics plugin using standalone Physics WASM module
+ * @brief Physics plugin — async wasm load + resource wiring
+ *
+ * Thin orchestration layer. Types live in `PhysicsTypes.ts`,
+ * the Physics API class in `Physics.ts`, and the per-frame loop
+ * + entity-tracking state in `PhysicsSystem.ts`. This file just
+ * loads the wasm module, wires resources, and hands off to the
+ * system layer.
*/
import type { Plugin, App } from '../app';
-import type { Entity, Vec2 } from '../types';
-import type { TransformData, ParentData, CanvasData } from '../component';
-import { Transform, Parent, Canvas } from '../component';
-import { defineResource, Res, Time, type TimeData } from '../resource';
-import { Schedule, defineSystem } from '../system';
-import { playModeOnly } from '../env';
import {
loadPhysicsModule,
type PhysicsWasmModule,
type PhysicsModuleFactory,
} from './PhysicsModuleLoader';
-import {
- RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
- SegmentCollider, PolygonCollider, ChainCollider,
- RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint,
- BodyType,
- type RigidBodyData, type BoxColliderData, type CircleColliderData,
- type CapsuleColliderData, type SegmentColliderData, type PolygonColliderData,
- type ChainColliderData, type RevoluteJointData,
- type DistanceJointData, type PrismaticJointData, type WeldJointData, type WheelJointData,
-} from './PhysicsComponents';
-import { setupPhysicsDebugDraw, PhysicsDebugDraw, type PhysicsDebugDrawConfig } from './PhysicsDebugDraw';
+import { setupPhysicsDebugDraw } from './PhysicsDebugDraw';
import { PhysicsRuntime } from './PhysicsRuntime';
+import { Physics, PhysicsAPI } from './Physics';
+import { registerPhysicsSystem } from './PhysicsSystem';
+import {
+ PhysicsEvents,
+ type PhysicsPluginConfig,
+ type ResolvedPhysicsConfig,
+} from './PhysicsTypes';
import { handleWasmError } from '../wasmError';
-// =============================================================================
-// Physics Config
-// =============================================================================
-
-export interface PhysicsPluginConfig {
- gravity?: Vec2;
- fixedTimestep?: number;
- subStepCount?: number;
- contactHertz?: number;
- contactDampingRatio?: number;
- contactSpeed?: number;
- collisionLayerMasks?: number[];
-}
-
-// =============================================================================
-// Collision Event Types
-// =============================================================================
-
-export interface CollisionEnterEvent {
- entityA: Entity;
- entityB: Entity;
- normalX: number;
- normalY: number;
- contactX: number;
- contactY: number;
-}
-
-export interface SensorEvent {
- sensorEntity: Entity;
- visitorEntity: Entity;
-}
-
-export interface PhysicsEventsData {
- collisionEnters: CollisionEnterEvent[];
- collisionExits: Array<{ entityA: Entity; entityB: Entity }>;
- sensorEnters: SensorEvent[];
- sensorExits: SensorEvent[];
-}
-
-export const PhysicsEvents = defineResource<PhysicsEventsData>({
- collisionEnters: [],
- collisionExits: [],
- sensorEnters: [],
- sensorExits: []
-}, 'PhysicsEvents');
-
-export interface RaycastHit {
- entity: Entity;
- point: Vec2;
- normal: Vec2;
- fraction: number;
-}
-
-export type ShapeCastHit = RaycastHit;
-
-export interface MassData {
- mass: number;
- inertia: number;
- centerOfMass: Vec2;
-}
-
-const COLLISION_EVENT_STRIDE = 6;
-const CAST_HIT_STRIDE = 6;
-
-export const PhysicsAPI = defineResource<Physics>(null!, 'PhysicsAPI');
+// Re-export the shapes consumers reach for via the plugin file so
+// existing `import from './physics/PhysicsPlugin'` sites keep working.
+export {
+ PhysicsEvents,
+ PhysicsAPI,
+ Physics,
+};
+export type {
+ PhysicsPluginConfig,
+ PhysicsEventsData,
+ CollisionEnterEvent,
+ SensorEvent,
+ RaycastHit,
+ ShapeCastHit,
+ MassData,
+} from './PhysicsTypes';
// =============================================================================
-// Quaternion <-> angle helpers
+// Config defaults
// =============================================================================
-function quatToAngleZ(q: { w: number; x: number; y: number; z: number }): number {
- return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
-}
-
-function angleZToQuat(angle: number): { w: number; x: number; y: number; z: number } {
- const half = angle * 0.5;
- return { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) };
+function resolveConfig(config: PhysicsPluginConfig): ResolvedPhysicsConfig {
+ return {
+ gravity: config.gravity ?? { x: 0, y: -9.81 },
+ fixedTimestep: config.fixedTimestep ?? 1 / 30,
+ subStepCount: config.subStepCount ?? 4,
+ contactHertz: config.contactHertz ?? 30,
+ contactDampingRatio: config.contactDampingRatio ?? 10,
+ contactSpeed: config.contactSpeed ?? 3,
+ collisionLayerMasks: config.collisionLayerMasks,
+ };
}
// =============================================================================
-// Physics Plugin
+// Plugin
// =============================================================================
-function readPixelsPerUnit(app: App): number {
- const entities = app.world.getEntitiesWithComponents([Canvas]);
- for (const entity of entities) {
- const canvas = app.world.get(entity, Canvas) as CanvasData;
- if (canvas && canvas.pixelsPerUnit) {
- return canvas.pixelsPerUnit;
- }
- }
- return 100;
-}
-
export class PhysicsPlugin implements Plugin {
name = 'physics';
- private config_: Required<Omit<PhysicsPluginConfig, 'collisionLayerMasks'>> & Pick<PhysicsPluginConfig, 'collisionLayerMasks'>;
+ private config_: ResolvedPhysicsConfig;
private wasmUrl_: string;
private factory_?: PhysicsModuleFactory;
constructor(wasmUrl: string, config: PhysicsPluginConfig = {}, factory?: PhysicsModuleFactory) {
this.wasmUrl_ = wasmUrl;
this.factory_ = factory;
- this.config_ = {
- gravity: config.gravity ?? { x: 0, y: -9.81 },
- fixedTimestep: config.fixedTimestep ?? 1 / 30,
- subStepCount: config.subStepCount ?? 4,
- contactHertz: config.contactHertz ?? 30,
- contactDampingRatio: config.contactDampingRatio ?? 10,
- contactSpeed: config.contactSpeed ?? 3,
- collisionLayerMasks: config.collisionLayerMasks,
- };
+ this.config_ = resolveConfig(config);
}
build(app: App): void {
@@ -148,16 +80,10 @@ export class PhysicsPlugin implements Plugin {
collisionEnters: [],
collisionExits: [],
sensorEnters: [],
- sensorExits: []
+ sensorExits: [],
});
app.insertResource(PhysicsRuntime, { module: null, initPromise: null });
- const trackedEntities = new Set<Entity>();
- const trackedJoints = new Set<Entity>();
- const parentedBodies = new Set<Entity>();
- const cachedProps = new Map<Entity, { bodyType: number; gravityScale: number; linearDamping: number; angularDamping: number; fixedRotation: boolean; bullet: boolean }>();
- let lastEntitySyncTick = -1;
-
const initPromise = loadPhysicsModule(this.wasmUrl_, this.factory_).then(
(module: PhysicsWasmModule) => {
module._physics_init(
@@ -167,139 +93,16 @@ export class PhysicsPlugin implements Plugin {
this.config_.subStepCount,
this.config_.contactHertz,
this.config_.contactDampingRatio,
- this.config_.contactSpeed
+ this.config_.contactSpeed,
);
- const world = app.world;
-
- world.onDespawn((entity: Entity) => {
- if (trackedJoints.has(entity)) {
- module._physics_destroyJoint(entity);
- trackedJoints.delete(entity);
- }
- if (trackedEntities.has(entity)) {
- module._physics_destroyBody(entity);
- trackedEntities.delete(entity);
- cachedProps.delete(entity);
- parentedBodies.delete(entity);
- }
- });
-
- app.addSystemToSchedule(
- Schedule.PostUpdate,
- 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 value
- // captured when the wasm module first loaded.
- const ppu = readPixelsPerUnit(app);
- const invPpu = 1 / ppu;
- const entities = world.getEntitiesWithComponents([RigidBody, Transform]);
- const currentEntities = new Set<Entity>();
-
- for (const entity of entities) {
- currentEntities.add(entity);
-
- if (!trackedEntities.has(entity)) {
- const rb = world.get(entity, RigidBody) as RigidBodyData;
- if (!rb.enabled) continue;
- const wt = world.get(entity, Transform) as TransformData;
- const hasParent = world.has(entity, Parent);
- const posX = hasParent ? wt.worldPosition.x : wt.position.x;
- const posY = hasParent ? wt.worldPosition.y : wt.position.y;
- const rot = hasParent ? wt.worldRotation : wt.rotation;
- const angle = quatToAngleZ(rot);
-
- module._physics_createBody(
- entity, rb.bodyType,
- posX * invPpu, posY * invPpu, angle,
- rb.gravityScale, rb.linearDamping, rb.angularDamping,
- rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0
- );
-
- addShapeForEntity(app, module, entity, this.config_.collisionLayerMasks);
- trackedEntities.add(entity);
- if (world.has(entity, Parent)) {
- parentedBodies.add(entity);
- }
- cachedProps.set(entity, {
- bodyType: rb.bodyType,
- gravityScale: rb.gravityScale,
- linearDamping: rb.linearDamping,
- angularDamping: rb.angularDamping,
- fixedRotation: rb.fixedRotation,
- bullet: rb.bullet,
- });
- } else {
- if (world.isChangedSince(entity, RigidBody, lastEntitySyncTick)) {
- const rb = world.get(entity, RigidBody) as RigidBodyData;
- const prev = cachedProps.get(entity);
- if (prev &&
- (prev.bodyType !== rb.bodyType ||
- prev.gravityScale !== rb.gravityScale ||
- prev.linearDamping !== rb.linearDamping ||
- prev.angularDamping !== rb.angularDamping ||
- prev.fixedRotation !== rb.fixedRotation ||
- prev.bullet !== rb.bullet)) {
- module._physics_updateBodyProperties(
- entity, rb.bodyType,
- rb.gravityScale, rb.linearDamping, rb.angularDamping,
- rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0
- );
- prev.bodyType = rb.bodyType;
- prev.gravityScale = rb.gravityScale;
- prev.linearDamping = rb.linearDamping;
- prev.angularDamping = rb.angularDamping;
- prev.fixedRotation = rb.fixedRotation;
- prev.bullet = rb.bullet;
- }
- }
-
- const cached = cachedProps.get(entity);
- if (cached && cached.bodyType === BodyType.Kinematic) {
- const wt = world.get(entity, Transform) as TransformData;
- const angle = quatToAngleZ(wt.worldRotation);
- module._physics_setBodyTransform(
- entity,
- wt.worldPosition.x * invPpu, wt.worldPosition.y * invPpu,
- angle
- );
- }
- }
- }
-
- lastEntitySyncTick = world.getWorldTick();
-
- for (const entity of trackedEntities) {
- if (!currentEntities.has(entity)) {
- module._physics_destroyBody(entity);
- trackedEntities.delete(entity);
- cachedProps.delete(entity);
- }
- }
-
- createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);
-
- if (trackedEntities.size > 0 && time.delta > 0) {
- module._physics_step(time.delta);
- }
-
- syncDynamicTransforms(app, module, ppu, parentedBodies);
- collectEvents(app, module, ppu);
- },
- { name: 'PhysicsSystem' }
- ),
- { runIf: playModeOnly }
- );
+ registerPhysicsSystem(app, module, this.config_);
app.getResource(PhysicsRuntime).module = module;
app.insertResource(PhysicsAPI, Physics._fromModule(module));
setupPhysicsDebugDraw(app, PhysicsAPI, PhysicsEvents);
app.setFixedTimestep(this.config_.fixedTimestep);
- }
+ },
);
initPromise.catch((e) => {
@@ -308,798 +111,3 @@ export class PhysicsPlugin implements Plugin {
app.getResource(PhysicsRuntime).initPromise = initPromise;
}
}
-
-// =============================================================================
-// Internal helpers
-// =============================================================================
-
-const MAX_COLLISION_LAYERS = 16;
-
-function resolveCollisionMask(categoryBits: number, maskBits: number, layerMasks?: number[]): number {
- if (!layerMasks) return maskBits;
- for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
- if (categoryBits === (1 << i)) return layerMasks[i];
- }
- return maskBits;
-}
-
-function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity, layerMasks?: number[]): void {
- const world = app.world;
-
- if (world.has(entity, BoxCollider)) {
- const box = world.get(entity, BoxCollider) as BoxColliderData;
- const category = box.categoryBits ?? 0x0001;
- const mask = resolveCollisionMask(category, box.maskBits ?? 0xFFFF, layerMasks);
- module._physics_addBoxShape(
- entity, box.halfExtents.x, box.halfExtents.y,
- box.offset.x, box.offset.y, box.radius ?? 0.05,
- box.density, box.friction, box.restitution, box.isSensor ? 1 : 0,
- category, mask
- );
- }
-
- if (world.has(entity, CircleCollider)) {
- const circle = world.get(entity, CircleCollider) as CircleColliderData;
- const category = circle.categoryBits ?? 0x0001;
- const mask = resolveCollisionMask(category, circle.maskBits ?? 0xFFFF, layerMasks);
- module._physics_addCircleShape(
- entity, circle.radius,
- circle.offset.x, circle.offset.y,
- circle.density, circle.friction, circle.restitution, circle.isSensor ? 1 : 0,
- category, mask
- );
- }
-
- if (world.has(entity, CapsuleCollider)) {
- const capsule = world.get(entity, CapsuleCollider) as CapsuleColliderData;
- const category = capsule.categoryBits ?? 0x0001;
- const mask = resolveCollisionMask(category, capsule.maskBits ?? 0xFFFF, layerMasks);
- module._physics_addCapsuleShape(
- entity, capsule.radius, capsule.halfHeight,
- capsule.offset.x, capsule.offset.y,
- capsule.density, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0,
- category, mask
- );
- }
-
- if (world.has(entity, SegmentCollider)) {
- const seg = world.get(entity, SegmentCollider) as SegmentColliderData;
- const category = seg.categoryBits ?? 0x0001;
- const mask = resolveCollisionMask(category, seg.maskBits ?? 0xFFFF, layerMasks);
- module._physics_addSegmentShape(
- entity, seg.point1.x, seg.point1.y, seg.point2.x, seg.point2.y,
- seg.density, seg.friction, seg.restitution, seg.isSensor ? 1 : 0,
- category, mask
- );
- }
-
- if (world.has(entity, PolygonCollider)) {
- const poly = world.get(entity, PolygonCollider) as PolygonColliderData;
- const category = poly.categoryBits ?? 0x0001;
- const mask = resolveCollisionMask(category, poly.maskBits ?? 0xFFFF, layerMasks);
- const verts = poly.vertices;
- const count = Math.min(verts.length, 8);
- const byteSize = count * 2 * 4;
- const ptr = module._malloc(byteSize);
- const base = ptr >> 2;
- for (let i = 0; i < count; i++) {
- module.HEAPF32[base + i * 2] = verts[i].x;
- module.HEAPF32[base + i * 2 + 1] = verts[i].y;
- }
- module._physics_addPolygonShape(
- entity, ptr, count, poly.radius ?? 0,
- poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
- category, mask
- );
- module._free(ptr);
- }
-
- if (world.has(entity, ChainCollider)) {
- const chain = world.get(entity, ChainCollider) as ChainColliderData;
- const pts = chain.points;
- if (pts.length < 4) return;
- const byteSize = pts.length * 2 * 4;
- const ptr = module._malloc(byteSize);
- const base = ptr >> 2;
- for (let i = 0; i < pts.length; i++) {
- module.HEAPF32[base + i * 2] = pts[i].x;
- module.HEAPF32[base + i * 2 + 1] = pts[i].y;
- }
- module._physics_addChainShape(
- entity, ptr, pts.length, chain.isLoop ? 1 : 0,
- chain.friction, chain.restitution,
- chain.categoryBits ?? 0x0001, chain.maskBits ?? 0xFFFF
- );
- module._free(ptr);
- }
-}
-
-function createPendingJoints(
- world: App['world'],
- module: PhysicsWasmModule,
- trackedEntities: Set<Entity>,
- trackedJoints: Set<Entity>,
- invPpu: number,
-): void {
- const jointEntities = world.getEntitiesWithComponents([RevoluteJoint, RigidBody]);
- for (const entity of jointEntities) {
- if (trackedJoints.has(entity)) continue;
- if (!trackedEntities.has(entity)) continue;
- const joint = world.get(entity, RevoluteJoint) as RevoluteJointData;
- if (!joint.enabled) continue;
- const connected = joint.connectedEntity as Entity;
- if (!trackedEntities.has(connected)) continue;
- module._physics_createRevoluteJoint(
- connected, entity,
- joint.anchorA.x * invPpu, joint.anchorA.y * invPpu,
- joint.anchorB.x * invPpu, joint.anchorB.y * invPpu,
- joint.enableMotor ? 1 : 0, joint.motorSpeed, joint.maxMotorTorque,
- joint.enableLimit ? 1 : 0, joint.lowerAngle, joint.upperAngle,
- joint.collideConnected ? 1 : 0,
- );
- trackedJoints.add(entity);
- }
-
- for (const entity of world.getEntitiesWithComponents([DistanceJoint, RigidBody])) {
- if (trackedJoints.has(entity)) continue;
- if (!trackedEntities.has(entity)) continue;
- const j = world.get(entity, DistanceJoint) as DistanceJointData;
- if (!j.enabled) continue;
- const connected = j.connectedEntity as Entity;
- if (!trackedEntities.has(connected)) continue;
- module._physics_createDistanceJoint(
- connected, entity,
- j.anchorA.x * invPpu, j.anchorA.y * invPpu,
- j.anchorB.x * invPpu, j.anchorB.y * invPpu,
- j.length * invPpu,
- j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
- j.enableLimit ? 1 : 0, j.minLength * invPpu, j.maxLength * invPpu,
- j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,
- j.collideConnected ? 1 : 0,
- );
- trackedJoints.add(entity);
- }
-
- for (const entity of world.getEntitiesWithComponents([PrismaticJoint, RigidBody])) {
- if (trackedJoints.has(entity)) continue;
- if (!trackedEntities.has(entity)) continue;
- const j = world.get(entity, PrismaticJoint) as PrismaticJointData;
- if (!j.enabled) continue;
- const connected = j.connectedEntity as Entity;
- if (!trackedEntities.has(connected)) continue;
- module._physics_createPrismaticJoint(
- connected, entity,
- j.anchorA.x * invPpu, j.anchorA.y * invPpu,
- j.anchorB.x * invPpu, j.anchorB.y * invPpu,
- j.axis.x, j.axis.y,
- j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
- j.enableLimit ? 1 : 0, j.lowerTranslation * invPpu, j.upperTranslation * invPpu,
- j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,
- j.collideConnected ? 1 : 0,
- );
- trackedJoints.add(entity);
- }
-
- for (const entity of world.getEntitiesWithComponents([WeldJoint, RigidBody])) {
- if (trackedJoints.has(entity)) continue;
- if (!trackedEntities.has(entity)) continue;
- const j = world.get(entity, WeldJoint) as WeldJointData;
- if (!j.enabled) continue;
- const connected = j.connectedEntity as Entity;
- if (!trackedEntities.has(connected)) continue;
- module._physics_createWeldJoint(
- connected, entity,
- j.anchorA.x * invPpu, j.anchorA.y * invPpu,
- j.anchorB.x * invPpu, j.anchorB.y * invPpu,
- j.linearHertz, j.angularHertz,
- j.linearDampingRatio, j.angularDampingRatio,
- j.collideConnected ? 1 : 0,
- );
- trackedJoints.add(entity);
- }
-
- for (const entity of world.getEntitiesWithComponents([WheelJoint, RigidBody])) {
- if (trackedJoints.has(entity)) continue;
- if (!trackedEntities.has(entity)) continue;
- const j = world.get(entity, WheelJoint) as WheelJointData;
- if (!j.enabled) continue;
- const connected = j.connectedEntity as Entity;
- if (!trackedEntities.has(connected)) continue;
- module._physics_createWheelJoint(
- connected, entity,
- j.anchorA.x * invPpu, j.anchorA.y * invPpu,
- j.anchorB.x * invPpu, j.anchorB.y * invPpu,
- j.axis.x, j.axis.y,
- j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
- j.enableLimit ? 1 : 0, j.lowerTranslation * invPpu, j.upperTranslation * invPpu,
- j.enableMotor ? 1 : 0, j.maxMotorTorque, j.motorSpeed,
- j.collideConnected ? 1 : 0,
- );
- trackedJoints.add(entity);
- }
-}
-
-const syncTransformBuf_ = {
- position: { x: 0, y: 0, z: 0 },
- rotation: { w: 1, x: 0, y: 0, z: 0 },
- scale: { x: 1, y: 1, z: 1 },
- worldPosition: { x: 0, y: 0, z: 0 },
- worldRotation: { w: 1, x: 0, y: 0, z: 0 },
- worldScale: { x: 1, y: 1, z: 1 },
-};
-
-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(
- app: App,
- module: PhysicsWasmModule,
- ppu: number,
- parentedBodies: Set<Entity>,
-): void {
- const count = module._physics_getDynamicBodyCount();
- 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;
-
- if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {
- const byteLen = count * PHYSICS_BODY_BYTES;
- const engineBuf = engineMod._malloc(byteLen);
- engineMod.HEAPU8.set(
- new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),
- engineBuf,
- );
- engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);
- engineMod._free(engineBuf);
- return;
- }
-
- const getTransformPtr = engineMod?.getTransformPtr
- ? (e: Entity) => engineMod!.getTransformPtr(registry!, e as number)
- : null;
- const engF32 = engineMod?.HEAPF32;
- 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];
-
- 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 cos = Math.cos(-parentAngleZ);
- const sin = Math.sin(-parentAngleZ);
- const sx = pwt.worldScale.x !== 0 ? pwt.worldScale.x : 1;
- const sy = pwt.worldScale.y !== 0 ? pwt.worldScale.y : 1;
- localX = (dx * cos - dy * sin) / sx;
- localY = (dx * sin + dy * cos) / sy;
- localAngle = localAngle - parentAngleZ;
- }
- }
-
- const half = localAngle * 0.5;
- const cosH = Math.cos(half);
- const sinH = Math.sin(half);
-
- if (getTransformPtr && engF32) {
- const tPtr = getTransformPtr(entityId);
- if (tPtr) {
- const fi = tPtr >> 2;
- engF32[fi] = localX;
- engF32[fi + 1] = localY;
- engF32[fi + 2] = 0;
- engF32[fi + 3] = 0;
- engF32[fi + 4] = 0;
- engF32[fi + 5] = sinH;
- engF32[fi + 6] = cosH;
- engF32[fi + 7] = 1;
- engF32[fi + 8] = 1;
- engF32[fi + 9] = 1;
- engF32[fi + 10] = localX;
- engF32[fi + 11] = localY;
- engF32[fi + 12] = 0;
- engF32[fi + 13] = 0;
- engF32[fi + 14] = 0;
- engF32[fi + 15] = sinH;
- engF32[fi + 16] = cosH;
- engF32[fi + 17] = 1;
- engF32[fi + 18] = 1;
- engF32[fi + 19] = 1;
- continue;
- }
- }
-
- t.position.x = localX;
- t.position.y = localY;
- t.rotation.w = cosH;
- t.rotation.x = 0;
- t.rotation.y = 0;
- t.rotation.z = sinH;
- t.worldPosition.x = localX;
- t.worldPosition.y = localY;
- t.worldRotation.w = cosH;
- t.worldRotation.x = 0;
- t.worldRotation.y = 0;
- t.worldRotation.z = sinH;
-
- addFn!(entityId, t);
- }
-}
-
-function collectEvents(app: App, module: PhysicsWasmModule, ppu: number): 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({
- entityA: module.HEAPU32[base] as Entity,
- entityB: module.HEAPU32[base + 1] as Entity,
- normalX: module.HEAPF32[base + 2],
- normalY: module.HEAPF32[base + 3],
- contactX: module.HEAPF32[base + 4] * ppu,
- contactY: module.HEAPF32[base + 5] * ppu,
- });
- }
- }
-
- 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({
- 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({
- 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({
- sensorEntity: module.HEAPU32[base] as Entity,
- visitorEntity: module.HEAPU32[base + 1] as Entity,
- });
- }
- }
-
- app.insertResource(PhysicsEvents, {
- collisionEnters,
- collisionExits,
- sensorEnters,
- sensorExits
- });
-}
-
-// =============================================================================
-// Physics API Helper
-// =============================================================================
-
-export class Physics {
- private module_: PhysicsWasmModule;
-
- constructor(app: App) {
- const module = app.hasResource(PhysicsRuntime)
- ? app.getResource(PhysicsRuntime).module
- : null;
- if (!module) {
- throw new Error('Physics module not loaded. Ensure PhysicsPlugin init is complete.');
- }
- this.module_ = module;
- }
-
- /** @internal */
- static _fromModule(module: PhysicsWasmModule): Physics {
- const instance = Object.create(Physics.prototype) as Physics;
- instance.module_ = module;
- return instance;
- }
-
- applyForce(entity: Entity, force: Vec2): void {
- this.module_._physics_applyForce(entity, force.x, force.y);
- }
-
- applyImpulse(entity: Entity, impulse: Vec2): void {
- this.module_._physics_applyImpulse(entity, impulse.x, impulse.y);
- }
-
- setLinearVelocity(entity: Entity, velocity: Vec2): void {
- this.module_._physics_setLinearVelocity(entity, velocity.x, velocity.y);
- }
-
- getLinearVelocity(entity: Entity): Vec2 {
- const ptr = this.module_._physics_getLinearVelocity(entity);
- const base = ptr >> 2;
- return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
- }
-
- setGravity(gravity: Vec2): void {
- this.module_._physics_setGravity(gravity.x, gravity.y);
- }
-
- getGravity(): Vec2 {
- const ptr = this.module_._physics_getGravity();
- const base = ptr >> 2;
- return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
- }
-
- setAngularVelocity(entity: Entity, omega: number): void {
- this.module_._physics_setAngularVelocity(entity, omega);
- }
-
- getAngularVelocity(entity: Entity): number {
- return this.module_._physics_getAngularVelocity(entity);
- }
-
- applyTorque(entity: Entity, torque: number): void {
- this.module_._physics_applyTorque(entity, torque);
- }
-
- applyAngularImpulse(entity: Entity, impulse: number): void {
- this.module_._physics_applyAngularImpulse(entity, impulse);
- }
-
- createRevoluteJoint(
- entityA: Entity, entityB: Entity,
- anchorA: Vec2, anchorB: Vec2,
- options?: {
- enableMotor?: boolean; motorSpeed?: number; maxMotorTorque?: number;
- enableLimit?: boolean; lowerAngle?: number; upperAngle?: number;
- collideConnected?: boolean;
- }
- ): boolean {
- const o = options ?? {};
- return this.module_._physics_createRevoluteJoint(
- entityA, entityB,
- anchorA.x, anchorA.y, anchorB.x, anchorB.y,
- o.enableMotor ? 1 : 0, o.motorSpeed ?? 0, o.maxMotorTorque ?? 0,
- o.enableLimit ? 1 : 0, o.lowerAngle ?? 0, o.upperAngle ?? 0,
- o.collideConnected ? 1 : 0,
- ) !== 0;
- }
-
- destroyJoint(entity: Entity): void {
- this.module_._physics_destroyJoint(entity);
- }
-
- setRevoluteMotorSpeed(entity: Entity, speed: number): void {
- this.module_._physics_setRevoluteMotorSpeed(entity, speed);
- }
-
- setRevoluteMaxMotorTorque(entity: Entity, torque: number): void {
- this.module_._physics_setRevoluteMaxMotorTorque(entity, torque);
- }
-
- enableRevoluteMotor(entity: Entity, enable: boolean): void {
- this.module_._physics_enableRevoluteMotor(entity, enable ? 1 : 0);
- }
-
- enableRevoluteLimit(entity: Entity, enable: boolean): void {
- this.module_._physics_enableRevoluteLimit(entity, enable ? 1 : 0);
- }
-
- setRevoluteLimits(entity: Entity, lower: number, upper: number): void {
- this.module_._physics_setRevoluteLimits(entity, lower, upper);
- }
-
- getRevoluteAngle(entity: Entity): number {
- return this.module_._physics_getRevoluteAngle(entity);
- }
-
- getRevoluteMotorTorque(entity: Entity): number {
- return this.module_._physics_getRevoluteMotorTorque(entity);
- }
-
- raycast(
- origin: Vec2, direction: Vec2, maxDistance: number,
- maskBits = 0xFFFF, ppu = 100,
- ): RaycastHit[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_raycast(
- origin.x * invPpu, origin.y * invPpu,
- direction.x, direction.y,
- maxDistance * invPpu, maskBits,
- );
- if (count === 0) return [];
-
- const ptr = this.module_._physics_getRaycastBuffer() >> 2;
- const results: RaycastHit[] = [];
- for (let i = 0; i < count; i++) {
- const base = ptr + i * CAST_HIT_STRIDE;
- results.push({
- entity: this.module_.HEAPU32[base] as Entity,
- point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
- normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
- fraction: this.module_.HEAPF32[base + 5],
- });
- }
- results.sort((a, b) => a.fraction - b.fraction);
- return results;
- }
-
- overlapCircle(center: Vec2, radius: number, maskBits = 0xFFFF, ppu = 100): Entity[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_overlapCircle(
- center.x * invPpu, center.y * invPpu,
- radius * invPpu, maskBits,
- );
- return this.readUniqueEntityBuffer_(count);
- }
-
- setAwake(entity: Entity, awake: boolean): void {
- this.module_._physics_setAwake(entity, awake ? 1 : 0);
- }
-
- isAwake(entity: Entity): boolean {
- return this.module_._physics_isAwake(entity) !== 0;
- }
-
- shapeCastCircle(
- center: Vec2, radius: number, translation: Vec2,
- maskBits = 0xFFFF, ppu = 100,
- ): ShapeCastHit[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_shapeCastCircle(
- center.x * invPpu, center.y * invPpu, radius * invPpu,
- translation.x * invPpu, translation.y * invPpu, maskBits,
- );
- return this.readShapeCastBuffer_(count, ppu);
- }
-
- shapeCastBox(
- center: Vec2, halfExtents: Vec2, angle: number, translation: Vec2,
- maskBits = 0xFFFF, ppu = 100,
- ): ShapeCastHit[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_shapeCastBox(
- center.x * invPpu, center.y * invPpu,
- halfExtents.x * invPpu, halfExtents.y * invPpu, angle,
- translation.x * invPpu, translation.y * invPpu, maskBits,
- );
- return this.readShapeCastBuffer_(count, ppu);
- }
-
- shapeCastCapsule(
- center1: Vec2, center2: Vec2, radius: number, translation: Vec2,
- maskBits = 0xFFFF, ppu = 100,
- ): ShapeCastHit[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_shapeCastCapsule(
- center1.x * invPpu, center1.y * invPpu,
- center2.x * invPpu, center2.y * invPpu,
- radius * invPpu,
- translation.x * invPpu, translation.y * invPpu, maskBits,
- );
- return this.readShapeCastBuffer_(count, ppu);
- }
-
- overlapAABB(min: Vec2, max: Vec2, maskBits = 0xFFFF, ppu = 100): Entity[] {
- const invPpu = 1 / ppu;
- const count = this.module_._physics_overlapAABB(
- min.x * invPpu, min.y * invPpu,
- max.x * invPpu, max.y * invPpu, maskBits,
- );
- return this.readUniqueEntityBuffer_(count);
- }
-
- getMass(entity: Entity): number {
- return this.module_._physics_getBodyMass(entity);
- }
-
- getInertia(entity: Entity): number {
- return this.module_._physics_getBodyInertia(entity);
- }
-
- getCenterOfMass(entity: Entity, ppu = 100): Vec2 {
- const ptr = this.module_._physics_getBodyCenterOfMass(entity);
- const base = ptr >> 2;
- return {
- x: this.module_.HEAPF32[base] * ppu,
- y: this.module_.HEAPF32[base + 1] * ppu,
- };
- }
-
- getMassData(entity: Entity, ppu = 100): MassData {
- return {
- mass: this.getMass(entity),
- inertia: this.getInertia(entity),
- centerOfMass: this.getCenterOfMass(entity, ppu),
- };
- }
-
- getDistanceJointLength(entity: Entity, ppu = 100): number {
- return this.module_._physics_getDistanceJointLength(entity) * ppu;
- }
-
- getDistanceJointCurrentLength(entity: Entity, ppu = 100): number {
- return this.module_._physics_getDistanceJointCurrentLength(entity) * ppu;
- }
-
- setDistanceJointLength(entity: Entity, length: number, ppu = 100): void {
- this.module_._physics_setDistanceJointLength(entity, length / ppu);
- }
-
- enableDistanceJointSpring(entity: Entity, enable: boolean): void {
- this.module_._physics_enableDistanceJointSpring(entity, enable ? 1 : 0);
- }
-
- enableDistanceJointLimit(entity: Entity, enable: boolean): void {
- this.module_._physics_enableDistanceJointLimit(entity, enable ? 1 : 0);
- }
-
- setDistanceJointLimits(entity: Entity, minLength: number, maxLength: number, ppu = 100): void {
- this.module_._physics_setDistanceJointLimits(entity, minLength / ppu, maxLength / ppu);
- }
-
- enableDistanceJointMotor(entity: Entity, enable: boolean): void {
- this.module_._physics_enableDistanceJointMotor(entity, enable ? 1 : 0);
- }
-
- setDistanceJointMotorSpeed(entity: Entity, speed: number): void {
- this.module_._physics_setDistanceJointMotorSpeed(entity, speed);
- }
-
- setDistanceJointMaxMotorForce(entity: Entity, force: number): void {
- this.module_._physics_setDistanceJointMaxMotorForce(entity, force);
- }
-
- getDistanceJointMotorForce(entity: Entity): number {
- return this.module_._physics_getDistanceJointMotorForce(entity);
- }
-
- getPrismaticJointTranslation(entity: Entity, ppu = 100): number {
- return this.module_._physics_getPrismaticJointTranslation(entity) * ppu;
- }
-
- getPrismaticJointSpeed(entity: Entity, ppu = 100): number {
- return this.module_._physics_getPrismaticJointSpeed(entity) * ppu;
- }
-
- enablePrismaticJointSpring(entity: Entity, enable: boolean): void {
- this.module_._physics_enablePrismaticJointSpring(entity, enable ? 1 : 0);
- }
-
- enablePrismaticJointLimit(entity: Entity, enable: boolean): void {
- this.module_._physics_enablePrismaticJointLimit(entity, enable ? 1 : 0);
- }
-
- setPrismaticJointLimits(entity: Entity, lower: number, upper: number, ppu = 100): void {
- this.module_._physics_setPrismaticJointLimits(entity, lower / ppu, upper / ppu);
- }
-
- enablePrismaticJointMotor(entity: Entity, enable: boolean): void {
- this.module_._physics_enablePrismaticJointMotor(entity, enable ? 1 : 0);
- }
-
- setPrismaticJointMotorSpeed(entity: Entity, speed: number): void {
- this.module_._physics_setPrismaticJointMotorSpeed(entity, speed);
- }
-
- setPrismaticJointMaxMotorForce(entity: Entity, force: number): void {
- this.module_._physics_setPrismaticJointMaxMotorForce(entity, force);
- }
-
- getPrismaticJointMotorForce(entity: Entity): number {
- return this.module_._physics_getPrismaticJointMotorForce(entity);
- }
-
- enableWheelJointSpring(entity: Entity, enable: boolean): void {
- this.module_._physics_enableWheelJointSpring(entity, enable ? 1 : 0);
- }
-
- enableWheelJointLimit(entity: Entity, enable: boolean): void {
- this.module_._physics_enableWheelJointLimit(entity, enable ? 1 : 0);
- }
-
- setWheelJointLimits(entity: Entity, lower: number, upper: number, ppu = 100): void {
- this.module_._physics_setWheelJointLimits(entity, lower / ppu, upper / ppu);
- }
-
- enableWheelJointMotor(entity: Entity, enable: boolean): void {
- this.module_._physics_enableWheelJointMotor(entity, enable ? 1 : 0);
- }
-
- setWheelJointMotorSpeed(entity: Entity, speed: number): void {
- this.module_._physics_setWheelJointMotorSpeed(entity, speed);
- }
-
- setWheelJointMaxMotorTorque(entity: Entity, torque: number): void {
- this.module_._physics_setWheelJointMaxMotorTorque(entity, torque);
- }
-
- getWheelJointMotorTorque(entity: Entity): number {
- return this.module_._physics_getWheelJointMotorTorque(entity);
- }
-
- private readUniqueEntityBuffer_(count: number): Entity[] {
- if (count === 0) return [];
- const ptr = this.module_._physics_getOverlapBuffer() >> 2;
- const results: Entity[] = [];
- const seen = new Set<number>();
- for (let i = 0; i < count; i++) {
- const entityId = this.module_.HEAPU32[ptr + i] as Entity;
- if (!seen.has(entityId)) {
- seen.add(entityId);
- results.push(entityId);
- }
- }
- return results;
- }
-
- private readShapeCastBuffer_(count: number, ppu: number): ShapeCastHit[] {
- if (count === 0) return [];
- const ptr = this.module_._physics_getShapeCastBuffer() >> 2;
- const results: ShapeCastHit[] = [];
- for (let i = 0; i < count; i++) {
- const base = ptr + i * CAST_HIT_STRIDE;
- results.push({
- entity: this.module_.HEAPU32[base] as Entity,
- point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
- normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
- fraction: this.module_.HEAPF32[base + 5],
- });
- }
- results.sort((a, b) => a.fraction - b.fraction);
- return results;
- }
-
- static setDebugDraw(app: App, enabled: boolean): void {
- const config = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
- if (config) {
- config.enabled = enabled;
- app.insertResource(PhysicsDebugDraw, config);
- }
- }
-
- static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void {
- const current = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
- if (current) {
- app.insertResource(PhysicsDebugDraw, { ...current, ...config });
- }
- }
-}
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
new file mode 100644
index 000000000..51cfd0ec1
--- /dev/null
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -0,0 +1,628 @@
+/**
+ * @file PhysicsSystem.ts
+ * @brief Per-frame physics driver: entity tracking, shape/joint create,
+ * step, transform readback, event collection.
+ *
+ * `registerPhysicsSystem` owns all closure state (tracked bodies, joint
+ * cache, cached RigidBody props). `PhysicsPlugin.build()` calls it once
+ * the wasm module finishes loading.
+ */
+
+import type { App } from '../app';
+import type { Entity } from '../types';
+import type { TransformData, ParentData, CanvasData } from '../component';
+import { Transform, Parent, Canvas } from '../component';
+import { Res, Time, type TimeData } from '../resource';
+import { Schedule, defineSystem } from '../system';
+import { playModeOnly } from '../env';
+import type { PhysicsWasmModule } from './PhysicsModuleLoader';
+import {
+ RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
+ SegmentCollider, PolygonCollider, ChainCollider,
+ RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint,
+ BodyType,
+ type RigidBodyData, type BoxColliderData, type CircleColliderData,
+ type CapsuleColliderData, type SegmentColliderData, type PolygonColliderData,
+ type ChainColliderData, type RevoluteJointData,
+ type DistanceJointData, type PrismaticJointData, type WeldJointData, type WheelJointData,
+} from './PhysicsComponents';
+import {
+ PhysicsEvents,
+ COLLISION_EVENT_STRIDE,
+ quatToAngleZ,
+ type ResolvedPhysicsConfig,
+ type CollisionEnterEvent,
+ type SensorEvent,
+} from './PhysicsTypes';
+
+// =============================================================================
+// Canvas pixelsPerUnit live read
+// =============================================================================
+
+function readPixelsPerUnit(app: App): number {
+ const entities = app.world.getEntitiesWithComponents([Canvas]);
+ for (const entity of entities) {
+ const canvas = app.world.get(entity, Canvas) as CanvasData;
+ if (canvas && canvas.pixelsPerUnit) {
+ return canvas.pixelsPerUnit;
+ }
+ }
+ return 100;
+}
+
+// =============================================================================
+// Collision filter resolution
+// =============================================================================
+
+const MAX_COLLISION_LAYERS = 16;
+
+function resolveCollisionMask(categoryBits: number, maskBits: number, layerMasks?: number[]): number {
+ if (!layerMasks) return maskBits;
+ for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
+ if (categoryBits === (1 << i)) return layerMasks[i];
+ }
+ return maskBits;
+}
+
+// =============================================================================
+// Shape attachment (one collider component per body)
+// =============================================================================
+
+function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity, layerMasks?: number[]): void {
+ const world = app.world;
+
+ if (world.has(entity, BoxCollider)) {
+ const box = world.get(entity, BoxCollider) as BoxColliderData;
+ const category = box.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, box.maskBits ?? 0xFFFF, layerMasks);
+ module._physics_addBoxShape(
+ entity, box.halfExtents.x, box.halfExtents.y,
+ box.offset.x, box.offset.y, box.radius ?? 0.05,
+ box.density, box.friction, box.restitution, box.isSensor ? 1 : 0,
+ category, mask
+ );
+ }
+
+ if (world.has(entity, CircleCollider)) {
+ const circle = world.get(entity, CircleCollider) as CircleColliderData;
+ const category = circle.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, circle.maskBits ?? 0xFFFF, layerMasks);
+ module._physics_addCircleShape(
+ entity, circle.radius,
+ circle.offset.x, circle.offset.y,
+ circle.density, circle.friction, circle.restitution, circle.isSensor ? 1 : 0,
+ category, mask
+ );
+ }
+
+ if (world.has(entity, CapsuleCollider)) {
+ const capsule = world.get(entity, CapsuleCollider) as CapsuleColliderData;
+ const category = capsule.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, capsule.maskBits ?? 0xFFFF, layerMasks);
+ module._physics_addCapsuleShape(
+ entity, capsule.radius, capsule.halfHeight,
+ capsule.offset.x, capsule.offset.y,
+ capsule.density, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0,
+ category, mask
+ );
+ }
+
+ if (world.has(entity, SegmentCollider)) {
+ const seg = world.get(entity, SegmentCollider) as SegmentColliderData;
+ const category = seg.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, seg.maskBits ?? 0xFFFF, layerMasks);
+ module._physics_addSegmentShape(
+ entity, seg.point1.x, seg.point1.y, seg.point2.x, seg.point2.y,
+ seg.density, seg.friction, seg.restitution, seg.isSensor ? 1 : 0,
+ category, mask
+ );
+ }
+
+ if (world.has(entity, PolygonCollider)) {
+ const poly = world.get(entity, PolygonCollider) as PolygonColliderData;
+ const category = poly.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, poly.maskBits ?? 0xFFFF, layerMasks);
+ const verts = poly.vertices;
+ const count = Math.min(verts.length, 8);
+ const byteSize = count * 2 * 4;
+ const ptr = module._malloc(byteSize);
+ const base = ptr >> 2;
+ for (let i = 0; i < count; i++) {
+ module.HEAPF32[base + i * 2] = verts[i].x;
+ module.HEAPF32[base + i * 2 + 1] = verts[i].y;
+ }
+ module._physics_addPolygonShape(
+ entity, ptr, count, poly.radius ?? 0,
+ poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
+ category, mask
+ );
+ module._free(ptr);
+ }
+
+ if (world.has(entity, ChainCollider)) {
+ const chain = world.get(entity, ChainCollider) as ChainColliderData;
+ const pts = chain.points;
+ if (pts.length < 4) return;
+ const byteSize = pts.length * 2 * 4;
+ const ptr = module._malloc(byteSize);
+ const base = ptr >> 2;
+ for (let i = 0; i < pts.length; i++) {
+ module.HEAPF32[base + i * 2] = pts[i].x;
+ module.HEAPF32[base + i * 2 + 1] = pts[i].y;
+ }
+ module._physics_addChainShape(
+ entity, ptr, pts.length, chain.isLoop ? 1 : 0,
+ chain.friction, chain.restitution,
+ chain.categoryBits ?? 0x0001, chain.maskBits ?? 0xFFFF
+ );
+ module._free(ptr);
+ }
+}
+
+// =============================================================================
+// Joint pending-list drain
+// =============================================================================
+
+function createPendingJoints(
+ world: App['world'],
+ module: PhysicsWasmModule,
+ trackedEntities: Set<Entity>,
+ trackedJoints: Set<Entity>,
+ invPpu: number,
+): void {
+ const jointEntities = world.getEntitiesWithComponents([RevoluteJoint, RigidBody]);
+ for (const entity of jointEntities) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const joint = world.get(entity, RevoluteJoint) as RevoluteJointData;
+ if (!joint.enabled) continue;
+ const connected = joint.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createRevoluteJoint(
+ connected, entity,
+ joint.anchorA.x * invPpu, joint.anchorA.y * invPpu,
+ joint.anchorB.x * invPpu, joint.anchorB.y * invPpu,
+ joint.enableMotor ? 1 : 0, joint.motorSpeed, joint.maxMotorTorque,
+ joint.enableLimit ? 1 : 0, joint.lowerAngle, joint.upperAngle,
+ joint.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+
+ for (const entity of world.getEntitiesWithComponents([DistanceJoint, RigidBody])) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const j = world.get(entity, DistanceJoint) as DistanceJointData;
+ if (!j.enabled) continue;
+ const connected = j.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createDistanceJoint(
+ connected, entity,
+ j.anchorA.x * invPpu, j.anchorA.y * invPpu,
+ j.anchorB.x * invPpu, j.anchorB.y * invPpu,
+ j.length * invPpu,
+ j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
+ j.enableLimit ? 1 : 0, j.minLength * invPpu, j.maxLength * invPpu,
+ j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,
+ j.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+
+ for (const entity of world.getEntitiesWithComponents([PrismaticJoint, RigidBody])) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const j = world.get(entity, PrismaticJoint) as PrismaticJointData;
+ if (!j.enabled) continue;
+ const connected = j.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createPrismaticJoint(
+ connected, entity,
+ j.anchorA.x * invPpu, j.anchorA.y * invPpu,
+ j.anchorB.x * invPpu, j.anchorB.y * invPpu,
+ j.axis.x, j.axis.y,
+ j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
+ j.enableLimit ? 1 : 0, j.lowerTranslation * invPpu, j.upperTranslation * invPpu,
+ j.enableMotor ? 1 : 0, j.maxMotorForce, j.motorSpeed,
+ j.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+
+ for (const entity of world.getEntitiesWithComponents([WeldJoint, RigidBody])) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const j = world.get(entity, WeldJoint) as WeldJointData;
+ if (!j.enabled) continue;
+ const connected = j.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createWeldJoint(
+ connected, entity,
+ j.anchorA.x * invPpu, j.anchorA.y * invPpu,
+ j.anchorB.x * invPpu, j.anchorB.y * invPpu,
+ j.linearHertz, j.angularHertz,
+ j.linearDampingRatio, j.angularDampingRatio,
+ j.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+
+ for (const entity of world.getEntitiesWithComponents([WheelJoint, RigidBody])) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const j = world.get(entity, WheelJoint) as WheelJointData;
+ if (!j.enabled) continue;
+ const connected = j.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createWheelJoint(
+ connected, entity,
+ j.anchorA.x * invPpu, j.anchorA.y * invPpu,
+ j.anchorB.x * invPpu, j.anchorB.y * invPpu,
+ j.axis.x, j.axis.y,
+ j.enableSpring ? 1 : 0, j.hertz, j.dampingRatio,
+ j.enableLimit ? 1 : 0, j.lowerTranslation * invPpu, j.upperTranslation * invPpu,
+ j.enableMotor ? 1 : 0, j.maxMotorTorque, j.motorSpeed,
+ j.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+}
+
+// =============================================================================
+// Dynamic transform readback (wasm -> ECS Transform components)
+// =============================================================================
+
+const syncTransformBuf_ = {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 1, y: 1, z: 1 },
+};
+
+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(
+ app: App,
+ module: PhysicsWasmModule,
+ ppu: number,
+ parentedBodies: Set<Entity>,
+): void {
+ const count = module._physics_getDynamicBodyCount();
+ 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;
+
+ if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {
+ const byteLen = count * PHYSICS_BODY_BYTES;
+ const engineBuf = engineMod._malloc(byteLen);
+ engineMod.HEAPU8.set(
+ new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),
+ engineBuf,
+ );
+ engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);
+ engineMod._free(engineBuf);
+ return;
+ }
+
+ const getTransformPtr = engineMod?.getTransformPtr
+ ? (e: Entity) => engineMod!.getTransformPtr(registry!, e as number)
+ : null;
+ const engF32 = engineMod?.HEAPF32;
+ 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];
+
+ 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 cos = Math.cos(-parentAngleZ);
+ const sin = Math.sin(-parentAngleZ);
+ const sx = pwt.worldScale.x !== 0 ? pwt.worldScale.x : 1;
+ const sy = pwt.worldScale.y !== 0 ? pwt.worldScale.y : 1;
+ localX = (dx * cos - dy * sin) / sx;
+ localY = (dx * sin + dy * cos) / sy;
+ localAngle = localAngle - parentAngleZ;
+ }
+ }
+
+ const half = localAngle * 0.5;
+ const cosH = Math.cos(half);
+ const sinH = Math.sin(half);
+
+ if (getTransformPtr && engF32) {
+ const tPtr = getTransformPtr(entityId);
+ if (tPtr) {
+ const fi = tPtr >> 2;
+ engF32[fi] = localX;
+ engF32[fi + 1] = localY;
+ engF32[fi + 2] = 0;
+ engF32[fi + 3] = 0;
+ engF32[fi + 4] = 0;
+ engF32[fi + 5] = sinH;
+ engF32[fi + 6] = cosH;
+ engF32[fi + 7] = 1;
+ engF32[fi + 8] = 1;
+ engF32[fi + 9] = 1;
+ engF32[fi + 10] = localX;
+ engF32[fi + 11] = localY;
+ engF32[fi + 12] = 0;
+ engF32[fi + 13] = 0;
+ engF32[fi + 14] = 0;
+ engF32[fi + 15] = sinH;
+ engF32[fi + 16] = cosH;
+ engF32[fi + 17] = 1;
+ engF32[fi + 18] = 1;
+ engF32[fi + 19] = 1;
+ continue;
+ }
+ }
+
+ t.position.x = localX;
+ t.position.y = localY;
+ t.rotation.w = cosH;
+ t.rotation.x = 0;
+ t.rotation.y = 0;
+ t.rotation.z = sinH;
+ t.worldPosition.x = localX;
+ t.worldPosition.y = localY;
+ t.worldRotation.w = cosH;
+ t.worldRotation.x = 0;
+ t.worldRotation.y = 0;
+ t.worldRotation.z = sinH;
+
+ addFn!(entityId, t);
+ }
+}
+
+// =============================================================================
+// Collision event drain
+// =============================================================================
+
+function collectEvents(app: App, module: PhysicsWasmModule, ppu: number): 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({
+ entityA: module.HEAPU32[base] as Entity,
+ entityB: module.HEAPU32[base + 1] as Entity,
+ normalX: module.HEAPF32[base + 2],
+ normalY: module.HEAPF32[base + 3],
+ contactX: module.HEAPF32[base + 4] * ppu,
+ contactY: module.HEAPF32[base + 5] * ppu,
+ });
+ }
+ }
+
+ 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({
+ 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({
+ 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({
+ sensorEntity: module.HEAPU32[base] as Entity,
+ visitorEntity: module.HEAPU32[base + 1] as Entity,
+ });
+ }
+ }
+
+ app.insertResource(PhysicsEvents, {
+ collisionEnters,
+ collisionExits,
+ sensorEnters,
+ sensorExits
+ });
+}
+
+// =============================================================================
+// System registration (ownership of tracked sets + per-frame loop)
+// =============================================================================
+
+interface CachedBodyProps {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+}
+
+/**
+ * Wire the per-frame physics system into the app. Owns tracked-entity
+ * / tracked-joint / parented sets via the enclosing closure so the
+ * plugin doesn't need to thread them through.
+ */
+export function registerPhysicsSystem(
+ app: App,
+ module: PhysicsWasmModule,
+ config: ResolvedPhysicsConfig,
+): void {
+ const trackedEntities = new Set<Entity>();
+ const trackedJoints = new Set<Entity>();
+ const parentedBodies = new Set<Entity>();
+ const cachedProps = new Map<Entity, CachedBodyProps>();
+ let lastEntitySyncTick = -1;
+
+ const world = app.world;
+
+ world.onDespawn((entity: Entity) => {
+ if (trackedJoints.has(entity)) {
+ module._physics_destroyJoint(entity);
+ trackedJoints.delete(entity);
+ }
+ if (trackedEntities.has(entity)) {
+ module._physics_destroyBody(entity);
+ trackedEntities.delete(entity);
+ cachedProps.delete(entity);
+ parentedBodies.delete(entity);
+ }
+ });
+
+ app.addSystemToSchedule(
+ Schedule.PostUpdate,
+ 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
+ // value captured when the wasm module first loaded.
+ const ppu = readPixelsPerUnit(app);
+ const invPpu = 1 / ppu;
+ const entities = world.getEntitiesWithComponents([RigidBody, Transform]);
+ const currentEntities = new Set<Entity>();
+
+ for (const entity of entities) {
+ currentEntities.add(entity);
+
+ if (!trackedEntities.has(entity)) {
+ const rb = world.get(entity, RigidBody) as RigidBodyData;
+ if (!rb.enabled) continue;
+ const wt = world.get(entity, Transform) as TransformData;
+ const hasParent = world.has(entity, Parent);
+ const posX = hasParent ? wt.worldPosition.x : wt.position.x;
+ const posY = hasParent ? wt.worldPosition.y : wt.position.y;
+ const rot = hasParent ? wt.worldRotation : wt.rotation;
+ const angle = quatToAngleZ(rot);
+
+ module._physics_createBody(
+ entity, rb.bodyType,
+ posX * invPpu, posY * invPpu, angle,
+ rb.gravityScale, rb.linearDamping, rb.angularDamping,
+ rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0
+ );
+
+ addShapeForEntity(app, module, entity, config.collisionLayerMasks);
+ trackedEntities.add(entity);
+ if (world.has(entity, Parent)) {
+ parentedBodies.add(entity);
+ }
+ cachedProps.set(entity, {
+ bodyType: rb.bodyType,
+ gravityScale: rb.gravityScale,
+ linearDamping: rb.linearDamping,
+ angularDamping: rb.angularDamping,
+ fixedRotation: rb.fixedRotation,
+ bullet: rb.bullet,
+ });
+ } else {
+ if (world.isChangedSince(entity, RigidBody, lastEntitySyncTick)) {
+ const rb = world.get(entity, RigidBody) as RigidBodyData;
+ const prev = cachedProps.get(entity);
+ if (prev &&
+ (prev.bodyType !== rb.bodyType ||
+ prev.gravityScale !== rb.gravityScale ||
+ prev.linearDamping !== rb.linearDamping ||
+ prev.angularDamping !== rb.angularDamping ||
+ prev.fixedRotation !== rb.fixedRotation ||
+ prev.bullet !== rb.bullet)) {
+ module._physics_updateBodyProperties(
+ entity, rb.bodyType,
+ rb.gravityScale, rb.linearDamping, rb.angularDamping,
+ rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0
+ );
+ prev.bodyType = rb.bodyType;
+ prev.gravityScale = rb.gravityScale;
+ prev.linearDamping = rb.linearDamping;
+ prev.angularDamping = rb.angularDamping;
+ prev.fixedRotation = rb.fixedRotation;
+ prev.bullet = rb.bullet;
+ }
+ }
+
+ const cached = cachedProps.get(entity);
+ if (cached && cached.bodyType === BodyType.Kinematic) {
+ const wt = world.get(entity, Transform) as TransformData;
+ const angle = quatToAngleZ(wt.worldRotation);
+ module._physics_setBodyTransform(
+ entity,
+ wt.worldPosition.x * invPpu, wt.worldPosition.y * invPpu,
+ angle
+ );
+ }
+ }
+ }
+
+ lastEntitySyncTick = world.getWorldTick();
+
+ for (const entity of trackedEntities) {
+ if (!currentEntities.has(entity)) {
+ module._physics_destroyBody(entity);
+ trackedEntities.delete(entity);
+ cachedProps.delete(entity);
+ }
+ }
+
+ createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);
+
+ if (trackedEntities.size > 0 && time.delta > 0) {
+ module._physics_step(time.delta);
+ }
+
+ syncDynamicTransforms(app, module, ppu, parentedBodies);
+ collectEvents(app, module, ppu);
+ },
+ { name: 'PhysicsSystem' }
+ ),
+ { runIf: playModeOnly }
+ );
+}
diff --git a/sdk/src/physics/PhysicsTypes.ts b/sdk/src/physics/PhysicsTypes.ts
new file mode 100644
index 000000000..cace7039a
--- /dev/null
+++ b/sdk/src/physics/PhysicsTypes.ts
@@ -0,0 +1,100 @@
+/**
+ * @file PhysicsTypes.ts
+ * @brief Shared data shapes for the physics plugin
+ *
+ * Plain-data types consumed by `PhysicsPlugin`, `Physics`, and `PhysicsSystem`.
+ * Kept dependency-free so all three files can import without cycles.
+ */
+
+import type { Entity, Vec2 } from '../types';
+import { defineResource } from '../resource';
+
+// =============================================================================
+// Plugin configuration
+// =============================================================================
+
+export interface PhysicsPluginConfig {
+ gravity?: Vec2;
+ fixedTimestep?: number;
+ subStepCount?: number;
+ contactHertz?: number;
+ contactDampingRatio?: number;
+ contactSpeed?: number;
+ collisionLayerMasks?: number[];
+}
+
+/** Fully-populated plugin config after defaults are applied. */
+export type ResolvedPhysicsConfig =
+ Required<Omit<PhysicsPluginConfig, 'collisionLayerMasks'>>
+ & Pick<PhysicsPluginConfig, 'collisionLayerMasks'>;
+
+// =============================================================================
+// Collision events
+// =============================================================================
+
+export interface CollisionEnterEvent {
+ entityA: Entity;
+ entityB: Entity;
+ normalX: number;
+ normalY: number;
+ contactX: number;
+ contactY: number;
+}
+
+export interface SensorEvent {
+ sensorEntity: Entity;
+ visitorEntity: Entity;
+}
+
+export interface PhysicsEventsData {
+ collisionEnters: CollisionEnterEvent[];
+ collisionExits: Array<{ entityA: Entity; entityB: Entity }>;
+ sensorEnters: SensorEvent[];
+ sensorExits: SensorEvent[];
+}
+
+export const PhysicsEvents = defineResource<PhysicsEventsData>({
+ collisionEnters: [],
+ collisionExits: [],
+ sensorEnters: [],
+ sensorExits: []
+}, 'PhysicsEvents');
+
+// =============================================================================
+// Query result shapes
+// =============================================================================
+
+export interface RaycastHit {
+ entity: Entity;
+ point: Vec2;
+ normal: Vec2;
+ fraction: number;
+}
+
+export type ShapeCastHit = RaycastHit;
+
+export interface MassData {
+ mass: number;
+ inertia: number;
+ centerOfMass: Vec2;
+}
+
+// =============================================================================
+// WASM buffer strides
+// =============================================================================
+
+export const COLLISION_EVENT_STRIDE = 6;
+export const CAST_HIT_STRIDE = 6;
+
+// =============================================================================
+// Quaternion <-> angle helpers (2D physics lives in XY, rotation on Z)
+// =============================================================================
+
+export function quatToAngleZ(q: { w: number; x: number; y: number; z: number }): number {
+ return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
+}
+
+export function angleZToQuat(angle: number): { w: number; x: number; y: number; z: number } {
+ const half = angle * 0.5;
+ return { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) };
+}
diff --git a/sdk/tests/physicsSyncTransforms.test.ts b/sdk/tests/physicsSyncTransforms.test.ts
index ccb51a4d2..27d80b301 100644
--- a/sdk/tests/physicsSyncTransforms.test.ts
+++ b/sdk/tests/physicsSyncTransforms.test.ts
@@ -3,7 +3,7 @@ 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/PhysicsPlugin';
+import { syncDynamicTransforms } from '../src/physics/PhysicsSystem';
import { createMockModule } from './mocks/wasm';
import { World } from '../src/world';