# @ferret/physics: API

Layers, triggers and raycasts; the rigid-body kernels (light and Havok); the capability host with scoped configuration; budgets and tiers.

169 exports. Generated from the source (`packages/physics/src`), so it matches the code.

## Classes

### Collider

*class* · `packages/physics/src/physics.ts:29`

```ts
class Collider extends Component<ColliderParams>
```

Anything on a layer that can be overlapped: triggers, interactables, characters. Static level geometry uses `markStatic` instead.

- `shape: ShapeKind`
- `layerBit: number`
- `maskBits: number`
- `physics: PhysicsService` — Set by the physics service when the component is attached.
- `onAttach()`
- `onDetach()`
- `get isTrigger()`
- `center(out = new BABYLON.Vector3()): BABYLON.Vector3`

### CollisionClient

*class* · `packages/physics/src/collision-world.ts:65`

```ts
class CollisionClient
```

the page's end: the world once, then moves as promises (a pool of one worker, so the state is in one place; without workers the same tasks run in this thread)

- `constructor(private readonly pool?: TaskPool, private readonly scheduler?: Scheduler)`
- `static collect(meshes: BABYLON.AbstractMesh[], layerOf?: (m: BABYLON.AbstractMesh) => number): CollisionMeshData[]` — the collidable meshes of a scene as plain data, in world space (the page's meshes are not touched)
- `setWorld(data: CollisionMeshData[]): Promise<number>`
- `info(): Promise<{ n: string; v: number; i: number; min: number[]; max: number[]; sub: number; chk: boolean; mat: boolean }[]>` — what the world holds (for tests and the inspector)
- `move(i: CollisionMoveIn): Promise<CollisionMoveOut>`

### CollisionLayers

*class* · `packages/physics/src/layers.ts:3`

```ts
class CollisionLayers
```

UE-style object channels: every collider is on one layer and tests against a mask of layers.

- `constructor(names: string[] = [])`
- `define(name: string): number`
- `bit(name: string): number`
- `mask(...names: string[]): number` — A mask from layer names; '*' = all layers.
- `names(): string[]`
- `namesOf(mask: number): string[]`

### CollisionSnapshot

*class* · `packages/physics/src/collision-snapshot.ts:18`

```ts
class CollisionSnapshot
```

- `reason: string` — why there is no copy now (empty while there is one)
- `constructor(private readonly scene: BABYLON.Scene, private readonly layerOf: (m: BABYLON.AbstractMesh) => number)`
- `current(tick: number): Snapshot | null` — the copy as it stands now, or null (with `reason`) while the meshes are changing faster than a copy is worth making
- `dispose()`

### FieldSupport

*class* · `packages/physics/src/walkers.ts:209`

```ts
class FieldSupport implements Support
```

a ground given by a function of (x, z): the sand, the sea bed, a mole's deck; `top` returns null where there is none

- `constructor(readonly name: string, private top: (x: number, z: number) => number | null, private solidTop?: (x: number, z: number) => number | null)`
- `query(x: number, z: number, feet: number, maxStep: number, reach: number, out: SupportHit)` — the ground a body can step onto from `feet` (the highest walkable top <= feet + maxStep) and whether something solid blocks him (a top between feet + maxStep and feet + reach)

### Governor

*class* · `packages/physics/src/budget.ts:58`

```ts
class Governor
```

Watches the world step and gives up detail in the order of `rules` when it stays over budget, then takes it back when there is
room again. It acts on the numbers the capabilities already read and on switching capabilities off; the events say what happened
(`physics:degrade` { level, rule, meanMs, budgetMs }), so a game can tell the player or log it.

- `readonly budget: TierBudget`
- `readonly rules: DegradeRule[]`
- `level: number`
- `constructor(private host: PhysicsHost, readonly opts: GovernorOptions = {})`
- `observe(ms: number)` — Called with the time of each step.

### GridSupport

*class* · `packages/physics/src/walkers.ts:168`

```ts
class GridSupport implements Support
```

- `cells: Map<number, GridCell>`
- `frame?: Support['frame']` — a moving support: world <-> its own frame, so a man on it is carried
- `range?: { x: number; z: number; r: number }` — world disc outside which the support is not asked (a ship far off costs nothing); the game keeps it at the support's place
- `constructor(readonly name: string, readonly spacing: number, readonly origin: [number, number], frame?: Support['frame'])`
- `add(x: number, y: number, z: number, walkable: boolean)` — add a top at local (x, z)
- `queryLocal(x: number, z: number, feet: number, maxStep: number, reach: number, out: SupportHit)` — local-frame query core (also for tests)
- `query(x: number, z: number, feet: number, maxStep: number, reach: number, out: SupportHit)` — the ground a body can step onto from `feet` (the highest walkable top <= feet + maxStep) and whether something solid blocks him (a top between feet + maxStep and feet + reach)

### HavokIslandStepper

*class* · `packages/physics/src/havok-islands.ts:50`

```ts
class HavokIslandStepper
```

what runs Havok's island step for a kernel: the worlds in the workers, the cost of a body, the sums of what was done

- `readonly KERNEL: "physics.havok.step"`
- `readonly INIT: "physics.havok.init"`
- `MIN_STEP_MS: number` — a step shorter than this is not worth a message (ms of estimated work)
- `CONTACT_MARGIN: number` — how far past the swept bounds Havok may still find a contact (m)
- `costPerBody: number | undefined` — worker time per awake body of one step, ms (measured here and in the workers)
- `reason: string` — why the last check kept the step in the game's thread ('' when it did not)
- `stats: { steps: number; islandSteps: number; pieces: number; islands: number; bodies: number; waitMs: number; residentRebuilds: number; moved: number; descs: number; }`
- `observe(ms: number, awake: number): void`
- `worth(k: HavokKernel, sched: Scheduler): boolean` — can this kernel's step leave the game's thread now? (no closures, workers, enough work)
- `async step(k: HavokKernel, dt: number, sched: Scheduler): Promise<boolean>` — step the kernel by islands in the workers; false when there is nothing to cut (no body awake), and the caller steps it here
- `dispose(): void`

### HavokKernel

*class* · `packages/physics/src/havok-kernel.ts:52`

```ts
class HavokKernel implements PhysicsKernel
```

The rigid-body kernel on Havok's own API (no Babylon scene needed, so it runs headless and in tests): bodies of any shape that move,
turn with their full inertia, stack and rest; joints that report their force and break; swept collision. The game loads the WASM
(`await HavokPhysics()`) and hands the module in, so a game that does not want rigid bodies does not carry it.

What Havok does not do the same way as the light kernel: contacts cannot be changed before they are solved (`caps.contactHooks` is
false: friction and restitution come from the materials, combined by the library's rules; a pair table is not used), and there is
no rolling resistance (a capability adds it as a torque).

- `readonly name: "havok"`
- `readonly caps: KernelCaps`
- `gravity: Vec3`
- `readonly materials: MaterialLibrary`
- `substeps: number`
- `readonly bodies: Body[]`
- `readonly constraints: Constraint[]`
- `readonly world: HP_WorldId`
- `readonly wasmUrl: string | undefined`
- `constructor(readonly hk: HavokPhysicsWithBindings, o: HavokKernelOptions = {})`
- `dispose()` — Free the Havok world and everything in it.
- `addBody(def: BodyDef, withId?: number): Body`
- `removeBody(b: Body)`
- `setMassProperties(b: Body, mass: number, centreOfMass: Vec3, inertia: Vec3)` — Mass, centre of mass (body space) and principal inertia set from outside (a vessel whose tanks fill); where the kernel can.
- `setSurface(b: Body, sf: { friction: number; kineticFriction: number; restitution: number })` — A body's own friction and restitution, over its material's: how a kernel without contact hooks takes a capability's dials.
- `describe(b: Body): HavokDesc` — what a body is, apart from where it is and how it moves: the description a worker makes its copy from
- `descSig(b: Body): unknown[]` — the numbers that make a description, to see that it has not changed (the shape and the arrays by identity: a change replaces them)
- `descSame(b: Body, sig: readonly unknown[]): boolean` — does the body still have the description `sig` (from `descSig`) says? (no allocation: it is asked of every body every step)
- `describeConstraint(c: Constraint): HavokConDesc`
- `staticsStamp(): number` — a number that changes when the static bodies change (added, removed, moved): a worker's world is made again then
- `adoptBody(d: HavokDesc, st: { position: Vec3; orientation: Quat; velocity: Vec3; angularVelocity: Vec3 }): Body` — put a body made elsewhere in this world by its description and state (a worker's copy of a piece of the world)
- `applyIslandResults(outs: HavokOut[]): void` — Put the results of a step done in pieces (havok-islands.ts) into the bodies, as `step` would have left them: the bodies' numbers, the constraints' forces and breaks, the contact events in a fixed order, the forces cleared. The Havok world here is not stepped while the pieces are; `push` writes what changed into it if this thread steps it again.
- `centreOf(b: Body): Vec3` — World position of the body's centre of mass.
- `applyForce(b: Body, f: Vec3, at?: Vec3)`
- `applyImpulse(b: Body, j: Vec3, at?: Vec3)`
- `applyTorque(b: Body, t: Vec3)`
- `setVelocity(b: Body, v: Vec3)`
- `setPosition(b: Body, p: Vec3)`
- `sleep(b: Body)`
- `wake(b: Body)`
- `addForceField(fn: (b: Body, h: number) => Vec3 | FieldForce | null, label?: string)` — A force that depends on where a body is (gravity, drag, buoyancy): evaluated at the position of every sub-step, so a fast or orbiting body gets the force it feels where it is, not where it was at the start of the step. Returns newtons, or null for none.
- `beforeSolve(_cb: (c: Contact) => void, _label?: string)` — Havok solves contacts inside its step: a hook is accepted and never called (`caps.contactHooks` is false).
- `addDataField(name: string, params: () => unknown, o: { local?: () => boolean } = {})` — a force field by name and plain parameters (field-kernels.ts), the same as the light kernel's
- `addDataHook(_name: string, _params: () => unknown, _o: { local?: () => boolean } = {})` — Havok cannot change a contact before it is solved: a hook by name is refused where the kernel has no contact hooks
- `get closures(): { fields: number; hooks: number; names: string[] }` — the fields that are closures: while there are any, the step cannot leave this thread (data fields can)
- `localOnly(): string | null` — the name of a data field whose parameters stand on code that cannot leave this thread, or null
- `dataSpecs(): { fields: { name: string; params: unknown }[]; hooks: { name: string; params: unknown }[] }`
- `setDataFields(list: { name: string; params: unknown }[])` — a worker's copy: the data fields of this step (replacing those of the step before)
- `onContact(cb: (e: ContactEvent) => void)` — Called after the step with what each contact did.
- `addConstraint(def: ConstraintDef): Constraint`
- `adoptConstraint(c: Constraint): Constraint` — put a joint made from a description (a constraint with its frames: a worker's copy) in the world between bodies that are in it
- `removeConstraint(c: Constraint)`
- `onConstraintBreak(cb: (c: Constraint) => void)` — Called after the step for each constraint whose force passed its limit; the constraint is already removed.
- `step(dt: number): void`
- `rayCast(origin: Vec3, dir: Vec3, maxDistance: number): KernelRayHit | null`

### IslandStepper

*class* · `packages/physics/src/island-step.ts:145`

```ts
class IslandStepper
```

what runs the island step for a kernel: the shared copies of the fixed bodies, the cost of a body, the sums of what was done

- `costPerBody: number | undefined` — worker time per awake body of one step, ms (an average over the last steps; measured here and in the workers)
- `reason: string` — why the last check kept the step in the game's thread ('' when it did not)
- `stats: { steps: number; islandSteps: number; pieces: number; islands: number; bodies: number; waitMs: number; residentRebuilds: number; }`
- `MIN_STEP_MS: number` — a step shorter than this is not worth a message (ms of estimated work)
- `readonly KERNEL: "physics.light.step"`
- `observe(ms: number, awake: number): void` — time the step this thread took, to know what a body costs
- `worth(k: LightKernel, sched: Scheduler): boolean` — can this kernel's step leave the game's thread now? (no closures, workers, enough work)
- `async step(k: LightKernel, dt: number, sched: Scheduler): Promise<boolean>` — step the kernel by islands in the workers; false when there is nothing to cut (one piece of work), and the caller steps it here
- `dispose(): void`

### LightKernel

*class* · `packages/physics/src/light-kernel.ts:32`

```ts
class LightKernel implements PhysicsKernel
```

A small deterministic rigid-body kernel: spheres that move, roll, slide and bounce against static planes, boxes and spheres and
against each other. No stacking of boxes and no joints; for projectiles, balls, debris, rolling and sliding tests, and as the
reference the capabilities are checked against. The same `PhysicsKernel` surface as a heavier backend, so a capability does not know.

- `readonly name: "light"`
- `readonly caps: KernelCaps`
- `gravity: Vec3`
- `readonly materials: MaterialLibrary`
- `substeps: number`
- `maxSubsteps: number`
- `iterations: number`
- `restitutionThreshold: number`
- `readonly bodies: Body[]`
- `readonly constraints: Constraint[]`
- `constructor(o: LightKernelOptions = {})`
- `addBody(def: BodyDef): Body`
- `removeBody(b: Body)`
- `addConstraint(def: ConstraintDef): Constraint`
- `removeConstraint(c: Constraint)`
- `onConstraintBreak(cb: (c: Constraint) => void)` — Called after the step for each constraint whose force passed its limit; the constraint is already removed.
- `applyForce(b: Body, f: Vec3, at?: Vec3)`
- `applyImpulse(b: Body, j: Vec3, at?: Vec3)`
- `applyTorque(b: Body, t: Vec3)`
- `setVelocity(b: Body, v: Vec3)`
- `setPosition(b: Body, p: Vec3)`
- `sleep(b: Body)`
- `wake(b: Body)`
- `addDataField(name: string, params: () => unknown, o: { local?: () => boolean } = {})` — a force field by name (see field-kernels.ts): `params` is asked once at the start of every step and must be plain data
- `addDataHook(name: string, params: () => unknown, o: { local?: () => boolean } = {})` — a contact hook by name, the same
- `get closures(): { fields: number; hooks: number; names: string[] }` — the fields and hooks that are closures: while there are any, the step cannot leave this thread (data fields and hooks can)
- `localOnly(): string | null` — the name of a data field or hook that cannot go to a worker now (it stands on something that is code: a flow box, a function a game gave), or null
- `dataSpecs(): { fields: { name: string; params: unknown }[]; hooks: { name: string; params: unknown }[] }` — the data fields and hooks of this step, with their parameters (what a worker is given)
- `addForceField(fn: (b: Body, h: number) => Vec3 | FieldForce | null, label?: string)` — A force that depends on where a body is (gravity, drag, buoyancy): evaluated at the position of every sub-step, so a fast or orbiting body gets the force it feels where it is, not where it was at the start of the step. Returns newtons, or null for none.
- `beforeSolve(cb: (c: Contact) => void, label?: string)` — Called for every contact before it is solved, so a capability can change friction or restitution.
- `onContact(cb: (e: ContactEvent) => void)` — Called after the step with what each contact did.
- `substepsFor(dt: number): number` — how many sub-steps a step of `dt` takes: the setting, more for a fast body (never more than maxSubsteps)
- `step(dt: number): void`
- `advance(dt: number, substeps?: number): ContactEvent[]` — the step without the contact listeners: the events it made, in a fixed order (a worker runs this; `step` calls it). `substeps` fixes the count (the game's thread counts it over all bodies, so a piece of the world steps as the whole would)
- `sleepTimers: Map<number, number>` — frames each body has been still (the sleep timers): a worker's piece is given them and gives them back
- `adopt(b: Body): Body` — put a body made elsewhere (a worker's copy of a piece of the world) in this kernel as it is, id included
- `adoptConstraint(c: Constraint): Constraint`
- `integrateKinematics(dt: number, n: number): void` — the kinematic bodies' part of a step (they move by their velocities, in the same sub-steps the dynamic ones take)
- `applyIslandResults(dt: number, n: number, outs: IslandOut[], islands: { constraints: Constraint[]; awake: boolean }[]): void` — Put the results of a step done in pieces (island-step.ts) into the bodies, as `step` would have left them: the bodies' numbers, the sleep timers, the constraints' forces and breaks, the contact events in the fixed order, the forces cleared. `islands` are all the islands (a sleeping one was not sent: its constraints carry no force).
- `staticsStamp(): number` — a number that changes when the static bodies change (added, removed, moved): a worker's copy of them is made again then
- `rayCast(origin: Vec3, dir: Vec3, maxDistance: number): KernelRayHit | null`

### MaterialLibrary

*class* · `packages/physics/src/materials.ts:58`

```ts
class MaterialLibrary
```

- `combine: CombineRules`
- `add(name: string, m: PhysicsMaterial): this`
- `get(name: string | undefined): PhysicsMaterial | undefined`
- `has(name: string)`
- `names()`
- `load(table: Record<string, PhysicsMaterial>): this` — Load `{name: material}`; throws with every problem listed when the table is invalid.
- `setPair(a: string, b: string, values: PhysicsMaterial): this` — The values for one pair of materials that override the combine rule (ice on rubber is not the mean of the two).
- `property(a: string | undefined, b: string | undefined, key: string): number | undefined` — One property of a pair: the pair table first, then the combine rule; a value only one side has is used as it is.
- `snapshot(): { mats: [string, PhysicsMaterial][]; pairs: [string, PhysicsMaterial][]; combine: CombineRules }` — the whole table as plain data (a worker's copy: `MaterialLibrary.restore`)
- `static restore(s: ReturnType<MaterialLibrary['snapshot']>): MaterialLibrary`
- `contact(a?: string, b?: string)` — What a contact between two materials uses.

### PhysicsHost

*class* · `packages/physics/src/host.ts:227`

```ts
class PhysicsHost implements Service
```

The home of the capabilities: the kernel, the materials, the registry and the fixed order of the step. A game registers the
capabilities it wants and switches them on (in code, in the manifest, or by command); nothing realistic runs otherwise.

- `readonly name: "physics.host"`
- `whyHere(): string | undefined` — why the step stays in the game's thread (what `perf.report` says), undefined when the islands take it
- `readonly schedule: ModuleDecl` — the module as the scheduler lists it: the kernel's step is one part that runs at its place between the host's own phases, by islands in the workers when it is worth it
- `readonly islands: IslandStepper` — the island step of the light kernel (workers); what it did is in `islands.stats`
- `readonly havokIslands: HavokIslandStepper` — the same for Havok's world (several worlds in the workers, one for the islands each worker holds); what it did is in `havokIslands.stats`
- `readonly kernel: PhysicsKernel`
- `readonly materials: MaterialLibrary`
- `readonly bodies: Set<RigidBody>`
- `readonly fields: PhysicsFields` — Fields that other code (a character, a vessel) may read when the capability behind them is on; each is set and cleared by its capability.
- `readonly capabilities: Map<string, Capability>`
- `world: World`
- `zoneAt(p: Vec3): string | null` — Which zone a point is in (none when the world has no ZoneService).
- `zonesData(): ZonesData | undefined` — the zones as plain data (the zone service's shapes, priorities and grid), for field kernels in workers; none without a zone service
- `lastStepMs: number` — Seconds the last step's physics took (ms), for the budget view.
- `constructor(o: PhysicsHostOptions = {})`
- `init(world: World)`
- `dispose()`
- `register(cap: Capability): this`
- `config(name: string): ScopedConfig`
- `isEnabled(name: string)`
- `enabled(): string[]`
- `enable(name: string, values?: Record<string, unknown>): this`
- `disable(name: string): this`
- `configure(c: PhysicsConfig, scope: 'world' | 'level' = 'level')` — Apply a `physics` block (from a level manifest or a game): materials, pair rules, combine rules, then the capabilities with their values.
- `readonly fractures: Map<string, LevelFracture>` — Pre-fractured bodies of the level, by the name of the intact body's node (read by the strength capability when that body breaks).
- `governor: Governor | null` — Gives up detail when the step runs over its tier's budget (see `Governor`); none until a game sets one.
- `beginLevel(c: PhysicsConfig): string[]` — A level's physics block: applied now, undone by `endLevel` (the capabilities it switched on go off, its scoped values go). Constraints and fractures name nodes, so the level's bodies must exist already. Returns what could not be linked.
- `endLevel()`
- `fixedUpdate(dt: number)` — Called before the components' fixed update, at the fixed rate.
- `async fixedUpdateAsync(dt: number): Promise<void>` — the step with the light kernel's work in the workers (the world's asynchronous step calls it when `wantsAsync`); the same phases in the same order as `fixedUpdate`
- `wantsAsync(): boolean` — true when the kernel's step is worth sending to the workers: the light kernel, no closure fields or hooks, enough bodies awake

### PhysicsService

*class* · `packages/physics/src/physics.ts:60`

```ts
class PhysicsService implements Service
```

Collision layers, trigger volumes with enter/exit events, raycasts and overlap queries. Static level geometry is Babylon
meshes with `checkCollisions`; characters move against it (see

- `readonly name: "physics"`
- `readonly layers: CollisionLayers`
- `readonly colliders: Set<Collider>`
- `constructor(opts: PhysicsOptions = {})`
- `init(world: World)`
- `markStatic(root: BABYLON.TransformNode | BABYLON.AbstractMesh, layer = 'World')` — Make a node's meshes static world geometry: blocking for characters and hit by raycasts.
- `get collisionCopy(): CollisionSnapshot` — the copy of the collidable meshes for the workers (characters' steps and others that sweep or cast rays off the game's thread)
- `raycast(origin: BABYLON.Vector3, dir: BABYLON.Vector3, maxDistance: number, opts: { mask?: number; ignore?: (m: BABYLON.AbstractMesh) => boolean } = {}): RayHit | null` — First hit of a ray against static geometry (and optionally entity colliders' meshes) on the masked layers.
- `overlapSphere(center: BABYLON.Vector3, radius: number, mask = -1): Collider[]` — Colliders whose volume overlaps a sphere.
- `dropColliderPairs(c: Collider)`
- `fixedUpdate()` — Called before the components' fixed update, at the fixed rate.
- `occupants(trigger: Collider): Entity[]` — Who is inside a trigger right now.
- `dispose()`

### RigidBody

*class* · `packages/physics/src/host.ts:118`

```ts
class RigidBody extends Component<RigidBodyParams>
```

A node that the physics kernel moves: the node's position and rotation follow the body after every step.

- `host: PhysicsHost`
- `body: Body`
- `onAttach()`
- `onDetach()`
- `get velocity(): Vec3`

### ScopedConfig

*class* · `packages/physics/src/host.ts:48`

```ts
class ScopedConfig
```

A capability's values at four scopes; the narrowest that has the key wins: entity, zone, level, world, then the defaults.

- `version: number` — grows with every change of a value (a cache that reads values is made again when it moves)
- `constructor(private host: PhysicsHost, readonly defaults: Record<string, unknown> = {})`
- `set(scope: 'world' | 'level', key: string, value: unknown): void`
- `set(scope: 'zone' | 'entity', key: string, value: unknown, id: string): void`
- `set(scope: Scope, key: string, value: unknown, id?: string)`
- `snapshot(keys: string[]): ScopedSnapshot` — the values of some keys at every scope, as plain data (a field kernel in a worker reads them with `ScopedData`); functions and objects with behaviour are not allowed in them
- `assign(scope: 'world' | 'level', values: Record<string, unknown>)`
- `clearLevel()`
- `where(key: string, ctx: ScopeContext = {}): Scope | 'default' | undefined` — Which layer a value comes from for this context: the narrowest scope that has the key, or `default` / undefined when none has it.
- `get<T = number>(key: string, ctx: ScopeContext = {}): T`

### ScopedData

*class* · `packages/physics/src/field-kernels.ts:58`

```ts
class ScopedData
```

the same lookup as `ScopedConfig.get`, over a snapshot: the entity's value, the zone's at the position, the level's, the world's, the default

- `constructor(readonly snap: ScopedSnapshot, readonly zones?: ZonesData)`
- `get<T = number>(key: string, ctx: { entityId?: string; position?: Vec3 } = {}): T`

### SphericalPendulum

*class* · `packages/physics/src/pendulum.ts:57`

```ts
class SphericalPendulum
```

- `q: Quat` — the rotation about the pivot since the rest pose
- `w: Vec3` — angular velocity, world frame, rad/s
- `readonly def: Required<PendulumDef>`
- `constructor(def: PendulumDef)`
- `push(force: Vec3)` — a force on the centre of mass (wind) for the coming step only; call it every frame it acts
- `impulseAt(point: Vec3, impulse: Vec3)` — an instantaneous impulse (N s) at a world point: the player's bump
- `step(dt: number)` — advance by dt seconds (sub-steps of at most 1/240 s)
- `pointAt(rest: Vec3): Vec3` — where a point of the body is now, given where it was at rest (world position)
- `position(): Vec3` — the centre of mass now
- `swing(): number` — the swing angle: how far the centre of mass hangs from straight below the pivot, radians
- `energy(): number` — kinetic + potential energy (J), potential measured from the rest pose
- `speed(): number` — how fast the centre of mass moves, m/s
- `rotation(base: Quat = qIdentity()): Quat` — the same for composing a rotation: this.q relative to a base rotation

### StripSupport

*class* · `packages/physics/src/walkers.ts:219`

```ts
class StripSupport implements Support
```

a sloped strip: a gangway or a ramp from a to b (world points), halfWidth m each side of the line; the height runs along it

- `a: Vec3`
- `b: Vec3`
- `halfWidth: number`
- `on: boolean`
- `extendA: number` — how far each end lies on over the ground it rests on, m (a gangway rests on the deck and the quay, it does not stop at a point): at a, at b
- `extendB: number`
- `readonly clears: true` — a bridge: where it gives ground, walls of other supports do not stop a man (a gangway through a rail, a ramp over a fender)
- `constructor(readonly name: string, halfWidth = 0.7, extendA = 0.6, extendB = 0.6)`
- `set(a: Vec3, b: Vec3)`
- `query(x: number, z: number, feet: number, maxStep: number, _reach: number, out: SupportHit)` — the ground a body can step onto from `feet` (the highest walkable top <= feet + maxStep) and whether something solid blocks him (a top between feet + maxStep and feet + reach)

### Walkers

*class* · `packages/physics/src/walkers.ts:66`

```ts
class Walkers
```

- `supports: Support[]`
- `readonly g: number`
- `readonly maxStep: number`
- `readonly maxDrop: number`
- `readonly reach: number`
- `readonly sink: number`
- `readonly swimDepth: number`
- `constructor(supports: Support[] = [], o: WalkersOptions = {})`
- `groundAt(x: number, z: number, feet = 1e6): number | null` — the ground a man would stand on at (x, z) seen from `feet` (or null): for the game's own questions (where may a man be put)
- `place(w: Walker, x: number, y: number, z: number)` — put a walker at (x, y, z): on the ground if he is at it, else in the air, and he falls
- `mount(w: Walker, support: Support, local: Vec3)` — put a walker on a moving support at a point of its own frame (a man on a deck): his world place follows from the frame, however it moves later
- `step(w: Walker, dt: number, dx = 0, dz = 0, careful = false): StepResult` — advance by dt: (dx, dz) is the move he wants this step (metres; ignored in the air). Gravity, supports, walls and water decide the rest. `careful`: he will not walk off an edge.

## Functions

### add

*function* · `packages/physics/src/vec.ts:8`

```ts
function add: (a: Vec3, b: Vec3) => Vec3
```

### addTo

*function* · `packages/physics/src/vec.ts:16`

```ts
function addTo: (a: Vec3, b: Vec3, s?: number) => void
```

### boundingRadius

*function* · `packages/physics/src/shapes.ts:104`

```ts
function boundingRadius(s: Shape): number
```

Radius of the sphere around the body's origin that holds the shape.

### boundRadius

*function* · `packages/physics/src/island-step.ts:57`

```ts
function boundRadius(s: Body['shape']): number
```

### bounds

*function* · `packages/physics/src/shapes.ts:37`

```ts
function bounds(s: Shape): [Vec3, Vec3]
```

Axis-aligned bounds in body space.

### boxInertia

*function* · `packages/physics/src/pendulum.ts:43`

```ts
function boxInertia(mass: number, size: Vec3, yaw = 0): number[]
```

the inertia tensor of a solid box about its centre, in the world frame when the box is turned `yaw` radians about the vertical (+Y) axis

### boxInertiaQ

*function* · `packages/physics/src/pendulum.ts:51`

```ts
function boxInertiaQ(mass: number, size: Vec3, q: Quat): number[]
```

the same for a box turned by any rotation (the node's rest orientation)

### buildIslands

*function* · `packages/physics/src/island-step.ts:108`

```ts
function buildIslands(k: { bodies: readonly Body[]; constraints: readonly Constraint[]; gravity: Vec3 }, dt: number, margin = 0, memo?: IslandMemo): Island[]
```

group the dynamic bodies: those whose bounds, grown by what they can travel in this step, meet, and those a constraint joins, are one island

### collisionOps

*function* · `packages/physics/src/collision-world.ts:18`

```ts
function collisionOps(st: CollisionState)
```

the collision world's work on a state (the tasks below and the engine's kernels, kernels-babylon.ts, are this)

### collisionTasks

*function* · `packages/physics/src/collision-world.ts:59`

```ts
function collisionTasks(): Record<string, TaskFn>
```

the two tasks of the collision world; the state (the headless scene and the body) lives in the thread that runs them

### combineValues

*function* · `packages/physics/src/materials.ts:48`

```ts
function combineValues(rule: CombineRule, a: number, b: number): number
```

### contactEntityId

*function* · `packages/physics/src/host.ts:502`

```ts
function contactEntityId(a: Body, b: Body): string | undefined
```

the id of the entity a contact is scoped by (the dynamic body's, else the other's), from the bodies' plain `entityId`: what a hook running in a worker has

### contactScope

*function* · `packages/physics/src/host.ts:503`

```ts
function contactScope(a: Body, b: Body, point: Vec3): ScopeContext
```

### copy

*function* · `packages/physics/src/vec.ts:17`

```ts
function copy: (a: Vec3) => Vec3
```

### cross

*function* · `packages/physics/src/vec.ts:12`

```ts
function cross: (a: Vec3, b: Vec3) => Vec3
```

### dataOf

*function* · `packages/physics/src/island-step.ts:33`

```ts
function dataOf: (b: Body) => BodyData
```

### defaultRules

*function* · `packages/physics/src/budget.ts:35`

```ts
function defaultRules: (t: TierBudget) => DegradeRule[]
```

### descOf

*function* · `packages/physics/src/island-step.ts:46`

```ts
function descOf: (b: Body) => BodyDesc
```

### dot

*function* · `packages/physics/src/vec.ts:11`

```ts
function dot: (a: Vec3, b: Vec3) => number
```

### entityOf

*function* · `packages/physics/src/host.ts:495`

```ts
function entityOf(b: Body): Entity | undefined
```

The entity a body belongs to (the RigidBody entity), when it has one.

### fieldKernel

*function* · `packages/physics/src/field-kernels.ts:17`

```ts
function fieldKernel(name: string): (params: any) => FieldFn
```

### fieldKernelNames

*function* · `packages/physics/src/field-kernels.ts:19`

```ts
function fieldKernelNames: () => string[]
```

### gravityAtData

*function* · `packages/physics/src/field-kernels.ts:84`

```ts
function gravityAtData(p: GravityFieldParams, pos: Vec3, entityId?: string, data = new ScopedData(p.scoped, p.zones)): Vec3
```

gravity acceleration at a point (m/s²) from the field's parameters: the vector of the scope plus the attractors, times the scale

### gravityVector

*function* · `packages/physics/src/field-kernels.ts:73`

```ts
function gravityVector(base: Vec3, attractors: Iterable<AttractorData>, p: Vec3): Vec3
```

the field vector at a point (before the scale) plus every attractor's pull

### havokModule

*function* · `packages/physics/src/havok-kernel.ts:12`

```ts
function havokModule: () => HavokPhysicsWithBindings | null
```

the Havok module the last kernel was made on: a worker that runs in this thread (a test, the page's fallback) steps its islands on it

### hookKernel

*function* · `packages/physics/src/field-kernels.ts:18`

```ts
function hookKernel(name: string): (params: any) => HookFn
```

### hookKernelNames

*function* · `packages/physics/src/field-kernels.ts:20`

```ts
function hookKernelNames: () => string[]
```

### len

*function* · `packages/physics/src/vec.ts:13`

```ts
function len: (a: Vec3) => number
```

### len2

*function* · `packages/physics/src/vec.ts:14`

```ts
function len2: (a: Vec3) => number
```

### localSdf

*function* · `packages/physics/src/shapes.ts:9`

```ts
function localSdf(s: Shape): (x: number, y: number, z: number) => number
```

Geometry of the body shapes in body space, for capabilities that need more than a radius: a signed distance (negative inside), the
volume, the bounding box, and a lattice of sample points that stand for the volume (buoyancy, drag, heat, a liquid's walls).

### lowestBelow

*function* · `packages/physics/src/shapes.ts:146`

```ts
function lowestBelow(s: Shape, q: [number, number, number, number]): number
```

Height of the shape's lowest point below the body's origin, the body turned by q (the radius, for a sphere), m.

### newWalker

*function* · `packages/physics/src/walkers.ts:40`

```ts
function newWalker: (x?: number, y?: number, z?: number) => Walker
```

### norm

*function* · `packages/physics/src/vec.ts:15`

```ts
function norm: (a: Vec3) => Vec3
```

### overlapsSphere

*function* · `packages/physics/src/physics.ts:165`

```ts
function overlapsSphere(c: Collider, center: BABYLON.Vector3, radius: number): boolean
```

Is a world-space sphere inside the collider's volume (box: oriented; sphere; capsule)?

### overlapsTrigger

*function* · `packages/physics/src/physics.ts:179`

```ts
function overlapsTrigger(t: Collider, o: Collider): boolean
```

Does collider `o` overlap the trigger volume `t`? A capsule is tested as a swept sphere along its axis (several samples).

### projectedArea

*function* · `packages/physics/src/shapes.ts:111`

```ts
function projectedArea(s: Shape, q: [number, number, number, number], dir: Vec3): number
```

Area the shape shows to a direction (world `dir`, the body turned by `q`), m²: exact for a sphere and a box, from the volume otherwise.

### qFromAxisAngle

*function* · `packages/physics/src/vec.ts:26`

```ts
function qFromAxisAngle(axis: Vec3, angle: number): Quat
```

### qIdentity

*function* · `packages/physics/src/vec.ts:19`

```ts
function qIdentity: () => Quat
```

### qIntegrate

*function* · `packages/physics/src/vec.ts:39`

```ts
function qIntegrate(q: Quat, w: Vec3, dt: number): Quat
```

Integrate an orientation by an angular velocity over dt (exact for constant w).

### qInverse

*function* · `packages/physics/src/vec.ts:25`

```ts
function qInverse: (q: Quat) => Quat
```

### qMul

*function* · `packages/physics/src/vec.ts:30`

```ts
function qMul(a: Quat, b: Quat): Quat
```

### qRotate

*function* · `packages/physics/src/vec.ts:20`

```ts
function qRotate(q: Quat, v: Vec3): Vec3
```

### registerFieldKernel

*function* · `packages/physics/src/field-kernels.ts:14`

```ts
function registerFieldKernel<P>(name: string, make: (params: P) => FieldFn): void
```

register a force field by name (a package's src/kernels.ts does it; the page and the worker bundle both import that file); `make` builds the field from the step's parameters

### registerHookKernel

*function* · `packages/physics/src/field-kernels.ts:16`

```ts
function registerHookKernel<P>(name: string, make: (params: P) => HookFn): void
```

register a contact hook by name: it changes a contact before it is solved

### sampleShape

*function* · `packages/physics/src/shapes.ts:98`

```ts
function sampleShape(s: Shape, n = 4): ShapeSamples
```

n cells along each axis of the bounds, the ones whose centre is inside; each carries an equal share of the volume.

### scale

*function* · `packages/physics/src/vec.ts:10`

```ts
function scale: (a: Vec3, s: number) => Vec3
```

### scopedSurface

*function* · `packages/physics/src/host.ts:512`

```ts
function scopedSurface(host: PhysicsHost, b: Body): { friction: number; kineticFriction: number; restitution: number }
```

A body's friction and restitution where it is now: its material's, times the friction capability's `scale` and the impact capability's
`scale` at its scope when they are on. What a kernel without contact hooks is given through `setSurface`.

### seededRng

*function* · `packages/physics/src/vec.ts:49`

```ts
function seededRng(seed: number): () => number
```

A seeded generator (mulberry32): the same seed gives the same sequence on every machine.

### shapeVolume

*function* · `packages/physics/src/shapes.ts:78`

```ts
function shapeVolume(s: Shape): number
```

Exact volume where the shape has a formula; otherwise from a fine lattice.

### splitShape

*function* · `packages/physics/src/shapes.ts:127`

```ts
function splitShape(s: Shape, n: number): Piece[]
```

Cut a shape into about n box pieces (body space): the bounds cut along their longest edges until there are n cells, the cells whose centre
lies outside the shape dropped and their volume shared among the rest, so the pieces hold the whole volume. A sphere is cut the same way.

### staticsStampOf

*function* · `packages/physics/src/island-step.ts:76`

```ts
function staticsStampOf(bodies: readonly Body[]): number
```

a number that changes when the static bodies change (added, removed, moved): a worker's copy of them is made again then

### sub

*function* · `packages/physics/src/vec.ts:9`

```ts
function sub: (a: Vec3, b: Vec3) => Vec3
```

### syncSurfaces

*function* · `packages/physics/src/host.ts:520`

```ts
function syncSurfaces(host: PhysicsHost, seen: Map<Body, string>)
```

Give every body whose scoped surface changed its new surface (kernels without contact hooks); `seen` keeps what each one has.

### v3

*function* · `packages/physics/src/vec.ts:7`

```ts
function v3: (x?: number, y?: number, z?: number) => Vec3
```

### validateMaterials

*function* · `packages/physics/src/materials.ts:34`

```ts
function validateMaterials(table: unknown, base = 'materials'): Issue[]
```

Check a materials table: numbers only, inside sane ranges. Returns the problems (empty when fine).

### validatePhysicsConfig

*function* · `packages/physics/src/host.ts:176`

```ts
function validatePhysicsConfig(c: unknown, known: string[] = []): Issue[]
```

### volumeBelow

*function* · `packages/physics/src/shapes.ts:157`

```ts
function volumeBelow(s: Shape, p: Vec3, q: [number, number, number, number], y: number): number
```

Volume of the shape below a horizontal surface at height y, the body at p turned by q: by its sample cells (exact for a sphere).

### zoneAtData

*function* · `packages/physics/src/field-kernels.ts:44`

```ts
function zoneAtData(z: ZonesData | undefined, x: number, y: number, zz: number): string | null
```

the zone a point is in: the highest-priority named zone that holds it (later ones win ties), else its grid cell, else none (the zone service's rule)

## Interfaces

### AttractorData

*interface* · `packages/physics/src/field-kernels.ts:70`

```ts
interface AttractorData
```

a point attractor at its centre now, softened

- `centre: Vec3`
- `mu: number`
- `soft: number`
- `range?: number`

### Body

*interface* · `packages/physics/src/kernel.ts:42`

```ts
interface Body
```

- `readonly id: number`
- `readonly kind: BodyKind`
- `readonly shape: Shape`
- `mass: number`
- `invMass: number`
- `invInertia: number`
- `inertia?: Vec3` — principal moments of inertia, kg·m², where the kernel knows them (a box, a hull); a sphere's three are equal
- `position: Vec3`
- `orientation: Quat`
- `velocity: Vec3`
- `angularVelocity: Vec3`
- `force: Vec3`
- `torque: Vec3`
- `material?: string`
- `linearDamping: number`
- `angularDamping: number`
- `gravityScale: number`
- `sleeping: boolean`
- `userData?: unknown`
- `entityId?: string`
- `removed: boolean`
- `exempt?: string[]` — capabilities that leave this body alone (a vessel computes its own weight and buoyancy: ['gravity', 'media'])

### BodyData

*interface* · `packages/physics/src/island-step.ts:10`

```ts
interface BodyData
```

- `id: number`
- `kind: Body['kind']`
- `shape: Body['shape']`
- `mass: number`
- `invMass: number`
- `invInertia: number`
- `position: Vec3`
- `orientation: Body['orientation']`
- `velocity: Vec3`
- `angularVelocity: Vec3`
- `material?: string`
- `linearDamping: number`
- `angularDamping: number`
- `gravityScale: number`
- `sleeping: boolean`
- `entityId?: string`
- `exempt?: string[]`

### BodyDef

*interface* · `packages/physics/src/kernel.ts:21`

```ts
interface BodyDef
```

- `shape: Shape`
- `kind?: BodyKind`
- `mass?: number`
- `position?: Vec3`
- `orientation?: Quat`
- `velocity?: Vec3`
- `angularVelocity?: Vec3`
- `material?: string`
- `linearDamping?: number`
- `angularDamping?: number`
- `gravityScale?: number`
- `lockRotation?: boolean` — No spin: the sphere slides like a block (a crate, a puck) instead of rolling.
- `noCollide?: boolean` — Touches nothing: other bodies pass through it (a pivot pin that only anchors joints). Joints still hold it. A rigid-body kernel only.
- `userData?: unknown`
- `entityId?: string` — the id of the entity the body belongs to (what a field kernel in a worker scopes its values by; userData is not sent to workers)

### Capability

*interface* · `packages/physics/src/host.ts:19`

```ts
interface Capability
```

- `readonly name: string`
- `readonly phase: Phase`
- `readonly order?: number` — Position among capabilities of the same phase (lower first); ties go by name, never by registration.
- `readonly cost?: string` — What it costs, in words, for the inspector and the budget notes.
- `readonly defaults?: Record<string, unknown>` — Values at every scope unless overridden.
- `readonly needsBodies?: boolean` — Needs rigid bodies from the kernel; it refuses to switch on when the kernel has none.
- `readonly requires?: string[]` — Names of capabilities that must be on first.
- `load?(host: PhysicsHost, value: unknown[], scope: 'world' | 'level'): void` — A list in the level's physics block under this capability's name (actuators): handed over when the block is applied.
- `loadBindings?(host: PhysicsHost, value: unknown[]): void` — The level's `physics.bindings` list (actuators): what drives its commands from input, interactables, zones and events. Dropped with the level.
- `unloadBindings?(): void`
- `enable?(host: PhysicsHost): void`
- `disable?(host: PhysicsHost): void`
- `step?(dt: number, host: PhysicsHost, contacts: readonly ContactEvent[]): void` — Phase 'field': add forces for this step. Phases 'strength' and 'stretch': act on what the step did.

### ColliderParams

*interface* · `packages/physics/src/physics.ts:8`

```ts
interface ColliderParams
```

- `shape?: ShapeKind`
- `size?: [number, number, number]` — box: full size (x, y, z)
- `radius?: number` — sphere / capsule radius
- `height?: number` — capsule total height (feet to head)
- `offset?: [number, number, number]` — centre offset from the entity's origin
- `layer?: string`
- `mask?: string[]` — layers this collider overlaps with (triggers) or collides with
- `trigger?: boolean` — a trigger fires enter/exit events instead of blocking

### CollisionMeshData

*interface* · `packages/physics/src/collision-world.ts:8`

```ts
interface CollisionMeshData
```

- `positions: Float32Array`
- `indices: Uint32Array`
- `matrix: number[]`
- `name?: string`
- `material?: boolean`
- `normals?: Float32Array`
- `layer?: number`
- `twoSided?: boolean`

