# @ferret/core: API

World, fixed-step loop, entities and components, services, event bus, logging and the debug command channel.

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

## Classes

### CommandChannel

*class* · `packages/core/src/commands.ts:10`

```ts
class CommandChannel
```

- `register(name: string, description: string, fn: CommandFn): void`
- `has(name: string): boolean`
- `unregister(name: string, restore?: { fn: CommandFn; description: string }): boolean` — Take a command back; the one it had replaced (a `register` of the same name overwrites) is given back with it.
- `entry(name: string): { fn: CommandFn; description: string } | undefined` — What is registered under the name now (to keep for `unregister`'s `restore`).
- `list(): CommandInfo[]`
- `async execute(name: string, args: any = {}): Promise<unknown>`

### Component

*class* · `packages/core/src/component.ts:11`

```ts
abstract class Component<P extends object = Record<string, any>>
```

A component is a plain class attached to an entity. Parameters come from the manifest (`params`).
Hooks: onAttach (attached), onStart (first fixed step after attach), onFixedUpdate(dt) at the fixed rate,
onUpdate(dt) once per rendered frame, onDetach (removed or entity destroyed).

- `entity: Entity`
- `started: boolean`
- `enabled: boolean`
- `constructor(public params: P = {} as P)`
- `get world(): World`
- `get scene(): BABYLON.Scene`
- `get node(): BABYLON.TransformNode`
- `onAttach?(): void`
- `onStart?(): void`
- `onFixedUpdate?(dt: number): void`
- `onFixedUpdateAsync?(dt: number): Promise<() => void> | null` — The same step for a component whose work can go to the workers: called instead of `onFixedUpdate` when the world steps asynchronously and `wantsAsync` is true. It takes what it needs from the component at its place in the step and returns a promise of the function that puts the result back; the world calls those functions in the order of the components when every component has had its turn, so a component after this one sees the result at the next step. It returns null to say that this step cannot go (the component then runs `onFixedUpdate` in its place).
- `wantsAsync?(): boolean` — the component class has work for the workers now (cheap: the world asks every step); a component that registers itself in `world.asyncComponents` is asked
- `onUpdate?(dt: number): void`
- `onDetach?(): void`
- `kernels?: KernelDecl[]` — kernels this component declares: taken at its first fixed step, dropped when it is detached
- `schedule?: ModuleDecl` — a module's description: taken at its first fixed step like `kernels`

### Entity

*class* · `packages/core/src/entity.ts:8`

```ts
class Entity
```

An entity wraps a Babylon TransformNode and carries components.

- `readonly id: string`
- `readonly components: Component[]`
- `readonly tags: Set<string>`
- `timeDilation: number` — Per-entity time dilation (a game may slow its NPCs). 1 = normal.
- `destroyed: boolean`
- `data: Record<string, any>`
- `constructor(readonly world: World, readonly node: BABYLON.TransformNode, id?: string)`
- `get name(): string`
- `get position(): BABYLON.Vector3`
- `add<C extends Component>(cls: ComponentClass<C> | string, params?: any): C`
- `get<C extends Component>(cls: ComponentClass<C> | string): C | undefined`
- `require<C extends Component>(cls: ComponentClass<C> | string): C`
- `remove(c: Component): void`
- `destroy(): void`

### EventBus

*class* · `packages/core/src/events.ts:5`

```ts
class EventBus
```

Small event bus. `emit` calls handlers synchronously, in subscription order.

- `on<T = any>(name: string, fn: Handler<T>): () => void`
- `once<T = any>(name: string, fn: Handler<T>): () => void`
- `off(name: string, fn: Handler): void`
- `emit<T = any>(name: string, payload?: T): void`
- `clear(): void`

### FramePacer

*class* · `packages/core/src/frame-pacer.ts:16`

```ts
class FramePacer
```

- `k: number` — refreshes per drawn frame
- `period: number` — the display's refresh period, ms (learnt)
- `constructor(readonly o: { maxK?: number; minPeriod?: number } = {})`
- `tick(now: number, lastWork = 0): PacerTick` — a display callback at `now` (ms); `lastWork` the ms the previous drawn frame's own work took (its callback)

### FrameProfiler

*class* · `packages/core/src/perf.ts:36`

```ts
class FrameProfiler
```

- `enabled: boolean`
- `window: number` — the window, in frames, over which the worst value is kept (the previous window's worst stays shown until the new one has one)
- `external: boolean` — true when the game calls `endFrame` itself (it runs its own loop); the world then leaves it alone
- `frames: number`
- `frameMs: number` — the whole frame, ms (wall clock between two `endFrame` calls), as a moving average and the worst
- `frameWorst: number`
- `time<T>(name: string, fn: () => T): T` — time `fn` into slot `name`
- `own<T>(name: string, fn: () => T): T` — time a function of the game's own into slot `own:name`: the report of what the game's code costs in the game's thread lists it with its share and what would take it off
- `begin(): number` — start a span: pass the result to `end`
- `end(name: string, t0: number): void`
- `add(name: string, ms: number): void` — add a measured span (ms) to the slot's frame total
- `probe(name: string, read: () => number): void` — a number read at the end of every frame and kept like a span (a probe may return NaN to say "not available")
- `endFrame(): void` — close the frame: every slot's total goes into its average and worst, the probes are read, the totals reset
- `bound(): FrameBound` — which side holds the frame, from the moving averages (the GPU's frame time comes from the `gpu:frame` probe of `instrumentScene`)
- `startTrace(seconds = 60, minMs = 1): void` — Record every frame for `seconds` (turns the profiler on): its length and the slots of at least `minMs` in it, the browser's long tasks, and the game's marks. For the start of a game: where the long frames come from. Read it with `trace()`.
- `mark(name: string): void` — a moment worth seeing in the trace (only while a trace runs)
- `stopTrace(): void`
- `trace(): PerfTrace | null` — the trace so far (null when none was started)
- `report(prefix?: string): PerfRow[]` — the slots, the most expensive first (names starting with `prefix` only, when given)
- `text(top = 24, prefix?: string): string` — the report as aligned text, with the frame line first
- `reset(): void`

### JobPool

*class* · `packages/core/src/job-pool.ts:66`

```ts
class JobPool
```

- `readonly size: number`
- `readonly shared_: Record<string, SharedArray>`
- `stats: { parallel: number; serial: number; }` — runs counted by how they ran, for the perf report
- `constructor(private o: JobPoolOptions)`
- `shared<T extends SharedArray>(name: string, ctor: Ctor<T>, length: number): T` — make (or fetch) a shared array every job can read and write by `name`
- `map(phase: string, n: number, args?: unknown): void` — run `phase` over items 0..n-1; returns when every item is done
- `async dispose(): Promise<void>`

### Logger

*class* · `packages/core/src/log.ts:5`

```ts
class Logger
```

- `level: LogLevel`
- `sinks: Array<(level: LogLevel, scope: string, msg: string) => void>` — Sinks receive every line at or above `level`; the OS Beroun platform adds one that posts to the shell's log.
- `constructor(readonly scope: string)`
- `debug(m: string)`
- `info(m: string)`
- `warn(m: string)`
- `error(m: string)`

### QualityService

*class* · `packages/core/src/quality.ts:94`

```ts
class QualityService implements Service
```

- `readonly name: "quality"`
- `get auto(): boolean` — the regulator is on (never true for a service made with `never`)
- `set auto(v: boolean)` — the regulator is on (never true for a service made with `never`)
- `readonly never: boolean` — this service never lowers quality (see `QualityOptions.never`)
- `readonly log: QualityDecision[]`
- `constructor(private o: QualityOptions = {})`
- `init(world: World): void`
- `register(knob: QualityKnob): void` — add a knob; a level remembered from an earlier run is put back at once
- `unregister(id: string): void`
- `scopedView(keep: (undo: () => void) => void): this` — The service as a docked level sees it (`Scope.view`): the knobs the level registers are taken off with the level.
- `has(id: string): boolean`
- `level(id: string): number`
- `hold(reason: string): void` — nothing changes while a hold is on (assets loading, a level coming in); the frames meanwhile are not counted
- `release(reason: string): void`
- `preset(share: number): void` — every knob at a share of its range (0 the richest, 1 the cheapest); the regulator goes on from there when it is on
- `targetHz(): number` — the frame rate being held now
- `update(): void` — Called once per rendered frame.
- `report(): QualityReport`
- `text(): string` — one line for the `?perf` overlay
- `dispose(): void`

### Registry

*class* · `packages/core/src/registry.ts:3`

```ts
class Registry<T>
```

A name -> constructor registry. A manifest names components and behaviours; games register the classes.

- `constructor(readonly kind: string)`
- `register(name: string, item: T): this`
- `unregister(name: string): boolean` — Take a registration back (a docked level's scope does at its end). Returns whether there was one.
- `get(name: string): T`
- `has(name: string): boolean`
- `names(): string[]`

### Replica

*class* · `packages/core/src/snapshot.ts:142`

```ts
class Replica
```

the objects of the last snapshot applied: plain objects with the spec's property paths, the same objects from frame to frame while their key lives

- `readonly codec: SnapshotCodec`
- `readonly lists: Record<string, any[]>` — each collection's objects in snapshot order (one array per name, kept and refilled)
- `readonly byKey: Record<string, Map<number, any>>` — each collection's objects by key
- `readonly records: Record<string, any>` — each record's object
- `tick: number`
- `time: number`
- `readonly undeclared: Set<string>` — the reads of undeclared properties seen while `audit` is on: "collection.path"
- `constructor(spec: SnapshotSpec | SnapshotCodec, private hooks: ReplicaHooks = {})`
- `apply(cur: SnapshotView, prev?: SnapshotView | null, alpha = 1): void` — Rebuild the objects from `cur`; with `prev` and `alpha` the interpolated fields are between the two (0 is `prev`, 1 is `cur`).

### ResidentLost

*class* · `packages/core/src/task-pool.ts:9`

```ts
class ResidentLost extends Error
```

a pinned task lost its worker (and the state the worker kept for its pin); the caller sets the state up again and asks again

- `constructor(readonly pin: string)`

### Roles

*class* · `packages/core/src/roles.ts:10`

```ts
class Roles implements Service
```

The roles of a parent game: a mechanism a game has at most once (the player's character, the camera, the input, the net room, the menu ...).
The parent `provide`s what it holds; while a level is docked (`dock`), the engine's own entry points that make a role (`spawnCharacter`, `CameraRig`, a service of the
same name) ask `takeOver` first, so code written for a game of its own that makes "its" character or camera gets the parent's instead, unless the level brings that role itself (`has`).
With no parent and no dock nothing here changes anything: `takeOver` makes what it is asked to make.

- `readonly name: "roles"`
- `provide(role: string, impl: unknown): () => void` — The parent gives its implementation of a role (an instance). Returns the way to withdraw it.
- `holds(role: string): boolean`
- `get<T = unknown>(role: string): T | undefined`
- `list(): string[]`
- `dock(level: string, has: Iterable<string> = []): () => void` — A level is docked: `has` are the roles it brings itself. Returns the way to end the dock.
- `get docked(): string | undefined` — the level docked now, if any
- `get given(): string[]` — The roles the docked code asked for and was given the parent's instance of (for the converter's run and the tests).
- `parentAnswers(role: string): boolean` — Is the parent's instance of the role the answer now: a level is docked, the parent holds the role and the level does not bring it.
- `takeOver<T>(role: string, make: () => T): T` — What an engine entry point calls to make a role: the parent's instance when it answers, else `make()`.

### RowLayout

*class* · `packages/core/src/snapshot.ts:29`

```ts
class RowLayout
```

the layout of one object's fields in a row of numbers (and the strings that go in the meta part)

- `readonly fields: Field[]`
- `stride: number`
- `metaCount: number`
- `constructor(specs: readonly string[])`

### SceneHost

*class* · `packages/core/src/host.ts:16`

```ts
class SceneHost implements Service
```

The scene host: the place for a second `World` over a second `Scene` on the same `Engine`, so a game's
interlude can be an ordinary scene with its own lights, camera and behaviours while the target level loads in the main one.
Both scenes share the GL context, shaders and texture caches. **Only the active world is rendered** (rendering both cost 15x in
WebKit, S0). The main world always advances (its services - ui, net, input - keep running, and its `paused` flag still decides
whether the simulation steps); another world advances only while it is the active one.

- `readonly name: "host"`
- `constructor(readonly engine: BABYLON.AbstractEngine)`
- `init(world: World): void`
- `get main(): World` — The world the level service builds into and the game normally plays in.
- `get active(): World` — The world that is advanced and rendered now.
- `worlds(): World[]`
- `get(name: string): World | undefined`
- `nameOf(w: World): string | undefined`
- `create(name: string, opts: HostWorldOptions = {}): World` — A new world over a new scene on the shared engine. It is not shown until `show`. The game owns what is in it.
- `show(world: World): void` — Show a world: from the next frame it is the one advanced and rendered. The one that was shown is not advanced any more.
- `showMain(): void` — Show the main world again (a travel does this when the player is let in, and when a transition fails).
- `dispose(world?: World): void` — Dispose a world the game created, with its scene (all of them with no argument: the service's own dispose). If it is shown, the main world is shown first.
- `advance(realDt: number): void` — One real frame: advance the main world, and the active one if it is another.
- `async advanceAsync(realDt: number): Promise<void>` — `advance` with the worlds' declared `step` kernels in the scheduler's workers (the same as `advance` when no world needs it)
- `get pooled(): boolean` — true when a world's step waits for kernels in workers: the loop then calls `advanceAsync`
- `render(): void` — Render the active world's scene.

### Scheduler

*class* · `packages/core/src/scheduler.ts:113`

```ts
class Scheduler
```

- `stats: { runs: number; inWorkers: number; applied: number; lost: number; }` — counts: kernel runs in all, in workers, and of `frame` kernels the answers applied
- `constructor(private readonly world: World)`
- `start(o: SchedulerStart): void` — start the pools (a game does it in createGame); before it, and with no `spawn`, kernels run here
- `startLike(o: Scheduler): void` — start with the options another scheduler was started with (a second world of the same game)
- `stop(): void`
- `respawn(): void` — drop the workers that run kernels and start new ones when a kernel next needs them (the spawn of the page changed: a docked level's kernels came or went); resident state is lost, as when a worker dies
- `get threads(): number` — workers that run kernels now (plain and Babylon)
- `get pooled(): boolean` — true when the step must be asynchronous: `step` kernels are declared and workers run them
- `readonly MIN_PIECE_MS: 0.15` — a piece cheaper than this is not worth a message
- `readonly PIECES_PER_WORKER: 4` — pieces per worker when a kernel is worth cutting: more pieces than workers, so a worker that is done takes the next (the pool's queue)
- `pieces(name: string, n: number, threads: number): number` — how many pieces a split kernel of n items is cut into: by its measured cost (one piece when the whole is cheap), the first time by the workers' number
- `workerStats(): { cls: KernelWorker; threads: number; workers: { tasks: number; ms: number }[] }[]` — per class of worker: how many workers and what each did (tasks finished, ms spent in them)
- `costOf(name: string): number | undefined` — the measured cost per item of a split kernel, ms (undefined before its first run)
- `declare(d: KernelDecl, owner?: unknown): () => void` — declare a kernel; `owner` lets `dropOwner` take all of an owner's kernels away. Returns the undeclare
- `task<I, O>(spec: { name: string; gather(world: World, dt: number): I | null; apply(world: World, out: O): void; sync?: 'step' | 'frame'; each?: boolean; reads?: string[]; writes?: string[]; every?: number }, owner?: unknown): () => void` — The author's short form: a task whose function is registered by `defineTask(name, fn)` in the game's src/kernels.ts. `gather` takes plain data out of the world (null: nothing to do), `apply` puts the answer back. `each` says the data is a list of independent items (the answer a list of as many): it is cut over the cores and put together in order. `frame` instead of `step` lets the page go on and applies the answer a step later. When the data is not plain (a node, a world, a function) the task runs in the game's thread and `Scheduler.stays()` / `scheduler.info` say why.
- `stays(): { task: string; why: string }[]` — the tasks that stay in the game's thread, and why (in words an author can act on)
- `dropOwner(owner: unknown): void`
- `refresh(name: string): void` — the resident state of a kernel is sent again before its next run (the world it holds changed)
- `module(m: ModuleDecl, owner?: unknown): () => void` — declare a module: all its parts, under the module's name; one undeclare for all
- `modules(): { name: string; stays?: string; parts: { name: string; sync: string; reads: string[]; writes: string[]; split: boolean; resident: boolean }[] }[]` — the declared modules: their parts (reads, writes, how each runs) and what stays in the game's thread
- `list(): { name: string; sync: string; owner: string; module?: string; resident?: string }[]` — the declared kernels
- `main: Scheduler | undefined` — the scheduler of the game's main world (the first one started, with workers or without): what views and loaders use when they are given none
- `shared(key: string, init: { kernel: string; payload: () => unknown }, o: { replicas?: number } = {}): SharedState` — A state kept in workers and asked by calls outside the step (a land to build chunks of, a collision world to sweep in): `init` is the kernel that sets it up from `payload()`, `update` adds to it (every copy, also those made later, gets every update in order). Calls go to the least loaded worker, each of which holds its own copy (at most `replicas`, default all), and to this thread when there are no workers. A copy lost with its worker is made again.
- `spent(kernel: string): { calls: number; ms: number }` — the worker time (ms) all finished calls of a kernel took so far, and how many calls: what a service measures its cost by
- `call<O = unknown>(name: string, input: unknown, transfer: Transferable[] = [], pin?: string): Promise<O>` — one call of a kernel outside the step (loading work): in a worker when there is one, here otherwise; never blocks the page
- `stepHere(dt: number): void` — the `step` kernels of this step, here, in waves (the synchronous step: tests, world.step, a world with no workers)
- `async stepPooled(dt: number): Promise<void>` — the `step` kernels of this step in the workers: each wave gathers, runs at the same time, applies in declaration order
- `endStep(dt: number): void` — the `frame` kernels at the end of a step: answers that came are applied (in declaration order), idle due ones are started. With no workers they run here at once and are applied at the next step, so the answer is one step late either way
- `dispose(): void`

### Scope

*class* · `packages/core/src/scope.ts:19`

```ts
class Scope
```

- `readonly entities: Set<Entity>` — the entities spawned while the scope was open: those still alive are destroyed with it
- `constructor(readonly world: World, readonly namespace: string)`
- `get closed(): boolean`
- `get size(): number` — how many takings-back wait
- `add(undo: Undo): Undo` — Keep `undo` for the end of the scope (run at once when the scope is closed already). Returns a function that runs it now and forgets it.
- `on<T = any>(event: string, fn: Handler<T>): Undo` — An event handler on the world's bus.
- `command(name: string, description: string, fn: CommandFn): Undo` — A command; the one it replaced is given back.
- `component(name: string, cls: ComponentClass): Undo` — A component class under a name of the manifests.
- `behaviour(name: string, cls: ComponentClass): Undo` — A behaviour class under a name of the manifests.
- `service<S extends Service>(s: S): S` — A service; it is disposed and removed with the scope. A service the parent already has under that name is the parent's role: it is given back (seen through the scope, `view`) and left alone.
- `view<S>(service: S): S` — A service of the parent as the scope's code sees it: its `scopedView` when it has one (what the code adds to it is then taken back with the scope), else the service itself.
- `observe<T, O>(obs: ObservableLike<T, O>, fn: (e: T) => void): O` — An observer of a Babylon observable (`scene.onBeforeRenderObservable`); removed with the scope.
- `listen(target: EventTarget, type: string, fn: EventListenerOrEventListenerObject, opts?: boolean | AddEventListenerOptions): Undo` — A DOM listener; removed with the scope.
- `interval(fn: () => void, ms: number): Undo` — `setInterval`, stopped with the scope.
- `async capture<R>(fn: () => R | Promise<R>): Promise<R>` — Run `fn` and take back every DOM listener and interval that the code it runs adds meanwhile (`EventTarget.prototype.addEventListener`, `setInterval`): the code of an example that was written for its own page reaches for `window` and `document` itself. Only for the span of the call (the promise it returns is awaited), so what the parent's own code adds at the same time would be caught too: dock while the parent has nothing to add (under the transition video). A worker, a message port and a channel are their maker's own and their listeners stay: the engine's pools make their workers the first time one is needed, which may be while a level installs, and they live on after it.
- `dispose(): void` — Take everything back, newest first; the entities that are left are destroyed. Safe to call twice.

### SimHost

*class* · `packages/core/src/sim-host.ts:202`

```ts
class SimHost
```

- `readonly replica: Replica`
- `readonly dt: number`
- `readonly mode: 'worker' | 'thread'`
- `readonly transport: 'ring' | 'transfer' | 'direct'` — snapshot transport actually in use
- `paused: boolean`
- `tick: number` — the most recent tick shown and the ticks that passed unseen (the render side was slower than the simulation)
- `skipped: number`
- `constructor(o: SimHostOptions)`
- `ready(): Promise<void>` — resolves when the program has initialised
- `on(name: string, fn: (data: any) => void): () => void`
- `command<T = unknown>(name: string, args?: unknown): Promise<T>` — send a command; it is applied at the next step boundary, in the order sent. The promise gives the program's answer.
- `pause(on = true)` — worker mode: start or stop the free-running simulation. Thread mode: pumped by `pump`.
- `start()`
- `step(n = 1)` — n steps by hand (a paused simulation, a test)
- `pump(now: number): void` — Call once a frame with the time in seconds. Thread mode steps the simulation by the time that passed (at most five steps); worker mode takes the snapshots that came. Then the replica is rebuilt, interpolated by how far into the step the render time is, and events are delivered.
- `alpha(now: number): number` — the renderer's alpha between the previous and the current snapshot at `now`
- `async dispose(): Promise<void>`

### SnapshotCodec

*class* · `packages/core/src/snapshot.ts:70`

```ts
class SnapshotCodec
```

- `readonly layouts: Map<string, { layout: RowLayout; cap: number; record: boolean; }>`
- `constructor(readonly spec: SnapshotSpec)`
- `static size(cap: number, stride: number): number` — numbers in the buffer of one collection of capacity `cap` and row width `stride`: the count, the keys, the rows
- `sizes(): Record<string, number>`
- `encode(src: SnapshotSource, tick: number, time: number, into?: (name: string, size: number) => Float64Array): SnapshotView` — Pack the objects of `src` into buffers. `into` gives the buffer to write for a name (a slot of the shared ring: its length is the full capacity) or nothing (a new array of exactly the rows is made).

### StateBuffer

*class* · `packages/core/src/state-buffer.ts:24`

```ts
class StateBuffer<T extends TypedArray = Float64Array>
```

- `readonly id: number`
- `readonly array: T`
- `readonly shared: boolean` — true: the array is in shared memory (slices are windows); false: slices are copies
- `constructor(ctor: new (n: number) => T, length: number, mode: 'auto' | 'shared' | 'copy' = 'auto')`
- `slice(from = 0, to = this.array.length, access: Access = 'rw'): StateSlice` — the range [from, to) for a kernel: `access` says whether the kernel reads it, writes it or both (a copy is made only for what is read)
- `write(from: number, data: TypedArray): void` — the answer's writes arrive here (copy mode)
- `dispose(): void`

### TaskPool

*class* · `packages/core/src/task-pool.ts:52`

```ts
class TaskPool
```

- `readonly threads: number`
- `done: number` — tasks finished, in total, and how many ran in a worker
- `inWorkers: number`
- `readonly worked: { tasks: number; ms: number }[]` — per worker: tasks it finished and the time it spent in them (ms, as the worker measured)
- `constructor(private readonly o: TaskPoolOptions)`
- `get capacity(): number`
- `get pending(): number`
- `spentOn(task: string): { calls: number; ms: number }` — the worker time (ms) all finished calls of a task took so far, and how many calls
- `alive(): { at: number; load: number }[]` — the workers that run (their indices) and the tasks each has in hand
- `pinTo(pin: string, at: number): void` — tie a pin to one worker (-1: this thread) before its first task; a pin already tied keeps its worker
- `pinGeneration(pin: string): number` — the generation of a pin: it changes when the worker that kept the pin's state is gone (0 before the pin's first task)
- `run<T = unknown>(task: string, payload: unknown, transfer: Transferable[] = [], pin?: string): Promise<T>` — run a task; `transfer` hands buffers of the payload over to the worker (they are empty here after). Tasks with the same `pin` run in one worker, in order, and share a state object there (the second argument of the task); if that worker dies they reject with `ResidentLost` and the pin moves on
- `dispose(): void`

### World

*class* · `packages/core/src/world.ts:42`

```ts
class World
```

The World owns the Babylon scene, the fixed-step simulation loop (decoupled from rendering), the clock
with time dilation, the event bus, the services and the entities.

- `readonly events: EventBus`
- `readonly components: Registry<ComponentClass>`
- `readonly behaviours: Registry<ComponentClass>`
- `readonly commands: CommandChannel`
- `readonly entities: Entity[]`
- `readonly fixedStep: number`
- `readonly perf: FrameProfiler` — where the time of a frame goes (off until `perf.enabled`; see perf.ts)
- `readonly scheduler: Scheduler` — the system scheduler: declared kernels of services and components, run in the workers it was started with (`scheduler.start`), here otherwise
- `readonly maxFrame: number`
- `timeScale: number` — Global time scale (slow motion < 1).
- `time: number` — Simulated seconds since the world was created (affected by timeScale, not by entity dilation).
- `tickCount: number` — Number of fixed steps run.
- `paused: boolean`
- `constructor(readonly scene: BABYLON.Scene, opts: WorldOptions = {})`
- `addService<S extends Service>(s: S): S`
- `service<S extends Service = Service>(name: string): S`
- `hasService(name: string): boolean`
- `removeService(name: string): boolean` — Take a service out of the world: its scheduled work is dropped and it is disposed (a docked level's scope does it at its end). Returns whether there was one.
- `forEachService(fn: (s: Service) => void): void` — every service, in the order they were added
- `get alpha(): number` — How far the render frame is between the last two fixed steps (0..1), for interpolating what the camera follows.
- `spawn(name: string, opts: { node?: BABYLON.TransformNode; position?: BABYLON.Vector3; id?: string; tags?: string[] } = {}): Entity` — Make an entity over a new TransformNode (or over an existing node of the scene).
- `removeEntity(e: Entity): void`
- `expose(name: string, get: () => unknown): () => void` — Show a named value of the game to tests and tools: `world.expose('rpm', () => car.rpm)`. Returns the function that takes it back.
- `exposed(name: string): unknown` — The current value of an exposed name; throws with the names there are when the game does not expose it.
- `exposedNames(): string[]` — The names the game exposes.
- `entity(id: string): Entity | undefined`
- `findByName(name: string): Entity | undefined`
- `findByTag(tag: string): Entity[]`
- `entitiesWith<C extends Component>(cls: ComponentClass<C>): Entity[]`
- `advance(realDt: number): number` — Advance by a real frame time: runs as many fixed steps as fit, then the per-frame updates.
- `async advanceAsync(realDt: number): Promise<number>` — `advance` with the declared `step` kernels run in the scheduler's workers (the step waits for them without blocking the page); the same as `advance` when there are none
- `step(): void` — Exactly one fixed step (also the way tests drive the world); declared `step` kernels run here, with the same result as in workers.
- `get stepsAsync(): boolean` — true when the step has work in workers that it must wait for: declared `step` kernels, or a service whose asynchronous step wants to run
- `readonly asyncComponents: Set<Component<Record<string, any>>>` — components that may step in the workers (they add themselves when attached and take themselves out when detached)
- `run(seconds: number): void` — Run the world headless for `seconds` of simulated time.
- `dispose(): void`

## Functions

### addPackageWorkers

*function* · `packages/core/src/web-workers.ts:26`

```ts
function addPackageWorkers(urls: Record<string, string>): () => void
```

a docked level's workers: added to the game's own while the level is current; the returned function takes them away

### buildKernelSpawn

*function* · `packages/core/src/web-workers.ts:69`

```ts
async function buildKernelSpawn(kernels: { path: string; text: string }[]): Promise<{ spawn: ((cls: KernelWorker) => WorkerLike) | null; urls: string[] }>
```

The kernel workers of a game (or a docked level) played from a package: module workers that load the release's kernel module (kernels/plain.js, or after
Babylon kernels/babylon.js), then the game's own kernels from its package (`entry.kernels`, their `@ferret/*` imports pointed at that module, so they register
where the worker runs them), then run. Messages that come while it loads wait. Without the release folder (`FERRET_LIB`) the page's own scripts stay.

### callWithSlices

*function* · `packages/core/src/state-buffer.ts:65`

```ts
function callWithSlices(fn: (input: any, st: Record<string, unknown>) => unknown, input: unknown, st: Record<string, unknown>): unknown
```

Runs a kernel function with the slices of its input turned into typed arrays (the input's own properties, one level deep). With no slices it is a plain call.
With copies, the arrays asked for writing come back in the answer (`finishWrites` on the game's side puts them into their StateBuffers).

### canShareMemory

*function* · `packages/core/src/sim-host.ts:197`

```ts
function canShareMemory(): boolean
```

can a `SharedArrayBuffer` ring be used here: the type exists and (in a page) it is cross-origin isolated

### defaultPoolSize

*function* · `packages/core/src/job-pool.ts:60`

```ts
function defaultPoolSize: () => number
```

### defineTask

*function* · `packages/core/src/task.ts:8`

```ts
function defineTask<I, O>(name: string, run: (input: I) => O): void
```

the function of a task: plain data in, plain data out. Put it in the game's `src/kernels.ts` (the build puts that file in the workers too)

### ensureBabylon

*function* · `packages/core/src/babylon.ts:23`

```ts
function ensureBabylon(...parts: string[]): Promise<void>
```

Make sure the named parts of Babylon are loaded (`core`, `gltf` with the PBR materials, `shadows`, `particles`, `pipeline`, `video`, `debug`; tools/babylon/parts.mjs): fetched from
`globalThis.FERRET_BABYLON` (the folder of the parts, set by the player or the page) and imported once. Resolves at once when they are there.

### finishWrites

*function* · `packages/core/src/state-buffer.ts:80`

```ts
function finishWrites(out: unknown): unknown
```

the game's side of a kernel's answer: the writes of copies go into their buffers, the kernel's own result comes out

### frameWork

*function* · `packages/core/src/quality.ts:364`

```ts
function frameWork(engine: { onBeginFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void }; onEndFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void } }): { read: () => number; stop: () => void }
```

The CPU work of a frame from a Babylon engine: the time from the start of the frame to the end of its rendering (what the frame's JavaScript cost,
without the wait for the next frame). Returns the reader and the function that stops it.

### gameWorker

*function* · `packages/core/src/web-workers.ts:37`

```ts
function gameWorker(name: string): WorkerLike
```

Starts one of the game's own workers by its script name (`gameWorker('sim-worker.js')`): from the game's package when the player runs it, else the script of
that name beside the page (a sample's own page, where tools/build.mjs puts it next to main.js).

### gpuTimer

*function* · `packages/core/src/perf.ts:180`

```ts
async function gpuTimer(engine: BABYLON.AbstractEngine): Promise<{ read: () => number; stop: () => void }>
```

The GPU time of the last frame (ms), from the browser's timer query (`EXT_disjoint_timer_query`); NaN where there is none. For the quality
regulator, without the whole scene instrumentation. Resolves to the reader and the function that stops it.

### guardFrame

*function* · `packages/core/src/frame-guard.ts:49`

```ts
function guardFrame(fn: () => void, o: GuardOptions = {}): () => void
```

wrap a frame callback: an exception is reported (once per kind, then every 100th time with the count) and the loop goes on

### hangWatcherSource

*function* · `packages/core/src/frame-guard.ts:89`

```ts
function hangWatcherSource(base: string, hangMs: number): string
```

The watcher's code (it runs in a Web Worker, as a string). Messages in: `{ v }` the page's visibility (a hidden page has no frames and runs its timers
rarely: not a hang; a change starts both clocks again), `{ a: 1 }` the main thread's timer, `{ b: 1 }` a finished frame (also proof that the thread runs).
Each second: no answer from the main thread for `hangMs` is a stuck thread; an answering thread with no frame for `hangMs` after the first frame is a
frame waiting forever. The first goes to the server's log at once (the main thread cannot send it), and when the stall ends its length goes back to the
page (`postMessage`). Exported for the unit test, which runs it with a fake clock.

### hasBabylonPart

*function* · `packages/core/src/babylon.ts:14`

```ts
function hasBabylonPart(part: string): boolean
```

Is `part` available now: the full build, or a part already loaded?

### hasKernel

*function* · `packages/core/src/scheduler.ts:30`

```ts
function hasKernel(name: string): boolean
```

### instrumentScene

*function* · `packages/core/src/perf.ts:153`

```ts
async function instrumentScene(profiler: FrameProfiler, scene: BABYLON.Scene, engine?: BABYLON.AbstractEngine): Promise<() => void>
```

Babylon's own phases as probes (ms of the last frame): the evaluation of the active meshes, the render targets, the scene render, the animations, the
particles, the sprites, plus the draw calls and the GPU frame time where the browser has the timer query (`gpu` is then NaN-free, else it is left out).
Loads the Babylon part `instrumentation` on a host that serves Babylon in parts. Resolves to the function that stops the instrumentation.

### isSlice

*function* · `packages/core/src/state-buffer.ts:18`

```ts
function isSlice: (v: unknown) => v is StateSlice
```

### kernelNames

*function* · `packages/core/src/scheduler.ts:29`

```ts
function kernelNames(): { name: string; worker: KernelWorker; resident: boolean }[]
```

the registered kernels (names and worker classes)

### kernelWorkerSpawn

*function* · `packages/core/src/web-workers.ts:32`

```ts
function kernelWorkerSpawn(): typeof kernelSpawn
```

the kernel worker spawn now in force (or null: the page's own scripts)

### nodePort

*function* · `packages/core/src/node-workers.ts:23`

```ts
function nodePort(): WorkerPort
```

the worker end, inside a Node worker script

### nodeWorker

*function* · `packages/core/src/node-workers.ts:13`

```ts
function nodeWorker(script: string | URL): WorkerLike
```

the page end of a Node worker started from a script file

### notPlain

*function* · `packages/core/src/task.ts:23`

```ts
function notPlain(v: unknown): string | null
```

what in `v` is not plain data (so it cannot go to a worker), as a path and a reason; null when it is all plain. Looks at most at a few thousand values

### ownReport

*function* · `packages/core/src/perf-advice.ts:23`

```ts
function ownReport(perf: FrameProfiler, scheduler: Scheduler, extra: (slot: string) => string | undefined = () => undefined): { frameMs: number; rows: OwnRow[] }
```

the rows of a profiler that are at least 2% of the frame (and 0.3 ms), with what takes each off the game's thread. Needs `perf.enabled` and a few frames

### perfOverlay

*function* · `packages/core/src/perf.ts:194`

```ts
function perfOverlay(profiler: FrameProfiler, opts: { top?: number; parent?: HTMLElement; extra?: () => string } = {}): () => void
```

A text panel in the corner of the page with the report, refreshed four times a second (a game starts it with `?perf`). Returns the stop function.
Without a DOM it does nothing.

### pointImports

*function* · `packages/core/src/web-workers.ts:60`

```ts
function pointImports(text: string, to: (name: string) => string): string
```

`@ferret/*` imports of a packaged script pointed at `to(name)` (a worker has no import map)

### registerKernels

*function* · `packages/core/src/scheduler.ts:21`

```ts
function registerKernels(kernels: Record<string, KernelFn | { run: KernelFn; init?: KernelEntry['init'] }>, o: { worker?: KernelWorker } = {}): void
```

register kernels by name (a package's src/kernels.ts does it at its top level; the page and the worker bundle both import that file)

### registerSnapshotCommands

*function* · `packages/core/src/snapshot.ts:232`

```ts
function registerSnapshotCommands(world: { commands: { register(name: string, description: string, fn: (a?: any) => unknown): void } }, replica: Replica): void
```

the report of the render side's reads of undeclared fields, for `edit.validate` (`snapshot.audit`), and the spec's own check: declared fields that no object had

### reportLine

*function* · `packages/core/src/frame-guard.ts:36`

```ts
function reportLine(line: string, o: GuardOptions = {}): void
```

record one report line (console, `__ferretErrors`, local storage, the server's log)

### rolesOf

*function* · `packages/core/src/roles.ts:54`

```ts
function rolesOf(world: World): Roles | undefined
```

The roles service of a world, if the parent made one (a world with no dock has none).

### runJobWorker

*function* · `packages/core/src/job-pool.ts:33`

```ts
function runJobWorker(jobs: Record<string, JobFn>, port: WorkerPort): void
```

the worker's end: call in the job worker's entry with the same jobs the pool was made with

### runKernelWorker

*function* · `packages/core/src/scheduler.ts:45`

```ts
function runKernelWorker(port: WorkerPortLike): void
```

the worker bundle's entry: `runKernelWorker(webPort())` after importing every kernels.ts

### runSimWorker

*function* · `packages/core/src/sim-host.ts:138`

```ts
function runSimWorker(make: () => SimProgram | Promise<SimProgram>, port: WorkerPort): void
```

### runTaskWorker

*function* · `packages/core/src/task-pool.ts:19`

```ts
function runTaskWorker(tasks: Record<string, TaskFn>, port: WorkerPortLike): void
```

the worker's script: `runTaskWorker({ analyseTree }, webPort())`

### scopedGame

*function* · `packages/core/src/scoped-view.ts:94`

```ts
function scopedGame<G extends { world: World; scene: object; input?: any }>(game: G, scope: Scope, _roles?: Roles): G
```

`game` seen by the code of a docked level: its world, scene and input are the scoped views; anything else is the parent's own

### scopedInput

*function* · `packages/core/src/scoped-view.ts:78`

```ts
function scopedInput<I extends { dispose(): void; attach(canvas: any, o?: any): void; setPointerLock?(on: boolean): void; pointerLock?: boolean }>(input: I, scope: Scope): I
```

the input as a docked level sees it: the parent's service, which the level may not dispose; `attach` changes only what the level asks (the pointer lock) and is undone with the scope

### scopedScene

*function* · `packages/core/src/scoped-view.ts:51`

```ts
function scopedScene<S extends object>(scene: S, scope: Scope): S
```

`scene` seen by the code of a docked level: its observables (`onBeforeRenderObservable` ...) record the observers they get

### scopedWorld

*function* · `packages/core/src/scoped-view.ts:14`

```ts
function scopedWorld<W extends World>(world: W, scope: Scope): W
```

`world` seen by the code of a docked level

### setKernelWorkerSpawn

*function* · `packages/core/src/web-workers.ts:47`

```ts
function setKernelWorkerSpawn(spawn: ((cls: 'plain' | 'babylon') => WorkerLike) | null): void
```

The player: how this page starts the kernel workers instead of ferret-worker.js beside it (a game played from a package has none there): the engine's
kernel module of the release with the game's own kernels from its package. `null` gives the page's own scripts back.

### setPackageWorkers

*function* · `packages/core/src/web-workers.ts:21`

```ts
function setPackageWorkers(urls: Record<string, string> | Map<string, string>): void
```

the player: the game's packaged workers, by their script name (`sim-worker.js`), each a URL a module worker starts from

### watchHangs

*function* · `packages/core/src/frame-guard.ts:64`

```ts
function watchHangs(o: GuardOptions & { hangMs?: number; onEndFrame?: { add(f: () => void): unknown; remove(x: unknown): void } } = {}): { beat: () => void; stop: () => void }
```

Watch for a stuck main thread from a Web Worker. `beat` is called after every finished frame (pass the engine's end-of-frame observable, or call the
returned `beat` yourself). Returns the stop function. Without Web Workers (a test, OS Beroun) it does nothing.

### webKernelWorker

*function* · `packages/core/src/web-workers.ts:50`

```ts
function webKernelWorker(cls: 'plain' | 'babylon'): WorkerLike
```

the engine's kernel workers of a page: ferret-worker.js, or ferret-worker-babylon.js for kernels that need Babylon, beside the page; for `world.scheduler.start`

### webPort

*function* · `packages/core/src/sim-host.ts:135`

```ts
function webPort: () => WorkerPort
```

### webWorker

*function* · `packages/core/src/web-workers.ts:6`

```ts
function webWorker(url: string | URL, name?: string, type?: 'classic' | 'module'): WorkerLike
```

the page's end of a Web Worker started from a script URL (relative to the page): the same shape as `nodeWorker`, for `SimHost` and `JobPool`; `type` 'module' for an ES module script

### withSlices

*function* · `packages/core/src/state-buffer.ts:87`

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

wrap a registry's tasks so slices in their input work (the worker bundle and the page's fallback use it)

### workersParam

*function* · `packages/core/src/web-workers.ts:55`

```ts
function workersParam(): number | undefined
```

the page's `?workers=N` (0: every kernel here), or undefined

## Interfaces

