@codexo/exojs-physics 0.16.1 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"PhysicsBody.d.ts","sourceRoot":"","sources":["../../src/PhysicsBody.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEvC,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAGxC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAExC,uCAAuC;AACvC,MAAM,WAAW,WAAW;IAC1B,4CAA4C;IAC5C,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,gDAAgD;IAChD,QAAQ,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC/B,gDAAgD;IAChD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kFAAkF;IAClF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yGAAyG;IACzG,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,kJAAkJ;IAClJ,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,4GAA4G;IAC5G,SAAS,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC,CAAC;CAC/C;AAED;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,mBAAmB,IAAI,MAAM,CAAC;IAC9B,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;CAC7C;AAED;;;;;;;;GAQG;AACH,qBAAa,WAAW;IACtB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yed body to a world.");
382
+ this._recomputeMass();
383
+ this._assertDynamicCarriesMass();
382
384
  this._owner = owner;
383
385
  this._id = id;
384
386
  this._attached = true;
385
387
  for (const collider of this._colliders) attachWithChainEdges(collider, this, owner);
386
- this._recomputeMass();
387
- this._assertDynamicCarriesMass();
388
388
  for (const collider of this._colliders) collider.synchronize(this._transform);
389
389
  for (const collider of this._colliders) owner._registerCollider(collider);
