# @ferret/core: API (continued)

### CollectionSpec

*interface* · `packages/core/src/snapshot.ts:18`

```ts
interface CollectionSpec
```

The snapshot contract: what a simulation shows to whoever draws it, as flat typed arrays, and the replica that rebuilds objects from them.

A snapshot spec says which fields of which objects the render side may read. The simulation side packs them (`SnapshotEncoder`), the render side unpacks
them into plain objects with the same property paths (`Replica`), so code that reads `craft.plane.pos[0]` or `ship.vessel.q` goes on reading it; nothing
else of the simulation is visible across the boundary. Values that move are interpolated between two snapshots by `alpha`, as `World.alpha` does for the
fixed step.

Fields (a path from the object, then a suffix):
  `x`            a number                  `plane.pos:3`   a vector of 3 numbers (any length)
  `plane.pos:3~` interpolated linearly      `plane.q:4~q`   a quaternion (interpolated by normalised lerp)      `heading~a`   an angle in radians (by the short way round)
  `gone?`        a boolean                  `state@idle|walk|board`   one of the listed words (stored as its index)
  `kind$`        a string                   `dmg{}`         any JSON value (a string or JSON field that the source gives as `undefined` is left as it was)
A collection is many objects with the same fields, each with a unique integer key, up to `capacity`; a record is one object.

- `fields: string[]`
- `capacity: number`

### CommandInfo

*interface* · `packages/core/src/commands.ts:8`

```ts
interface CommandInfo
```

- `name: string`
- `description: string`

### FrameBound

*interface* · `packages/core/src/perf.ts:17`

```ts
interface FrameBound
```

which side holds the frame: the GPU when its frame time is most of the frame, else the CPU ('?' without the GPU timer)

- `by: 'cpu' | 'gpu' | '?'`
- `frameMs: number`
- `gpuMs: number`

### Gathered

*interface* · `packages/core/src/scheduler.ts:48`

```ts
interface Gathered<I>
```

what a gather gives: the input, and the buffers to hand over (they are not used here after)

- `input: I`
- `transfer: Transferable[]`

### GuardOptions

*interface* · `packages/core/src/frame-guard.ts:18`

```ts
interface GuardOptions
```

