# API reference

How to drive the engine from TypeScript: `createGame`, the `Game` object, the wasm `World`'s state and scratch buffers, raycasts and the `window.__pebble3d` probe. The member lists further down are generated by `pnpm docs:gen`.

Task-sized examples: [cookbook/](https://pebble3d.github.io/pebble3d/docs/cookbook/README.md). Where each feature is used in the games: [examples.md](https://pebble3d.github.io/pebble3d/docs/examples.md).

## Imports

| Import | What you get |
| --- | --- |
| `@pebble3d/sdk/game` | `createGame`, `Game`, `PlayerRig`, `Pebble3DHook` |
| `@pebble3d/sdk/schema` | `parseScene`, `SceneSchema`, `SceneInput`, `mergePrefab`, `resolveCollider` |
| `@pebble3d/sdk/expand` | `expandScene` (scene to sim descs and render entities) |
| `@pebble3d/sdk/sim` | `loadSim`, `StateViews`, `SCRATCH_LEN` |
| `@pebble3d/sdk/loop` | `FixedStepLoop` |
| `@pebble3d/sdk/input` | `cameraRelativeInput` |
| `@pebble3d/sdk/types` | `GameStats`, `EntityDescJson` (the JSON `World.spawn` takes) |
| `@pebble3d/renderer` | `createRenderer`, controllers, `ToonNodeMaterial`, `InstanceRegistry`, state-flag constants |
| `@pebble3d/studio-overlay` | `mountOverlay(game, el?, { startVisible })`: the stats overlay |

Wasm URLs come from Vite `?url` imports of `packages/sdk/wasm/det/engine_core_det_bg.wasm` and `packages/sdk/wasm/fast/engine_core_fast_bg.wasm` (see [getting-started.md](https://pebble3d.github.io/pebble3d/docs/getting-started.md#srcmaints-boot-input-probes)).

## createGame

`createGame(opts)` parses and expands the scene, loads the wasm build named by `scene.sim.build`, spawns every entity, builds the renderer and the entity visuals, and returns a `Game`. It does not start: call `game.start()`. Source: `packages/sdk/src/game.ts`.

| Option | Type | Default | Meaning |
| --- | --- | --- | --- |
| `canvas` | `HTMLCanvasElement` | required | Render target. Sized from `clientWidth`/`clientHeight` (DPR capped at 2) and re-sized by a `ResizeObserver`. |
| `scene` | `SceneInput` | required | Scene JSON. Validated with `parseScene`; a bad scene throws `SceneError` with the field path. |
| `wasmUrls` | `{ deterministic: string; fast: string }` | required | URLs of both `_bg.wasm` builds; only the one `scene.sim.build` names is loaded. |
| `mode` | `"realtime" \| "fixed"` | `"realtime"` | `realtime`: ticks follow wall time, at most 5 per frame (the excess is dropped). `fixed`: exactly one tick per frame, render alpha 1 (screenshots, reproducible captures). |
| `stopAtTick` | `number` | none | Fixed mode only: the sim stops advancing at this tick and `__pebble3d.done` turns true once that frame has rendered. |
| `backend` | `"webgpu" \| "webgl"` | `"webgpu"` | A WebGPU request that falls back throws `BackendUnavailable: webgpu`; retry on a fresh canvas with `"webgl"` (`apps/playground/src/main.ts`, lines 200-212). |
| `splatOnly` | `boolean` | `false` | Debug: draw only the splat, no meshes or post. |
| `assetBase` | `string` | `VITE_PEBBLE3D_ASSET_BASE`, else Vite's `BASE_URL`, else `"/"` | Prefix for root-absolute asset URLs (`/assets/...` in the scene, `renderer.loadGltf`, the `/basis/` transcoder). See [cookbook/sub-path-hosting.md](https://pebble3d.github.io/pebble3d/docs/cookbook/sub-path-hosting.md). |
| `webglFallback` | `boolean` | on only with `VITE_PEBBLE3D_WEBGL_FALLBACK=1` or `?webglFallback=1` | When WebGPU is missing, keep WebGL on the same canvas (with a small notice) instead of throwing `BackendUnavailable`. |

What happens each frame, in order:

1. `FixedStepLoop.advance` decides the tick count; `world.step(n)` runs them.
2. Bodies created by spawners are drained (`drainSpawned`) and given visuals (`renderer.addSpawned`).
3. `views.refresh()`, then `renderer.sync(prev, curr, alpha)` interpolates every body.
4. The player callback reads `characterState`, updates the character view and third-person camera, and sends `setCharacterInput` for the **next** tick.
5. Your `onFrame` callbacks run, in registration order.
6. `renderer.render(dt)`; `__pebble3d.frame`/`tick`/`ready`/`done` update.

There is no per-tick hook. To run game rules once per tick, either count `world.tick()` inside `onFrame` (getting-started's `while (sim.tick < world.tick())`) or own the loop (see [cookbook/deterministic-game-loop.md](https://pebble3d.github.io/pebble3d/docs/cookbook/deterministic-game-loop.md)).

## The Game object

| Member | Meaning |
| --- | --- |
| `start()` / `stop()` | Start or cancel the `requestAnimationFrame` loop. `start()` twice is a no-op. |
| `sim` | `SimHandle`: `world` (the wasm `World`), `memory` (its `WebAssembly.Memory`), `build`, `seed`, `spawnScene(entries)`. |
| `views` | `StateViews`: `prev`, `curr` (Float32Array, 8 floats per slot), `scratch` (Float32Array of `SCRATCH_LEN`), `capacity`, `refresh()`. |
| `ids` | `Map<sceneId, simId>`. Includes the generated `__ground` and `__bounds.<side>` statics. Spawner-created bodies are not in it. |
| `player` | `PlayerRig \| null`, the scene's first entity with a `character`: `simId`, `view` (a `CharacterView`), `camera` (`ThirdPersonController` when `camera.controller` is `"thirdPerson"`, else null), `input` (`{ keys: { f, b, l, r }, jump, sprint }`). Keyboard listeners (WASD/arrows, Space, Shift) write `input`; scripts and bots may write it directly. Every frame, 0-tick frames included, `input` is sent with `setCharacterInput`, overwriting any `setCharacterInput` your code made for this character (re-send yours at the end of `onFrame`). Other characters get no animation until you call `renderer.attachCharacter` ([cookbook/character-and-camera.md](https://pebble3d.github.io/pebble3d/docs/cookbook/character-and-camera.md)). |
| `renderer` | `EngineRenderer`: `three` (`renderer`, `scene`, `camera`), `controller` (settable: `dispose()` it and set `null` to own the camera, [cookbook/custom-camera.md](https://pebble3d.github.io/pebble3d/docs/cookbook/custom-camera.md)), `instances`, `dof`, `splatColor`, `style`, `stylize(root)`, `loadGltf(url)`, `assetUrl(url)`, `attachCharacter(simId, clipMap)`, `setCameraPreset(name)`, `reportError(msg)`. |
| `onFrame(cb)` | `cb(dt)` every frame after `renderer.sync`, before `render`. `dt` is wall seconds in realtime and `ticks / 60` in fixed mode (`1/60`, or 0 once stopped). |
| `setCamera(name)` | A camera preset from `camera.presets`, or `"controller"` to hand back to the scene's controller. A preset suspends the third-person camera; the player still moves relative to its yaw. |
| `stats()` | `GameStats` (fps, frameMs, drawCalls, triangles, splats, physicsMs, activeBodies, sleepingBodies, build, tick, errors). Returns the same mutated object every call. |

Read state from `views` only after `views.refresh()`: wasm memory can grow on any spawn, which detaches old typed-array views (they then read as empty, `byteLength` 0). `createGame` refreshes once per frame before `onFrame`; refresh again after you spawn or step yourself. Every world made from the same wasm module shares one memory, so a spawn in one world detaches the views of all the others. Read `views.curr` and `views.scratch` from the `views` object each time; a `Float32Array` kept in a local or a field across calls goes stale.

## State buffers

Each body with a slot occupies 8 `f32` in both `views.prev` and `views.curr` (`STATE_STRIDE = 8`, the renderer's mirror in `packages/renderer/src/dynamics/instances.ts` of the Rust `STRIDE` in `crates/engine-core/src/slots.rs`). Get the slot with `world.slotOf(simId)` (-1 if none); slots are reused after `despawn`.

| Offset | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Value | `px` | `py` | `pz` | `qx` | `qy` | `qz` | `qw` | `flags` |

| Flag bit | Value | Meaning |
| --- | --- | --- |
| `ACTIVE` | 1 | The slot holds a live body (a freed slot reads 0). |
| `SLEEPING` | 2 | Rapier put the body to sleep. |
| `NO_INTERP` | 4 | Snap, don't interpolate: set on spawn and by `teleport`, cleared after the next tick. |

The flags are stored as a float; read them with `views.curr[slot * 8 + 7] & 4` style integer tests (JS converts). The constants are exported from `@pebble3d/renderer` (`ACTIVE`, `SLEEPING`, `NO_INTERP`, `STATE_STRIDE`). `readSlot(prev, curr, slot, alpha, outPos, outQuat)` writes the interpolated pose and honours `NO_INTERP`. `prev` is the pose before the last tick, so `prev + (curr - prev) * alpha` is the render pose.

## Scratch buffer

Query methods write results into a fixed `SCRATCH_LEN` (24) float region at `world.scratchPtr()` and return `true`; `views.scratch` is a view over it. They return `false` and leave the scratch untouched when the id is unknown (or not a character, for `characterState`). Read the values right away: the next query overwrites them.

| Method | Writes | Indices |
| --- | --- | --- |
| `raycast(...)` | `toi, nx, ny, nz, hitId` | `[0..5)` |
| `characterState(id)` | `grounded (0/1), vx, vz, vy` (note the order: vz before vy) | `[8..12)` |
| `linearVelocity(id)` | `vx, vy, vz` (m/s) | `[12..15)` |
| `angularVelocity(id)` | `wx, wy, wz` (rad/s) | `[16..19)` |

`world.scratchLen()` returns 24 and the sdk's `SCRATCH_LEN` mirrors it (a test checks the match). Indices 5-7, 15 and 19-23 are unused.

## Raycasts

```ts
const hit = world.raycast(ox, oy, oz, dx, dy, dz, maxToi, filter, excludeId);
if (hit) {
	const sc = game.views.scratch;
	const dist = sc[0], hitId = sc[4]; // normal: sc[1], sc[2], sc[3]
}
```

| `filter` | Hits | `excludeId` |
| --- | --- | --- |
| `0` | every collider | ignored (pass 0) |
| `1` | static bodies only (ground, bounds, static entities) | ignored |
| `2` | everything except the body of `excludeId` | the entity to skip (the caster itself) |

The direction is normalised for you, so `toi` is metres. `hitId` is the entity id (compare with `game.ids`). Raycasts see the broad phase as of the last `step`: a body spawned since then is invisible until the next tick, and a world that has never stepped misses everything, static floor included. Step a new world once before probing it. A zero direction or `maxToi <= 0` returns false. The third-person camera uses filter 1 so moving props never pull the camera in.

## Body control

All take the entity id and return `false` for unknown ids or the wrong body type.

| Method | Works on | Effect |
| --- | --- | --- |
| `applyImpulse(id, ix, iy, iz)` | dynamic | Adds `impulse / mass` to the velocity (N·s); wakes the body. |
| `applyTorqueImpulse(id, tx, ty, tz)` | dynamic | Angular impulse in **world** axes (N·m·s); the angular velocity changes by the inverse world-space inertia times it. Wakes the body. |
| `setVelocity(id, vx, vy, vz, wx, wy, wz)` | dynamic | Sets linear and angular velocity; wakes the body. |
| `setKinematicPose(id, px, py, pz, qx, qy, qz, qw)` | kinematic | Target pose, reached on the next step. Position and rotation only: colliders cannot be rescaled after spawn. |
| `teleport(id, x, y, z)` | any with a body | Moves instantly, zeroes a dynamic body's velocity, sets `NO_INTERP`. Returns nothing. |
| `setCharacterInput(id, wx, wz, jump, sprint)` | character | World-space XZ direction (clamped to length 1). `createGame` overwrites it every frame for `game.player`. |
| `spawn(json)` / `despawn(id)` | | `spawn` takes an `EntityDescJson` string (camelCase: `position`, `rotation`, `body: { type, mass, friction, restitution, linearDamping, angularDamping, ccd, collider }`, `character`, `spawner`) and returns the id; it throws on bad JSON. Bodies spawned this way get no visual: add one yourself. |

Default mass is collider volume at density 1 (a 1 m box is 1 kg, a 0.5 m radius sphere about 0.52 kg). The inertia tensor comes from the collider shape at uniform density; an explicit `mass` scales it with the mass. Damping defaults to 0, and Rapier has no rolling resistance, so a rolling sphere needs `angularDamping` to ever stop ([cookbook/bodies-impulses-velocity.md](https://pebble3d.github.io/pebble3d/docs/cookbook/bodies-impulses-velocity.md)).

There are no contact or collision events. Detect hits in your rules after each step from positions and velocities (overlap distance, closing speed, an unexplained one-tick velocity change); the bodies recipe has the patterns and the games that use them.

## The `window.__pebble3d` probe

`createGame` installs it; `pnpm shot` and benches read it ([verification.md](https://pebble3d.github.io/pebble3d/docs/verification.md)).

| Field | Meaning |
| --- | --- |
| `ready` | True once the first frame rendered. |
| `done` | Fixed mode: true once the frame at `stopAtTick` rendered. |
| `frame`, `tick` | Frames rendered, current sim tick. |
| `stats()` | `GameStats`. |
| `adapterInfo` | `{ backend, vendor, architecture, device, description }`; `pnpm shot` refuses SwiftShader. |
| `stateHash()` | `world.stateHash()`: 16 hex chars, FNV-1a 64 over the sim state. |
| `setCamera(name)` | As `game.setCamera`. |
| `player()` | `{ position, grounded, velocity, anim, modelMinY, camera, arm }` or null. Allocates. |
| `position(sceneId)` | `[x, y, z]` of a scene entity's body, or null. Allocates. |
| `error` | Set by your `main().catch` so automation reports the failure instead of timing out. |

Add game probes with `Object.assign(window.__pebble3d ?? {}, { game: { score: () => sim.score } })`. `pnpm shot` calls every function in `game` and writes the results to the sidecar. An app that runs its game in its own worlds (Chain Reaction, Ringout, Pebble Garden) must override `stateHash` the same way, `Object.assign(window.__pebble3d ?? {}, { stateHash: () => myWorld.stateHash() })`, or every capture reports `createGame`'s idle world and the hash never changes ([cookbook/owning-the-world.md](https://pebble3d.github.io/pebble3d/docs/cookbook/owning-the-world.md)). An app that boots without `createGame` must install the whole hook itself: `ready`, `done`, `frame`, `tick`, `stats`, `adapterInfo`, `stateHash`, `setCamera` (`apps/rockfall/src/main.ts`, lines 274-322).

## Validating scenes

`parseScene(input)` (and `createGame`) throws a `SceneError` for the **first** problem only, with its `path` (`entities[3].prefab`). To list every problem at once (an editor, an import dialog, a level linter), call `SceneSchema.safeParse(input)` and walk `error.issues`; `formatPath(issue.path)` gives the same path text:

```ts
import { formatPath, SceneSchema } from "@pebble3d/sdk/schema";

const r = SceneSchema.safeParse(json);
if (!r.success)
	for (const i of r.error.issues) console.log(`${formatPath(i.path)}: ${i.message}`);
```

Validation runs in two passes. The cross-field checks (duplicate ids, unknown prefabs, "entity needs a mesh, body or spawner", collider/body combinations) run only once the whole scene passes the field-level schema, so a scene with a bad field reports only field errors; fix those and the cross-field errors appear on the next run.

## Booting without createGame

For a sim that owns its world (bodies created in code, a different tick rate cap, a worker), compose the parts as `apps/rockfall/src/main.ts` does (lines 180-199 and 324-411):

```ts
const scene = parseScene(sceneJson);
const x = expandScene(scene); // x.settings feeds the renderer; x.sim are the spawn descs
const [handle, renderer] = await Promise.all([
	loadSim(scene.sim.build, wasmUrl, { seed: scene.sim.seed, gravity: scene.sim.gravity }),
	createRenderer(canvas, x.settings, { backend: "webgpu" }),
]);
const loop = new FixedStepLoop({ mode, maxTicksPerFrame: 2 });
// per frame: adv = loop.advance(dt, tick); step adv.ticks times;
// views.refresh(); renderer.sync(views.prev, views.curr, adv.alpha); renderer.render(dt);
```

In Node, pass the wasm bytes instead of a URL: `loadSim("deterministic", readFileSync(".../engine_core_det_bg.wasm"))` (`apps/chain-reaction/src/puzzle/node-engine.ts`). More worlds in the same module: `new (handle.world.constructor)(seed, gravity)`; each needs its own `StateViews`-style views and must be `free()`d (`apps/ghostline/src/game/physics.ts`).

## Headless: SimHandle, SimEntry, StateViews

The `@pebble3d/sdk/sim` types you need to run a scene in Node (or own the world in the browser). Full worked example: [cookbook/json-levels-and-headless-verify.md](https://pebble3d.github.io/pebble3d/docs/cookbook/json-levels-and-headless-verify.md#spawn-a-scene-and-read-state-in-node).

| Name | Shape | Notes |
| --- | --- | --- |
| `loadSim(build, wasm, opts?)` | `Promise<SimHandle>` | `wasm` is a URL (browser, async fetch) or the `_bg.wasm` bytes (Node, sync init). `opts`: `{ seed?: number; gravity?: number }`, defaults 1 and -9.81; pass `scene.sim.seed` / `scene.sim.gravity` to match `createGame`. |
| `SimHandle` | `{ world: World; memory: WebAssembly.Memory; build: SimBuild; seed: number; spawnScene(entries: SimEntry[]): Map<string, number> }` | `spawnScene` spawns in order and returns sceneId -> sim id (the same map as `game.ids`). |
| `SimEntry` (`@pebble3d/sdk/types`) | `{ sceneId: string; desc: EntityDescJson }` | What `expandScene(scene).sim` holds: `__ground`, then `__bounds.<side>`, then each entity. `desc` is the JSON `World.spawn` parses (`spawnScene` calls `world.spawn(JSON.stringify(e.desc))`). Entries listed in `pendingHulls` need glTF hull points first; Node skips them. |
| `new StateViews(handle)` | `prev`, `curr`, `scratch` (`Float32Array`), `capacity`, `refresh(): boolean` | Needs only `handle.world` and `handle.memory`, so a second world gets views with `new StateViews({ ...handle, world: w2 })`. Call `refresh()` after spawning or stepping before reading. |

Reading a body: `slot = world.slotOf(id)`, position `views.curr[slot * 8 + 0..2]` ([State buffers](#state-buffers)); velocity `if (world.linearVelocity(id))` then `views.scratch[12..14]` ([Scratch buffer](#scratch-buffer)). In tests, `world.transformOf(id)` returns `[px, py, pz, qx, qy, qz, qw]` (allocates).

Tick order: `createGame` steps physics and then calls `onFrame`, so a headless run that must reproduce a `createGame` app's `stateHash` does `world.step(1); views.refresh();` and then the rules, every tick ([getting-started.md](https://pebble3d.github.io/pebble3d/docs/getting-started.md#tick-order)).

## Generated member lists

Every export of each package, and every `World` method, regenerated from source by `pnpm docs:gen`.

## @pebble3d/sdk

<!-- gen:begin api-sdk -->
### @pebble3d/sdk/types

Source: `packages/sdk/src/types.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `BodyJson` | interface |  |  |
| `CharacterJson` | interface |  |  |
| `ColliderJson` | type |  |  |
| `EntityDescJson` | interface | `{ name?: string; position: Vec3; rotation: Quat; body?: BodyJson \| null; character?: CharacterJson \| null; spawner?: SpawnerJson \| null }` |  |
| `ExpandedScene` | interface | `{ settings: RenderSettings; sim: SimEntry[]; render: RenderEntity[]; pendingHulls: string[] }` |  |
| `GameStats` | interface |  |  |
| `Quat` | type | `[number, number, number, number]` |  |
| `RenderEntity` | interface |  |  |
| `RenderSettings` | interface |  |  |
| `RenderStats` | interface | `{ fps: number; frameMs: number; drawCalls: number; triangles: number; splats: number; textureMB?: number; backend: 'webgpu'\|'webgl' }` |  |
| `SimEntry` | interface | `{ sceneId: string; desc: EntityDescJson }` |  |
| `SpawnerJson` | interface | `{ template: EntityDescJson; rate: number; count: number; areaMin: Vec3; areaMax: Vec3; seed: number }` |  |
| `Vec3` | type | `[number, number, number]` |  |

### @pebble3d/sdk/schema

Source: `packages/sdk/src/schema.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `ANIM_STATES` | const | `readonly ["idle", "walk", "run", "jump", "fall"]` |  |
| `ColliderResult` | type | `{ collider: ColliderJson; pendingHull: boolean } \| { error: string }` |  |
| `ENTITY_DEFAULTS` | const |  |  |
| `ENV_DEFAULTS` | const |  | Per-preset environment defaults, resolved by `expandScene` (they depend on `preset`). |
| `PRIMITIVES` | const | `readonly ["box", "sphere", "capsule", "plane", "cylinder"]` |  |
| `Prefab` | type | `z.output<typeof PrefabSchema>` |  |
| `Scene` | type | `z.output<typeof SceneSchema>` |  |
| `SceneEntity` | type | `z.output<typeof EntitySchema>` |  |
| `SceneError` | class | `new (path: string, message: string)` |  |
| `SceneInput` | type | `z.input<typeof SceneSchema>` |  |
| `SceneSchema` | const |  |  |
| `bodyType` | function | `(e: Prefab) => "dynamic" \| "static" \| "kinematic"` |  |
| `deepMerge` | function | `<T extends Record<string, unknown>>(base: Partial<T>, over: T) => T` | Recursive merge; `over` wins. |
| `formatPath` | function | `(path: readonly PropertyKey[]) => string` |  |
| `mergePrefab` | function | `(scene: Pick<Scene, "prefabs">, e: SceneEntity) => SceneEntity` | The entity with its prefab (if any) merged underneath. |
| `parseScene` | function | `(input: unknown) => Scene` | Validates a scene and fills defaults. |
| `resolveCollider` | function | `(e: Prefab) => ColliderResult` | Resolves `collider` (explicit or `'auto'`) for an entity or prefab that has a body. |

### @pebble3d/sdk/expand

Source: `packages/sdk/src/expand.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `expandScene` | function | `(scene: Scene) => ExpandedScene` | Turns a parsed scene into sim descs (spawned in order: ground, bounds, then entities) and render entities. |

### @pebble3d/sdk/sim

Source: `packages/sdk/src/sim.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `LoadSimOptions` | interface | `{ seed?: number; gravity?: number }` |  |
| `SCRATCH_LEN` | const | `24` | Floats in the wasm query scratch region; mirrors engine-core `SCRATCH_LEN`. |
| `SimBuild` | type | `"deterministic" \| "fast"` |  |
| `SimHandle` | interface | `{ world: World; memory: WebAssembly.Memory; build: SimBuild; seed: number; spawnScene(sim: SimEntry[]): Map<string, number> }` |  |
| `StateViews` | class | `new (h: SimHandle)` | Typed-array views over the wasm state buffers; rebuilt when memory moves or grows. |
| `loadSim` | function | `(build: SimBuild, wasm: BufferSource \| string, opts: LoadSimOptions = {}) => Promise<SimHandle>` | Loads one wasm build. |

### @pebble3d/sdk/loop

Source: `packages/sdk/src/loop.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `FixedStepLoop` | class | `new (opts: FixedStepOptions)` |  |
| `FixedStepOptions` | interface | `{ mode: "realtime" \| "fixed"; dt?: number; maxTicksPerFrame?: number; stopAtTick?: number }` |  |

### @pebble3d/sdk/game

Source: `packages/sdk/src/game.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `AdapterInfo` | interface | `{ backend: "webgpu" \| "webgl"; vendor: string; architecture: string; device: string; description: string }` |  |
| `CreateGameOptions` | interface |  |  |
| `Game` | interface |  |  |
| `Pebble3DHook` | interface |  | Test/automation hook installed on `window.__pebble3d` (read by the shot CLI). |
| `PlayerInput` | interface | `{ keys: MoveKeys; jump: boolean; sprint: boolean }` | The player's held input. |
| `PlayerProbe` | interface |  |  |
| `PlayerRig` | interface | `{ simId: number; view: CharacterView; camera: ThirdPersonController \| null; input: PlayerInput }` | The scene's first character, driven by `input` every frame. |
| `createGame` | function | `(opts: CreateGameOptions) => Promise<Game>` | Builds a running game from a scene: parse, expand, load the sim build, spawn, build the renderer and entity visuals, then drive the fixed-step loop from requestAnimationFrame. |

### @pebble3d/sdk/input

Source: `packages/sdk/src/input.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `MoveKeys` | interface | `{ f: boolean; b: boolean; l: boolean; r: boolean }` |  |
| `cameraRelativeInput` | function | `(keys: MoveKeys, yaw: number, out: Float32Array) => void` | Turns WASD-style keys into a normalised world-space XZ move direction relative to the camera yaw (radians about +Y; yaw 0 looks down -Z). |
<!-- gen:end api-sdk -->

## @pebble3d/renderer

<!-- gen:begin api-renderer -->
Source: `packages/renderer/src/index.ts`

| export | kind | type | summary |
| --- | --- | --- | --- |
| `ACTIVE` | const | `1` |  |
| `AO_RESOLUTION_SCALE` | const | `0.5` |  |
| `AnimClipSpec` | interface | `{ clip: string; speed?: number }` |  |
| `AnimState` | type | `'idle'\|'walk'\|'run'\|'jump'\|'fall'` |  |
| `ArmRaycast` | type | `(origin: Vector3, dir: Vector3, max: number) => number \| null` | Ray query used by the spring arm: origin, unit direction, max distance -> hit toi or null. |
| `CROSSFADE_SECONDS` | const | `0.2` | Cross-fade length between animation states, seconds. |
| `CSM_CASCADES` | const | `3` | Cascaded shadow map settings: 3 cascades, maxFar 120, practical splits, lightMargin 20. |
| `CSM_LIGHT_MARGIN` | const | `20` |  |
| `CSM_MAX_FAR` | const | `120` |  |
| `CameraController` | interface | `{ update(dt: number): void; setPose(position: Vector3, target: Vector3): void; enabled: boolean; dispose(): void }` | Common shape of the camera controllers. |
| `CharacterFrame` | interface | `{ grounded: boolean; vx: number; vz: number; vy: number; sprintSpeed: number }` |  |
| `CharacterView` | class | `new (root: Object3D, clips: AnimationClip[], clipMap: Partial<Record<AnimState, AnimClipSpec>>)` | Drives one character's visuals from its sim state: a state machine over the mapped clips (0.2 s cross-fades, only on a state change) and a facing that slerps toward `atan2(vx, vz)` while moving faster than 0.1 m/s (the model faces +Z at yaw 0). |
| `DOF_DEFAULTS` | const | `{ readonly focus: 5; readonly range: 3; readonly bokeh: 1; readonly backdrop: 30; }` |  |
| `DepthOfFieldControls` | interface | `{ enabled: boolean; focus: { value: number }; range: { value: number }; bokeh: { value: number }; backdrop: { value: number } }` | Opt-in depth of field (photo modes). |
| `EngineRenderer` | interface |  |  |
| `EquirectImage` | interface | `{ data: Uint16Array \| Float32Array; width: number; height: number }` | Minimal view of a decoded equirect `DataTexture` image (RGBA, half or 32-bit float). |
| `FALLBACK_NOTICE_ID` | const | `"pebble3d-webgl-notice"` | `id` of the notice element, so it is shown at most once per page. |
| `FALLBACK_NOTICE_TEXT` | const |  |  |
| `FlyController` | class | `new (camera: PerspectiveCamera, dom: HTMLElement)` | Fly camera: WASD to move, Q/E (or Space/C) down/up, Shift to go fast, drag with a mouse button to look. |
| `IDLE_SPEED` | const | `0.1` | Below this XZ speed (m/s) the character is idle and keeps its facing. |
| `InstanceRegistry` | class | `new (scene: Scene)` | One `InstancedMesh` per key (geometry kind + size + material params). |
| `LoadedSplat` | interface | `{ object: GaussianSplat; count: number; color: SplatColorControls }` |  |
| `LookSpec` | interface | `{ envIntensity?: number; saturation?: number }` |  |
| `MaterialSpec` | interface | `{ color: string; roughness: number; metalness: number; emissive?: string }` |  |
| `MeshSpec` | type |  |  |
| `NO_INTERP` | const | `4` |  |
| `OrbitController` | class | `new (camera: PerspectiveCamera, dom: HTMLElement)` |  |
| `PITCH_MAX` | const | `0.3` |  |
| `PITCH_MIN` | const | `-1.2` |  |
| `RUN_FRACTION` | const | `0.75` | Walk/run boundary as a fraction of `sprintSpeed`. |
| `RenderEntity` | interface |  |  |
| `RenderSettings` | interface |  |  |
| `RenderStats` | interface | `{ fps: number; frameMs: number; drawCalls: number; triangles: number; splats: number; textureMB?: number; backend: 'webgpu'\|'webgl' }` |  |
| `SLEEPING` | const | `2` |  |
| `SPLAT_BUDGET` | const | `1500000` | Soft splat budget: a scene above this many splats logs a warning. |
| `SPLAT_LAYER` | const | `1` | Splats live on this camera layer (meshes stay on layer 0). |
| `SPLAT_LOADERS` | const | `SplatLoaderFactories` |  |
| `STATE_STRIDE` | const | `8` | State buffer layout: 8 f32 per slot, `px,py,pz,qx,qy,qz,qw,flags`. |
| `SplatColorControls` | interface | `{ exposure: { value: number }; saturation: { value: number }; tint: { value: Color } }` | Per-splat colour controls, uniforms so `splatOnly` debug can bypass them at runtime. |
| `SplatConfig` | type | `NonNullable<RenderSettings["splat"]>` |  |
| `SplatFormat` | type | `"spz" \| "splat" \| "ksplat" \| "ply"` |  |
| `SplatLoadError` | class | `new (url: string, cause?: unknown)` | Any failure to produce a splat from `url` (network, parse, unsupported extension). |
| `TOON` | const |  | Toon style (opt-in, `post.style: "toon"`): cel-banded mesh lighting, ink outlines (see `style/outline.ts`) and a posterised splat grade (see `style/splat-grade.ts`). |
| `TOON_DEFAULTS` | const | `ToonSettings` | Defaults of `post.toon` (mirrored by the scene schema). |
| `TOON_INK_CONTEXT` | const | `"getToonInk"` | Scene-pass context key under which the pipeline hands `ToonInk` to toon materials. |
| `ThirdPersonController` | class | `new (camera: PerspectiveCamera, raycast: ArmRaycast)` | Third-person orbit camera on a spring arm. |
| `ToonInk` | interface | `{ edge: Node<"float">; color: Node<"vec3"> }` | What `ToonNodeMaterial` reads from the scene pass context to ink itself. |
| `ToonNodeMaterial` | class |  |  |
| `ToonSettings` | interface |  |  |
| `WEBGL_HDR_MAX_RADIANCE` | const | `16384` | WebGL fallback only: the brightest radiance an HDRI texel may keep before PMREM filtering. |
| `applyLook` | function | `(root: Object3D, look: LookSpec \| undefined) => void` | Applies `look` to every mesh under `root` (load time, once per glTF + look). |
| `applySplatGrade` | function | `(splat: GaussianSplat, g: ToonSettings["splat"]) => void` | Painterly grade of a splat to sit with toon-shaded meshes, per splat (colour stage, so it costs nothing per pixel): the lightness is posterised into `levels` flat values (in a gamma-2 perceptual space) while hue and chroma are kept, saturation is pushed, and a split tone runs from a cool `shadowTint` to a warm `highlightTint`. |
| `attachSound` | function | `(object: Object3D, listener: AudioListener, url: string) => Promise<PositionalAudio>` | Loads `url` (cached) and attaches a (non-looping) `PositionalAudio` to `object`. |
| `bandOf` | function | `(x: number, n: number) => number` | CPU mirror of `bandsOf` without the antialiasing (tests, docs). |
| `createEnvironment` | function | `(renderer: WebGPURenderer, settings: RenderSettings) => Promise<Texture>` |  |
| `createPipeline` | function | `(renderer: WebGPURenderer, scene: Scene, camera: PerspectiveCamera, settings: RenderSettings, opts: { splatOnly?: boolean } = {}) => RenderPipeline` | Single-composite design: one scene pass holds meshes and splats (splats depth-test, no depth write). |
| `createRenderer` | function | `(canvas: HTMLCanvasElement, settings: RenderSettings, opts: { backend: "webgpu" \| "webgl"; splatOnly?: boolean; transcoderPath?: string; assetBase?: string; webglFallback?: boolean; }) => Promise<EngineRenderer>` |  |
| `createShadowCatcher` | function | `(floorY: number, size: number) => Mesh` | An invisible floor at `floorY` that only shows the shadows cast onto it (splats neither cast nor receive shadows). |
| `createSun` | function | `(settings: RenderSettings, camera: PerspectiveCamera) => { light: DirectionalLight; csm: CSMShadowNode }` | The sun: a DirectionalLight placed along `settings.sun.direction` (scene -> sun), shadowing through a `CSMShadowNode`. |
| `defaultAssetBase` | function | `() => string` | The asset base used when `createRenderer` / `createGame` get no `assetBase` option: `VITE_PEBBLE3D_ASSET_BASE` if the app was built with it, else Vite's `BASE_URL` (the `--base` the app was built with, `"/"` by default), else `"/"`. |
| `defaultWebglFallback` | function | `(search: string \| undefined = globalThis.location?.search) => boolean` | Whether the opt-in automatic WebGL fallback is on when `createRenderer` gets no `webglFallback` option: the app was built with `VITE_PEBBLE3D_WEBGL_FALLBACK=1`, or the page URL has `?webglFallback=1`. |
| `envFromSplat` | function | `(renderer: WebGPURenderer, scene: Scene, splat: GaussianSplat) => RenderTarget` | Image-based lighting from a splat capture: a 256 px cube capture of the scene (splat plus the current background, so the sky above the capture still lights from above) from the splat's world bounding-box centre, PMREM-filtered once. |
| `floorProxyViewZ` | function | `(dirViewZ: number, dirWorldY: number, camY: number, floorY: number, backdrop: number) => number` | View-space z (negative, metres) of the floor-plane proxy for a depthless pixel. |
| `loadEnvironment` | function | `(renderer: WebGPURenderer, settings: RenderSettings) => Promise<LoadedEnvironment>` | `outdoor`: `HDRLoader` + `PMREMGenerator` from `settings.hdri`, plus a horizon-coloured haze. |
| `loadSplat` | function | `(cfg: SplatConfig, loaders: SplatLoaderFactories = SPLAT_LOADERS) => Promise<LoadedSplat>` | Loads `cfg.url` (loader by extension), wraps it in a `GaussianSplat` with the authored transform on `SPLAT_LAYER`, and linearises its colour. |
| `loadSplatGeometry` | function | `(url: string, loaders: SplatLoaderFactories = SPLAT_LOADERS) => Promise<BufferGeometry>` | Loads the splat geometry with the loader for its extension; every failure is a `SplatLoadError`. |
| `pickAnimState` | function | `(f: CharacterFrame) => AnimState` | Animation state from the character's sim state. |
| `posterize` | function | `(l: number, levels: number) => number` | CPU mirror of the posterise step: perceptual lightness `l` in [0, 1] to the centre of its band. |
| `primitiveGeometry` | function | `(primitive: Extract<MeshSpec, { kind: "primitive" }>["primitive"], size: [number, number, number]) => BufferGeometry` |  |
| `readSlot` | function | `(prev: Float32Array, curr: Float32Array, slot: number, alpha: number, outPos: Vector3, outQuat: Quaternion) => boolean` | Writes the interpolated (or NO_INTERP-snapped) transform of `slot` into `outPos`/`outQuat`. |
| `resolveAssetUrl` | function | `(url: string, base: string \| undefined) => string` | Prefixes a root-absolute `url` (`/assets/x.glb`) with `base` (`/pebble3d/` gives `/pebble3d/assets/x.glb`). |
| `setToonUniforms` | function | `(s: ToonSettings) => void` | Pushes `s` into the global `TOON` uniforms. |
| `showFallbackNotice` | function | `(doc: Document \| undefined = globalThis.document) => HTMLElement \| null` | Shows a small dismissible notice (bottom-left, above the game) saying the renderer fell back to WebGL. |
| `splatFormatOf` | function | `(url: string) => SplatFormat \| null` | The splat format of `url` from its extension (query and hash ignored), or null. |
| `spreadEquirectPeaks` | function | `(img: EquirectImage, cap: number, half: boolean) => { changed: number; converged: boolean }` | Caps every texel of an equirect RGBA image at `cap` (on its brightest channel) without losing energy: the excess of an over-cap texel is scattered to its 3x3 neighbourhood, weighted by texel solid angle (cos latitude), and repeated until nothing exceeds `cap`. |
| `springArmDistance` | function | `(desired: number, hitToi: number \| null, padding = 0.2, min = 0.5) => number` | Spring-arm length: the desired distance, pulled in to `hitToi - padding` when the arm's ray hits something closer, never below `min`. |
| `stylizeToon` | function | `(root: Object3D) => void` | Swaps every convertible mesh material under `root` for its toon copy (one copy per source material, so sharing is kept). |
| `toneMappingOf` | function | `(name: RenderSettings["toneMapping"]) => ToneMapping` |  |
| `toonInk` | function | `(depth: TextureNode, normal: TextureNode, camera: PerspectiveCamera, pixelRatio: () => number, o: ToonSettings["outline"]) => ToonInk` | Ink-line coverage at the current fragment, from the mesh-only prepass (depth + view normal; splats and transparents never reach it, so the splat gets no lines). |
| `toonMaterialFrom` | function | `(src: Material) => Material` | A `ToonNodeMaterial` copy of a standard / physical material (classic or node), copied key by key as WebGPURenderer converts classic materials (value objects cloned, textures and nodes shared). |
| `unitTint` | function | `(hex: string) => Color` | `hex` as linear RGB scaled to unit luminance (a pure hue/temperature tint). |
| `updateCsmFrustums` | function | `(csm: CSMShadowNode) => void` | Safe to call before the first render: the CSM binds its camera lazily on first build. |
<!-- gen:end api-renderer -->

## World (wasm)

<!-- gen:begin api-world -->
Source: `packages/sdk/wasm/det/engine_core_det.d.ts` (wasm-bindgen output, committed; rebuilt by `pnpm build:wasm` after Rust changes). "Scratch" is the `SCRATCH_LEN`-float region at `scratchPtr()`.

| method | signature | doc |
| --- | --- | --- |
| `constructor` | `new World(seed: number, gravity_y: number)` |  |
| `free` | `free(): void` |  |
| `angularVelocity` | `angularVelocity(id: number): boolean` | Writes `[wx, wy, wz]` to scratch `[16..19)` and returns true, or returns false (scratch untouched) for unknown ids (static bodies read zero). |
| `applyImpulse` | `applyImpulse(id: number, ix: number, iy: number, iz: number): boolean` | Adds a linear impulse to a dynamic body (wakes it). Returns false for unknown ids and non-dynamic bodies. |
| `applyTorqueImpulse` | `applyTorqueImpulse(id: number, tx: number, ty: number, tz: number): boolean` | Adds a torque impulse to a dynamic body (wakes it). Returns false for unknown ids and non-dynamic bodies. |
| `bodyCounts` | `bodyCounts(): Uint32Array` | `[active, sleeping]`. Allocates; call on stats ticks only. |
| `characterState` | `characterState(id: number): boolean` | Writes `[grounded 0/1, vx, vz, vy]` to scratch `[8..12)` and returns true, or returns false (scratch untouched) if `id` is not a character. |
| `despawn` | `despawn(id: number): boolean` |  |
| `drainSpawned` | `drainSpawned(): Uint32Array` | Flat `(id, slot, spawnerSimId)` triples. Call only when `spawnedPending() > 0`. |
| `linearVelocity` | `linearVelocity(id: number): boolean` | Writes `[vx, vy, vz]` to scratch `[12..15)` and returns true, or returns false (scratch untouched) for unknown ids (static bodies read zero). |
| `raycast` | `raycast(ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, max_toi: number, filter: number, exclude_id: number): boolean` | filter: 0 = all, 1 = static-only, 2 = exclude `exclude_id`. On hit writes `[toi, nx, ny, nz, id]` to scratch `[0..5)` and returns true. |
| `scratchLen` | `scratchLen(): number` | `SCRATCH_LEN`: floats in the scratch region (the sdk mirrors it and tests the match). |
| `scratchPtr` | `scratchPtr(): number` | Byte offset of the fixed `SCRATCH_LEN`-float scratch region. |
| `setCharacterInput` | `setCharacterInput(id: number, wx: number, wz: number, jump: boolean, sprint: boolean): void` | World-space XZ direction (clamped to length 1), jump and sprint. No-op for non-characters. |
| `setKinematicPose` | `setKinematicPose(id: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number): boolean` | Sets the pose a kinematic body moves to on the next step. Returns false for unknown ids and non-kinematic bodies. |
| `setVelocity` | `setVelocity(id: number, vx: number, vy: number, vz: number, wx: number, wy: number, wz: number): boolean` | Sets a dynamic body's linear and angular velocity (wakes it). Returns false for unknown ids and non-dynamic bodies. |
| `slotCapacity` | `slotCapacity(): number` | Number of slots (each `STRIDE` = 8 floats) in each state buffer. |
| `slotOf` | `slotOf(id: number): number` | Slot index, or -1 if the entity has no slot. |
| `spawn` | `spawn(desc_json: string): number` | Parses an `EntityDesc` JSON string and spawns it. Throws with the Rust message on error. |
| `spawnedPending` | `spawnedPending(): number` |  |
| `stateHash` | `stateHash(): string` | FNV-1a 64 state hash as 16 lowercase hex characters. |
| `statePtrCurr` | `statePtrCurr(): number` | Byte offset of the curr buffer in `memory.buffer`. Changes when buffers grow. |
| `statePtrPrev` | `statePtrPrev(): number` | Byte offset of the prev buffer in `memory.buffer`. Changes when buffers grow. |
| `step` | `step(n: number): void` |  |
| `teleport` | `teleport(id: number, x: number, y: number, z: number): void` |  |
| `tick` | `tick(): number` |  |
| `transformOf` | `transformOf(id: number): Float32Array \| undefined` | `[px,py,pz,qx,qy,qz,qw]`, or undefined. Debug/tests only (allocates). |
<!-- gen:end api-world -->