390
390
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PhysicsBody.js","names":[],"sources":["../../src/PhysicsBody.ts"],"sourcesContent":["import type { PointLike } from '@codexo/exojs';\nimport { Vector } from '@codexo/exojs';\n\nimport { Collider, type ColliderOptions } from './Collider';\nimport type { Transform } from './math';\nimport { applyTransform, createTransform, setTransform } from './math';\nimport type { ShapeMassProperties } from './shapes/Shape';\nimport type { BodyType } from './types';\n\n/** Construction options for a body. */\nexport interface BodyOptions {\n /** Simulation role. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position. Default `(0, 0)`. */\n position?: Readonly<PointLike>;\n /** Initial rotation in radians. Default `0`. */\n angle?: number;\n /** Linear damping applied to the velocity each sub-step. Default `0`. */\n linearDamping?: number;\n /** Angular damping applied to the angular velocity each sub-step. Default `0`. */\n angularDamping?: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts (infinite rotational inertia). Default `false`. */\n fixedRotation?: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. Default `false`. */\n isBullet?: boolean;\n /** Colliders to attach up-front. Each may be a {@link Collider} instance or its {@link ColliderOptions}. */\n colliders?: Array<Collider | ColliderOptions>;\n}\n\n/**\n * Internal hook the world hands to each body so colliders can be id-allocated\n * and registered without the body importing the concrete world class.\n */\nexport interface BodyOwner {\n _allocateColliderId(): number;\n _registerCollider(collider: Collider): void;\n}\n\n/**\n * A rigid body: a world transform plus mass properties aggregated from its\n * colliders. Dynamic bodies integrate under gravity, accumulated forces/torque\n * and contact impulses each fixed sub-step; static bodies never move; kinematic\n * bodies move by their velocity only and stay immovable under contacts. Drive a\n * body with {@link applyForce}, {@link applyTorque} and {@link applyImpulse}, or\n * set {@link linearVelocityX}/{@link linearVelocityY}/{@link angularVelocity}\n * directly; reposition it (teleport, no velocity) with {@link setTransform}.\n */\nexport class PhysicsBody {\n public readonly type: BodyType;\n\n /** Linear damping applied to the velocity each sub-step. */\n public linearDamping: number;\n /** Angular damping applied to the angular velocity each sub-step. */\n public angularDamping: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). */\n public gravityScale: number;\n /** When `true`, rotational inertia is treated as infinite. */\n public fixedRotation: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. */\n public isBullet: boolean;\n\n /** Total mass (0 for static/kinematic). */\n public mass = 0;\n /** Inverse mass (`0` = immovable). */\n public invMass = 0;\n /** Rotational inertia about the centre of mass (0 for static/kinematic or fixed rotation). */\n public inertia = 0;\n /** Inverse rotational inertia (`0` = no angular response). */\n public invInertia = 0;\n\n /** Linear velocity X in px/s. */\n public linearVelocityX = 0;\n /** Linear velocity Y in px/s. */\n public linearVelocityY = 0;\n /** Angular velocity in rad/s. */\n public angularVelocity = 0;\n\n /** When `false`, this body is never put to sleep. Default `true`. */\n public allowSleep = true;\n\n /** @internal - Delta position X accumulated across the frame's sub-steps by the TGS integrator; written into the transform once per frame by {@link _finalizePosition}. */\n public _deltaPosX = 0;\n /** @internal - Delta position Y accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaPosY = 0;\n /** @internal - Delta rotation (radians) accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaAngle = 0;\n /** @internal - `cos(_deltaAngle)`, cached so the solver can rotate the contact anchors by the live sub-step rotation without a per-contact trig call. */\n public _deltaCos = 1;\n /** @internal - `sin(_deltaAngle)`, cached alongside {@link _deltaCos}. */\n public _deltaSin = 0;\n\n private _forceX = 0;\n private _forceY = 0;\n private _torque = 0;\n\n /** @internal - seconds the body has stayed below the sleep thresholds (frozen while asleep). Read by the world's island pass. */\n public _sleepTime = 0;\n /** @internal - dense union-find index assigned by the world's island pass each step. */\n public _islandIndex = 0;\n /**\n * @internal - raised by {@link setTransform}, cleared once the fixed step that\n * saw it completes. A static/kinematic body driven by teleporting carries no\n * velocity, so this is the world's only signal that such a body moved and its\n * sleeping contact partners must be woken.\n */\n public _teleported = false;\n /** @internal - world-space centre of mass at the start of the current fixed step (CCD swept-test origin). */\n public _ccdPrevX = 0;\n /** @internal - see {@link _ccdPrevX}. */\n public _ccdPrevY = 0;\n\n private _sleeping = false;\n\n private _id = -1;\n private _owner: BodyOwner | null = null;\n private _attached = false;\n\n private readonly _transform: Transform;\n // Transform at the START of the most recent fixed step. Presentation only:\n // the solver never reads it, and it is captured before the step writes its\n // delta so a teleport can collapse it onto the current state.\n private _previousX: number;\n private _previousY: number;\n private _previousAngle: number;\n private readonly _colliders: Collider[] = [];\n private _comX = 0;\n private _comY = 0;\n private _massReady = false;\n private _destroyed = false;\n\n public constructor(options: BodyOptions = {}) {\n this.type = options.type ?? 'dynamic';\n this._transform = createTransform(options.position?.x ?? 0, options.position?.y ?? 0, options.angle ?? 0);\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n this.linearDamping = options.linearDamping ?? 0;\n this.angularDamping = options.angularDamping ?? 0;\n this.gravityScale = options.gravityScale ?? 1;\n this.fixedRotation = options.fixedRotation ?? false;\n this.isBullet = options.isBullet ?? false;\n\n // Build up-front colliders now (no id/world registration until the body\n // joins a world via `world.add()`). They sit in `_colliders` unsynchronised;\n // `_attachToWorld` assigns ids, registers them and computes the mass model.\n if (options.colliders) {\n for (const entry of options.colliders) {\n this._colliders.push(entry instanceof Collider ? entry : new Collider(entry));\n }\n }\n }\n\n /** Stable id, assigned when the body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /** `true` once the body has been added to a world (guards against double-add). */\n public get attached(): boolean {\n return this._attached;\n }\n\n /** World X. */\n public get x(): number {\n return this._transform.x;\n }\n\n /** World Y. */\n public get y(): number {\n return this._transform.y;\n }\n\n /** Rotation in radians. */\n public get angle(): number {\n return this._transform.angle;\n }\n\n /**\n * World X at the start of the most recent fixed step. With {@link x} it\n * brackets the last step, which is what an interpolating presentation blends\n * between; a teleport collapses it onto {@link x}. Never read by the solver.\n */\n public get previousX(): number {\n return this._previousX;\n }\n\n /** World Y at the start of the most recent fixed step; see {@link previousX}. */\n public get previousY(): number {\n return this._previousY;\n }\n\n /**\n * Rotation in radians at the start of the most recent fixed step; see\n * {@link previousX}. Body angles are continuous and unbounded, never wrapped\n * to a range, so this and {@link angle} can be blended with a plain lerp.\n */\n public get previousAngle(): number {\n return this._previousAngle;\n }\n\n /** A fresh `Vector` copy of the body's world position. */\n public get position(): Vector {\n return new Vector(this._transform.x, this._transform.y);\n }\n\n /** The body's world transform (read-only; mutate via {@link setTransform}). */\n public get transform(): Readonly<Transform> {\n return this._transform;\n }\n\n /** The body's colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassX(): number {\n return this._comX;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassY(): number {\n return this._comY;\n }\n\n /**\n * `true` when the body is ready to simulate. Static/kinematic bodies are\n * always ready (infinite-mass semantics); a dynamic body is ready only once\n * it has at least one positive-density collider.\n */\n public get isMassReady(): boolean {\n return this.type !== 'dynamic' || this._massReady;\n }\n\n /** `true` after the owning world has destroyed this body. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /** `true` when the body is asleep - skipped by the integrator and solver until woken. */\n public get isSleeping(): boolean {\n return this._sleeping;\n }\n\n /**\n * Attach a collider to this body. Accepts a {@link Collider} instance or its\n * {@link ColliderOptions} (a convenience that constructs the collider for you).\n * When the body is already in a world, the collider is id-allocated, registered,\n * the mass model is recomputed and the world geometry synchronised immediately;\n * on a free-standing body the collider is simply held until `world.add()`.\n * Returns the collider.\n */\n public addCollider(collider: Collider | ColliderOptions): Collider {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a collider to a destroyed body.');\n }\n\n // Collider imports PhysicsBody type-only (erased), so this value import is\n // one-directional - no runtime cycle.\n const instance = collider instanceof Collider ? collider : new Collider(collider);\n\n this._colliders.push(instance);\n\n // Before the body joins a world there is no owner to allocate ids / register\n // with; `_attachToWorld` does that (and the mass/sync pass) for every held\n // collider. Once attached, mirror the world's create order exactly.\n if (this._attached && this._owner) {\n attachWithChainEdges(instance, this, this._owner);\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n instance.synchronize(this._transform);\n this._owner._registerCollider(instance);\n }\n\n return instance;\n }\n\n /**\n * Set the body's world transform. Resets the body's cached collider geometry\n * immediately so subsequent queries see the new placement. Returns `this`.\n */\n public setTransform(position: Readonly<PointLike>, angle: number = this._transform.angle): this {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot move a destroyed body.');\n }\n\n this.wake();\n\n this._teleported = true;\n\n setTransform(this._transform, position.x, position.y, angle);\n\n // A teleport is a discontinuity, not motion - collapsing the pair keeps an\n // interpolating presentation from sweeping the node across the jump.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n return this;\n }\n\n /** Refresh every collider's world geometry from the current transform. */\n public synchronizeColliders(): void {\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** World-space centre of mass X (body origin + rotated local centre of mass). */\n public get worldCenterOfMassX(): number {\n return this._transform.x + this._transform.cos * this._comX - this._transform.sin * this._comY;\n }\n\n /** World-space centre of mass Y. */\n public get worldCenterOfMassY(): number {\n return this._transform.y + this._transform.sin * this._comX + this._transform.cos * this._comY;\n }\n\n /**\n * Accumulate a world-space force at the centre of mass; integrated on the next\n * sub-step and then cleared. No-op on static/kinematic bodies. Returns `this`.\n */\n public applyForce(forceX: number, forceY: number): this {\n this.wake();\n this._forceX += forceX;\n this._forceY += forceY;\n\n return this;\n }\n\n /**\n * Accumulate a torque; integrated on the next sub-step and then cleared. No-op\n * on static/kinematic bodies (and fixed-rotation bodies). Returns `this`.\n */\n public applyTorque(torque: number): this {\n this.wake();\n this._torque += torque;\n\n return this;\n }\n\n /**\n * Apply an instantaneous world-space impulse at `(pointX, pointY)` (world space;\n * defaults to the centre of mass), changing velocity immediately. No-op on\n * static/kinematic bodies (infinite mass). Returns `this`.\n */\n public applyImpulse(impulseX: number, impulseY: number, pointX?: number, pointY?: number): this {\n if (this.invMass === 0) {\n return this;\n }\n\n this.wake();\n this.linearVelocityX += impulseX * this.invMass;\n this.linearVelocityY += impulseY * this.invMass;\n\n if (pointX !== undefined && pointY !== undefined && this.invInertia !== 0) {\n const rx = pointX - this.worldCenterOfMassX;\n const ry = pointY - this.worldCenterOfMassY;\n\n this.angularVelocity += (rx * impulseY - ry * impulseX) * this.invInertia;\n }\n\n return this;\n }\n\n /**\n * @internal - integrate velocity from gravity, accumulated forces/torque and\n * damping over the sub-step `h`. No-op for static/kinematic (infinite mass\n * keeps their velocity solver-driven only). Called once per TGS sub-step, so\n * gravity/forces are applied with `h` each sub-step (`N·h = dt`, same total\n * impulse, but the small-step position error scales with `h²`). The\n * force/torque accumulators are **not** cleared here - they are consumed by\n * every sub-step and cleared once per frame by {@link _finalizePosition}.\n */\n public _integrateVelocity(h: number, gravityX: number, gravityY: number): void {\n if (this.invMass === 0 || this._sleeping) {\n return;\n }\n\n this.linearVelocityX += (gravityX * this.gravityScale + this._forceX * this.invMass) * h;\n this.linearVelocityY += (gravityY * this.gravityScale + this._forceY * this.invMass) * h;\n this.angularVelocity += this._torque * this.invInertia * h;\n\n // Exponential damping (no-op when damping is 0).\n this.linearVelocityX /= 1 + h * this.linearDamping;\n this.linearVelocityY /= 1 + h * this.linearDamping;\n this.angularVelocity /= 1 + h * this.angularDamping;\n }\n\n /**\n * @internal - accumulate this sub-step's velocity into the per-frame delta\n * position/rotation (TGS sub-stepping). The transform itself is **not** moved\n * here; {@link _finalizePosition} writes the accumulated delta once per frame.\n * Tracking the delta (rather than moving the transform each sub-step) lets the\n * solver recompute contact separation from it without re-running detection or\n * re-syncing collider geometry per sub-step. Static bodies never move.\n */\n public _integratePosition(h: number): void {\n if (this.type === 'static' || this._sleeping) {\n return;\n }\n\n this._deltaPosX += this.linearVelocityX * h;\n this._deltaPosY += this.linearVelocityY * h;\n this._deltaAngle += this.angularVelocity * h;\n\n // Cache the rotation so the solver can rotate the contact anchors by the\n // live sub-step rotation (TGS): without it the anchors stay frozen at frame\n // start and a tilting tower's restoring torque is mis-computed, so the tilt\n // grows instead of being corrected. Only non-zero rotation pays the trig.\n if (this._deltaAngle !== 0) {\n this._deltaCos = Math.cos(this._deltaAngle);\n this._deltaSin = Math.sin(this._deltaAngle);\n }\n }\n\n /**\n * @internal - advance the sleep timer over one fixed step `dt`. A body below\n * both velocity thresholds accumulates time; a too-fast body, or one that opts\n * out via {@link allowSleep}, resets it. The sleep/wake decision is made per\n * island by the world (so a stack sleeps as a unit) from {@link _sleepTime}.\n */\n public _accumulateSleepTime(dt: number, linearThreshold: number, angularThreshold: number): void {\n const tooFast =\n this.linearVelocityX * this.linearVelocityX + this.linearVelocityY * this.linearVelocityY > linearThreshold * linearThreshold ||\n Math.abs(this.angularVelocity) > angularThreshold;\n\n this._sleepTime = !this.allowSleep || tooFast ? 0 : this._sleepTime + dt;\n }\n\n /** @internal - set the sleep state. Sleeping zeroes the velocity; waking resets the sleep timer. */\n public _setSleeping(sleeping: boolean): void {\n if (this._sleeping === sleeping) {\n return;\n }\n\n this._sleeping = sleeping;\n\n if (sleeping) {\n this.linearVelocityX = 0;\n this.linearVelocityY = 0;\n this.angularVelocity = 0;\n } else {\n this._sleepTime = 0;\n }\n }\n\n /**\n * Wake the body if it is asleep, resetting its sleep timer. The rest of its\n * island wakes with it on the next step (a contact to an awake body keeps the\n * whole island awake). Returns `this`.\n */\n public wake(): this {\n this._setSleeping(false);\n this._sleepTime = 0;\n\n return this;\n }\n\n /**\n * @internal - apply the frame's accumulated delta position/rotation to the\n * transform (rotating about the centre of mass), re-sync collider geometry and\n * clear the force/torque accumulators. Called once per frame after the\n * sub-step loop. Static bodies never move; the force clear still runs (forces\n * are a no-op on infinite mass but the accumulator is reset for consistency).\n */\n public _finalizePosition(): void {\n this._forceX = 0;\n this._forceY = 0;\n this._torque = 0;\n this._teleported = false;\n\n // Captured before the step's delta is applied, and before the no-motion\n // early return below - a body that did not move must report previous ===\n // current rather than a stale pair from the last step it did move in.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n if (this.type === 'static' || (this._deltaPosX === 0 && this._deltaPosY === 0 && this._deltaAngle === 0)) {\n this._resetDelta();\n\n return;\n }\n\n const newComX = this.worldCenterOfMassX + this._deltaPosX;\n const newComY = this.worldCenterOfMassY + this._deltaPosY;\n const newAngle = this._transform.angle + this._deltaAngle;\n const cos = Math.cos(newAngle);\n const sin = Math.sin(newAngle);\n\n // origin = newCoM − R(newAngle)·comLocal (so rotation pivots about the CoM).\n setTransform(this._transform, newComX - (cos * this._comX - sin * this._comY), newComY - (sin * this._comX + cos * this._comY), newAngle);\n\n this._resetDelta();\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** Clear the per-frame TGS delta accumulators (position, rotation and its cached cos/sin). */\n private _resetDelta(): void {\n this._deltaPosX = 0;\n this._deltaPosY = 0;\n this._deltaAngle = 0;\n this._deltaCos = 1;\n this._deltaSin = 0;\n }\n\n /** Internal: detach a collider (called by the world during destruction). */\n public _removeCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n this._recomputeMass();\n }\n }\n\n /**\n * @internal - join `owner`'s world with the allocated `id`. Allocates ids for\n * and registers every held collider, then aggregates the mass model and\n * synchronises world geometry. Called once by {@link PhysicsWorld.add}.\n *\n * Ordering matters and mirrors the per-collider create path exactly: ids and\n * the body link go on first, then a single mass recompute over the full\n * collider set (so the centre of mass / inertia aggregate is correct), then\n * `synchronize` over every collider (the cached world geometry the broad/narrow\n * phase reads), then world registration last. Recomputing mass before all\n * colliders are linked, or syncing before the mass model exists, would feed the\n * solver a stale CoM and produce subtle integration bugs.\n */\n public _attachToWorld(owner: BodyOwner, id: number): void {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a destroyed body to a world.');\n }\n\n this._owner = owner;\n this._id = id;\n this._attached = true;\n\n for (const collider of this._colliders) {\n attachWithChainEdges(collider, this, owner);\n }\n\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n for (const collider of this._colliders) {\n owner._registerCollider(collider);\n }\n }\n\n /** Internal: mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n }\n\n /**\n * A dynamic body has to carry mass. Boundary geometry (a segment, a chain)\n * reports no mass properties, and a collider may also be given zero density,\n * so a dynamic body can end up with none at all - which the solver cannot tell\n * apart from a static body, since both have `invMass === 0`. Rejecting it is\n * the difference between a clear error and a body that silently stops moving.\n */\n private _assertDynamicCarriesMass(): void {\n if (this.type !== 'dynamic' || this._massReady || this._colliders.length === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsBody: a dynamic body must carry at least one collider with mass — every collider it holds is either boundary geometry (a segment or chain, which has no interior) or has zero density. Add a solid collider, or make the body static or kinematic.',\n );\n }\n\n /** Recompute mass, centre of mass and rotational inertia from the colliders. */\n private _recomputeMass(): void {\n if (this.type !== 'dynamic') {\n this.mass = 0;\n this.invMass = 0;\n this.inertia = 0;\n this.invInertia = 0;\n this._comX = 0;\n this._comY = 0;\n this._massReady = false;\n\n return;\n }\n\n let mass = 0;\n let cx = 0;\n let cy = 0;\n let inertiaOrigin = 0;\n const point = { x: 0, y: 0 };\n\n for (const collider of this._colliders) {\n // Boundary geometry (a segment, later a chain) has no interior and reports\n // no mass properties; it contributes collision only.\n const massProperties: ShapeMassProperties | null = collider.shape.massProperties;\n\n if (massProperties === null) {\n continue;\n }\n\n const m = collider.density * massProperties.area;\n\n if (m <= 0) {\n continue;\n }\n\n // Shape centroid expressed in body-local space (offset + local rotation).\n applyTransform(collider.localTransform, massProperties.centroidX, massProperties.centroidY, point);\n mass += m;\n cx += m * point.x;\n cy += m * point.y;\n // Parallel-axis to the body origin: I_origin += I_centroid + m·d².\n inertiaOrigin += collider.density * massProperties.unitInertia + m * (point.x * point.x + point.y * point.y);\n }\n\n if (mass > 0) {\n cx /= mass;\n cy /= mass;\n }\n\n this.mass = mass;\n this.invMass = mass > 0 ? 1 / mass : 0;\n this._comX = cx;\n this._comY = cy;\n // Shift inertia from the body origin to the centre of mass.\n const inertiaCom = inertiaOrigin - mass * (cx * cx + cy * cy);\n\n this.inertia = this.fixedRotation ? 0 : inertiaCom;\n this.invInertia = this.fixedRotation || inertiaCom <= 0 ? 0 : 1 / inertiaCom;\n this._massReady = mass > 0;\n }\n}\n\n/**\n * Give a collider its id, and a chain collider's edge proxies theirs. The\n * proxies are ids in the same space as authored colliders - the contact graph\n * keys pairs on them - but they never appear in `body.colliders`.\n */\nconst attachWithChainEdges = (collider: Collider, body: PhysicsBody, owner: BodyOwner): void => {\n collider._attach(body, owner._allocateColliderId());\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n return;\n }\n\n for (const edge of edges) {\n edge._attach(body, owner._allocateColliderId());\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAiDA,IAAa,cAAb,MAAyB;CACvB,AAAgB;;CAGhB,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAGP,AAAO,OAAO;;CAEd,AAAO,UAAU;;CAEjB,AAAO,UAAU;;CAEjB,AAAO,aAAa;;CAGpB,AAAO,kBAAkB;;CAEzB,AAAO,kBAAkB;;CAEzB,AAAO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AM,oBAAoB,CAAC;CAElD,MAAM,QAAQ,SAAS;CAEvB,IAAI,UAAU,MACZ;CAGF,KAAK,MAAM,QAAQ,OACjB,KAAK,QAAQ,MAAM,MAAM,oBAAoB,CAAC;AAElD"}
1
+ {"version":3,"file":"PhysicsBody.js","names":[],"sources":["../../src/PhysicsBody.ts"],"sourcesContent":["import type { PointLike } from '@codexo/exojs';\nimport { Vector } from '@codexo/exojs';\n\nimport { Collider, type ColliderOptions } from './Collider';\nimport type { Transform } from './math';\nimport { applyTransform, createTransform, setTransform } from './math';\nimport type { ShapeMassProperties } from './shapes/Shape';\nimport type { BodyType } from './types';\n\n/** Construction options for a body. */\nexport interface BodyOptions {\n /** Simulation role. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position. Default `(0, 0)`. */\n position?: Readonly<PointLike>;\n /** Initial rotation in radians. Default `0`. */\n angle?: number;\n /** Linear damping applied to the velocity each sub-step. Default `0`. */\n linearDamping?: number;\n /** Angular damping applied to the angular velocity each sub-step. Default `0`. */\n angularDamping?: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts (infinite rotational inertia). Default `false`. */\n fixedRotation?: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. Default `false`. */\n isBullet?: boolean;\n /** Colliders to attach up-front. Each may be a {@link Collider} instance or its {@link ColliderOptions}. */\n colliders?: Array<Collider | ColliderOptions>;\n}\n\n/**\n * Internal hook the world hands to each body so colliders can be id-allocated\n * and registered without the body importing the concrete world class.\n */\nexport interface BodyOwner {\n _allocateColliderId(): number;\n _registerCollider(collider: Collider): void;\n}\n\n/**\n * A rigid body: a world transform plus mass properties aggregated from its\n * colliders. Dynamic bodies integrate under gravity, accumulated forces/torque\n * and contact impulses each fixed sub-step; static bodies never move; kinematic\n * bodies move by their velocity only and stay immovable under contacts. Drive a\n * body with {@link applyForce}, {@link applyTorque} and {@link applyImpulse}, or\n * set {@link linearVelocityX}/{@link linearVelocityY}/{@link angularVelocity}\n * directly; reposition it (teleport, no velocity) with {@link setTransform}.\n */\nexport class PhysicsBody {\n public readonly type: BodyType;\n\n /** Linear damping applied to the velocity each sub-step. */\n public linearDamping: number;\n /** Angular damping applied to the angular velocity each sub-step. */\n public angularDamping: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). */\n public gravityScale: number;\n /** When `true`, rotational inertia is treated as infinite. */\n public fixedRotation: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. */\n public isBullet: boolean;\n\n /** Total mass (0 for static/kinematic). */\n public mass = 0;\n /** Inverse mass (`0` = immovable). */\n public invMass = 0;\n /** Rotational inertia about the centre of mass (0 for static/kinematic or fixed rotation). */\n public inertia = 0;\n /** Inverse rotational inertia (`0` = no angular response). */\n public invInertia = 0;\n\n /** Linear velocity X in px/s. */\n public linearVelocityX = 0;\n /** Linear velocity Y in px/s. */\n public linearVelocityY = 0;\n /** Angular velocity in rad/s. */\n public angularVelocity = 0;\n\n /** When `false`, this body is never put to sleep. Default `true`. */\n public allowSleep = true;\n\n /** @internal - Delta position X accumulated across the frame's sub-steps by the TGS integrator; written into the transform once per frame by {@link _finalizePosition}. */\n public _deltaPosX = 0;\n /** @internal - Delta position Y accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaPosY = 0;\n /** @internal - Delta rotation (radians) accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaAngle = 0;\n /** @internal - `cos(_deltaAngle)`, cached so the solver can rotate the contact anchors by the live sub-step rotation without a per-contact trig call. */\n public _deltaCos = 1;\n /** @internal - `sin(_deltaAngle)`, cached alongside {@link _deltaCos}. */\n public _deltaSin = 0;\n\n private _forceX = 0;\n private _forceY = 0;\n private _torque = 0;\n\n /** @internal - seconds the body has stayed below the sleep thresholds (frozen while asleep). Read by the world's island pass. */\n public _sleepTime = 0;\n /** @internal - dense union-find index assigned by the world's island pass each step. */\n public _islandIndex = 0;\n /**\n * @internal - raised by {@link setTransform}, cleared once the fixed step that\n * saw it completes. A static/kinematic body driven by teleporting carries no\n * velocity, so this is the world's only signal that such a body moved and its\n * sleeping contact partners must be woken.\n */\n public _teleported = false;\n /** @internal - world-space centre of mass at the start of the current fixed step (CCD swept-test origin). */\n public _ccdPrevX = 0;\n /** @internal - see {@link _ccdPrevX}. */\n public _ccdPrevY = 0;\n\n private _sleeping = false;\n\n private _id = -1;\n private _owner: BodyOwner | null = null;\n private _attached = false;\n\n private readonly _transform: Transform;\n // Transform at the START of the most recent fixed step. Presentation only:\n // the solver never reads it, and it is captured before the step writes its\n // delta so a teleport can collapse it onto the current state.\n private _previousX: number;\n private _previousY: number;\n private _previousAngle: number;\n private readonly _colliders: Collider[] = [];\n private _comX = 0;\n private _comY = 0;\n private _massReady = false;\n private _destroyed = false;\n\n public constructor(options: BodyOptions = {}) {\n this.type = options.type ?? 'dynamic';\n this._transform = createTransform(options.position?.x ?? 0, options.position?.y ?? 0, options.angle ?? 0);\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n this.linearDamping = options.linearDamping ?? 0;\n this.angularDamping = options.angularDamping ?? 0;\n this.gravityScale = options.gravityScale ?? 1;\n this.fixedRotation = options.fixedRotation ?? false;\n this.isBullet = options.isBullet ?? false;\n\n // Build up-front colliders now (no id/world registration until the body\n // joins a world via `world.add()`). They sit in `_colliders` unsynchronised;\n // `_attachToWorld` assigns ids, registers them and computes the mass model.\n if (options.colliders) {\n for (const entry of options.colliders) {\n this._colliders.push(entry instanceof Collider ? entry : new Collider(entry));\n }\n }\n }\n\n /** Stable id, assigned when the body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /** `true` once the body has been added to a world (guards against double-add). */\n public get attached(): boolean {\n return this._attached;\n }\n\n /** World X. */\n public get x(): number {\n return this._transform.x;\n }\n\n /** World Y. */\n public get y(): number {\n return this._transform.y;\n }\n\n /** Rotation in radians. */\n public get angle(): number {\n return this._transform.angle;\n }\n\n /**\n * World X at the start of the most recent fixed step. With {@link x} it\n * brackets the last step, which is what an interpolating presentation blends\n * between; a teleport collapses it onto {@link x}. Never read by the solver.\n */\n public get previousX(): number {\n return this._previousX;\n }\n\n /** World Y at the start of the most recent fixed step; see {@link previousX}. */\n public get previousY(): number {\n return this._previousY;\n }\n\n /**\n * Rotation in radians at the start of the most recent fixed step; see\n * {@link previousX}. Body angles are continuous and unbounded, never wrapped\n * to a range, so this and {@link angle} can be blended with a plain lerp.\n */\n public get previousAngle(): number {\n return this._previousAngle;\n }\n\n /** A fresh `Vector` copy of the body's world position. */\n public get position(): Vector {\n return new Vector(this._transform.x, this._transform.y);\n }\n\n /** The body's world transform (read-only; mutate via {@link setTransform}). */\n public get transform(): Readonly<Transform> {\n return this._transform;\n }\n\n /** The body's colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassX(): number {\n return this._comX;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassY(): number {\n return this._comY;\n }\n\n /**\n * `true` when the body is ready to simulate. Static/kinematic bodies are\n * always ready (infinite-mass semantics); a dynamic body is ready only once\n * it has at least one positive-density collider.\n */\n public get isMassReady(): boolean {\n return this.type !== 'dynamic' || this._massReady;\n }\n\n /** `true` after the owning world has destroyed this body. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /** `true` when the body is asleep - skipped by the integrator and solver until woken. */\n public get isSleeping(): boolean {\n return this._sleeping;\n }\n\n /**\n * Attach a collider to this body. Accepts a {@link Collider} instance or its\n * {@link ColliderOptions} (a convenience that constructs the collider for you).\n * When the body is already in a world, the collider is id-allocated, registered,\n * the mass model is recomputed and the world geometry synchronised immediately;\n * on a free-standing body the collider is simply held until `world.add()`.\n * Returns the collider.\n */\n public addCollider(collider: Collider | ColliderOptions): Collider {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a collider to a destroyed body.');\n }\n\n // Collider imports PhysicsBody type-only (erased), so this value import is\n // one-directional - no runtime cycle.\n const instance = collider instanceof Collider ? collider : new Collider(collider);\n\n this._colliders.push(instance);\n\n // Before the body joins a world there is no owner to allocate ids / register\n // with; `_attachToWorld` does that (and the mass/sync pass) for every held\n // collider. Once attached, mirror the world's create order exactly.\n if (this._attached && this._owner) {\n attachWithChainEdges(instance, this, this._owner);\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n instance.synchronize(this._transform);\n this._owner._registerCollider(instance);\n }\n\n return instance;\n }\n\n /**\n * Set the body's world transform. Resets the body's cached collider geometry\n * immediately so subsequent queries see the new placement. Returns `this`.\n */\n public setTransform(position: Readonly<PointLike>, angle: number = this._transform.angle): this {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot move a destroyed body.');\n }\n\n this.wake();\n\n this._teleported = true;\n\n setTransform(this._transform, position.x, position.y, angle);\n\n // A teleport is a discontinuity, not motion - collapsing the pair keeps an\n // interpolating presentation from sweeping the node across the jump.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n return this;\n }\n\n /** Refresh every collider's world geometry from the current transform. */\n public synchronizeColliders(): void {\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** World-space centre of mass X (body origin + rotated local centre of mass). */\n public get worldCenterOfMassX(): number {\n return this._transform.x + this._transform.cos * this._comX - this._transform.sin * this._comY;\n }\n\n /** World-space centre of mass Y. */\n public get worldCenterOfMassY(): number {\n return this._transform.y + this._transform.sin * this._comX + this._transform.cos * this._comY;\n }\n\n /**\n * Accumulate a world-space force at the centre of mass; integrated on the next\n * sub-step and then cleared. No-op on static/kinematic bodies. Returns `this`.\n */\n public applyForce(forceX: number, forceY: number): this {\n this.wake();\n this._forceX += forceX;\n this._forceY += forceY;\n\n return this;\n }\n\n /**\n * Accumulate a torque; integrated on the next sub-step and then cleared. No-op\n * on static/kinematic bodies (and fixed-rotation bodies). Returns `this`.\n */\n public applyTorque(torque: number): this {\n this.wake();\n this._torque += torque;\n\n return this;\n }\n\n /**\n * Apply an instantaneous world-space impulse at `(pointX, pointY)` (world space;\n * defaults to the centre of mass), changing velocity immediately. No-op on\n * static/kinematic bodies (infinite mass). Returns `this`.\n */\n public applyImpulse(impulseX: number, impulseY: number, pointX?: number, pointY?: number): this {\n if (this.invMass === 0) {\n return this;\n }\n\n this.wake();\n this.linearVelocityX += impulseX * this.invMass;\n this.linearVelocityY += impulseY * this.invMass;\n\n if (pointX !== undefined && pointY !== undefined && this.invInertia !== 0) {\n const rx = pointX - this.worldCenterOfMassX;\n const ry = pointY - this.worldCenterOfMassY;\n\n this.angularVelocity += (rx * impulseY - ry * impulseX) * this.invInertia;\n }\n\n return this;\n }\n\n /**\n * @internal - integrate velocity from gravity, accumulated forces/torque and\n * damping over the sub-step `h`. No-op for static/kinematic (infinite mass\n * keeps their velocity solver-driven only). Called once per TGS sub-step, so\n * gravity/forces are applied with `h` each sub-step (`N·h = dt`, same total\n * impulse, but the small-step position error scales with `h²`). The\n * force/torque accumulators are **not** cleared here - they are consumed by\n * every sub-step and cleared once per frame by {@link _finalizePosition}.\n */\n public _integrateVelocity(h: number, gravityX: number, gravityY: number): void {\n if (this.invMass === 0 || this._sleeping) {\n return;\n }\n\n this.linearVelocityX += (gravityX * this.gravityScale + this._forceX * this.invMass) * h;\n this.linearVelocityY += (gravityY * this.gravityScale + this._forceY * this.invMass) * h;\n this.angularVelocity += this._torque * this.invInertia * h;\n\n // Exponential damping (no-op when damping is 0).\n this.linearVelocityX /= 1 + h * this.linearDamping;\n this.linearVelocityY /= 1 + h * this.linearDamping;\n this.angularVelocity /= 1 + h * this.angularDamping;\n }\n\n /**\n * @internal - accumulate this sub-step's velocity into the per-frame delta\n * position/rotation (TGS sub-stepping). The transform itself is **not** moved\n * here; {@link _finalizePosition} writes the accumulated delta once per frame.\n * Tracking the delta (rather than moving the transform each sub-step) lets the\n * solver recompute contact separation from it without re-running detection or\n * re-syncing collider geometry per sub-step. Static bodies never move.\n */\n public _integratePosition(h: number): void {\n if (this.type === 'static' || this._sleeping) {\n return;\n }\n\n this._deltaPosX += this.linearVelocityX * h;\n this._deltaPosY += this.linearVelocityY * h;\n this._deltaAngle += this.angularVelocity * h;\n\n // Cache the rotation so the solver can rotate the contact anchors by the\n // live sub-step rotation (TGS): without it the anchors stay frozen at frame\n // start and a tilting tower's restoring torque is mis-computed, so the tilt\n // grows instead of being corrected. Only non-zero rotation pays the trig.\n if (this._deltaAngle !== 0) {\n this._deltaCos = Math.cos(this._deltaAngle);\n this._deltaSin = Math.sin(this._deltaAngle);\n }\n }\n\n /**\n * @internal - advance the sleep timer over one fixed step `dt`. A body below\n * both velocity thresholds accumulates time; a too-fast body, or one that opts\n * out via {@link allowSleep}, resets it. The sleep/wake decision is made per\n * island by the world (so a stack sleeps as a unit) from {@link _sleepTime}.\n */\n public _accumulateSleepTime(dt: number, linearThreshold: number, angularThreshold: number): void {\n const tooFast =\n this.linearVelocityX * this.linearVelocityX + this.linearVelocityY * this.linearVelocityY > linearThreshold * linearThreshold ||\n Math.abs(this.angularVelocity) > angularThreshold;\n\n this._sleepTime = !this.allowSleep || tooFast ? 0 : this._sleepTime + dt;\n }\n\n /** @internal - set the sleep state. Sleeping zeroes the velocity; waking resets the sleep timer. */\n public _setSleeping(sleeping: boolean): void {\n if (this._sleeping === sleeping) {\n return;\n }\n\n this._sleeping = sleeping;\n\n if (sleeping) {\n this.linearVelocityX = 0;\n this.linearVelocityY = 0;\n this.angularVelocity = 0;\n } else {\n this._sleepTime = 0;\n }\n }\n\n /**\n * Wake the body if it is asleep, resetting its sleep timer. The rest of its\n * island wakes with it on the next step (a contact to an awake body keeps the\n * whole island awake). Returns `this`.\n */\n public wake(): this {\n this._setSleeping(false);\n this._sleepTime = 0;\n\n return this;\n }\n\n /**\n * @internal - apply the frame's accumulated delta position/rotation to the\n * transform (rotating about the centre of mass), re-sync collider geometry and\n * clear the force/torque accumulators. Called once per frame after the\n * sub-step loop. Static bodies never move; the force clear still runs (forces\n * are a no-op on infinite mass but the accumulator is reset for consistency).\n */\n public _finalizePosition(): void {\n this._forceX = 0;\n this._forceY = 0;\n this._torque = 0;\n this._teleported = false;\n\n // Captured before the step's delta is applied, and before the no-motion\n // early return below - a body that did not move must report previous ===\n // current rather than a stale pair from the last step it did move in.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n if (this.type === 'static' || (this._deltaPosX === 0 && this._deltaPosY === 0 && this._deltaAngle === 0)) {\n this._resetDelta();\n\n return;\n }\n\n const newComX = this.worldCenterOfMassX + this._deltaPosX;\n const newComY = this.worldCenterOfMassY + this._deltaPosY;\n const newAngle = this._transform.angle + this._deltaAngle;\n const cos = Math.cos(newAngle);\n const sin = Math.sin(newAngle);\n\n // origin = newCoM − R(newAngle)·comLocal (so rotation pivots about the CoM).\n setTransform(this._transform, newComX - (cos * this._comX - sin * this._comY), newComY - (sin * this._comX + cos * this._comY), newAngle);\n\n this._resetDelta();\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** Clear the per-frame TGS delta accumulators (position, rotation and its cached cos/sin). */\n private _resetDelta(): void {\n this._deltaPosX = 0;\n this._deltaPosY = 0;\n this._deltaAngle = 0;\n this._deltaCos = 1;\n this._deltaSin = 0;\n }\n\n /** Internal: detach a collider (called by the world during destruction). */\n public _removeCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n this._recomputeMass();\n }\n }\n\n /**\n * @internal - join `owner`'s world with the allocated `id`. Allocates ids for\n * and registers every held collider, then aggregates the mass model and\n * synchronises world geometry. Called once by {@link PhysicsWorld.add}.\n *\n * Ordering matters and mirrors the per-collider create path exactly: ids and\n * the body link go on first, then a single mass recompute over the full\n * collider set (so the centre of mass / inertia aggregate is correct), then\n * `synchronize` over every collider (the cached world geometry the broad/narrow\n * phase reads), then world registration last. Recomputing mass before all\n * colliders are linked, or syncing before the mass model exists, would feed the\n * solver a stale CoM and produce subtle integration bugs.\n */\n public _attachToWorld(owner: BodyOwner, id: number): void {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a destroyed body to a world.');\n }\n\n // Validate before touching `_owner`/`_id`/`_attached`: the mass check only\n // reads the held colliders, so it can run before the body claims a world at\n // all. Throwing after that point would leave the body half-attached -\n // `attached === true` with nothing else done - and unrecoverable, since a\n // second `add()` then rejects it as already-added.\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n\n this._owner = owner;\n this._id = id;\n this._attached = true;\n\n for (const collider of this._colliders) {\n attachWithChainEdges(collider, this, owner);\n }\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n for (const collider of this._colliders) {\n owner._registerCollider(collider);\n }\n }\n\n /** Internal: mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n }\n\n /**\n * A dynamic body has to carry mass. Boundary geometry (a segment, a chain)\n * reports no mass properties, and a collider may also be given zero density,\n * so a dynamic body can end up with none at all - which the solver cannot tell\n * apart from a static body, since both have `invMass === 0`. Rejecting it is\n * the difference between a clear error and a body that silently stops moving.\n */\n private _assertDynamicCarriesMass(): void {\n if (this.type !== 'dynamic' || this._massReady || this._colliders.length === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsBody: a dynamic body must carry at least one collider with mass — every collider it holds is either boundary geometry (a segment or chain, which has no interior) or has zero density. Add a solid collider, or make the body static or kinematic.',\n );\n }\n\n /** Recompute mass, centre of mass and rotational inertia from the colliders. */\n private _recomputeMass(): void {\n if (this.type !== 'dynamic') {\n this.mass = 0;\n this.invMass = 0;\n this.inertia = 0;\n this.invInertia = 0;\n this._comX = 0;\n this._comY = 0;\n this._massReady = false;\n\n return;\n }\n\n let mass = 0;\n let cx = 0;\n let cy = 0;\n let inertiaOrigin = 0;\n const point = { x: 0, y: 0 };\n\n for (const collider of this._colliders) {\n // Boundary geometry (a segment, later a chain) has no interior and reports\n // no mass properties; it contributes collision only.\n const massProperties: ShapeMassProperties | null = collider.shape.massProperties;\n\n if (massProperties === null) {\n continue;\n }\n\n const m = collider.density * massProperties.area;\n\n if (m <= 0) {\n continue;\n }\n\n // Shape centroid expressed in body-local space (offset + local rotation).\n applyTransform(collider.localTransform, massProperties.centroidX, massProperties.centroidY, point);\n mass += m;\n cx += m * point.x;\n cy += m * point.y;\n // Parallel-axis to the body origin: I_origin += I_centroid + m·d².\n inertiaOrigin += collider.density * massProperties.unitInertia + m * (point.x * point.x + point.y * point.y);\n }\n\n if (mass > 0) {\n cx /= mass;\n cy /= mass;\n }\n\n this.mass = mass;\n this.invMass = mass > 0 ? 1 / mass : 0;\n this._comX = cx;\n this._comY = cy;\n // Shift inertia from the body origin to the centre of mass.\n const inertiaCom = inertiaOrigin - mass * (cx * cx + cy * cy);\n\n this.inertia = this.fixedRotation ? 0 : inertiaCom;\n this.invInertia = this.fixedRotation || inertiaCom <= 0 ? 0 : 1 / inertiaCom;\n this._massReady = mass > 0;\n }\n}\n\n/**\n * Give a collider its id, and a chain collider's edge proxies theirs. The\n * proxies are ids in the same space as authored colliders - the contact graph\n * keys pairs on them - but they never appear in `body.colliders`.\n */\nconst attachWithChainEdges = (collider: Collider, body: PhysicsBody, owner: BodyOwner): void => {\n collider._attach(body, owner._allocateColliderId());\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n return;\n }\n\n for (const edge of edges) {\n edge._attach(body, owner._allocateColliderId());\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAiDA,IAAa,cAAb,MAAyB;CACvB,AAAgB;;CAGhB,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAGP,AAAO,OAAO;;CAEd,AAAO,UAAU;;CAEjB,AAAO,UAAU;;CAEjB,AAAO,aAAa;;CAGpB,AAAO,kBAAkB;;CAEzB,AAAO,kBAA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,QAAQ,MAAM,MAAM,oBAAoB,CAAC;CAElD,MAAM,QAAQ,SAAS;CAEvB,IAAI,UAAU,MACZ;CAGF,KAAK,MAAM,QAAQ,OACjB,KAAK,QAAQ,MAAM,MAAM,oBAAoB,CAAC;AAElD"}
@@ -227,6 +227,10 @@ export declare class PhysicsWorld implements BodyOwner {
227
227
  private readonly _bindings;
228
228
  private readonly _query;
229
229
  private readonly _commands;
230
+ /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */
231
+ private readonly _pendingColliderRemovals;
232
+ /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */
233
+ private readonly _warnedUnsweptKinds;
230
234
  /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */
231
235
  private readonly _islandParent;
232
236
  /** Pooled per-island minimum sleep time, indexed by union-find root. */
@@ -1 +1 @@
1
- {"version":3,"file":"PhysicsWorld.d.ts","sourceRoot":"","sources":["../../src/PhysicsWorld.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAU,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAoB,QAAQ,EAAE,MAAM,YAAY,CAAC;AAIxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC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AAC,YAAY;CAKrB"}
@@ -37,12 +37,12 @@ const clampAlpha = (alpha) => {
37
37
  * Removing the body's *only* collider is fine: a body with no geometry at all is
38
38
  * a body still being assembled, not a silently broken one.
39
39
  */
40
- const assertBodyKeepsItsMass = (collider) => {
40
+ const assertBodyKeepsItsMass = (collider, pendingRemovals) => {
41
41
  const body = collider.body;
42
42
  if (body.type !== "dynamic" || collider.shape.massProperties === null || collider.density <= 0) return;
43
43
  let remaining = 0;
44
44
  for (const other of body.colliders) {
45
- if (other === collider) continue;
45
+ if (other === collider || pendingRemovals.has(other)) continue;
46
46
  if (other.shape.massProperties !== null && other.density > 0) return;
47
47
  remaining++;
48
48
  }
@@ -234,6 +234,10 @@ var PhysicsWorld = class {
234
234
  _bindings = new BindingRegistry();
235
235
  _query;
236
236
  _commands = [];
237
+ /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */
238
+ _pendingColliderRemovals = /* @__PURE__ */ new Set();
239
+ /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */
240
+ _warnedUnsweptKinds = /* @__PURE__ */ new Set();
237
241
  /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */
238
242
  _islandParent = [];
239
243
  /** Pooled per-island minimum sleep time, indexed by union-find root. */
@@ -381,8 +385,12 @@ var PhysicsWorld = class {
381
385
  * called inside a callback.
382
386
  */
383
387
  destroyCollider(collider) {
384
- assertBodyKeepsItsMass(collider);
385
- this._defer(() => this._removeCollider(collider));
388
+ assertBodyKeepsItsMass(collider, this._pendingColliderRemovals);
389
+ this._pendingColliderRemovals.add(collider);
390
+ this._defer(() => {
391
+ this._pendingColliderRemovals.delete(collider);
392
+ this._removeCollider(collider);
393
+ });
386
394
  }
387
395
  /** Live joints (read-only view). */
388
396
  get joints() {
@@ -448,8 +456,10 @@ var PhysicsWorld = class {
448
456
  const dampingRatio = this.dampingRatio;
449
457
  const hasJoints = this._joints.length > 0;
450
458
  const hasBullets = this._hasBullets();
451
- for (let step = 0; step < steps; step++) this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);
452
- this._dispatchEvents();
459
+ for (let step = 0; step < steps; step++) {
460
+ this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);
461
+ this._dispatchEvents();
462
+ }
453
463
  }
454
464
  this._syncBindings();
455
465
  this._drainCommands();
@@ -555,6 +565,7 @@ var PhysicsWorld = class {
555
565
  destroy() {
556
566
  if (this._destroyed) return;
557
567
  this._destroyed = true;
568
+ this._drainCommands();
558
569
  for (const body of this._bodies) {
559
570
  for (const collider of body.colliders) collider._markDestroyed();
560
571
  body._markDestroyed();
@@ -729,7 +740,7 @@ var PhysicsWorld = class {
729
740
  * Filters and sensors behave exactly as in the discrete narrow phase.
730
741
  */
731
742
  _advanceBullets() {
732
- this._backend.spatialIndex?.sync(this._colliders);
743
+ this._backend.spatialIndex?.sync(this._detectionColliders);
733
744
  for (const body of this._bodies) {
734
745
  if (!body.isBullet || body.type !== "dynamic" || body.isSleeping) continue;
735
746
  const newX = body.worldCenterOfMassX;
@@ -1 +1 @@
1
- {"version":3,"file":"PhysicsWorld.js","names":[],"sources":["../../src/PhysicsWorld.ts"],"sourcesContent":["import type { AabbLike, PointLike, SceneNode, Seconds } from '@codexo/exojs';\nimport { logger, Signal, Vector } from '@codexo/exojs';\n\nimport { aabbOverlap, createAabb } from './Aabb';\nimport { NativePhysicsBackend } from './backend/NativePhysicsBackend';\nimport type { PhysicsBackend } from './backend/PhysicsBackend';\nimport { BindingRegistry } from './binding/BindingRegistry';\nimport type { PhysicsBinding } from './binding/PhysicsBinding';\nimport { authoredCollider, Collider } from './Collider';\nimport type { Manifold } from './collision/Manifold';\nimport type { SweepHit } from './collision/sweep';\nimport { canSweep, sweepProxies } from './collision/sweep';\nimport type { ContactModifier } from './ContactModifier';\nimport type { CollisionEvent, SensorEvent } from './events';\nimport type { Joint } from './joints/Joint';\nimport type { BodyOwner } from './PhysicsBody';\nimport { PhysicsBody } from './PhysicsBody';\nimport type { QueryFilter, RayHit } from './query/QueryEngine';\nimport { QueryEngine } from './query/QueryEngine';\nimport type { AnyShape } from './shapes/AnyShape';\nimport { sleepPenetrationTolerance } from './solver/tolerances';\nimport { TimeStepper } from './TimeStepper';\nimport type { BodyType, CollisionFilter } from './types';\nimport { shouldCollide } from './types';\n\n/**\n * Overlap left after clamping a bullet at its time of impact (the clamp\n * overshoots the contact by this much along the motion), so the next step's\n * discrete detection forms a real contact and the solver owns resting,\n * friction and events from then on.\n */\nconst ccdEmbed = 0.05;\n/** Impact speed (px/s) below which a bullet's CCD response does not bounce (mirrors the contact solver). */\nconst ccdRestitutionThreshold = 1;\n\n/**\n * Keep a host-supplied blend factor inside `[0, 1]`. A caller's own accumulator\n * can hand over a value outside it (a stale read, a custom scheduler), and an\n * unclamped one extrapolates the node past the simulated state instead of\n * blending between two known ones.\n */\nconst clampAlpha = (alpha: number): number => {\n // Written as two comparisons rather than Math.min/Math.max so a NaN factor\n // lands on 0 instead of propagating into every bound node's transform.\n if (!(alpha > 0)) {\n return 0;\n }\n\n return alpha < 1 ? alpha : 1;\n};\n\n/**\n * Reject removing the last collider a dynamic body's mass rests on while it still\n * holds others. Such a body keeps colliding but has `invMass === 0`, which the\n * solver cannot tell apart from a static body - the same state `PhysicsBody`\n * refuses to be constructed in.\n *\n * Removing the body's *only* collider is fine: a body with no geometry at all is\n * a body still being assembled, not a silently broken one.\n */\nconst assertBodyKeepsItsMass = (collider: Collider): void => {\n const body = collider.body;\n\n if (body.type !== 'dynamic' || collider.shape.massProperties === null || collider.density <= 0) {\n return;\n }\n\n let remaining = 0;\n\n for (const other of body.colliders) {\n if (other === collider) {\n continue;\n }\n\n if (other.shape.massProperties !== null && other.density > 0) {\n return;\n }\n\n remaining++;\n }\n\n if (remaining === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsWorld.destroyCollider: this is the only collider carrying mass for a dynamic body — removing it would leave the body colliding but massless. Destroy the body instead, or give it another solid collider first.',\n );\n};\n\n/** Shape kinds already reported as unswept, so the warning fires once per kind. */\nconst warnedUnsweptKinds = new Set<string>();\n\n/**\n * Dev-only: boundary geometry is never swept as the moving operand, so a bullet\n * body carrying it is not protected against tunnelling on that collider.\n * Reporting it beats a silent pass-through.\n */\nconst warnUnsweptBulletShape = (collider: Collider): void => {\n const kind = collider.shape.type;\n\n if (canSweep(kind, 'polygon') || warnedUnsweptKinds.has(kind)) {\n return;\n }\n\n warnedUnsweptKinds.add(kind);\n logger.warn(\n `PhysicsWorld: a bullet body carries a '${kind}' collider. Boundary geometry is level structure and is only ever a ` +\n 'sweep target, never the moving operand, so this collider can still cross thin geometry within one step. ' +\n 'Give a fast body a solid collider (circle, capsule or polygon).',\n { source: 'physics' },\n );\n};\n\n/**\n * `true` when a static/kinematic body - an island boundary, never an island\n * member - is being driven this step, either through its velocity or by a\n * {@link PhysicsBody.setTransform} teleport. Speed is deliberately not compared\n * against the sleep thresholds: a platform creeping along at 1 px/s still has to\n * push its passengers, and it is exactly that sub-threshold case where nothing\n * else would keep them awake.\n */\nconst isMovingBoundary = (body: PhysicsBody): boolean =>\n body._teleported || body.linearVelocityX !== 0 || body.linearVelocityY !== 0 || body.angularVelocity !== 0;\n\n/**\n * `true` while a contact still carries more overlap than the solver leaves\n * behind at rest. Read from the manifold detection just produced, which is the\n * same separation the solver's push-out bias is about to act on - the sleep gate\n * and the constraint it gates therefore agree by construction.\n */\nconst isUnresolved = (manifold: Manifold): boolean => {\n for (let i = 0; i < manifold.pointCount; i++) {\n // i in 0..pointCount-1 and pointCount ≤ 2, so the manifold point exists.\n if ((i === 0 ? manifold.points[0] : manifold.points[1]).penetration > sleepPenetrationTolerance) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `position`: `node`'s current WORLD\n * translation, duck-typed the same way `AudioListener` reads a follow target -\n * real {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit\n * it fall back to `(0, 0)` (the previous, surprising default).\n */\nconst worldPositionOf = (node: SceneNode): Readonly<PointLike> => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return { x: world.x, y: world.y };\n }\n\n return { x: 0, y: 0 };\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `angle` (radians): `node`'s current\n * WORLD rotation, decomposed from `getWorldTransform()`'s linear part\n * (`atan2(-c, a)` - `SceneNode.updateTransform` builds its rotation block as\n * `[[cosθ, sinθ], [-sinθ, cosθ]]`, i.e. `b = sinθ`/`c = -sinθ`, matching the\n * radians ⇄ degrees round-trip `PhysicsBinding.sync` already relies on).\n * Falls back to `0` for a duck-typed node without `getWorldTransform`.\n */\nconst worldAngleOf = (node: SceneNode): number => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return Math.atan2(-world.c, world.a);\n }\n\n return 0;\n};\n\n/** Construction options for a {@link PhysicsWorld}. */\nexport interface PhysicsWorldOptions {\n /** Gravity in px/s² (+Y down). Integrated each sub-step. Default `(0, 0)`. */\n gravity?: Readonly<PointLike>;\n /** Fixed timestep in seconds. Default `1 / 60`. */\n fixedDelta?: number;\n /** Maximum fixed steps per `step` call (spiral-of-death guard). Default `8`. */\n maxSubSteps?: number;\n /**\n * TGS-Soft sub-steps per fixed step (the solver's stiffness scales with this,\n * not iteration count). Default `4`. Must be ≥ 1. Values below `2` visibly\n * degrade tall-stack stability (a 10-box tower jitters at `1`), so the default\n * is load-bearing - do not lower it for performance.\n */\n subStepCount?: number;\n /** Soft-contact stiffness in Hz (the contact behaves as a damped spring at this frequency). Default `30`. */\n contactHertz?: number;\n /** Soft-contact damping ratio (≥ 1 keeps contacts from oscillating). Default `10`. */\n dampingRatio?: number;\n /** Put resting bodies to sleep so they skip integration and solving. Default `true`. */\n enableSleeping?: boolean;\n /**\n * Adjust each solid contact for the coming step (one-way platforms,\n * conditional friction, per-pair material overrides). At most one per world;\n * see {@link PhysicsWorld.contactModifier}. Default none.\n */\n contactModifier?: ContactModifier | null;\n /**\n * Place bound nodes between the last two fixed states instead of snapping them\n * to the latest one, which smooths motion when the fixed rate is below the\n * frame rate. Default `false`.\n *\n * The blend factor comes from {@link frameAlphaSource}; a world driven as a\n * `System` has to supply one.\n */\n interpolation?: boolean;\n /**\n * Where interpolated bindings read their blend factor, in `[0, 1)`.\n *\n * Defaults to this world's own accumulator - correct when the world is driven\n * with {@link PhysicsWorld.step}, which is what advances it. A world driven as\n * a `System` goes through {@link PhysicsWorld.fixedUpdate} and bypasses that\n * accumulator entirely, so the host owns the fraction: pass\n * `() => app.frameAlpha`.\n */\n frameAlphaSource?: () => number;\n /** Linear speed at or below which a body is a sleep candidate, px/s. Default `5`. */\n sleepLinearVelocity?: number;\n /** Angular speed at or below which a body is a sleep candidate, rad/s. Default `0.06`. */\n sleepAngularVelocity?: number;\n /** Seconds a body must stay below the sleep thresholds before it sleeps. Default `0.5`. */\n timeToSleep?: number;\n}\n\n/**\n * {@link PhysicsWorld.attach} convenience options: a body type plus a single\n * collider, attached to a scene node in one call.\n */\nexport interface AttachOptions {\n /** Simulation role of the created body. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position of the body. Default the node's current WORLD position ({@link SceneNode.getWorldTransform}) at attach time. */\n position?: Readonly<PointLike>;\n /** Initial rotation (radians) of the body. Default the node's current WORLD rotation at attach time. */\n angle?: number;\n /** Per-body multiplier on world gravity. Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts. Default `false`. */\n fixedRotation?: boolean;\n /** The collider geometry. */\n shape: AnyShape;\n /** Body-local offset of the collider. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the collider (radians). Default `0`. */\n rotation?: number;\n /** Collider density (mass per px²). Default `1`. */\n density?: number;\n /** Coulomb friction coefficient. Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]`. Default `0`. */\n restitution?: number;\n /** When `true`, the collider generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group collision filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n}\n\n/**\n * The collision/query world: owns bodies, colliders, the detection backend,\n * bindings, the query engine and the fixed-step accumulator. Stepped by the\n * caller (commonly from a `Scene.update`), each fixed sub-step it integrates\n * body velocities, runs broad- and narrow-phase detection, solves contacts and\n * integrates positions, then fires immutable contact/sensor events and writes\n * bound node transforms. It holds **no module-level state**, so any number of\n * worlds run in isolation.\n *\n * The dynamics are a native, warm-started **TGS-Soft** solver (Box2D-v3 \"soft\n * step\"): each fixed step runs detection once, then several sub-steps, each\n * integrating gravity over the sub-step and solving contacts with a soft\n * position bias plus a bias-free relax pass; a 2-point block normal solve\n * propagates stack loads, and restitution is a separate final pass. Decoupling\n * stiffness from the iteration count keeps tall towers stable. The detection\n * backend sits behind an internal seam, so the solver is swappable without\n * touching this public surface.\n *\n * **Operating envelope.** The soft solver trades a little accuracy for\n * robustness, so it has a few documented limits - each stays finite and stable,\n * and each is pinned by a gate in `dynamics.test.ts` or\n * `contact-push-out.test.ts`:\n * - **Resting contacts** settle within a small, fixed tolerance. A face contact\n * settles at exactly that tolerance; a single-point contact settles slightly\n * deeper, and that gap grows with acceleration. Very high accelerations\n * eventually exceed what the push-out can resolve within a step, at which\n * point the contact holds a slightly deeper resting depth instead of the\n * tolerance - keep gravity in the range ordinary 2D games use.\n * - **Mass ratio** - contacts between bodies of very different mass degrade\n * gradually rather than at a fixed ratio. What sets the practical limit is how\n * thick the supporting geometry is relative to the lighter body, not the ratio\n * alone: a light body squeezed against a boundary thinner than itself is the\n * case that fails first, and it fails by sinking through.\n * - **Scale-relative behaviour** - the solver's tolerances are absolute lengths,\n * so a very small shape sees them as a large fraction of itself, and a very\n * large one as a negligible one. Keep the shapes of one world within a couple\n * of orders of magnitude of each other.\n * - **CCD is opt-in and translation-only** - detection runs once per fixed\n * step, so an ordinary body that crosses more than roughly half a barrier's\n * total thickness within one step may end up on the wrong side of it, either\n * passing through or being resolved out of the far face. Flag fast\n * projectiles with {@link PhysicsBody.isBullet}: each of the body's colliders\n * is then shape-cast along the step's motion (an exact translation-only sweep\n * of the full shape, not just the centre) and clamped at the first impact.\n * Rotation over the step is not swept - a long body spinning fast enough to\n * sweep past an obstacle within one step can still miss it.\n * - **{@link PhysicsWorldOptions.subStepCount}** - the default `4` is\n * load-bearing for tall-stack stability; lowering it below `2` visibly\n * degrades stacking, so do not reduce it for performance.\n * - **Broad phase is a dynamic AABB tree** (`AabbTreeBroadPhase`), stateful\n * across fixed steps: a collider whose tight AABB stays inside its stored\n * fat AABB costs nothing to re-sync, and only colliders that actually move\n * outside their margin trigger a tree update and a local re-query for new\n * neighbours. Detection still walks every live collider once per step (a\n * cheap containment check for each), so there is a small linear floor, but\n * the dominant cost - reinsertion and neighbour discovery - is driven by\n * how much actually moved, not by the total live collider count; sleeping\n * bodies skip that dominant cost entirely. Scales to tens of thousands of\n * simultaneously-live colliders, including dense clusters that would\n * degrade a sort-and-sweep broad phase; very large or highly dynamic\n * worlds may still benefit from splitting into several smaller\n * `PhysicsWorld` instances (e.g. per room/chunk).\n */\nexport class PhysicsWorld implements BodyOwner {\n /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */\n public readonly onCollisionStart = new Signal<[CollisionEvent]>();\n /** Fires when two solid colliders stop touching (or one is destroyed). */\n public readonly onCollisionEnd = new Signal<[CollisionEvent]>();\n /** Fires when a collider enters a sensor. */\n public readonly onSensorEnter = new Signal<[SensorEvent]>();\n /** Fires when a collider leaves a sensor. */\n public readonly onSensorExit = new Signal<[SensorEvent]>();\n\n /** World gravity (px/s², +Y down). Integrated each sub-step. */\n public readonly gravity: Vector;\n /** The fixed-step accumulator. */\n public readonly timeStepper: TimeStepper;\n /** TGS-Soft sub-steps per fixed step. */\n public readonly subStepCount: number;\n /** Soft-contact stiffness in Hz. */\n public readonly contactHertz: number;\n /** Soft-contact damping ratio. */\n public readonly dampingRatio: number;\n /** Whether resting bodies are put to sleep. */\n public readonly enableSleeping: boolean;\n /** Linear sleep threshold (px/s). */\n public readonly sleepLinearVelocity: number;\n /** Angular sleep threshold (rad/s). */\n public readonly sleepAngularVelocity: number;\n /** Seconds below the thresholds before a body sleeps. */\n public readonly timeToSleep: number;\n\n /**\n * Runs once per solid contact per fixed step, after contact generation and\n * before island building and the solver, so a contact it disables applies no\n * impulse and does not couple its two bodies into one sleeping island.\n *\n * At most one modifier per world - it mutates simulation state, so a\n * multi-listener signal would make the outcome depend on registration order.\n * Set to `null` to remove it; the per-contact values then stay at the\n * defaults derived from the two colliders.\n */\n public contactModifier: ContactModifier | null;\n\n /**\n * Whether bound nodes are placed between the last two fixed states rather than\n * snapped to the latest one. Toggleable at runtime; switching it off snaps\n * every bound node back to the current fixed state on the next sync.\n */\n public interpolation: boolean;\n\n /**\n * Supplies the `[0, 1)` blend factor for interpolated bindings. Defaults to\n * this world's own accumulator; point it at the host's own fraction\n * (`() => app.frameAlpha`) when the world runs as a `System`, because\n * {@link fixedUpdate} never advances the local accumulator.\n */\n public frameAlphaSource: () => number;\n\n private readonly _backend: PhysicsBackend = new NativePhysicsBackend();\n private readonly _bodies: PhysicsBody[] = [];\n private readonly _colliders: Collider[] = [];\n /**\n * What detection actually runs over: the authored colliders, with a chain\n * replaced by the edge proxies it fans out into. The broad phase, the narrow\n * phase and the queries all read this list; `_colliders` stays the authored\n * set every public surface reports.\n */\n private readonly _detectionColliders: Collider[] = [];\n /** Pooled scratch for re-syncing a single body's broad-phase leaves. */\n private readonly _leafScratch: Collider[] = [];\n private readonly _joints: Joint[] = [];\n private readonly _bindings = new BindingRegistry();\n private readonly _query: QueryEngine;\n private readonly _commands: Array<() => void> = [];\n /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */\n private readonly _islandParent: number[] = [];\n /** Pooled per-island minimum sleep time, indexed by union-find root. */\n private readonly _islandMinSleep: number[] = [];\n /** Pooled scratch for the CCD pass (clamp target, per-pair sweep hit, best hit, swept AABB) - keeps the sweep allocation-free. */\n private readonly _ccdClampPosition = { x: 0, y: 0 };\n private readonly _ccdSweepHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdBestHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdSweptAabb: AabbLike = createAabb();\n /** Pooled result buffer for the CCD pass's broad-phase query (refilled per bullet collider). */\n private readonly _ccdCandidates: Collider[] = [];\n\n /**\n * Narrow-phase sweep tests run by the CCD pass since world creation. Pairs\n * rejected by the swept-AABB prune never count, so slow bullets far from any\n * geometry keep this at zero (the cheap path).\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdSweepTests = 0;\n\n /**\n * Colliders the CCD pass pulled out of the broad phase since world creation -\n * the size of the candidate set the swept-AABB prune and the narrow-phase\n * sweep then work on. Counted separately from {@link _ccdSweepTests} because\n * the two measure different halves: this is what the pass looks at, that is\n * what it actually sweeps. Stays proportional to the geometry near the\n * bullets, not to the world's collider count.\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdBroadPhaseCandidates = 0;\n\n private _nextBodyId = 1;\n private _nextColliderId = 1;\n private _dispatching = false;\n private _destroyed = false;\n\n public constructor(options: PhysicsWorldOptions = {}) {\n this.gravity = new Vector(options.gravity?.x ?? 0, options.gravity?.y ?? 0);\n this.timeStepper = new TimeStepper({\n ...(options.fixedDelta !== undefined && { fixedDelta: options.fixedDelta }),\n ...(options.maxSubSteps !== undefined && { maxSubSteps: options.maxSubSteps }),\n });\n\n const subStepCount = options.subStepCount ?? 4;\n\n if (!Number.isInteger(subStepCount) || subStepCount < 1) {\n throw new RangeError(`PhysicsWorld: subStepCount must be an integer ≥ 1, received ${subStepCount}.`);\n }\n\n this.subStepCount = subStepCount;\n this.contactHertz = options.contactHertz ?? 30;\n this.dampingRatio = options.dampingRatio ?? 10;\n this.enableSleeping = options.enableSleeping ?? true;\n this.sleepLinearVelocity = options.sleepLinearVelocity ?? 5;\n this.sleepAngularVelocity = options.sleepAngularVelocity ?? 0.06;\n this.timeToSleep = options.timeToSleep ?? 0.5;\n this.contactModifier = options.contactModifier ?? null;\n this.interpolation = options.interpolation ?? false;\n this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);\n this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);\n }\n\n /** Live bodies (read-only view). */\n public get bodies(): readonly PhysicsBody[] {\n return this._bodies;\n }\n\n /** Live colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /**\n * @internal - the geometry the broad phase and the narrow phase actually hold:\n * every authored collider, with a chain replaced by its per-edge proxies.\n * Consumed by the debug draw layer, which visualises what the solver sees;\n * public identity stays {@link colliders}.\n */\n public get detectionGeometry(): readonly Collider[] {\n return this._detectionColliders;\n }\n\n // ── lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Add a body to the world: allocates the body and its collider ids, registers\n * the colliders, computes the mass model and tracks the body for stepping.\n * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.\n * Safe to call inside an event callback - the body push is deferred to the end\n * of the step, exactly like collider registration. Returns the body.\n *\n * @throws if the body has already been added to a world.\n */\n public add(body: PhysicsBody): PhysicsBody {\n this._assertAlive();\n\n if (body.attached) {\n throw new Error('PhysicsWorld.add: this body has already been added to a world.');\n }\n\n // Allocate the id + link/register colliders + aggregate mass now (matches the\n // old createBody, which allocated the id synchronously); only the body-list\n // push is deferred so it is safe inside an event dispatch.\n body._attachToWorld(this, this._nextBodyId++);\n\n this._defer(() => {\n if (!body.destroyed) {\n this._bodies.push(body);\n }\n });\n\n return body;\n }\n\n /**\n * Convenience: create a body carrying a single collider, add it to the world\n * and bind it to `node` in one call. The node tracks `body.position` after each\n * step. Returns the body. Equivalent to `new PhysicsBody(...)` + `add` + `bind`.\n *\n * When `options.position`/`options.angle` are omitted, the body starts at\n * `node`'s current WORLD position/rotation (via `getWorldTransform()`,\n * composed through any transform-group boundary) rather than `(0, 0)` -\n * otherwise a body attached to an already-placed node would visibly \"teleport\"\n * to the origin on the next step. Pass `position`/`angle` explicitly to override.\n */\n public attach(node: SceneNode, options: AttachOptions): PhysicsBody {\n const body = new PhysicsBody({\n ...(options.type !== undefined && { type: options.type }),\n position: options.position ?? worldPositionOf(node),\n angle: options.angle ?? worldAngleOf(node),\n ...(options.gravityScale !== undefined && { gravityScale: options.gravityScale }),\n ...(options.fixedRotation !== undefined && { fixedRotation: options.fixedRotation }),\n colliders: [\n new Collider({\n shape: options.shape,\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.rotation !== undefined && { rotation: options.rotation }),\n ...(options.density !== undefined && { density: options.density }),\n ...(options.friction !== undefined && { friction: options.friction }),\n ...(options.restitution !== undefined && { restitution: options.restitution }),\n ...(options.isSensor !== undefined && { isSensor: options.isSensor }),\n ...(options.filter !== undefined && { filter: options.filter }),\n }),\n ],\n });\n\n this.add(body);\n this.bind(body, node);\n\n return body;\n }\n\n /**\n * Destroy a body and its colliders. Every dynamic body touching it is woken,\n * so anything that was resting on the destroyed body falls once its support is\n * gone. Deferred when called inside a callback.\n */\n public destroyBody(body: PhysicsBody): void {\n this._defer(() => this._removeBody(body));\n }\n\n /**\n * Destroy a single collider, recomputing its body's mass. Wakes every dynamic\n * body touching it, the same way {@link destroyBody} does. Deferred when\n * called inside a callback.\n */\n public destroyCollider(collider: Collider): void {\n // Checked here rather than in the deferred removal so the error surfaces at\n // the call site that caused it, not out of the middle of a `step()`.\n assertBodyKeepsItsMass(collider);\n\n this._defer(() => this._removeCollider(collider));\n }\n\n /** Live joints (read-only view). */\n public get joints(): readonly Joint[] {\n return this._joints;\n }\n\n /**\n * Add a constraint joint. Construct it first (`new DistanceJoint({ ... })`),\n * then add it. Wakes both bodies; safe inside a callback (registration is\n * deferred). Returns the joint.\n */\n public addJoint<T extends Joint>(joint: T): T {\n this._assertAlive();\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n if (!this._joints.includes(joint)) {\n this._joints.push(joint);\n }\n });\n\n return joint;\n }\n\n /** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */\n public removeJoint(joint: Joint): void {\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n const index = this._joints.indexOf(joint);\n\n if (index !== -1) {\n this._joints.splice(index, 1);\n }\n });\n }\n\n // ── stepping ───────────────────────────────────────────────────────────\n\n /**\n * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each\n * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate\n * gravity, solve contacts with a soft bias, integrate positions, relax) and a\n * restitution pass, then writes the accumulated motion into each body. Finally\n * dispatches events and writes bound node transforms.\n *\n * **Prefer registering the world as a system instead**\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) so {@link fixedUpdate} drives stepping directly from the\n * engine's own fixed-timestep scheduler - one call per fixed step, no\n * accumulator duplication. `step` remains available here for manual/advanced\n * driving (e.g. a fixed-but-non-standard rate, or stepping outside the\n * normal frame loop entirely): pass any delta and this accumulator converts\n * it into the right number of fixed sub-steps (0, 1, or several, clamped by\n * {@link PhysicsWorldOptions.maxSubSteps}).\n *\n * Either way the simulation is frame-rate independent and deterministic -\n * the same sequence of deltas replays identically. `timeStepper.alpha`\n * (`[0, 1)`) is the leftover sub-step fraction after this call, for callers\n * that want to interpolate a bound node's rendered position between the last\n * two fixed states instead of snapping to the latest one (bindings do not do\n * this automatically - {@link bind} always writes the latest fixed-step\n * transform verbatim).\n */\n public step(frameDeltaSeconds: number): void {\n this._assertAlive();\n\n const steps = this.timeStepper.advance(frameDeltaSeconds);\n\n if (steps > 0) {\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n const gravityX = this.gravity.x;\n const gravityY = this.gravity.y;\n const contactHertz = this.contactHertz;\n const dampingRatio = this.dampingRatio;\n const hasJoints = this._joints.length > 0;\n const hasBullets = this._hasBullets();\n\n for (let step = 0; step < steps; step++) {\n this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);\n }\n\n this._dispatchEvents();\n }\n\n // `step` is called once per rendered frame, so presenting here is already\n // the variable-rate slot an interpolated binding needs.\n this._syncBindings();\n this._drainCommands();\n }\n\n /**\n * Advance by exactly one fixed step, driven directly by the engine's own\n * fixed-timestep scheduler when this world is registered as a `System`\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) - bypasses {@link timeStepper}'s variable-delta accumulator\n * entirely, since the caller has already decided exactly when a fixed step\n * occurs. Prefer this over manual {@link step} once the world is\n * system-registered; `step` remains available for advanced manual driving.\n * Always advances by exactly {@link timeStepper}'s configured `fixedDelta`,\n * regardless of the caller's actual fixed-step interval - if the engine's\n * `Application.fixedTimeStep` doesn't match this world's `fixedDelta`, the\n * simulation stays deterministic but runs at the wrong wall-clock speed\n * relative to real time.\n */\n public fixedUpdate(_step: Seconds): void {\n this._assertAlive();\n\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n\n this._stepOnce(h, subStepCount, this.gravity.x, this.gravity.y, this.contactHertz, this.dampingRatio, this._joints.length > 0, this._hasBullets());\n\n this._dispatchEvents();\n\n // Interpolated presentation is a per-FRAME job and moves to `update`; this\n // phase can run several times per frame, and the blend factor is only final\n // once the last of them has run.\n if (!this.interpolation) {\n this._bindings.sync();\n }\n\n this._drainCommands();\n }\n\n /**\n * Variable-rate `System` phase: places bound nodes for the frame that is about\n * to be drawn. Only does work while {@link interpolation} is on - otherwise\n * {@link fixedUpdate} has already snapped them to the latest fixed state.\n */\n public update(_delta: Seconds): void {\n this._assertAlive();\n\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n }\n }\n\n /** Present bound nodes, snapping or interpolating according to {@link interpolation}. */\n private _syncBindings(): void {\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n } else {\n this._bindings.sync();\n }\n }\n\n private _stepOnce(\n h: number,\n subStepCount: number,\n gravityX: number,\n gravityY: number,\n contactHertz: number,\n dampingRatio: number,\n hasJoints: boolean,\n hasBullets: boolean,\n ): void {\n // Detection runs once per fixed step (collider geometry is already current\n // from the previous frame's finalize / attach / setTransform). TGS-Soft\n // reuses the manifolds across the sub-steps below.\n this._backend.detect(this._detectionColliders);\n\n // The contact modifier runs between detection and the sleep decision: a\n // contact it disables must neither reach the solver nor union its two bodies\n // into one island, and both of those are decided below.\n if (this.contactModifier !== null) {\n this._backend.applyContactModifier(this.contactModifier);\n }\n\n // Sleep decision runs after detection (islands need the current contact\n // set) and before the solver (so sleeping contacts are skipped, and a\n // sleeping island touched by an awake body is woken first).\n if (this.enableSleeping) {\n this._updateSleeping(this.timeStepper.fixedDelta);\n }\n\n this._backend.prepareSolve(h, contactHertz, dampingRatio);\n\n if (hasJoints) {\n this._prepareJoints(h);\n }\n\n if (hasBullets) {\n this._recordBulletPositions();\n }\n\n for (let subStep = 0; subStep < subStepCount; subStep++) {\n // Integrate gravity/forces over the sub-step (forces persist across\n // sub-steps; cleared once per frame by `_finalizePosition`).\n for (const body of this._bodies) {\n body._integrateVelocity(h, gravityX, gravityY);\n }\n\n // Warm-start every sub-step (Box2D-v3 soft step): the relax pass leaves\n // each contact's normal velocity at zero, so re-applying the\n // accumulated impulse re-balances exactly this sub-step's gravity - the\n // impulse converges to the per-sub-step load (m·h·g), not the per-frame\n // load, which is what keeps tall stacks from pumping energy.\n this._backend.warmStart();\n\n if (hasJoints) {\n this._warmStartJoints();\n }\n\n // Main soft-bias velocity solve, integrate positions (accumulating\n // per-body delta), then the bias-free relax pass. Joints solve right\n // after the contacts in each pass (contacts are the stiffer constraint).\n this._backend.solveVelocities(true);\n\n if (hasJoints) {\n this._solveJoints(true);\n }\n\n for (const body of this._bodies) {\n body._integratePosition(h);\n }\n\n this._backend.solveVelocities(false);\n\n if (hasJoints) {\n this._solveJoints(false);\n }\n }\n\n // Separate restitution pass, then write the accumulated delta into each\n // body's transform and re-sync collider geometry.\n this._backend.applyRestitution();\n\n for (const body of this._bodies) {\n body._finalizePosition();\n }\n\n if (hasBullets) {\n this._advanceBullets();\n }\n }\n\n // ── binding ────────────────────────────────────────────────────────────\n\n /**\n * Link a body to a scene node; the node tracks the body after each step.\n * Destroying the node is enough to end the link - the next step drops it\n * rather than writing into the node's released transform, so an explicit\n * {@link unbind} is only needed to stop tracking a node that stays alive.\n *\n * @throws if `node` is already destroyed.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n return this._bindings.bind(body, node);\n }\n\n /** Remove a body↔node link. */\n public unbind(body: PhysicsBody): void {\n this._bindings.unbind(body);\n }\n\n // ── queries ────────────────────────────────────────────────────────────\n\n /** Colliders containing `point`. Fresh array. */\n public queryPoint(point: Readonly<PointLike>, filter?: QueryFilter): Collider[] {\n return this._query.queryPoint(point, filter);\n }\n\n /** Colliders whose AABB overlaps `bounds`. Writes into `out` (cleared) if given. */\n public queryAabb(bounds: AabbLike, filter?: QueryFilter, out?: Collider[]): Collider[] {\n return this._query.queryAabb(bounds, filter, out);\n }\n\n /** Invoke `callback` for each collider whose AABB overlaps `bounds`. Allocation-free. */\n public forEachAabbHit(bounds: AabbLike, filter: QueryFilter | undefined, callback: (collider: Collider) => void): void {\n this._query.forEachAabbHit(bounds, filter, callback);\n }\n\n /** Nearest collider hit by the ray, or `null`. */\n public rayCast(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, maxDistance?: number): RayHit | null {\n return this._query.rayCast(origin, direction, filter, maxDistance);\n }\n\n /** All collider hits along the ray, sorted by distance. Writes into `out` (cleared) if given. */\n public rayCastAll(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, out?: RayHit[], maxDistance?: number): RayHit[] {\n return this._query.rayCastAll(origin, direction, filter, out, maxDistance);\n }\n\n /** Colliders overlapping `shape` placed at `position`/`angle`. Fresh array. */\n public overlapShape(shape: AnyShape, position: Readonly<PointLike>, filter?: QueryFilter, angle?: number): Collider[] {\n return this._query.overlapShape(shape, position, filter, angle);\n }\n\n /** Release every body, collider, binding and backend resource. */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n // Mark colliders before their bodies: a collider that still reported\n // `destroyed === false` while `collider.body.destroyed === true` would look\n // usable after the world that owned it is gone. Walk each body's own list\n // rather than `this._colliders`, so colliders whose deferred registration\n // never ran are covered too. `_backend.destroy()` below releases their\n // broad-phase proxies.\n for (const body of this._bodies) {\n for (const collider of body.colliders) {\n collider._markDestroyed();\n }\n\n body._markDestroyed();\n }\n\n this._bodies.length = 0;\n this._colliders.length = 0;\n this._detectionColliders.length = 0;\n this._joints.length = 0;\n this._commands.length = 0;\n this._bindings.clear();\n this._backend.destroy();\n this.onCollisionStart.destroy();\n this.onCollisionEnd.destroy();\n this.onSensorEnter.destroy();\n this.onSensorExit.destroy();\n }\n\n // ── BodyOwner ──────────────────────────────────────────────────────────\n\n public _allocateColliderId(): number {\n return this._nextColliderId++;\n }\n\n public _registerCollider(collider: Collider): void {\n this._defer(() => {\n if (collider.destroyed) {\n return;\n }\n\n this._colliders.push(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._detectionColliders.push(collider);\n\n return;\n }\n\n for (const edge of edges) {\n this._detectionColliders.push(edge);\n }\n });\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n /** The detection backend (internal; consumed by the debug draw layer). */\n public get backend(): PhysicsBackend {\n return this._backend;\n }\n\n private _dispatchEvents(): void {\n const graph = this._backend.contactGraph;\n\n this._dispatching = true;\n\n for (const event of graph.collisionEnd) {\n this.onCollisionEnd.dispatch(event);\n }\n\n for (const event of graph.sensorExit) {\n this.onSensorExit.dispatch(event);\n }\n\n for (const event of graph.collisionStart) {\n this.onCollisionStart.dispatch(event);\n }\n\n for (const event of graph.sensorEnter) {\n this.onSensorEnter.dispatch(event);\n }\n\n this._dispatching = false;\n }\n\n /**\n * Accumulate per-body sleep timers and put/keep islands of resting bodies\n * asleep so a stack sleeps and wakes as one unit. An island is a connected\n * component of dynamic bodies joined by touching solid contacts (static and\n * kinematic bodies are boundaries, not nodes); it sleeps once every member has\n * stayed below the sleep thresholds for `timeToSleep`, and wakes the instant\n * any member does (e.g. an awake body merges into it via a new contact).\n * A boundary that is itself moving resets the sleep timer of every dynamic\n * body it touches, so a platform keeps its passengers awake however slowly it\n * travels; so does a contact still carrying more penetration than the solver\n * leaves at rest, because the push-out that resolves it is slower than the\n * sleep velocity threshold and a body would otherwise be frozen embedded.\n * Deterministic: union-find roots break ties by lower index and the contact\n * set is id-sorted.\n */\n private _updateSleeping(dt: number): void {\n const bodies = this._bodies;\n const count = bodies.length;\n const parent = this._islandParent;\n const minSleep = this._islandMinSleep;\n\n // Assign dense indices, reset the union-find, and accumulate sleep timers for\n // awake dynamic bodies (a sleeping body's timer stays frozen ≥ timeToSleep).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n body._islandIndex = i;\n parent[i] = i;\n minSleep[i] = Infinity;\n\n if (body.type === 'dynamic' && !body.isSleeping) {\n body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);\n }\n }\n\n parent.length = count;\n minSleep.length = count;\n\n this._unionContactIslands();\n\n // Joints couple their two bodies into the same island (sleep/wake together).\n for (const joint of this._joints) {\n const bodyA = joint.bodyA;\n const bodyB = joint.bodyB;\n\n if (joint.enabled && bodyA.type === 'dynamic' && bodyB.type === 'dynamic') {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n }\n }\n\n // Per-island minimum sleep time over its dynamic members.\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n const root = this._find(i);\n\n if (body._sleepTime < minSleep[root]!) {\n minSleep[root] = body._sleepTime;\n }\n }\n }\n\n // Sleep an island iff every member has rested for `timeToSleep`; otherwise\n // wake it (which also wakes any member dragged awake by a fresh contact).\n const timeToSleep = this.timeToSleep;\n\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n body._setSleeping(minSleep[this._find(i)]! >= timeToSleep);\n }\n }\n }\n\n /**\n * Union dynamic↔dynamic solid contacts into islands. A dynamic body touching a\n * MOVING static/kinematic body has its sleep timer reset instead: those types\n * are island boundaries, not members, so nothing else would keep the passenger\n * of a slow-moving platform awake - and the solver skips a contact whose\n * dynamic side is asleep, letting the platform drive straight through it.\n *\n * The same traversal resets the sleep timer of both sides of a contact whose\n * penetration the solver has not worked off yet, so the island it belongs to\n * stays awake until the overlap is within the tolerance the solver itself\n * converges to.\n */\n private _unionContactIslands(): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n // A contact the modifier disabled carries no load this step, so it neither\n // forms an island, nor keeps a passenger of a moving platform awake, nor\n // has an overlap anything is going to resolve.\n if (!contact.enabled) {\n continue;\n }\n\n const bodyA = contact.a.body;\n const bodyB = contact.b.body;\n const dynamicA = bodyA.type === 'dynamic';\n const dynamicB = bodyB.type === 'dynamic';\n\n if (dynamicA && dynamicB) {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n } else if (dynamicA && isMovingBoundary(bodyB)) {\n bodyA._sleepTime = 0;\n } else if (dynamicB && isMovingBoundary(bodyA)) {\n bodyB._sleepTime = 0;\n }\n\n // Unresolved overlap only matters where there is a dynamic body to hold\n // awake; a static↔static pair reaches the contact set but has no sleep\n // decision to gate.\n if ((dynamicA || dynamicB) && isUnresolved(contact.manifold)) {\n if (dynamicA) {\n bodyA._sleepTime = 0;\n }\n\n if (dynamicB) {\n bodyB._sleepTime = 0;\n }\n }\n }\n }\n\n /** Union-find union by lower index (deterministic roots). */\n private _union(a: number, b: number): void {\n const rootA = this._find(a);\n const rootB = this._find(b);\n\n if (rootA < rootB) {\n this._islandParent[rootB] = rootA;\n } else if (rootB < rootA) {\n this._islandParent[rootA] = rootB;\n }\n }\n\n /** Union-find find with path halving. */\n private _find(index: number): number {\n const parent = this._islandParent;\n\n while (parent[index]! !== index) {\n const grandparent = parent[parent[index]!]!;\n parent[index] = grandparent;\n index = grandparent;\n }\n\n return index;\n }\n\n /** Build each joint's per-frame constraint data (once per fixed step). */\n private _prepareJoints(h: number): void {\n for (const joint of this._joints) {\n joint._prepare(h);\n }\n }\n\n /** Re-apply each joint's accumulated impulse (each sub-step). */\n private _warmStartJoints(): void {\n for (const joint of this._joints) {\n joint._warmStart();\n }\n }\n\n /** One joint velocity pass (each sub-step, after the contacts). */\n private _solveJoints(useBias: boolean): void {\n for (const joint of this._joints) {\n joint._solve(useBias);\n }\n }\n\n /** Whether any dynamic body is flagged for continuous collision (bullet mode). */\n private _hasBullets(): boolean {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n return true;\n }\n }\n\n return false;\n }\n\n /** Snapshot each bullet's centre of mass at the start of the fixed step (the swept-test origin). */\n private _recordBulletPositions(): void {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n body._ccdPrevX = body.worldCenterOfMassX;\n body._ccdPrevY = body.worldCenterOfMassY;\n }\n }\n }\n\n /**\n * Shape-cast each bullet's colliders along this fixed step's motion against\n * every other body's colliders; if any would cross one, clamp the body at the\n * earliest impact and resolve it about the surface normal (a slide for a\n * non-bouncy body, an elastic reflection as restitution → 1) so it cannot\n * tunnel. The sweep is an exact translation-only cast of the full shapes\n * (Minkowski ray for circles, swept SAT for polygon pairs) - the step's\n * rotation is applied before the sweep, not swept through. Pairs already\n * overlapping at the start of the step are skipped: the discrete solver owns\n * them (that hand-off is what lets a landed bullet rest on real contacts).\n * Filters and sensors behave exactly as in the discrete narrow phase.\n */\n private _advanceBullets(): void {\n // `_finalizePosition` moved collider geometry after this step's detection\n // pass, so the index's leaves are stale for the sweep queries below. A leaf\n // whose tight AABB is still inside its fat one costs nothing to re-sync.\n this._backend.spatialIndex?.sync(this._colliders);\n\n for (const body of this._bodies) {\n if (!body.isBullet || body.type !== 'dynamic' || body.isSleeping) {\n continue;\n }\n\n // The step's centre-of-mass motion; every collider translated by it too.\n const newX = body.worldCenterOfMassX;\n const newY = body.worldCenterOfMassY;\n const dx = newX - body._ccdPrevX;\n const dy = newY - body._ccdPrevY;\n const distance = Math.hypot(dx, dy);\n\n if (distance < 1e-6) {\n continue;\n }\n\n const blocked = this._sweepBulletColliders(body, dx, dy);\n\n if (blocked === null) {\n continue;\n }\n\n // Clamp the step's translation at the impact, overshooting by a small\n // embed along the motion (a pure translation - the rotation is already\n // applied) so the next step's detection forms a real discrete contact.\n const best = this._ccdBestHit;\n const clampDistance = Math.min(distance, best.t * distance + ccdEmbed);\n\n if (clampDistance < distance) {\n const pullBack = (clampDistance - distance) / distance;\n\n this._ccdClampPosition.x = body.x + dx * pullBack;\n this._ccdClampPosition.y = body.y + dy * pullBack;\n body.setTransform(this._ccdClampPosition, body.angle);\n\n // The clamp pulled this body back behind the pose the index was synced\n // from; refresh just its own leaves so a later bullet's query still sees it.\n this._backend.spatialIndex?.sync(this._detectionLeavesOf(body));\n }\n\n // Reflect about the true surface normal: a slide for a non-bouncy body\n // (restitution 0), an elastic bounce as restitution → 1. The body's own\n // restitution combines (max) with the surface's, matching the contact solver.\n const vn = body.linearVelocityX * best.normalX + body.linearVelocityY * best.normalY;\n\n if (vn < 0) {\n const restitution = vn < -ccdRestitutionThreshold ? Math.max(this._bulletRestitution(body), blocked.restitution) : 0;\n const impulse = -(1 + restitution) * vn;\n\n body.linearVelocityX += impulse * best.normalX;\n body.linearVelocityY += impulse * best.normalY;\n }\n }\n }\n\n /**\n * Find the earliest impact for a bullet whose colliders translated by\n * `(dx, dy)` this step. Each of the bullet's colliders queries the broad\n * phase with its swept AABB, so the pass costs what the geometry around the\n * bullet's path costs - not one iteration per collider in the world. Returns\n * the blocking collider (with the impact written into {@link _ccdBestHit}),\n * or `null` when nothing blocks the motion.\n */\n private _sweepBulletColliders(body: PhysicsBody, dx: number, dy: number): Collider | null {\n const hit = this._ccdSweepHit;\n const best = this._ccdBestHit;\n const swept = this._ccdSweptAabb;\n const spatialIndex = this._backend.spatialIndex;\n let blocked: Collider | null = null;\n\n best.t = Infinity;\n\n for (const collider of body.colliders) {\n if (collider.isSensor) {\n continue; // Sensors never block — not even their own body's motion.\n }\n\n if (__DEV__) {\n warnUnsweptBulletShape(collider);\n }\n\n // The collider's end-pose AABB unioned with its start pose; anything\n // outside it cannot be hit, so no narrow-phase sweep runs.\n const aabb = collider.aabb;\n\n swept.minX = dx > 0 ? aabb.minX - dx : aabb.minX;\n swept.maxX = dx < 0 ? aabb.maxX - dx : aabb.maxX;\n swept.minY = dy > 0 ? aabb.minY - dy : aabb.minY;\n swept.maxY = dy < 0 ? aabb.maxY - dy : aabb.maxY;\n\n // Tree hits are keyed on the leaves' fat AABBs, so the candidate set is a\n // conservative superset - the exact `aabbOverlap` below still decides.\n // A backend without a spatial index falls back to the full collider list.\n const candidates = spatialIndex === undefined ? this._detectionColliders : spatialIndex.queryAabb(swept, this._ccdCandidates);\n\n this._ccdBroadPhaseCandidates += candidates.length;\n\n for (const other of candidates) {\n // A chain edge proxy blocks under its chain's material and filter, and\n // reports the chain as the blocking collider - the sweep never hands a\n // caller a solver-side proxy.\n const target = authoredCollider(other);\n\n // Sweep against every other body (static, kinematic, dynamic) under the\n // discrete narrow phase's rules: sensors never block, filtered pairs never collide.\n if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter)) {\n continue;\n }\n\n if (!aabbOverlap(swept, other.aabb)) {\n continue;\n }\n\n this._ccdSweepTests++;\n\n if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {\n best.t = hit.t;\n best.normalX = hit.normalX;\n best.normalY = hit.normalY;\n blocked = target;\n }\n }\n }\n\n return blocked;\n }\n\n /** The highest restitution among a body's colliders (its CCD bounce factor). */\n private _bulletRestitution(body: PhysicsBody): number {\n let restitution = 0;\n\n for (const collider of body.colliders) {\n if (collider.restitution > restitution) {\n restitution = collider.restitution;\n }\n }\n\n return restitution;\n }\n\n /** Run `command` now, or queue it when inside an event dispatch (deferred to end of step). */\n private _defer(command: () => void): void {\n if (this._dispatching) {\n this._commands.push(command);\n } else {\n command();\n }\n }\n\n private _drainCommands(): void {\n if (this._commands.length === 0) {\n return;\n }\n\n const commands = this._commands.splice(0);\n\n for (const command of commands) {\n command();\n }\n }\n\n private _removeBody(body: PhysicsBody): void {\n const index = this._bodies.indexOf(body);\n\n if (index === -1) {\n // Never added (created and destroyed within the same dispatch) - still\n // tear down its colliders and mark it dead.\n this._teardownBody(body);\n\n return;\n }\n\n this._bodies.splice(index, 1);\n this._teardownBody(body);\n }\n\n private _teardownBody(body: PhysicsBody): void {\n for (const collider of body.colliders) {\n this._detachCollider(collider);\n }\n\n this._bindings.unbind(body);\n body._markDestroyed();\n }\n\n private _removeCollider(collider: Collider): void {\n this._detachCollider(collider);\n collider.body._removeCollider(collider);\n }\n\n private _detachCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n }\n\n this._wakeTouchingBodies(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._removeDetectionCollider(collider);\n } else {\n for (const edge of edges) {\n this._removeDetectionCollider(edge);\n }\n }\n\n collider._markDestroyed();\n }\n\n /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */\n private _removeDetectionCollider(collider: Collider): void {\n const index = this._detectionColliders.indexOf(collider);\n\n if (index !== -1) {\n this._detectionColliders.splice(index, 1);\n }\n\n this._backend.removeCollider(collider);\n }\n\n /**\n * The broad-phase leaves of one body - its colliders, with a chain replaced by\n * its edge proxies. Returns pooled scratch, valid until the next call.\n */\n private _detectionLeavesOf(body: PhysicsBody): Collider[] {\n const leaves = this._leafScratch;\n\n leaves.length = 0;\n\n for (const collider of body.colliders) {\n const edges = collider.chainEdges;\n\n if (edges === null) {\n leaves.push(collider);\n\n continue;\n }\n\n for (const edge of edges) {\n leaves.push(edge);\n }\n }\n\n return leaves;\n }\n\n /**\n * Wake every dynamic body still touching `collider` at the moment it leaves\n * the world. A sleeping body's sleep timer is frozen, so the island pass alone\n * can never re-open its sleep decision: losing the support it rested on just\n * removes a contact, and the island (now smaller, or a lone body) still reports\n * a long-expired timer and is put straight back to sleep - a stack whose floor,\n * platform or bottom box is destroyed would hang in mid-air forever. Kinematic\n * and static supports are the sharp edge, since they are island boundaries\n * rather than nodes and so are invisible to wake propagation, but the same hole\n * exists for a dynamic support. Waking the far side of each contact is enough:\n * the woken body's reset timer propagates through the rest of its sleeping\n * island on the next step, exactly like any other wake event.\n */\n private _wakeTouchingBodies(collider: Collider): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n let other: Collider;\n\n if (contact.ownerA === collider) {\n other = contact.ownerB;\n } else if (contact.ownerB === collider) {\n other = contact.ownerA;\n } else {\n continue;\n }\n\n // Only reached for a collider that is part of a live contact, so it is\n // attached and `body` cannot throw - a free-standing collider (a body\n // destroyed before it was ever stepped) has no contacts to match.\n if (other.body.type === 'dynamic') {\n other.body.wake();\n }\n }\n }\n\n private _assertAlive(): void {\n if (this._destroyed) {\n throw new Error('PhysicsWorld: the world has been destroyed.');\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAUjB,MAAM,cAAc,UAA0B;CAG5C,IAAI,EAAE,QAAQ,IACZ,OAAO;CAGT,OAAO,QAAQ,IAAI,QAAQ;AAC7B;;;;;;;;;;AAWA,MAAM,0BAA0B,aAA6B;CAC3D,MAAM,OAAO,SAAS;CAEtB,IAAI,KAAK,SAAS,aAAa,SAAS,MAAM,mBAAmB,QAAQ,SAAS,WAAW,GAC3F;CAGF,IAAI,YAAY;CAEhB,KAAK,MAAM,SAAS,KAAK,WAAW;EAClC,IAAI,UAAU,UACZ;EAGF,IAAI,MAAM,MAAM,mBAAmB,QAAQ,MAAM,UAAU,GACzD;EAGF;CACF;CAEA,IAAI,cAAc,GAChB;CAGF,MAAM,IAAI,MACR,wNACF;AACF;;;;;;;;;AAkCA,MAAM,oBAAoB,SACxB,KAAK,eAAe,KAAK,oBAAoB,KAA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,WAAW,UACrB,QAAQ,QAAQ;QACX,IAAI,QAAQ,WAAW,UAC5B,QAAQ,QAAQ;QAEhB;GAMF,IAAI,MAAM,KAAK,SAAS,WACtB,MAAM,KAAK,KAAK;EAEpB;CACF;CAEA,AAAQ,eAAqB;EAC3B,IAAI,KAAK,YACP,MAAM,IAAI,MAAM,6CAA6C;CAEjE;AACF"}
1
+ {"version":3,"file":"PhysicsWorld.js","names":[],"sources":["../../src/PhysicsWorld.ts"],"sourcesContent":["import type { AabbLike, PointLike, SceneNode, Seconds } from '@codexo/exojs';\nimport { logger, Signal, Vector } from '@codexo/exojs';\n\nimport { aabbOverlap, createAabb } from './Aabb';\nimport { NativePhysicsBackend } from './backend/NativePhysicsBackend';\nimport type { PhysicsBackend } from './backend/PhysicsBackend';\nimport { BindingRegistry } from './binding/BindingRegistry';\nimport type { PhysicsBinding } from './binding/PhysicsBinding';\nimport { authoredCollider, Collider } from './Collider';\nimport type { Manifold } from './collision/Manifold';\nimport type { SweepHit } from './collision/sweep';\nimport { canSweep, sweepProxies } from './collision/sweep';\nimport type { ContactModifier } from './ContactModifier';\nimport type { CollisionEvent, SensorEvent } from './events';\nimport type { Joint } from './joints/Joint';\nimport type { BodyOwner } from './PhysicsBody';\nimport { PhysicsBody } from './PhysicsBody';\nimport type { QueryFilter, RayHit } from './query/QueryEngine';\nimport { QueryEngine } from './query/QueryEngine';\nimport type { AnyShape } from './shapes/AnyShape';\nimport { sleepPenetrationTolerance } from './solver/tolerances';\nimport { TimeStepper } from './TimeStepper';\nimport type { BodyType, CollisionFilter } from './types';\nimport { shouldCollide } from './types';\n\n/**\n * Overlap left after clamping a bullet at its time of impact (the clamp\n * overshoots the contact by this much along the motion), so the next step's\n * discrete detection forms a real contact and the solver owns resting,\n * friction and events from then on.\n */\nconst ccdEmbed = 0.05;\n/** Impact speed (px/s) below which a bullet's CCD response does not bounce (mirrors the contact solver). */\nconst ccdRestitutionThreshold = 1;\n\n/**\n * Keep a host-supplied blend factor inside `[0, 1]`. A caller's own accumulator\n * can hand over a value outside it (a stale read, a custom scheduler), and an\n * unclamped one extrapolates the node past the simulated state instead of\n * blending between two known ones.\n */\nconst clampAlpha = (alpha: number): number => {\n // Written as two comparisons rather than Math.min/Math.max so a NaN factor\n // lands on 0 instead of propagating into every bound node's transform.\n if (!(alpha > 0)) {\n return 0;\n }\n\n return alpha < 1 ? alpha : 1;\n};\n\n/**\n * Reject removing the last collider a dynamic body's mass rests on while it still\n * holds others. Such a body keeps colliding but has `invMass === 0`, which the\n * solver cannot tell apart from a static body - the same state `PhysicsBody`\n * refuses to be constructed in.\n *\n * Removing the body's *only* collider is fine: a body with no geometry at all is\n * a body still being assembled, not a silently broken one.\n */\nconst assertBodyKeepsItsMass = (collider: Collider, pendingRemovals: ReadonlySet<Collider>): void => {\n const body = collider.body;\n\n if (body.type !== 'dynamic' || collider.shape.massProperties === null || collider.density <= 0) {\n return;\n }\n\n let remaining = 0;\n\n for (const other of body.colliders) {\n // A collider already queued for removal in this same dispatch is as good as\n // gone: without this, two `destroyCollider` calls in one callback each pass\n // the check against the pre-deferral set, and both deferred removals then\n // apply, leaving the body massless.\n if (other === collider || pendingRemovals.has(other)) {\n continue;\n }\n\n if (other.shape.massProperties !== null && other.density > 0) {\n return;\n }\n\n remaining++;\n }\n\n if (remaining === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsWorld.destroyCollider: this is the only collider carrying mass for a dynamic body — removing it would leave the body colliding but massless. Destroy the body instead, or give it another solid collider first.',\n );\n};\n\n/**\n * Dev-only: boundary geometry is never swept as the moving operand, so a bullet\n * body carrying it is not protected against tunnelling on that collider.\n * Reporting it beats a silent pass-through.\n */\nconst warnUnsweptBulletShape = (collider: Collider, warnedKinds: Set<string>): void => {\n const kind = collider.shape.type;\n\n if (canSweep(kind, 'polygon') || warnedKinds.has(kind)) {\n return;\n }\n\n warnedKinds.add(kind);\n logger.warn(\n `PhysicsWorld: a bullet body carries a '${kind}' collider. Boundary geometry is level structure and is only ever a ` +\n 'sweep target, never the moving operand, so this collider can still cross thin geometry within one step. ' +\n 'Give a fast body a solid collider (circle, capsule or polygon).',\n { source: 'physics' },\n );\n};\n\n/**\n * `true` when a static/kinematic body - an island boundary, never an island\n * member - is being driven this step, either through its velocity or by a\n * {@link PhysicsBody.setTransform} teleport. Speed is deliberately not compared\n * against the sleep thresholds: a platform creeping along at 1 px/s still has to\n * push its passengers, and it is exactly that sub-threshold case where nothing\n * else would keep them awake.\n */\nconst isMovingBoundary = (body: PhysicsBody): boolean =>\n body._teleported || body.linearVelocityX !== 0 || body.linearVelocityY !== 0 || body.angularVelocity !== 0;\n\n/**\n * `true` while a contact still carries more overlap than the solver leaves\n * behind at rest. Read from the manifold detection just produced, which is the\n * same separation the solver's push-out bias is about to act on - the sleep gate\n * and the constraint it gates therefore agree by construction.\n */\nconst isUnresolved = (manifold: Manifold): boolean => {\n for (let i = 0; i < manifold.pointCount; i++) {\n // i in 0..pointCount-1 and pointCount ≤ 2, so the manifold point exists.\n if ((i === 0 ? manifold.points[0] : manifold.points[1]).penetration > sleepPenetrationTolerance) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `position`: `node`'s current WORLD\n * translation, duck-typed the same way `AudioListener` reads a follow target -\n * real {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit\n * it fall back to `(0, 0)` (the previous, surprising default).\n */\nconst worldPositionOf = (node: SceneNode): Readonly<PointLike> => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return { x: world.x, y: world.y };\n }\n\n return { x: 0, y: 0 };\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `angle` (radians): `node`'s current\n * WORLD rotation, decomposed from `getWorldTransform()`'s linear part\n * (`atan2(-c, a)` - `SceneNode.updateTransform` builds its rotation block as\n * `[[cosθ, sinθ], [-sinθ, cosθ]]`, i.e. `b = sinθ`/`c = -sinθ`, matching the\n * radians ⇄ degrees round-trip `PhysicsBinding.sync` already relies on).\n * Falls back to `0` for a duck-typed node without `getWorldTransform`.\n */\nconst worldAngleOf = (node: SceneNode): number => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return Math.atan2(-world.c, world.a);\n }\n\n return 0;\n};\n\n/** Construction options for a {@link PhysicsWorld}. */\nexport interface PhysicsWorldOptions {\n /** Gravity in px/s² (+Y down). Integrated each sub-step. Default `(0, 0)`. */\n gravity?: Readonly<PointLike>;\n /** Fixed timestep in seconds. Default `1 / 60`. */\n fixedDelta?: number;\n /** Maximum fixed steps per `step` call (spiral-of-death guard). Default `8`. */\n maxSubSteps?: number;\n /**\n * TGS-Soft sub-steps per fixed step (the solver's stiffness scales with this,\n * not iteration count). Default `4`. Must be ≥ 1. Values below `2` visibly\n * degrade tall-stack stability (a 10-box tower jitters at `1`), so the default\n * is load-bearing - do not lower it for performance.\n */\n subStepCount?: number;\n /** Soft-contact stiffness in Hz (the contact behaves as a damped spring at this frequency). Default `30`. */\n contactHertz?: number;\n /** Soft-contact damping ratio (≥ 1 keeps contacts from oscillating). Default `10`. */\n dampingRatio?: number;\n /** Put resting bodies to sleep so they skip integration and solving. Default `true`. */\n enableSleeping?: boolean;\n /**\n * Adjust each solid contact for the coming step (one-way platforms,\n * conditional friction, per-pair material overrides). At most one per world;\n * see {@link PhysicsWorld.contactModifier}. Default none.\n */\n contactModifier?: ContactModifier | null;\n /**\n * Place bound nodes between the last two fixed states instead of snapping them\n * to the latest one, which smooths motion when the fixed rate is below the\n * frame rate. Default `false`.\n *\n * The blend factor comes from {@link frameAlphaSource}; a world driven as a\n * `System` has to supply one.\n */\n interpolation?: boolean;\n /**\n * Where interpolated bindings read their blend factor, in `[0, 1)`.\n *\n * Defaults to this world's own accumulator - correct when the world is driven\n * with {@link PhysicsWorld.step}, which is what advances it. A world driven as\n * a `System` goes through {@link PhysicsWorld.fixedUpdate} and bypasses that\n * accumulator entirely, so the host owns the fraction: pass\n * `() => app.frameAlpha`.\n */\n frameAlphaSource?: () => number;\n /** Linear speed at or below which a body is a sleep candidate, px/s. Default `5`. */\n sleepLinearVelocity?: number;\n /** Angular speed at or below which a body is a sleep candidate, rad/s. Default `0.06`. */\n sleepAngularVelocity?: number;\n /** Seconds a body must stay below the sleep thresholds before it sleeps. Default `0.5`. */\n timeToSleep?: number;\n}\n\n/**\n * {@link PhysicsWorld.attach} convenience options: a body type plus a single\n * collider, attached to a scene node in one call.\n */\nexport interface AttachOptions {\n /** Simulation role of the created body. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position of the body. Default the node's current WORLD position ({@link SceneNode.getWorldTransform}) at attach time. */\n position?: Readonly<PointLike>;\n /** Initial rotation (radians) of the body. Default the node's current WORLD rotation at attach time. */\n angle?: number;\n /** Per-body multiplier on world gravity. Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts. Default `false`. */\n fixedRotation?: boolean;\n /** The collider geometry. */\n shape: AnyShape;\n /** Body-local offset of the collider. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the collider (radians). Default `0`. */\n rotation?: number;\n /** Collider density (mass per px²). Default `1`. */\n density?: number;\n /** Coulomb friction coefficient. Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]`. Default `0`. */\n restitution?: number;\n /** When `true`, the collider generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group collision filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n}\n\n/**\n * The collision/query world: owns bodies, colliders, the detection backend,\n * bindings, the query engine and the fixed-step accumulator. Stepped by the\n * caller (commonly from a `Scene.update`), each fixed sub-step it integrates\n * body velocities, runs broad- and narrow-phase detection, solves contacts and\n * integrates positions, then fires immutable contact/sensor events and writes\n * bound node transforms. It holds **no module-level state**, so any number of\n * worlds run in isolation.\n *\n * The dynamics are a native, warm-started **TGS-Soft** solver (Box2D-v3 \"soft\n * step\"): each fixed step runs detection once, then several sub-steps, each\n * integrating gravity over the sub-step and solving contacts with a soft\n * position bias plus a bias-free relax pass; a 2-point block normal solve\n * propagates stack loads, and restitution is a separate final pass. Decoupling\n * stiffness from the iteration count keeps tall towers stable. The detection\n * backend sits behind an internal seam, so the solver is swappable without\n * touching this public surface.\n *\n * **Operating envelope.** The soft solver trades a little accuracy for\n * robustness, so it has a few documented limits - each stays finite and stable,\n * and each is pinned by a gate in `dynamics.test.ts` or\n * `contact-push-out.test.ts`:\n * - **Resting contacts** settle within a small, fixed tolerance. A face contact\n * settles at exactly that tolerance; a single-point contact settles slightly\n * deeper, and that gap grows with acceleration. Very high accelerations\n * eventually exceed what the push-out can resolve within a step, at which\n * point the contact holds a slightly deeper resting depth instead of the\n * tolerance - keep gravity in the range ordinary 2D games use.\n * - **Mass ratio** - contacts between bodies of very different mass degrade\n * gradually rather than at a fixed ratio. What sets the practical limit is how\n * thick the supporting geometry is relative to the lighter body, not the ratio\n * alone: a light body squeezed against a boundary thinner than itself is the\n * case that fails first, and it fails by sinking through.\n * - **Scale-relative behaviour** - the solver's tolerances are absolute lengths,\n * so a very small shape sees them as a large fraction of itself, and a very\n * large one as a negligible one. Keep the shapes of one world within a couple\n * of orders of magnitude of each other.\n * - **CCD is opt-in and translation-only** - detection runs once per fixed\n * step, so an ordinary body that crosses more than roughly half a barrier's\n * total thickness within one step may end up on the wrong side of it, either\n * passing through or being resolved out of the far face. Flag fast\n * projectiles with {@link PhysicsBody.isBullet}: each of the body's colliders\n * is then shape-cast along the step's motion (an exact translation-only sweep\n * of the full shape, not just the centre) and clamped at the first impact.\n * Rotation over the step is not swept - a long body spinning fast enough to\n * sweep past an obstacle within one step can still miss it.\n * - **{@link PhysicsWorldOptions.subStepCount}** - the default `4` is\n * load-bearing for tall-stack stability; lowering it below `2` visibly\n * degrades stacking, so do not reduce it for performance.\n * - **Broad phase is a dynamic AABB tree** (`AabbTreeBroadPhase`), stateful\n * across fixed steps: a collider whose tight AABB stays inside its stored\n * fat AABB costs nothing to re-sync, and only colliders that actually move\n * outside their margin trigger a tree update and a local re-query for new\n * neighbours. Detection still walks every live collider once per step (a\n * cheap containment check for each), so there is a small linear floor, but\n * the dominant cost - reinsertion and neighbour discovery - is driven by\n * how much actually moved, not by the total live collider count; sleeping\n * bodies skip that dominant cost entirely. Scales to tens of thousands of\n * simultaneously-live colliders, including dense clusters that would\n * degrade a sort-and-sweep broad phase; very large or highly dynamic\n * worlds may still benefit from splitting into several smaller\n * `PhysicsWorld` instances (e.g. per room/chunk).\n */\nexport class PhysicsWorld implements BodyOwner {\n /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */\n public readonly onCollisionStart = new Signal<[CollisionEvent]>();\n /** Fires when two solid colliders stop touching (or one is destroyed). */\n public readonly onCollisionEnd = new Signal<[CollisionEvent]>();\n /** Fires when a collider enters a sensor. */\n public readonly onSensorEnter = new Signal<[SensorEvent]>();\n /** Fires when a collider leaves a sensor. */\n public readonly onSensorExit = new Signal<[SensorEvent]>();\n\n /** World gravity (px/s², +Y down). Integrated each sub-step. */\n public readonly gravity: Vector;\n /** The fixed-step accumulator. */\n public readonly timeStepper: TimeStepper;\n /** TGS-Soft sub-steps per fixed step. */\n public readonly subStepCount: number;\n /** Soft-contact stiffness in Hz. */\n public readonly contactHertz: number;\n /** Soft-contact damping ratio. */\n public readonly dampingRatio: number;\n /** Whether resting bodies are put to sleep. */\n public readonly enableSleeping: boolean;\n /** Linear sleep threshold (px/s). */\n public readonly sleepLinearVelocity: number;\n /** Angular sleep threshold (rad/s). */\n public readonly sleepAngularVelocity: number;\n /** Seconds below the thresholds before a body sleeps. */\n public readonly timeToSleep: number;\n\n /**\n * Runs once per solid contact per fixed step, after contact generation and\n * before island building and the solver, so a contact it disables applies no\n * impulse and does not couple its two bodies into one sleeping island.\n *\n * At most one modifier per world - it mutates simulation state, so a\n * multi-listener signal would make the outcome depend on registration order.\n * Set to `null` to remove it; the per-contact values then stay at the\n * defaults derived from the two colliders.\n */\n public contactModifier: ContactModifier | null;\n\n /**\n * Whether bound nodes are placed between the last two fixed states rather than\n * snapped to the latest one. Toggleable at runtime; switching it off snaps\n * every bound node back to the current fixed state on the next sync.\n */\n public interpolation: boolean;\n\n /**\n * Supplies the `[0, 1)` blend factor for interpolated bindings. Defaults to\n * this world's own accumulator; point it at the host's own fraction\n * (`() => app.frameAlpha`) when the world runs as a `System`, because\n * {@link fixedUpdate} never advances the local accumulator.\n */\n public frameAlphaSource: () => number;\n\n private readonly _backend: PhysicsBackend = new NativePhysicsBackend();\n private readonly _bodies: PhysicsBody[] = [];\n private readonly _colliders: Collider[] = [];\n /**\n * What detection actually runs over: the authored colliders, with a chain\n * replaced by the edge proxies it fans out into. The broad phase, the narrow\n * phase and the queries all read this list; `_colliders` stays the authored\n * set every public surface reports.\n */\n private readonly _detectionColliders: Collider[] = [];\n /** Pooled scratch for re-syncing a single body's broad-phase leaves. */\n private readonly _leafScratch: Collider[] = [];\n private readonly _joints: Joint[] = [];\n private readonly _bindings = new BindingRegistry();\n private readonly _query: QueryEngine;\n private readonly _commands: Array<() => void> = [];\n /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */\n private readonly _pendingColliderRemovals = new Set<Collider>();\n /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */\n private readonly _warnedUnsweptKinds = new Set<string>();\n /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */\n private readonly _islandParent: number[] = [];\n /** Pooled per-island minimum sleep time, indexed by union-find root. */\n private readonly _islandMinSleep: number[] = [];\n /** Pooled scratch for the CCD pass (clamp target, per-pair sweep hit, best hit, swept AABB) - keeps the sweep allocation-free. */\n private readonly _ccdClampPosition = { x: 0, y: 0 };\n private readonly _ccdSweepHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdBestHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdSweptAabb: AabbLike = createAabb();\n /** Pooled result buffer for the CCD pass's broad-phase query (refilled per bullet collider). */\n private readonly _ccdCandidates: Collider[] = [];\n\n /**\n * Narrow-phase sweep tests run by the CCD pass since world creation. Pairs\n * rejected by the swept-AABB prune never count, so slow bullets far from any\n * geometry keep this at zero (the cheap path).\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdSweepTests = 0;\n\n /**\n * Colliders the CCD pass pulled out of the broad phase since world creation -\n * the size of the candidate set the swept-AABB prune and the narrow-phase\n * sweep then work on. Counted separately from {@link _ccdSweepTests} because\n * the two measure different halves: this is what the pass looks at, that is\n * what it actually sweeps. Stays proportional to the geometry near the\n * bullets, not to the world's collider count.\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdBroadPhaseCandidates = 0;\n\n private _nextBodyId = 1;\n private _nextColliderId = 1;\n private _dispatching = false;\n private _destroyed = false;\n\n public constructor(options: PhysicsWorldOptions = {}) {\n this.gravity = new Vector(options.gravity?.x ?? 0, options.gravity?.y ?? 0);\n this.timeStepper = new TimeStepper({\n ...(options.fixedDelta !== undefined && { fixedDelta: options.fixedDelta }),\n ...(options.maxSubSteps !== undefined && { maxSubSteps: options.maxSubSteps }),\n });\n\n const subStepCount = options.subStepCount ?? 4;\n\n if (!Number.isInteger(subStepCount) || subStepCount < 1) {\n throw new RangeError(`PhysicsWorld: subStepCount must be an integer ≥ 1, received ${subStepCount}.`);\n }\n\n this.subStepCount = subStepCount;\n this.contactHertz = options.contactHertz ?? 30;\n this.dampingRatio = options.dampingRatio ?? 10;\n this.enableSleeping = options.enableSleeping ?? true;\n this.sleepLinearVelocity = options.sleepLinearVelocity ?? 5;\n this.sleepAngularVelocity = options.sleepAngularVelocity ?? 0.06;\n this.timeToSleep = options.timeToSleep ?? 0.5;\n this.contactModifier = options.contactModifier ?? null;\n this.interpolation = options.interpolation ?? false;\n this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);\n this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);\n }\n\n /** Live bodies (read-only view). */\n public get bodies(): readonly PhysicsBody[] {\n return this._bodies;\n }\n\n /** Live colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /**\n * @internal - the geometry the broad phase and the narrow phase actually hold:\n * every authored collider, with a chain replaced by its per-edge proxies.\n * Consumed by the debug draw layer, which visualises what the solver sees;\n * public identity stays {@link colliders}.\n */\n public get detectionGeometry(): readonly Collider[] {\n return this._detectionColliders;\n }\n\n // ── lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Add a body to the world: allocates the body and its collider ids, registers\n * the colliders, computes the mass model and tracks the body for stepping.\n * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.\n * Safe to call inside an event callback - the body push is deferred to the end\n * of the step, exactly like collider registration. Returns the body.\n *\n * @throws if the body has already been added to a world.\n */\n public add(body: PhysicsBody): PhysicsBody {\n this._assertAlive();\n\n if (body.attached) {\n throw new Error('PhysicsWorld.add: this body has already been added to a world.');\n }\n\n // Allocate the id + link/register colliders + aggregate mass now (matches the\n // old createBody, which allocated the id synchronously); only the body-list\n // push is deferred so it is safe inside an event dispatch.\n body._attachToWorld(this, this._nextBodyId++);\n\n this._defer(() => {\n if (!body.destroyed) {\n this._bodies.push(body);\n }\n });\n\n return body;\n }\n\n /**\n * Convenience: create a body carrying a single collider, add it to the world\n * and bind it to `node` in one call. The node tracks `body.position` after each\n * step. Returns the body. Equivalent to `new PhysicsBody(...)` + `add` + `bind`.\n *\n * When `options.position`/`options.angle` are omitted, the body starts at\n * `node`'s current WORLD position/rotation (via `getWorldTransform()`,\n * composed through any transform-group boundary) rather than `(0, 0)` -\n * otherwise a body attached to an already-placed node would visibly \"teleport\"\n * to the origin on the next step. Pass `position`/`angle` explicitly to override.\n */\n public attach(node: SceneNode, options: AttachOptions): PhysicsBody {\n const body = new PhysicsBody({\n ...(options.type !== undefined && { type: options.type }),\n position: options.position ?? worldPositionOf(node),\n angle: options.angle ?? worldAngleOf(node),\n ...(options.gravityScale !== undefined && { gravityScale: options.gravityScale }),\n ...(options.fixedRotation !== undefined && { fixedRotation: options.fixedRotation }),\n colliders: [\n new Collider({\n shape: options.shape,\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.rotation !== undefined && { rotation: options.rotation }),\n ...(options.density !== undefined && { density: options.density }),\n ...(options.friction !== undefined && { friction: options.friction }),\n ...(options.restitution !== undefined && { restitution: options.restitution }),\n ...(options.isSensor !== undefined && { isSensor: options.isSensor }),\n ...(options.filter !== undefined && { filter: options.filter }),\n }),\n ],\n });\n\n this.add(body);\n this.bind(body, node);\n\n return body;\n }\n\n /**\n * Destroy a body and its colliders. Every dynamic body touching it is woken,\n * so anything that was resting on the destroyed body falls once its support is\n * gone. Deferred when called inside a callback.\n */\n public destroyBody(body: PhysicsBody): void {\n this._defer(() => this._removeBody(body));\n }\n\n /**\n * Destroy a single collider, recomputing its body's mass. Wakes every dynamic\n * body touching it, the same way {@link destroyBody} does. Deferred when\n * called inside a callback.\n */\n public destroyCollider(collider: Collider): void {\n // Checked here rather than in the deferred removal so the error surfaces at\n // the call site that caused it, not out of the middle of a `step()`.\n assertBodyKeepsItsMass(collider, this._pendingColliderRemovals);\n\n this._pendingColliderRemovals.add(collider);\n this._defer(() => {\n this._pendingColliderRemovals.delete(collider);\n this._removeCollider(collider);\n });\n }\n\n /** Live joints (read-only view). */\n public get joints(): readonly Joint[] {\n return this._joints;\n }\n\n /**\n * Add a constraint joint. Construct it first (`new DistanceJoint({ ... })`),\n * then add it. Wakes both bodies; safe inside a callback (registration is\n * deferred). Returns the joint.\n */\n public addJoint<T extends Joint>(joint: T): T {\n this._assertAlive();\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n if (!this._joints.includes(joint)) {\n this._joints.push(joint);\n }\n });\n\n return joint;\n }\n\n /** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */\n public removeJoint(joint: Joint): void {\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n const index = this._joints.indexOf(joint);\n\n if (index !== -1) {\n this._joints.splice(index, 1);\n }\n });\n }\n\n // ── stepping ───────────────────────────────────────────────────────────\n\n /**\n * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each\n * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate\n * gravity, solve contacts with a soft bias, integrate positions, relax) and a\n * restitution pass, then writes the accumulated motion into each body. Finally\n * dispatches events and writes bound node transforms.\n *\n * **Prefer registering the world as a system instead**\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) so {@link fixedUpdate} drives stepping directly from the\n * engine's own fixed-timestep scheduler - one call per fixed step, no\n * accumulator duplication. `step` remains available here for manual/advanced\n * driving (e.g. a fixed-but-non-standard rate, or stepping outside the\n * normal frame loop entirely): pass any delta and this accumulator converts\n * it into the right number of fixed sub-steps (0, 1, or several, clamped by\n * {@link PhysicsWorldOptions.maxSubSteps}).\n *\n * Either way the simulation is frame-rate independent and deterministic -\n * the same sequence of deltas replays identically. `timeStepper.alpha`\n * (`[0, 1)`) is the leftover sub-step fraction after this call, for callers\n * that want to interpolate a bound node's rendered position between the last\n * two fixed states instead of snapping to the latest one (bindings do not do\n * this automatically - {@link bind} always writes the latest fixed-step\n * transform verbatim).\n */\n public step(frameDeltaSeconds: number): void {\n this._assertAlive();\n\n const steps = this.timeStepper.advance(frameDeltaSeconds);\n\n if (steps > 0) {\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n const gravityX = this.gravity.x;\n const gravityY = this.gravity.y;\n const contactHertz = this.contactHertz;\n const dampingRatio = this.dampingRatio;\n const hasJoints = this._joints.length > 0;\n const hasBullets = this._hasBullets();\n\n for (let step = 0; step < steps; step++) {\n this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);\n this._dispatchEvents();\n }\n }\n\n // `step` is called once per rendered frame, so presenting here is already\n // the variable-rate slot an interpolated binding needs.\n this._syncBindings();\n this._drainCommands();\n }\n\n /**\n * Advance by exactly one fixed step, driven directly by the engine's own\n * fixed-timestep scheduler when this world is registered as a `System`\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) - bypasses {@link timeStepper}'s variable-delta accumulator\n * entirely, since the caller has already decided exactly when a fixed step\n * occurs. Prefer this over manual {@link step} once the world is\n * system-registered; `step` remains available for advanced manual driving.\n * Always advances by exactly {@link timeStepper}'s configured `fixedDelta`,\n * regardless of the caller's actual fixed-step interval - if the engine's\n * `Application.fixedTimeStep` doesn't match this world's `fixedDelta`, the\n * simulation stays deterministic but runs at the wrong wall-clock speed\n * relative to real time.\n */\n public fixedUpdate(_step: Seconds): void {\n this._assertAlive();\n\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n\n this._stepOnce(h, subStepCount, this.gravity.x, this.gravity.y, this.contactHertz, this.dampingRatio, this._joints.length > 0, this._hasBullets());\n\n this._dispatchEvents();\n\n // Interpolated presentation is a per-FRAME job and moves to `update`; this\n // phase can run several times per frame, and the blend factor is only final\n // once the last of them has run.\n if (!this.interpolation) {\n this._bindings.sync();\n }\n\n this._drainCommands();\n }\n\n /**\n * Variable-rate `System` phase: places bound nodes for the frame that is about\n * to be drawn. Only does work while {@link interpolation} is on - otherwise\n * {@link fixedUpdate} has already snapped them to the latest fixed state.\n */\n public update(_delta: Seconds): void {\n this._assertAlive();\n\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n }\n }\n\n /** Present bound nodes, snapping or interpolating according to {@link interpolation}. */\n private _syncBindings(): void {\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n } else {\n this._bindings.sync();\n }\n }\n\n private _stepOnce(\n h: number,\n subStepCount: number,\n gravityX: number,\n gravityY: number,\n contactHertz: number,\n dampingRatio: number,\n hasJoints: boolean,\n hasBullets: boolean,\n ): void {\n // Detection runs once per fixed step (collider geometry is already current\n // from the previous frame's finalize / attach / setTransform). TGS-Soft\n // reuses the manifolds across the sub-steps below.\n this._backend.detect(this._detectionColliders);\n\n // The contact modifier runs between detection and the sleep decision: a\n // contact it disables must neither reach the solver nor union its two bodies\n // into one island, and both of those are decided below.\n if (this.contactModifier !== null) {\n this._backend.applyContactModifier(this.contactModifier);\n }\n\n // Sleep decision runs after detection (islands need the current contact\n // set) and before the solver (so sleeping contacts are skipped, and a\n // sleeping island touched by an awake body is woken first).\n if (this.enableSleeping) {\n this._updateSleeping(this.timeStepper.fixedDelta);\n }\n\n this._backend.prepareSolve(h, contactHertz, dampingRatio);\n\n if (hasJoints) {\n this._prepareJoints(h);\n }\n\n if (hasBullets) {\n this._recordBulletPositions();\n }\n\n for (let subStep = 0; subStep < subStepCount; subStep++) {\n // Integrate gravity/forces over the sub-step (forces persist across\n // sub-steps; cleared once per frame by `_finalizePosition`).\n for (const body of this._bodies) {\n body._integrateVelocity(h, gravityX, gravityY);\n }\n\n // Warm-start every sub-step (Box2D-v3 soft step): the relax pass leaves\n // each contact's normal velocity at zero, so re-applying the\n // accumulated impulse re-balances exactly this sub-step's gravity - the\n // impulse converges to the per-sub-step load (m·h·g), not the per-frame\n // load, which is what keeps tall stacks from pumping energy.\n this._backend.warmStart();\n\n if (hasJoints) {\n this._warmStartJoints();\n }\n\n // Main soft-bias velocity solve, integrate positions (accumulating\n // per-body delta), then the bias-free relax pass. Joints solve right\n // after the contacts in each pass (contacts are the stiffer constraint).\n this._backend.solveVelocities(true);\n\n if (hasJoints) {\n this._solveJoints(true);\n }\n\n for (const body of this._bodies) {\n body._integratePosition(h);\n }\n\n this._backend.solveVelocities(false);\n\n if (hasJoints) {\n this._solveJoints(false);\n }\n }\n\n // Separate restitution pass, then write the accumulated delta into each\n // body's transform and re-sync collider geometry.\n this._backend.applyRestitution();\n\n for (const body of this._bodies) {\n body._finalizePosition();\n }\n\n if (hasBullets) {\n this._advanceBullets();\n }\n }\n\n // ── binding ────────────────────────────────────────────────────────────\n\n /**\n * Link a body to a scene node; the node tracks the body after each step.\n * Destroying the node is enough to end the link - the next step drops it\n * rather than writing into the node's released transform, so an explicit\n * {@link unbind} is only needed to stop tracking a node that stays alive.\n *\n * @throws if `node` is already destroyed.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n return this._bindings.bind(body, node);\n }\n\n /** Remove a body↔node link. */\n public unbind(body: PhysicsBody): void {\n this._bindings.unbind(body);\n }\n\n // ── queries ────────────────────────────────────────────────────────────\n\n /** Colliders containing `point`. Fresh array. */\n public queryPoint(point: Readonly<PointLike>, filter?: QueryFilter): Collider[] {\n return this._query.queryPoint(point, filter);\n }\n\n /** Colliders whose AABB overlaps `bounds`. Writes into `out` (cleared) if given. */\n public queryAabb(bounds: AabbLike, filter?: QueryFilter, out?: Collider[]): Collider[] {\n return this._query.queryAabb(bounds, filter, out);\n }\n\n /** Invoke `callback` for each collider whose AABB overlaps `bounds`. Allocation-free. */\n public forEachAabbHit(bounds: AabbLike, filter: QueryFilter | undefined, callback: (collider: Collider) => void): void {\n this._query.forEachAabbHit(bounds, filter, callback);\n }\n\n /** Nearest collider hit by the ray, or `null`. */\n public rayCast(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, maxDistance?: number): RayHit | null {\n return this._query.rayCast(origin, direction, filter, maxDistance);\n }\n\n /** All collider hits along the ray, sorted by distance. Writes into `out` (cleared) if given. */\n public rayCastAll(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, out?: RayHit[], maxDistance?: number): RayHit[] {\n return this._query.rayCastAll(origin, direction, filter, out, maxDistance);\n }\n\n /** Colliders overlapping `shape` placed at `position`/`angle`. Fresh array. */\n public overlapShape(shape: AnyShape, position: Readonly<PointLike>, filter?: QueryFilter, angle?: number): Collider[] {\n return this._query.overlapShape(shape, position, filter, angle);\n }\n\n /** Release every body, collider, binding and backend resource. */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n // Apply queued commands first: a body added (or a collider registered)\n // from inside the event dispatch that triggered this destroy() is not in\n // `_bodies` yet, and clearing `_commands` without running them first would\n // leave it reporting `attached === true` / `destroyed === false` forever.\n this._drainCommands();\n\n // Mark colliders before their bodies: a collider that still reported\n // `destroyed === false` while `collider.body.destroyed === true` would look\n // usable after the world that owned it is gone. Walk each body's own list\n // rather than `this._colliders`, so colliders whose deferred registration\n // never ran are covered too. `_backend.destroy()` below releases their\n // broad-phase proxies.\n for (const body of this._bodies) {\n for (const collider of body.colliders) {\n collider._markDestroyed();\n }\n\n body._markDestroyed();\n }\n\n this._bodies.length = 0;\n this._colliders.length = 0;\n this._detectionColliders.length = 0;\n this._joints.length = 0;\n this._commands.length = 0;\n this._bindings.clear();\n this._backend.destroy();\n this.onCollisionStart.destroy();\n this.onCollisionEnd.destroy();\n this.onSensorEnter.destroy();\n this.onSensorExit.destroy();\n }\n\n // ── BodyOwner ──────────────────────────────────────────────────────────\n\n public _allocateColliderId(): number {\n return this._nextColliderId++;\n }\n\n public _registerCollider(collider: Collider): void {\n this._defer(() => {\n if (collider.destroyed) {\n return;\n }\n\n this._colliders.push(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._detectionColliders.push(collider);\n\n return;\n }\n\n for (const edge of edges) {\n this._detectionColliders.push(edge);\n }\n });\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n /** The detection backend (internal; consumed by the debug draw layer). */\n public get backend(): PhysicsBackend {\n return this._backend;\n }\n\n private _dispatchEvents(): void {\n const graph = this._backend.contactGraph;\n\n this._dispatching = true;\n\n for (const event of graph.collisionEnd) {\n this.onCollisionEnd.dispatch(event);\n }\n\n for (const event of graph.sensorExit) {\n this.onSensorExit.dispatch(event);\n }\n\n for (const event of graph.collisionStart) {\n this.onCollisionStart.dispatch(event);\n }\n\n for (const event of graph.sensorEnter) {\n this.onSensorEnter.dispatch(event);\n }\n\n this._dispatching = false;\n }\n\n /**\n * Accumulate per-body sleep timers and put/keep islands of resting bodies\n * asleep so a stack sleeps and wakes as one unit. An island is a connected\n * component of dynamic bodies joined by touching solid contacts (static and\n * kinematic bodies are boundaries, not nodes); it sleeps once every member has\n * stayed below the sleep thresholds for `timeToSleep`, and wakes the instant\n * any member does (e.g. an awake body merges into it via a new contact).\n * A boundary that is itself moving resets the sleep timer of every dynamic\n * body it touches, so a platform keeps its passengers awake however slowly it\n * travels; so does a contact still carrying more penetration than the solver\n * leaves at rest, because the push-out that resolves it is slower than the\n * sleep velocity threshold and a body would otherwise be frozen embedded.\n * Deterministic: union-find roots break ties by lower index and the contact\n * set is id-sorted.\n */\n private _updateSleeping(dt: number): void {\n const bodies = this._bodies;\n const count = bodies.length;\n const parent = this._islandParent;\n const minSleep = this._islandMinSleep;\n\n // Assign dense indices, reset the union-find, and accumulate sleep timers for\n // awake dynamic bodies (a sleeping body's timer stays frozen ≥ timeToSleep).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n body._islandIndex = i;\n parent[i] = i;\n minSleep[i] = Infinity;\n\n if (body.type === 'dynamic' && !body.isSleeping) {\n body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);\n }\n }\n\n parent.length = count;\n minSleep.length = count;\n\n this._unionContactIslands();\n\n // Joints couple their two bodies into the same island (sleep/wake together).\n for (const joint of this._joints) {\n const bodyA = joint.bodyA;\n const bodyB = joint.bodyB;\n\n if (joint.enabled && bodyA.type === 'dynamic' && bodyB.type === 'dynamic') {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n }\n }\n\n // Per-island minimum sleep time over its dynamic members.\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n const root = this._find(i);\n\n if (body._sleepTime < minSleep[root]!) {\n minSleep[root] = body._sleepTime;\n }\n }\n }\n\n // Sleep an island iff every member has rested for `timeToSleep`; otherwise\n // wake it (which also wakes any member dragged awake by a fresh contact).\n const timeToSleep = this.timeToSleep;\n\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n body._setSleeping(minSleep[this._find(i)]! >= timeToSleep);\n }\n }\n }\n\n /**\n * Union dynamic↔dynamic solid contacts into islands. A dynamic body touching a\n * MOVING static/kinematic body has its sleep timer reset instead: those types\n * are island boundaries, not members, so nothing else would keep the passenger\n * of a slow-moving platform awake - and the solver skips a contact whose\n * dynamic side is asleep, letting the platform drive straight through it.\n *\n * The same traversal resets the sleep timer of both sides of a contact whose\n * penetration the solver has not worked off yet, so the island it belongs to\n * stays awake until the overlap is within the tolerance the solver itself\n * converges to.\n */\n private _unionContactIslands(): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n // A contact the modifier disabled carries no load this step, so it neither\n // forms an island, nor keeps a passenger of a moving platform awake, nor\n // has an overlap anything is going to resolve.\n if (!contact.enabled) {\n continue;\n }\n\n const bodyA = contact.a.body;\n const bodyB = contact.b.body;\n const dynamicA = bodyA.type === 'dynamic';\n const dynamicB = bodyB.type === 'dynamic';\n\n if (dynamicA && dynamicB) {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n } else if (dynamicA && isMovingBoundary(bodyB)) {\n bodyA._sleepTime = 0;\n } else if (dynamicB && isMovingBoundary(bodyA)) {\n bodyB._sleepTime = 0;\n }\n\n // Unresolved overlap only matters where there is a dynamic body to hold\n // awake; a static↔static pair reaches the contact set but has no sleep\n // decision to gate.\n if ((dynamicA || dynamicB) && isUnresolved(contact.manifold)) {\n if (dynamicA) {\n bodyA._sleepTime = 0;\n }\n\n if (dynamicB) {\n bodyB._sleepTime = 0;\n }\n }\n }\n }\n\n /** Union-find union by lower index (deterministic roots). */\n private _union(a: number, b: number): void {\n const rootA = this._find(a);\n const rootB = this._find(b);\n\n if (rootA < rootB) {\n this._islandParent[rootB] = rootA;\n } else if (rootB < rootA) {\n this._islandParent[rootA] = rootB;\n }\n }\n\n /** Union-find find with path halving. */\n private _find(index: number): number {\n const parent = this._islandParent;\n\n while (parent[index]! !== index) {\n const grandparent = parent[parent[index]!]!;\n parent[index] = grandparent;\n index = grandparent;\n }\n\n return index;\n }\n\n /** Build each joint's per-frame constraint data (once per fixed step). */\n private _prepareJoints(h: number): void {\n for (const joint of this._joints) {\n joint._prepare(h);\n }\n }\n\n /** Re-apply each joint's accumulated impulse (each sub-step). */\n private _warmStartJoints(): void {\n for (const joint of this._joints) {\n joint._warmStart();\n }\n }\n\n /** One joint velocity pass (each sub-step, after the contacts). */\n private _solveJoints(useBias: boolean): void {\n for (const joint of this._joints) {\n joint._solve(useBias);\n }\n }\n\n /** Whether any dynamic body is flagged for continuous collision (bullet mode). */\n private _hasBullets(): boolean {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n return true;\n }\n }\n\n return false;\n }\n\n /** Snapshot each bullet's centre of mass at the start of the fixed step (the swept-test origin). */\n private _recordBulletPositions(): void {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n body._ccdPrevX = body.worldCenterOfMassX;\n body._ccdPrevY = body.worldCenterOfMassY;\n }\n }\n }\n\n /**\n * Shape-cast each bullet's colliders along this fixed step's motion against\n * every other body's colliders; if any would cross one, clamp the body at the\n * earliest impact and resolve it about the surface normal (a slide for a\n * non-bouncy body, an elastic reflection as restitution → 1) so it cannot\n * tunnel. The sweep is an exact translation-only cast of the full shapes\n * (Minkowski ray for circles, swept SAT for polygon pairs) - the step's\n * rotation is applied before the sweep, not swept through. Pairs already\n * overlapping at the start of the step are skipped: the discrete solver owns\n * them (that hand-off is what lets a landed bullet rest on real contacts).\n * Filters and sensors behave exactly as in the discrete narrow phase.\n */\n private _advanceBullets(): void {\n // `_finalizePosition` moved collider geometry after this step's detection\n // pass, so the index's leaves are stale for the sweep queries below. A leaf\n // whose tight AABB is still inside its fat one costs nothing to re-sync.\n this._backend.spatialIndex?.sync(this._detectionColliders);\n\n for (const body of this._bodies) {\n if (!body.isBullet || body.type !== 'dynamic' || body.isSleeping) {\n continue;\n }\n\n // The step's centre-of-mass motion; every collider translated by it too.\n const newX = body.worldCenterOfMassX;\n const newY = body.worldCenterOfMassY;\n const dx = newX - body._ccdPrevX;\n const dy = newY - body._ccdPrevY;\n const distance = Math.hypot(dx, dy);\n\n if (distance < 1e-6) {\n continue;\n }\n\n const blocked = this._sweepBulletColliders(body, dx, dy);\n\n if (blocked === null) {\n continue;\n }\n\n // Clamp the step's translation at the impact, overshooting by a small\n // embed along the motion (a pure translation - the rotation is already\n // applied) so the next step's detection forms a real discrete contact.\n const best = this._ccdBestHit;\n const clampDistance = Math.min(distance, best.t * distance + ccdEmbed);\n\n if (clampDistance < distance) {\n const pullBack = (clampDistance - distance) / distance;\n\n this._ccdClampPosition.x = body.x + dx * pullBack;\n this._ccdClampPosition.y = body.y + dy * pullBack;\n body.setTransform(this._ccdClampPosition, body.angle);\n\n // The clamp pulled this body back behind the pose the index was synced\n // from; refresh just its own leaves so a later bullet's query still sees it.\n this._backend.spatialIndex?.sync(this._detectionLeavesOf(body));\n }\n\n // Reflect about the true surface normal: a slide for a non-bouncy body\n // (restitution 0), an elastic bounce as restitution → 1. The body's own\n // restitution combines (max) with the surface's, matching the contact solver.\n const vn = body.linearVelocityX * best.normalX + body.linearVelocityY * best.normalY;\n\n if (vn < 0) {\n const restitution = vn < -ccdRestitutionThreshold ? Math.max(this._bulletRestitution(body), blocked.restitution) : 0;\n const impulse = -(1 + restitution) * vn;\n\n body.linearVelocityX += impulse * best.normalX;\n body.linearVelocityY += impulse * best.normalY;\n }\n }\n }\n\n /**\n * Find the earliest impact for a bullet whose colliders translated by\n * `(dx, dy)` this step. Each of the bullet's colliders queries the broad\n * phase with its swept AABB, so the pass costs what the geometry around the\n * bullet's path costs - not one iteration per collider in the world. Returns\n * the blocking collider (with the impact written into {@link _ccdBestHit}),\n * or `null` when nothing blocks the motion.\n */\n private _sweepBulletColliders(body: PhysicsBody, dx: number, dy: number): Collider | null {\n const hit = this._ccdSweepHit;\n const best = this._ccdBestHit;\n const swept = this._ccdSweptAabb;\n const spatialIndex = this._backend.spatialIndex;\n let blocked: Collider | null = null;\n\n best.t = Infinity;\n\n for (const collider of body.colliders) {\n if (collider.isSensor) {\n continue; // Sensors never block — not even their own body's motion.\n }\n\n if (__DEV__) {\n warnUnsweptBulletShape(collider, this._warnedUnsweptKinds);\n }\n\n // The collider's end-pose AABB unioned with its start pose; anything\n // outside it cannot be hit, so no narrow-phase sweep runs.\n const aabb = collider.aabb;\n\n swept.minX = dx > 0 ? aabb.minX - dx : aabb.minX;\n swept.maxX = dx < 0 ? aabb.maxX - dx : aabb.maxX;\n swept.minY = dy > 0 ? aabb.minY - dy : aabb.minY;\n swept.maxY = dy < 0 ? aabb.maxY - dy : aabb.maxY;\n\n // Tree hits are keyed on the leaves' fat AABBs, so the candidate set is a\n // conservative superset - the exact `aabbOverlap` below still decides.\n // A backend without a spatial index falls back to the full collider list.\n const candidates = spatialIndex === undefined ? this._detectionColliders : spatialIndex.queryAabb(swept, this._ccdCandidates);\n\n this._ccdBroadPhaseCandidates += candidates.length;\n\n for (const other of candidates) {\n // A chain edge proxy blocks under its chain's material and filter, and\n // reports the chain as the blocking collider - the sweep never hands a\n // caller a solver-side proxy.\n const target = authoredCollider(other);\n\n // Sweep against every other body (static, kinematic, dynamic) under the\n // discrete narrow phase's rules: sensors never block, filtered pairs never collide.\n if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter)) {\n continue;\n }\n\n if (!aabbOverlap(swept, other.aabb)) {\n continue;\n }\n\n this._ccdSweepTests++;\n\n if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {\n best.t = hit.t;\n best.normalX = hit.normalX;\n best.normalY = hit.normalY;\n blocked = target;\n }\n }\n }\n\n return blocked;\n }\n\n /** The highest restitution among a body's colliders (its CCD bounce factor). */\n private _bulletRestitution(body: PhysicsBody): number {\n let restitution = 0;\n\n for (const collider of body.colliders) {\n if (collider.restitution > restitution) {\n restitution = collider.restitution;\n }\n }\n\n return restitution;\n }\n\n /** Run `command` now, or queue it when inside an event dispatch (deferred to end of step). */\n private _defer(command: () => void): void {\n if (this._dispatching) {\n this._commands.push(command);\n } else {\n command();\n }\n }\n\n private _drainCommands(): void {\n if (this._commands.length === 0) {\n return;\n }\n\n const commands = this._commands.splice(0);\n\n for (const command of commands) {\n command();\n }\n }\n\n private _removeBody(body: PhysicsBody): void {\n const index = this._bodies.indexOf(body);\n\n if (index === -1) {\n // Never added (created and destroyed within the same dispatch) - still\n // tear down its colliders and mark it dead.\n this._teardownBody(body);\n\n return;\n }\n\n this._bodies.splice(index, 1);\n this._teardownBody(body);\n }\n\n private _teardownBody(body: PhysicsBody): void {\n for (const collider of body.colliders) {\n this._detachCollider(collider);\n }\n\n this._bindings.unbind(body);\n body._markDestroyed();\n }\n\n private _removeCollider(collider: Collider): void {\n this._detachCollider(collider);\n collider.body._removeCollider(collider);\n }\n\n private _detachCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n }\n\n this._wakeTouchingBodies(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._removeDetectionCollider(collider);\n } else {\n for (const edge of edges) {\n this._removeDetectionCollider(edge);\n }\n }\n\n collider._markDestroyed();\n }\n\n /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */\n private _removeDetectionCollider(collider: Collider): void {\n const index = this._detectionColliders.indexOf(collider);\n\n if (index !== -1) {\n this._detectionColliders.splice(index, 1);\n }\n\n this._backend.removeCollider(collider);\n }\n\n /**\n * The broad-phase leaves of one body - its colliders, with a chain replaced by\n * its edge proxies. Returns pooled scratch, valid until the next call.\n */\n private _detectionLeavesOf(body: PhysicsBody): Collider[] {\n const leaves = this._leafScratch;\n\n leaves.length = 0;\n\n for (const collider of body.colliders) {\n const edges = collider.chainEdges;\n\n if (edges === null) {\n leaves.push(collider);\n\n continue;\n }\n\n for (const edge of edges) {\n leaves.push(edge);\n }\n }\n\n return leaves;\n }\n\n /**\n * Wake every dynamic body still touching `collider` at the moment it leaves\n * the world. A sleeping body's sleep timer is frozen, so the island pass alone\n * can never re-open its sleep decision: losing the support it rested on just\n * removes a contact, and the island (now smaller, or a lone body) still reports\n * a long-expired timer and is put straight back to sleep - a stack whose floor,\n * platform or bottom box is destroyed would hang in mid-air forever. Kinematic\n * and static supports are the sharp edge, since they are island boundaries\n * rather than nodes and so are invisible to wake propagation, but the same hole\n * exists for a dynamic support. Waking the far side of each contact is enough:\n * the woken body's reset timer propagates through the rest of its sleeping\n * island on the next step, exactly like any other wake event.\n */\n private _wakeTouchingBodies(collider: Collider): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n let other: Collider;\n\n if (contact.ownerA === collider) {\n other = contact.ownerB;\n } else if (contact.ownerB === collider) {\n other = contact.ownerA;\n } else {\n continue;\n }\n\n // Only reached for a collider that is part of a live contact, so it is\n // attached and `body` cannot throw - a free-standing collider (a body\n // destroyed before it was ever stepped) has no contacts to match.\n if (other.body.type === 'dynamic') {\n other.body.wake();\n }\n }\n }\n\n private _assertAlive(): void {\n if (this._destroyed) {\n throw new Error('PhysicsWorld: the world has been destroyed.');\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAUjB,MAAM,cAAc,UAA0B;CAG5C,IAAI,EAAE,QAAQ,IACZ,OAAO;CAGT,OAAO,QAAQ,IAAI,QAAQ;AAC7B;;;;;;;;;;AAWA,MAAM,0BAA0B,UAAoB,oBAAiD;CACnG,MAAM,OAAO,SAAS;CAEtB,IAAI,KAAK,SAAS,aAAa,SAAS,MAAM,mBAAmB,QAAQ,SAAS,WAAW,GAC3F;CAGF,IAAI,YAAY;CAEhB,KAAK,MAAM,SAAS,KAAK,WAAW;EAKlC,IAAI,UAAU,YAAY,gBAAgB,IAAI,KAAK,GACjD;EAGF,IAAI,MAAM,MAAM,mBAAmB,QAAQ,MAAM,UAAU,GACzD;EAGF;CACF;CAEA,IAAI,cAAc,GAChB;CAGF,MAAM,IAAI,MACR,wNACF;AACF;;;;;;;;;AA+BA,MAAM,oBAAoB,SACxB,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AAO,KAAK,QAAQ;IAEpB;GACF;GAEA,KAAK,MAAM,QAAQ,OACjB,OAAO,KAAK,IAAI;EAEpB;EAEA,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAQ,oBAAoB,UAA0B;EACpD,KAAK,MAAM,WAAW,KAAK,SAAS,aAAa,eAAe;GAC9D,IAAI;GAEJ,IAAI,QAAQ,WAAW,UACrB,QAAQ,QAAQ;QACX,IAAI,QAAQ,WAAW,UAC5B,QAAQ,QAAQ;QAEhB;GAMF,IAAI,MAAM,KAAK,SAAS,WACtB,MAAM,KAAK,KAAK;EAEpB;CACF;CAEA,AAAQ,eAAqB;EAC3B,IAAI,KAAK,YACP,MAAM,IAAI,MAAM,6CAA6C;CAEjE;AACF"}
@@ -24,7 +24,14 @@ export declare class BindingRegistry {
24
24
  * pool, so a `sync()` that kept writing would not merely update a dead node -
25
25
  * it would write through recycled state into whichever live node next takes
26
26
  * that slot. Pruning here (rather than only on an explicit `unbind`) is what
27
- * makes destroying a bound node safe without a physics-side teardown call.
27
+ * makes destroying a bound node safe from THAT hazard without a
28
+ * physics-side call.
29
+ *
30
+ * It does not remove the body: pruning only drops this registry's link, so
31
+ * a destroyed node's body stays in {@link PhysicsWorld}, keeps being
32
+ * integrated, and keeps generating contacts and query results with nothing
33
+ * on screen. The body's owner is responsible for destroying it (or calling
34
+ * {@link unbind} first) when the node it was driving is destroyed.
28
35
  */
29
36
  sync(): void;
30
37
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"BindingRegistry.d.ts","sourceRoot":"","sources":["../../../src/binding/BindingRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAgDlD;;;GAGG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0C;IAEpE;;;;;OAKG;IACI,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,GAAG,cAAc;IAqB/D,0CAA0C;IACnC,MAAM,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI;IAItC;;;;;;;;;OASG;IACI,IAAI,IAAI,IAAI;IAWnB;;;;OAIG;IACI,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAW5C,+CAA+C;IAC/C,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,sBAAsB;IACf,KAAK,IAAI,IAAI;CAGrB"}
1
+ {"version":3,"file":"BindingRegistry.d.ts","sourceRoot":"","sources":["../../../src/binding/BindingRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAgDlD;;;GAGG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0C;IAEpE;;;;;OAKG;IACI,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,GAAG,cAAc;IAqB/D,0CAA0C;IACnC,MAAM,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI;IAItC;;;;;;;;;;;;;;;;OAgBG;IACI,IAAI,IAAI,IAAI;IAWnB;;;;OAIG;IACI,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAW5C,+CAA+C;IAC/C,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,sBAAsB;IACf,KAAK,IAAI,IAAI;CAGrB"}
@@ -34,7 +34,14 @@ var BindingRegistry = class {
34
34
  * pool, so a `sync()` that kept writing would not merely update a dead node -
35
35
  * it would write through recycled state into whichever live node next takes
36
36
  * that slot. Pruning here (rather than only on an explicit `unbind`) is what
37
- * makes destroying a bound node safe without a physics-side teardown call.
37
+ * makes destroying a bound node safe from THAT hazard without a
38
+ * physics-side call.
39
+ *
40
+ * It does not remove the body: pruning only drops this registry's link, so
41
+ * a destroyed node's body stays in {@link PhysicsWorld}, keeps being
42
+ * integrated, and keeps generating contacts and query results with nothing
43
+ * on screen. The body's owner is responsible for destroying it (or calling
44
+ * {@link unbind} first) when the node it was driving is destroyed.
38
45
  */
39
46
  sync() {
40
47
  for (const [body, binding] of this._bindings) {
@@ -1 +1 @@
1
- {"version":3,"file":"BindingRegistry.js","names":[],"sources":["../../../src/binding/BindingRegistry.ts"],"sourcesContent":["import { logger, type SceneNode } from '@codexo/exojs';\n\nimport type { PhysicsBody } from '../PhysicsBody';\nimport { PhysicsBinding } from './PhysicsBinding';\n\n/** `true` when `ancestor` contributes anything beyond identity to a descendant's world transform. */\nconst hasNonIdentityTransform = (ancestor: SceneNode): boolean =>\n ancestor.x !== 0 ||\n ancestor.y !== 0 ||\n ancestor.rotation !== 0 ||\n ancestor.skewX !== 0 ||\n ancestor.skewY !== 0 ||\n ancestor.scale.x !== 1 ||\n ancestor.scale.y !== 1 ||\n ancestor.origin.x !== 0 ||\n ancestor.origin.y !== 0;\n\n/**\n * Dev-only bind-time guard (F16): {@link PhysicsBinding.sync} writes the\n * body's WORLD transform into the node's LOCAL position/rotation, which is\n * only correct when local space == world space. Walk the parent chain and\n * warn when an ancestor either carries a non-identity transform or is a\n * transform-group boundary (RetainedContainer) - in both cases the ancestor\n * contribution is applied ON TOP of the world-space values sync() writes,\n * double-transforming the node on screen.\n */\nconst warnUnlessWorldSpaceRooted = (node: SceneNode): void => {\n // Duck-typed test doubles may omit `parent`; treat that as world-space-rooted.\n let ancestor: SceneNode | null = node.parent ?? null;\n\n while (ancestor !== null) {\n if (ancestor._isTransformGroupBoundary || hasNonIdentityTransform(ancestor)) {\n const nodeName = node.name !== null && node.name !== '' ? ` '${node.name}'` : '';\n const ancestorName = ancestor.name !== null && ancestor.name !== '' ? ` '${ancestor.name}'` : '';\n\n logger.warn(\n `PhysicsBinding: the bound node${nodeName} is not world-space-rooted — ancestor${ancestorName} ${\n ancestor._isTransformGroupBoundary ? 'is a transform-group boundary (RetainedContainer)' : 'has a non-identity transform'\n }. sync() writes the body's WORLD transform into the node's LOCAL position/rotation, so nesting it under a ` +\n 'moved/rotated/scaled container (or a transform group) will double-transform it on screen. Re-parent the node ' +\n 'to a world-space-rooted container.',\n { source: 'physics' },\n );\n\n return;\n }\n\n ancestor = ancestor.parent ?? null;\n }\n};\n\n/**\n * Owns the body ↔ node links and writes bound node transforms after each step.\n * Backend-agnostic (frontend-level) - it reads only the public body transform.\n */\nexport class BindingRegistry {\n private readonly _bindings = new Map<PhysicsBody, PhysicsBinding>();\n\n /**\n * Link `body` to `node`. Rejects destroyed nodes and nodes with non-zero\n * skew; runtime scale is ignored. In dev builds, warns when the node is not\n * world-space-rooted (moved ancestor or transform-group boundary above it) -\n * see {@link PhysicsBinding} for the local==world contract.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n if (node.destroyed) {\n throw new Error('PhysicsBinding: cannot bind a destroyed node — its pooled transform has already been released.');\n }\n\n if (node.skewX !== 0 || node.skewY !== 0) {\n throw new Error(`PhysicsBinding: the bound node has non-zero skew (${node.skewX}°, ${node.skewY}°); skewed nodes are not supported.`);\n }\n\n if (__DEV__) {\n warnUnlessWorldSpaceRooted(node);\n }\n\n const binding = new PhysicsBinding(body, node);\n\n this._bindings.set(body, binding);\n binding.sync();\n\n return binding;\n }\n\n /** Remove the link for `body`, if any. */\n public unbind(body: PhysicsBody): void {\n this._bindings.delete(body);\n }\n\n /**\n * Write every bound node's transform from its body, dropping links whose node\n * has been destroyed.\n *\n * `SceneNode.destroy()` returns the node's position/rotation state to a shared\n * pool, so a `sync()` that kept writing would not merely update a dead node -\n * it would write through recycled state into whichever live node next takes\n * that slot. Pruning here (rather than only on an explicit `unbind`) is what\n * makes destroying a bound node safe without a physics-side teardown call.\n */\n public sync(): void {\n for (const [body, binding] of this._bindings) {\n if (binding.node.destroyed) {\n this._bindings.delete(body);\n continue;\n }\n\n binding.sync();\n }\n }\n\n /**\n * Like {@link sync}, but places each node `alpha` of the way from its body's\n * previous fixed state to its current one - see\n * {@link PhysicsBinding.syncInterpolated}. Same destroyed-node pruning.\n */\n public syncInterpolated(alpha: number): void {\n for (const [body, binding] of this._bindings) {\n if (binding.node.destroyed) {\n this._bindings.delete(body);\n continue;\n }\n\n binding.syncInterpolated(alpha);\n }\n }\n\n /** `true` when at least one binding exists. */\n public get size(): number {\n return this._bindings.size;\n }\n\n /** Drop all links. */\n public clear(): void {\n this._bindings.clear();\n }\n}\n"],"mappings":";;;;;;;;AAuDA,IAAa,kBAAb,MAA6B;CAC3B,AAAiB,4BAAY,IAAI,IAAiC;;;;;;;CAQlE,AAAO,KAAK,MAAmB,MAAiC;EAC9D,IAAI,KAAK,WACP,MAAM,IAAI,MAAM,gGAAgG;EAGlH,IAAI,KAAK,UAAU,KAAK,KAAK,UAAU,GACrC,MAAM,IAAI,MAAM,qDAAqD,KAAK,MAAM,KAAK,KAAK,MAAM,oCAAoC;EAOtI,MAAM,UAAU,IAAI,eAAe,MAAM,IAAI;EAE7C,KAAK,UAAU,IAAI,MAAM,OAAO;EAChC,QAAQ,KAAK;EAEb,OAAO;CACT;;CAGA,AAAO,OAAO,MAAyB;EACrC,KAAK,UAAU,OAAO,IAAI;CAC5B;;;;;;;;;;;CAYA,AAAO,OAAa;EAClB,KAAK,MAAM,CAAC,MAAM,YAAY,KAAK,WAAW;GAC5C,IAAI,QAAQ,KAAK,WAAW;IAC1B,KAAK,UAAU,OAAO,IAAI;IAC1B;GACF;GAEA,QAAQ,KAAK;EACf;CACF;;;;;;CAOA,AAAO,iBAAiB,OAAqB;EAC3C,KAAK,MAAM,CAAC,MAAM,YAAY,KAAK,WAAW;GAC5C,IAAI,QAAQ,KAAK,WAAW;IAC1B,KAAK,UAAU,OAAO,IAAI;IAC1B;GACF;GAEA,QAAQ,iBAAiB,KAAK;EAChC;CACF;;CAGA,IAAW,OAAe;EACxB,OAAO,KAAK,UAAU;CACxB;;CAGA,AAAO,QAAc;EACnB,KAAK,UAAU,MAAM;CACvB;AACF"}
1
+ {"version":3,"file":"BindingRegistry.js","names":[],"sources":["../../../src/binding/BindingRegistry.ts"],"sourcesContent":["import { logger, type SceneNode } from '@codexo/exojs';\n\nimport type { PhysicsBody } from '../PhysicsBody';\nimport { PhysicsBinding } from './PhysicsBinding';\n\n/** `true` when `ancestor` contributes anything beyond identity to a descendant's world transform. */\nconst hasNonIdentityTransform = (ancestor: SceneNode): boolean =>\n ancestor.x !== 0 ||\n ancestor.y !== 0 ||\n ancestor.rotation !== 0 ||\n ancestor.skewX !== 0 ||\n ancestor.skewY !== 0 ||\n ancestor.scale.x !== 1 ||\n ancestor.scale.y !== 1 ||\n ancestor.origin.x !== 0 ||\n ancestor.origin.y !== 0;\n\n/**\n * Dev-only bind-time guard (F16): {@link PhysicsBinding.sync} writes the\n * body's WORLD transform into the node's LOCAL position/rotation, which is\n * only correct when local space == world space. Walk the parent chain and\n * warn when an ancestor either carries a non-identity transform or is a\n * transform-group boundary (RetainedContainer) - in both cases the ancestor\n * contribution is applied ON TOP of the world-space values sync() writes,\n * double-transforming the node on screen.\n */\nconst warnUnlessWorldSpaceRooted = (node: SceneNode): void => {\n // Duck-typed test doubles may omit `parent`; treat that as world-space-rooted.\n let ancestor: SceneNode | null = node.parent ?? null;\n\n while (ancestor !== null) {\n if (ancestor._isTransformGroupBoundary || hasNonIdentityTransform(ancestor)) {\n const nodeName = node.name !== null && node.name !== '' ? ` '${node.name}'` : '';\n const ancestorName = ancestor.name !== null && ancestor.name !== '' ? ` '${ancestor.name}'` : '';\n\n logger.warn(\n `PhysicsBinding: the bound node${nodeName} is not world-space-rooted — ancestor${ancestorName} ${\n ancestor._isTransformGroupBoundary ? 'is a transform-group boundary (RetainedContainer)' : 'has a non-identity transform'\n }. sync() writes the body's WORLD transform into the node's LOCAL position/rotation, so nesting it under a ` +\n 'moved/rotated/scaled container (or a transform group) will double-transform it on screen. Re-parent the node ' +\n 'to a world-space-rooted container.',\n { source: 'physics' },\n );\n\n return;\n }\n\n ancestor = ancestor.parent ?? null;\n }\n};\n\n/**\n * Owns the body ↔ node links and writes bound node transforms after each step.\n * Backend-agnostic (frontend-level) - it reads only the public body transform.\n */\nexport class BindingRegistry {\n private readonly _bindings = new Map<PhysicsBody, PhysicsBinding>();\n\n /**\n * Link `body` to `node`. Rejects destroyed nodes and nodes with non-zero\n * skew; runtime scale is ignored. In dev builds, warns when the node is not\n * world-space-rooted (moved ancestor or transform-group boundary above it) -\n * see {@link PhysicsBinding} for the local==world contract.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n if (node.destroyed) {\n throw new Error('PhysicsBinding: cannot bind a destroyed node — its pooled transform has already been released.');\n }\n\n if (node.skewX !== 0 || node.skewY !== 0) {\n throw new Error(`PhysicsBinding: the bound node has non-zero skew (${node.skewX}°, ${node.skewY}°); skewed nodes are not supported.`);\n }\n\n if (__DEV__) {\n warnUnlessWorldSpaceRooted(node);\n }\n\n const binding = new PhysicsBinding(body, node);\n\n this._bindings.set(body, binding);\n binding.sync();\n\n return binding;\n }\n\n /** Remove the link for `body`, if any. */\n public unbind(body: PhysicsBody): void {\n this._bindings.delete(body);\n }\n\n /**\n * Write every bound node's transform from its body, dropping links whose node\n * has been destroyed.\n *\n * `SceneNode.destroy()` returns the node's position/rotation state to a shared\n * pool, so a `sync()` that kept writing would not merely update a dead node -\n * it would write through recycled state into whichever live node next takes\n * that slot. Pruning here (rather than only on an explicit `unbind`) is what\n * makes destroying a bound node safe from THAT hazard without a\n * physics-side call.\n *\n * It does not remove the body: pruning only drops this registry's link, so\n * a destroyed node's body stays in {@link PhysicsWorld}, keeps being\n * integrated, and keeps generating contacts and query results with nothing\n * on screen. The body's owner is responsible for destroying it (or calling\n * {@link unbind} first) when the node it was driving is destroyed.\n */\n public sync(): void {\n for (const [body, binding] of this._bindings) {\n if (binding.node.destroyed) {\n this._bindings.delete(body);\n continue;\n }\n\n binding.sync();\n }\n }\n\n /**\n * Like {@link sync}, but places each node `alpha` of the way from its body's\n * previous fixed state to its current one - see\n * {@link PhysicsBinding.syncInterpolated}. Same destroyed-node pruning.\n */\n public syncInterpolated(alpha: number): void {\n for (const [body, binding] of this._bindings) {\n if (binding.node.destroyed) {\n this._bindings.delete(body);\n continue;\n }\n\n binding.syncInterpolated(alpha);\n }\n }\n\n /** `true` when at least one binding exists. */\n public get size(): number {\n return this._bindings.size;\n }\n\n /** Drop all links. */\n public clear(): void {\n this._bindings.clear();\n }\n}\n"],"mappings":";;;;;;;;AAuDA,IAAa,kBAAb,MAA6B;CAC3B,AAAiB,4BAAY,IAAI,IAAiC;;;;;;;CAQlE,AAAO,KAAK,MAAmB,MAAiC;EAC9D,IAAI,KAAK,WACP,MAAM,IAAI,MAAM,gGAAgG;EAGlH,IAAI,KAAK,UAAU,KAAK,KAAK,UAAU,GACrC,MAAM,IAAI,MAAM,qDAAqD,KAAK,MAAM,KAAK,KAAK,MAAM,oCAAoC;EAOtI,MAAM,UAAU,IAAI,eAAe,MAAM,IAAI;EAE7C,KAAK,UAAU,IAAI,MAAM,OAAO;EAChC,QAAQ,KAAK;EAEb,OAAO;CACT;;CAGA,AAAO,OAAO,MAAyB;EACrC,KAAK,UAAU,OAAO,IAAI;CAC5B;;;;;;;;;;;;;;;;;;CAmBA,AAAO,OAAa;EAClB,KAAK,MAAM,CAAC,MAAM,YAAY,KAAK,WAAW;GAC5C,IAAI,QAAQ,KAAK,WAAW;IAC1B,KAAK,UAAU,OAAO,IAAI;IAC1B;GACF;GAEA,QAAQ,KAAK;EACf;CACF;;;;;;CAOA,AAAO,iBAAiB,OAAqB;EAC3C,KAAK,MAAM,CAAC,MAAM,YAAY,KAAK,WAAW;GAC5C,IAAI,QAAQ,KAAK,WAAW;IAC1B,KAAK,UAAU,OAAO,IAAI;IAC1B;GACF;GAEA,QAAQ,iBAAiB,KAAK;EAChC;CACF;;CAGA,IAAW,OAAe;EACxB,OAAO,KAAK,UAAU;CACxB;;CAGA,AAAO,QAAc;EACnB,KAAK,UAAU,MAAM;CACvB;AACF"}
@@ -1,7 +1,7 @@
1
1
  //#region src/physicsBuildInfo.ts
2
2
  const physicsBuildInfo = Object.freeze({
3
- version: "0.16.1",
4
- revision: "b1afc5f",
3
+ version: "0.16.2",
4
+ revision: "59afd58",
5
5
  development: false
6
6
  });
7
7
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codexo/exojs-physics",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "description": "Native 2D collision, query and sensor runtime for ExoJS.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,7 +34,7 @@
34
34
  "@codexo/exojs": "0.16.x"
35
35
  },
36
36
  "devDependencies": {
37
- "@codexo/exojs": "0.16.1",
37
+ "@codexo/exojs": "0.16.2",
38
38
  "@codexo/exojs-config": "0.0.0"
39
39
  },
40
40
  "license": "MIT",