- `game?: string` — the game's name in the reports
- `report?: (line: string) => void` — where a report line goes besides the console and local storage (default: the server's log on https)

### HostWorldOptions

*interface* · `packages/core/src/host.ts:5`

```ts
interface HostWorldOptions extends WorldOptions
```

- `clearColor?: [number, number, number]`

### JobContext

*interface* · `packages/core/src/job-pool.ts:18`

```ts
interface JobContext
```

- `shared: Record<string, SharedArray>`
- `args: any`

### JobPoolOptions

*interface* · `packages/core/src/job-pool.ts:49`

```ts
interface JobPoolOptions
```

- `jobs: Record<string, JobFn>` — the jobs by phase name (the same registry the worker entry gets)
- `spawn?: () => WorkerLike` — makes one job worker; without it, or with `size` 0, every phase runs serially
- `size?: number` — number of workers (default: hardware threads - 2, between 0 and 8)
- `minItems?: number` — a phase with fewer items than this runs serially (the call overhead is more than the work)

### KernelDecl

*interface* · `packages/core/src/scheduler.ts:50`

```ts
interface KernelDecl<I = any, O = any>
```

- `name: string` — the kernel's name in the registry
- `inline?: boolean` — a part its service runs itself at its place in the step (a kernel's step between a service's own phases): listed in the module, left out of the waves
- `module?: string` — the module this part belongs to (set by `Scheduler.module`)
- `sync: 'step' | 'frame'` — `step`: the step waits for it (gameplay, physics; deterministic); `frame`: the page does not wait, the answer is applied at a later step (the view)
- `reads?: string[]` — names of the resources it reads and writes: kernels that do not touch the same resources (one writing what the other reads or writes) run at the same time
- `writes?: string[]`
- `every?: number` — run it every n-th step (default 1)
- `resident?: { key: string; init(world: World): unknown | Gathered<unknown> }` — a state the kernel keeps in its worker (a collision world, a surface): sent by `init` once, again when the worker is lost or `refresh` asks
- `split?: { count(input: I): number; slice(input: I, from: number, to: number): I; merge(outs: O[], input: I): O }` — independent items: cut into one range per worker, each range a kernel call, the answers merged in index order (the result is the same for any number of workers)
- `author?: boolean` — set by the author's short form (`Scheduler.task`): what it is given is looked at, and when it is not plain data the task runs in the game's thread and the engine says why
- `gather(world: World, dt: number): I | Gathered<I> | null` — take the input out of the world here (null: nothing to do at this step)
- `apply(world: World, out: O): void` — write the answer back here

### KernelEntry

*interface* · `packages/core/src/scheduler.ts:16`

```ts
interface KernelEntry
```

- `run: KernelFn`
- `init?: (payload: any, state: Record<string, unknown>) => void`
- `worker: KernelWorker`

### ModuleDecl

*interface* · `packages/core/src/scheduler.ts:103`

```ts
interface ModuleDecl
```

A module's description, written once by the engine's developers: its parts (kernels with what each reads and writes, `step` or `frame`,
and how its data splits), and in words what stays in the game's thread. The step of 9.2 follows from it: parts that touch nothing in common run at the same
time, a part that reads what another writes waits, a split part runs as many pieces as there are workers, the step ends at a barrier.

- `name: string`
- `parts: KernelDecl[]`
- `stays?: string`

### ObservableLike

*interface* · `packages/core/src/scope.ts:17`

```ts
interface ObservableLike<T = unknown, O = unknown>
```

a Babylon `Observable`, as far as the scope needs it

- `add(fn: (e: T) => void, ...rest: any[]): O`
- `remove(o: O): unknown`

### OwnRow

*interface* · `packages/core/src/perf-advice.ts:9`

```ts
interface OwnRow
```

- `name: string` — the slot: `own:name` (a function of the game, timed by its author), `component:Class.onFixedUpdate`, `fixed:service`, `update:service`
- `ms: number` — ms in the game's thread per frame, and its share of the frame
- `share: number`
- `kind: 'own' | 'engine' | 'code'` — `own`: the author's function; `engine`: a module of the engine that is declared to the scheduler; `code`: a component or service no module is declared for
- `say: string` — what the engine says about this row: where it runs and why it is the narrow place

### PacerTick

*interface* · `packages/core/src/frame-pacer.ts:14`

```ts
interface PacerTick
```

Even frame pacing. A frame that takes a little more than one refresh of the display is shown after two, the next after one, then two: the pictures come at uneven
intervals and the motion jerks although the average rate is fair. The pacer draws every k-th refresh instead, k the smallest that the frames keep without being late,
and gives the world exactly k refreshes of time a frame, so things move the same distance every picture.

- the refresh period is learnt from the callbacks that come after one that drew nothing (60 Hz until there are some, less if callbacks come faster);
- a drawn frame that comes later than its slot by more than half a refresh is a miss; misses in more than 4% of the last two seconds of frames raise k at once;
- after four seconds without a miss, k is lowered by one if the frame's own work fits the shorter step with a third to spare; when that brings misses back
  within ten seconds, the shorter step is not tried again for half a minute (the work a frame gives the GPU is not in its own work);
- the time given to the world is k periods while on schedule; a frame really late gets the time that really passed (the world never falls behind the clock).
Pure: no Babylon. `tick(now, work)` is called on every display callback; it says whether to draw and with how much time.

- `draw: boolean`
- `dt: number`

### PerfRow

*interface* · `packages/core/src/perf.ts:14`

```ts
interface PerfRow
```

- `name: string`
- `avgMs: number`
- `worstMs: number`
- `lastMs: number`
- `callsPerFrame: number`

### PerfTrace

*interface* · `packages/core/src/perf.ts:21`

```ts
interface PerfTrace
```

- `frames: TraceFrame[]` — the frames, in order
- `longTasks: { t: number; ms: number }[]` — the main thread's long tasks (over 50 ms) the browser reported, inside frames or between them
- `marks: { t: number; name: string }[]` — what the game marked (an asset loaded, a level shown)
- `done: boolean` — the trace has run its time

### QualityDecision

*interface* · `packages/core/src/quality.ts:73`

```ts
interface QualityDecision
```

- `t: number`
- `id: string`
- `from: number`
- `to: number`
- `why: string`

### QualityKnob

*interface* · `packages/core/src/quality.ts:25`

```ts
interface QualityKnob
```

- `readonly id: string` — unique id, `module.what` ('render.scale', 'perspective.distance', 'crowd.near')
- `readonly load: QualityLoad` — which side of the frame a step down relieves
- `readonly steps: number` — number of steps, 0 the richest, `steps - 1` the cheapest
- `visibility?: number | ((level: number) => number)` — how visible it is to be at `level` (the step about to be taken): the least visible is given up first. Default: 1 for every step
- `apply(level: number): void` — put the knob at `level`
- `ready?(): boolean` — may the knob change now (a framebuffer change only behind a fade, say); default yes
- `active?(): boolean` — is the knob in play now (a headset knob only during a session); default yes
- `label?: string`

### QualityOptions

*interface* · `packages/core/src/quality.ts:43`

```ts
interface QualityOptions
```

- `targetHz?: number | (() => number)` — the frame rate to hold on a flat screen (default 60). A function is read every decision
- `xrHz?: () => number` — the headset's display rate while a session runs (the XR service sets it); a positive value wins over `targetHz`
- `floorHz?: number` — a flat screen may settle at this lower steady rate when every knob is spent (never a headset); default none
- `gpuMs?: () => number` — GPU time of the last frame in ms, NaN when unknown (see `gpuTimer`)
- `workMs?: () => number` — CPU work of the last frame in ms (see `frameWork`); without it the wall time stands for it
- `every?: number` — seconds between decisions (0.5), the window measured (1 s), the wait after a change (2 s), the comfort time before a step back (4 s)
- `window?: number`
- `settle?: number`
- `upAfter?: number`
- `late?: number` — a frame is late above this share of the budget (1.08), comfortable below `comfort` (0.7)
- `comfort?: number`
- `remember?: { load(): unknown; save(v: unknown): void } | false` — remember the levels between runs: `load` gives what `save` was given; default: the browser's local storage under `key`
- `key?: string` — the name the levels are remembered under (a game name and a device class are good: 'dunkirk:desktop')
- `auto?: boolean` — start regulating at once (default true); `quality.auto` switches it
- `never?: boolean` — Never lower quality (a game that holds its picture before its frame rate): the regulator is off and cannot be switched on, the levels remembered from earlier runs are not loaded and nothing is saved, every knob stays at its richest (level 0). The commands `quality.set` and `quality.preset` still work by hand.
- `busy?: () => boolean` — something loads now (besides the services' own `qualityBusy()` and the scene's waiting items): the frames are not judged meanwhile

### QualityReport

*interface* · `packages/core/src/quality.ts:74`

```ts
interface QualityReport
```

- `auto: boolean`
- `targetHz: number`
- `budgetMs: number`
- `xr: boolean`
- `frameP95: number`
- `workP95: number`
- `gpuP95: number`
- `by: 'cpu' | 'gpu' | '?'`
- `holds: string[]`
- `knobs: { id: string; load: QualityLoad; level: number; steps: number; pinned: boolean; active: boolean }[]`
- `log: QualityDecision[]`

### ReplicaHooks

*interface* · `packages/core/src/snapshot.ts:131`

```ts
interface ReplicaHooks
```

- `audit?: boolean` — dev check: every read of a property the spec does not declare is recorded in `Replica.undeclared` (the objects are proxies); off by default
- `make?(collection: string, key: number): any` — an object for a key that is new (default `{}`): a game can give it methods or a class
- `remove?(collection: string, key: number, obj: any): void` — an object whose key is no longer in the snapshots

### SchedulerStart

*interface* · `packages/core/src/scheduler.ts:76`

```ts
interface SchedulerStart
```

- `spawn?: (cls: KernelWorker) => WorkerLike` — starts a worker of a class (`webKernelWorker` on a page); without it every kernel runs here
- `threads?: number` — plain workers (default: the cores less two, 1 to 7)
- `babylonThreads?: number` — Babylon workers, started when a kernel needs one (default 1)

### Service

*interface* · `packages/core/src/world.ts:12`

```ts
interface Service
```

A world-wide singleton (the rough equivalent of a UE subsystem): input, levels, zones, physics, ui ...

- `readonly name: string`
- `init?(world: World): void`
- `fixedUpdate?(dt: number): void` — Called before the components' fixed update, at the fixed rate.
- `update?(dt: number): void` — Called once per rendered frame.
- `dispose?(): void`
- `readonly kernels?: KernelDecl[]` — kernels this service declares: taken when the service is added
- `readonly schedule?: ModuleDecl` — a module's description: its parts, what splits, what stays in the game's thread; taken when the service is added
- `fixedUpdateAsync?(dt: number): Promise<void>` — the same step, asynchronous, for a service whose work goes to workers at its place in the step: used by `advanceAsync` when `wantsAsync` says yes
- `wantsAsync?(): boolean`
- `whyHere?(): string | undefined` — why its work stays in the game's thread right now (in words), or undefined when it goes to the cores: what `perf.report` tells the author

### SharedState

*interface* · `packages/core/src/scheduler.ts:86`

```ts
interface SharedState
```

a state kept in workers (see `Scheduler.shared`)

- `call<O = unknown>(kernel: string, input: unknown, transfer?: Transferable[], slot?: number): Promise<O>` — a kernel on the state, in the least loaded worker that holds a copy (or makes one); with a `slot`, in the slot's own worker (slot 0 is the first worker that runs, slot 1 the next, and so on round), which keeps what the kernel left in that worker's copy for the slot's next call
- `update(kernel: string, payload: unknown): void` — change every copy (and those made later) by a kernel
- `readonly copies: number` — how many copies were made
- `drop(): void` — let the workers forget the state (the copies are made again at the next call); for a state that is replaced by a new one

### SimEmitter

*interface* · `packages/core/src/sim-host.ts:15`

```ts
interface SimEmitter
```

- `emit(name: string, data?: unknown): void`

### SimHostOptions

*interface* · `packages/core/src/sim-host.ts:161`

```ts
interface SimHostOptions
```

- `mode?: 'worker' | 'thread'` — where the simulation runs; default: in a worker when `spawn` is given and the platform has workers, else in this thread (`program` needed)
- `spawn?: () => WorkerLike` — worker mode: makes the worker (the entry calls `runSimWorker`)
- `program?: () => SimProgram` — thread mode: the program itself
- `spec: SnapshotSpec`
- `dt?: number`
- `opts?: unknown` — options for `SimProgram.init`
- `shared?: boolean` — share the ring by `SharedArrayBuffer` (needs cross-origin isolation); default: when the environment has it
- `catchUp?: { maxFrame?: number; maxSteps?: number; drop?: number }` — Thread mode: how the simulation catches up after a long frame. At most `maxFrame` seconds of a frame count, at most `maxSteps` steps are taken in one `pump`, and when more than `drop` seconds are owed they are dropped (the machine cannot keep up: slow motion, not a spiral). Default: 0.1 s, 0.15 s worth of steps, 0.25 s.
- `reuse?: boolean` — thread mode: reuse the snapshot buffers (default true)
- `interpDelay?: number` — Worker mode: the drawing runs this many seconds behind the newest snapshot (default 0.05, never less than 2.5 snapshot spacings), on a clock of its own that is steered gently toward that point (at most 10 % faster or slower) and never goes back; the picture is interpolated between the two snapshots round the clock, so snapshots that arrive unevenly (a slow frame, the worker's own jitter) do not show as jerks.
- `hooks?: ReplicaHooks`
- `paused?: boolean` — Created paused: game time does not run until `start()` (thread mode: `pump` does not step; worker mode: the worker does not free-run). A game made so that nothing happens before Ready creates its host paused and starts it when the splash leaves. Default false (thread mode steps from the first `pump`).

### SimProgram

*interface* · `packages/core/src/sim-host.ts:17`

```ts
interface SimProgram
```

- `readonly spec: SnapshotSpec`
- `init(opts: unknown, out: SimEmitter): void | Promise<void>` — called once with the options the host was given, before the first step
- `command(name: string, args: unknown): unknown` — a command from the render side, applied at a step boundary; its result goes back to the caller
- `step(dt: number): void` — one fixed step
- `source(): SnapshotSource` — the objects to show now
- `readonly time: number` — simulation seconds so far
- `snapshotDue?(): boolean` — Is the state worth a snapshot after this step? A program whose world changes only on some steps (a 20 Hz world in 60 Hz steps) says no on the others, so the drawing interpolates between real changes and not between equal snapshots. Default: every step.
- `dispose?(): void`

### SnapshotSource

*interface* · `packages/core/src/snapshot.ts:57`

```ts
interface SnapshotSource
```

what the simulation hands the encoder: where the objects of each collection are, and each object's key

- `collections?: Record<string, { items: Iterable<any>; key: (item: any) => number }>`
- `records?: Record<string, any>`

### SnapshotSpec

*interface* · `packages/core/src/snapshot.ts:19`

```ts
interface SnapshotSpec
```

- `collections: Record<string, CollectionSpec>`
- `records?: Record<string, string[]>` — single objects: name -> fields

### SnapshotView

*interface* · `packages/core/src/snapshot.ts:63`

```ts
interface SnapshotView
```

one snapshot: the time of the simulation it shows, one Float64Array per collection or record ([count, keys..., rows...]) and the rest as JSON

- `tick: number`
- `time: number`
- `data: Record<string, Float64Array>`
- `meta: Record<string, unknown[][]>` — per collection or record: the rows' strings and JSON values, aligned with the rows

### StateSlice

*interface* · `packages/core/src/state-buffer.ts:14`

```ts
interface StateSlice
```

what travels in a kernel's input in place of a typed array

- `$slice: 1`
- `id: number`
- `ctor: string`
- `from: number`
- `to: number`
- `access: Access`
- `buffer?: SharedArrayBuffer`
- `byteOffset?: number`
- `data?: TypedArray`

### TaskPoolOptions

*interface* · `packages/core/src/task-pool.ts:43`

```ts
interface TaskPoolOptions
```

- `spawn?: () => WorkerLike` — starts a worker (`() => webWorker(new URL('task-worker.js', document.baseURI))`); without it, or with `threads` 0, tasks run in this thread, one per turn of the event loop
- `threads?: number` — how many workers (default: the cores less two, 1 to 4)
- `tasks: Record<string, TaskFn>` — the same functions the worker's script has: the fallback in this thread

### TraceFrame

*interface* · `packages/core/src/perf.ts:20`

```ts
interface TraceFrame
```

one frame of a trace: when it ended (ms, page clock), how long it was, and the slots that took at least `minMs` in it

- `t: number`
- `dt: number`
- `slots: Record<string, number>`

### WorkerLike

*interface* · `packages/core/src/sim-host.ts:38`

```ts
interface WorkerLike
```

what a worker and the page's end of it share: the two ends of a Web Worker or a Node worker

- `postMessage(msg: unknown, transfer?: Transferable[]): void`
- `on(event: 'message', fn: (msg: any) => void): void`
- `terminate(): void | Promise<unknown>`

### WorkerPort

*interface* · `packages/core/src/sim-host.ts:134`

```ts
interface WorkerPort
```

The worker's side: call this in the worker's entry with a function that makes the program. `port` is the worker's end (`self` of a Web Worker, or
`parentPort` of a Node worker; use `nodePort`/`webPort` below).

- `post(msg: unknown, transfer?: Transferable[]): void`
- `onMessage(fn: (msg: any) => void): void`
- `close(): void`

### WorkerPortLike

*interface* · `packages/core/src/task-pool.ts:10`

```ts
interface WorkerPortLike
```

- `post(msg: unknown, transfer?: Transferable[]): void`
- `onMessage(fn: (msg: any) => void): void`
- `close(): void`

### WorldOptions

*interface* · `packages/core/src/world.ts:31`

```ts
interface WorldOptions
```

- `fixedStep?: number` — Fixed simulation step in seconds (default 1/60).
- `maxFrame?: number` — Longest real frame time that is simulated, in seconds; a stall is not a jump (default 0.1).

## Types

### Access

*type* · `packages/core/src/state-buffer.ts:12`

```ts
type Access = 'r' | 'w' | 'rw'
```

### CommandFn

*type* · `packages/core/src/commands.ts:6`

```ts
type CommandFn = (args: any) => unknown | Promise<unknown>
```

The debug command channel: named commands that a tool (the inspector, the model viewer, an AI agent over
MCP) calls to look at and change a running world. Commands are plain JSON in, plain JSON out.

### ComponentClass

*type* · `packages/core/src/component.ts:41`

```ts
type ComponentClass<C extends Component = Component> = new (params?: any) => C
```

### Handler

*type* · `packages/core/src/events.ts:2`

```ts
type Handler<T = any> = (payload: T) => void
```

### JobFn

*type* · `packages/core/src/job-pool.ts:19`

```ts
type JobFn = (from: number, to: number, ctx: JobContext) => void
```

### KernelFn

*type* · `packages/core/src/scheduler.ts:13`

```ts
type KernelFn<I = any, O = any> = (input: I, state: Record<string, unknown>) => O | { result: O; transfer: Transferable[] }
```

a kernel: pure, on plain data (typed arrays, numbers, strings, plain objects); `state` is the resident state of its pin in the worker that runs it

### KernelWorker

*type* · `packages/core/src/scheduler.ts:15`

```ts
type KernelWorker = 'plain' | 'babylon'
```

the class of worker a kernel needs: plain (no Babylon), or one that loads Babylon first (ferret-worker-babylon.js)

### LogLevel

*type* · `packages/core/src/log.ts:2`

```ts
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
```

### QualityLoad

*type* · `packages/core/src/quality.ts:23`

```ts
type QualityLoad = 'cpu' | 'gpu' | 'both'
```

### SharedArray

*type* · `packages/core/src/job-pool.ts:16`

```ts
type SharedArray = Float64Array | Float32Array | Int32Array | Uint32Array | Uint8Array | Int16Array | Uint16Array
```

### TaskFn

*type* · `packages/core/src/task-pool.ts:7`

```ts
type TaskFn = (payload: any, state: Record<string, unknown>) => unknown | { result: unknown; transfer: Transferable[] }
```

a task: the result, or `{ result, transfer }` to hand typed arrays' buffers back without a copy

### TypedArray

*type* · `packages/core/src/state-buffer.ts:8`

```ts
type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array
```

### Undo

*type* · `packages/core/src/scope.ts:14`

```ts
type Undo = () => void
```

Scoped registration: a view of the world that records what a docked level adds and takes all of it back when the level goes.
Commands, components, behaviours, services, event handlers, entities, Babylon observers, DOM listeners and intervals made through the scope are undone by `dispose`,
newest first. A game that is not docked never makes one, so nothing changes for it. A name clash with the parent is the level's own error and is thrown as it is
without a scope (`Registry.register`); a command of the same name replaces the parent's for the time of the level and is given back after it.

## Constants

### BABYLON_VERSION

*const* · `packages/core/src/version.ts:11`

```ts
const BABYLON_VERSION: "9.33.1"
```

the Babylon version this engine was built and tested with

### FERRET_BUILD

*const* · `packages/core/src/version.ts:13`

```ts
const FERRET_BUILD: string
```

the build stamp `yyyymmddHHMM` in the LOCAL time of the build machine, never UTC; `dev` when the code runs unbuilt (tests, the repository)

### FERRET_VERSION

*const* · `packages/core/src/version.ts:9`

```ts
const FERRET_VERSION: "0.1.0"
```

the engine's version (semver); every module of a release shares it

### FERRET_VERSION_FULL

*const* · `packages/core/src/version.ts:15`

```ts
const FERRET_VERSION_FULL: string
```

what to show a person: `0.1.0+202611051430`

