# @ferret/levels: API

Level manifests, the level registry, load, unload and travel, environment and the `.ferret` package format.

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

## Classes

### AssetLibrary

*class* · `packages/levels/src/library.ts:148`

```ts
class AssetLibrary implements Service
```

- `readonly name: "asset-library"`
- `qualityBusy(): boolean` — for the quality regulator (`QualityService` finds it): something of the library is loading
- `constructor(private readonly o: AssetLibraryOptions)`
- `init(world: World): void`
- `async find(q: LibraryFind = {}): Promise<LibraryCard[]>` — Candidates for a request, from the service: a keyword search that returns a generous set (`car` brings `carbon` too), as cards for the one who asks to read and pick from. The library is English only: whoever asks translates the user's words first. The service returns at most 200 candidates, so `offset` pages within them.
- `async open(url?: string): Promise<Catalog>` — Open the catalog (once; again to refresh).
- `list(q: LibraryQuery = {}): LibraryEntry[]` — Items of the catalog, filtered; no package is opened.
- `rubrics(under?: string): RubricNode[]` — The tree of the library with the number of items in each rubric (`under`: only that branch, itself included).
- `has(ref: string): boolean`
- `versionsOf(id: string, e: CatalogAsset = this.cat.assets![id]): string[]` — the versions of an item (the server's numbers, oldest first): those of its package that hold it; a catalog made before versions has 1.0.0 only
- `entry(ref: string): LibraryEntry` — An item by reference (`id` or `id@version`), with the version it resolves to: the reference's own, else the version the package is already open at, else 1.0.0, else (an item added by a later version of its package) the first version that holds it. Never the latest.
- `previewUrl(ref: string): string | undefined` — Absolute URL of an item's preview image (from the catalog, nothing is opened).
- `async pkg(pkgId: string): Promise<FerretPackage>` — The package of the catalog, open in the mount (with its dependencies), at the version this instance selected (default 1.0.0, never the latest).
- `async item<T extends LibraryItem = LibraryItem>(ref: string): Promise<T>` — The item file, read from its package.
- `async impostor(id: string, pose?: string): Promise<{ entry: ImpostorEntry; bytes: Uint8Array } | null>` — The baked impostor of an item and its packed atlas bytes (`@ferret/perspective`'s `unpackAtlas` reads them): the item's own (`impostor`), or for a character the one of a pose (`impostors[pose]`: stand, walk, sit...). Null when the item has none.
- `async url(ref: string): Promise<string>` — A URL the engine's loaders can read for a `ferret://<package>/<path>` reference (a clip set's file, a map).
- `async texture(id: string, o: { scene?: BABYLON.Scene } = {}): Promise<Partial<Record<TextureChannel, BABYLON.Texture>>>` — The maps of a texture item as Babylon textures (colour spaces set: base colour and emissive are sRGB, the others linear).
- `async image(id: string, channel: TextureChannel): Promise<ImageBitmap>` — one map of a texture item as a decoded image (no colour conversion), for code that packs maps itself (the ground's texture arrays of
- `material(id: string, o: MaterialOptions = {}): Promise<BABYLON.PBRMaterial>` — A PBR material from a material item (and a variant of it): the description maps one to one to `PBRMaterial`.
- `async clipsOf(characterId: string, o: { compatible?: boolean } = {}): Promise<ClipRef[]>` — The clip sets a character names (and the clip sets of its skeleton in the catalog), with the reference of each file.
- `async bindClips(c: LibraryCharacter, o: BindOptions = {}): Promise<BoundClips>` — Put the clip sets of a character on its bones (matched by bone name; a clip set is loaded once however many bodies use it). Waits for the model. `groups` are one AnimationGroup per clip name, ready for an `Animator` or `group.start()`.
- `async character(id: string, o: CharacterOptions = {}): Promise<LibraryCharacter>` — A character in the world at once (a placeholder until the model is in).
- `async model(id: string, o: ModelPlacement = {}): Promise<LibraryModel>` — A static model of the library in the world at once (a placeholder of its bounds until the file is in).
- `async modelRef(id: string, tier?: LibraryTier): Promise<string>` — The `ferret://` file of a static model (its tier chosen as `model()` does): what a placement list names by library id.
- `placementResolver(): PlacementResolver` — What placement lists (`*.placements.json`, placements.ts) need to find models and materials of this library by id; give it to the package loader's `placements`.
- `async attach(character: LibraryCharacter, partId: string, o: AttachOptions = {}): Promise<LibraryCharacter | null>` — Hang a part (a weapon, a hat, a rider) on a body that is in, by a socket of the body's item (`sockets`: a bone and an offset) or by a bone and an offset of your own. The part follows the bone through every clip. Resolves with the part (dispose it to take it off), or null when the body or the bone is not found. Offsets are in the glTF's own space: metres of the bone's local frame and a quaternion.
- `async module<T = Record<string, unknown>>(id: string): Promise<T>` — A ready-made package of code (a `module` item): its package is opened through the catalog with its dependencies, its code runs once under the code policy (`code` of the options: the library's own origin, or a signature), checked against the sha256 in its manifest, and its exports come back. The same module asked twice runs once. `const sea = await library.module<typeof import('sea')>('sea-surface'); new sea.SeaView(scene)`.
- `soundFormat(item: SoundItem, o: { format?: 'wav' | 'mp3'; tier?: LibraryTier } = {}): 'wav' | 'mp3'` — Which file of a sound item a device takes.
- `async sound(id: string, o: SoundOptions): Promise<LibrarySound>` — A sound item made playable: its file is read from the package, handed to the audio service and defined there with the item's bus, volume, loop (and loop points) and distance falloff.
- `async flipbook(id: string): Promise<{ item: FlipbookItem; files: Partial<Record<keyof FlipbookItem['files'], Uint8Array>> }>` — A flipbook item and the bytes of its images (the encoded files, by name: color, light, light2, motion, depth). Decoding them into textures is the effects view's work, so this stays free of the drawing code.
- `async volume(id: string): Promise<{ item: VolumeItem; bytes: Uint8Array }>` — A volume item and its voxel bytes (frames x z x y x x, one byte per channel per voxel).
- `async preload(id: string, tier?: LibraryTier): Promise<void>` — Bring an item's files to the device now (a model's file, a texture's maps), so a later call does not wait.
- `release(): void` — Free what the library made: materials, textures, characters. Packages stay open (they cost the mount nothing but the index).
- `dispose(): void`

### CatalogClient

*class* · `packages/levels/src/catalog.ts:37`

```ts
class CatalogClient
```

- `readonly registrations: CatalogRegistration[]` — every catalog registered through this client, in order
- `constructor(private readonly levels: LevelService, private readonly mount: PackageMount, private readonly store: AssetStore, private readonly defaults: CatalogOptions = {})`
- `async register(url: string, o: CatalogOptions = {}): Promise<CatalogRegistration>`

### ClipPlayer

*class* · `packages/levels/src/fmdl-motion.ts:223`

```ts
class ClipPlayer
```

the skeletal clips of a model on its own skeleton: a graph with a state of the first clip, montages over it

- `readonly groups: Record<string, BABYLON.AnimationGroup>`
- `readonly graph: AnimGraph`
- `readonly missing: Record<string, string[]>`
- `constructor(scene: BABYLON.Scene, root: Node, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {})`
- `names(): string[]`
- `duration(clip: string): number`
- `play(clip: string, o: { loop?: boolean; rate?: number; blend?: number; mask?: string[] } = {}): Waitable` — play a clip over the graph; a one-shot is done when it ends, a loop when it is stopped
- `stop(clip: string): void`
- `playingNow(): string[]`
- `update(dt: number): void` — one rendered frame
- `dispose(): void`

### CodeLoader

*class* · `packages/levels/src/code.ts:65`

```ts
class CodeLoader
```

- `constructor(readonly world: World, readonly mount: PackageMount, private o: CodeLoaderOptions = {})`
- `list(): LoadedCode[]` — The code loaded so far, in load order.
- `exports(id: string): LibraryModule | null | undefined` — The exports of a loaded package's code, or undefined.
- `require(id: string, range = '*'): Promise<LoadedCode>` — Load the code of a package (and of its dependencies first) and run its `install` once. Resolves at once when it is loaded; concurrent calls share one load. Rejects with the reason when the package may not run code or something is missing.
- `dispose(): void` — Call the `dispose` that `install` returned, newest first (the modules themselves stay: a page cannot unload them).

### CollisionChunks

*class* · `packages/levels/src/collision-chunks.ts:32`

```ts
class CollisionChunks
```

Keeps the chunks round the player resident. `update` is cheap (a few dozen boxes); fetching and instancing happen in the background.

- `constructor(private def: CollisionChunksDef, private assets: PackageAssets, private at: (file: string) => string, private name: string, private places: () => [number, number, number][], private onError: (message: string) => void = () => {})`
- `async ready(): Promise<void>` — Start the chunks near `places` and wait for them (the level is not playable before the ground round the spawn is solid).
- `update(): void`
- `get loaded(): number`
- `dispose(): void`

### DependencyError

*class* · `packages/levels/src/dependencies.ts:36`

```ts
class DependencyError extends Error
```

- `constructor(message: string, readonly id: string, readonly range: string, readonly tried: { url: string; error?: string }[])`

### DependencyResolver

*class* · `packages/levels/src/dependencies.ts:40`

```ts
class DependencyResolver
```

- `readonly opened: OpenedDependency[]` — every dependency opened by this resolver, in the order it was opened
- `constructor(private readonly o: DependencyOptions)`
- `async find(id: string, range = '*', extra: readonly string[] = []): Promise<OpenedDependency | null>` — Find a package by id and range in `extra` (searched first) and then the resolver's own catalogs, and open it. Null when no catalog has it; throws a DependencyError that names every catalog tried and why when one has it but not in range, or none could be read.
- `async openAll(pkg: FerretPackage, into: DependencyTarget, base: string): Promise<OpenedDependency[]>` — Open every dependency of `pkg` (and theirs) that `into` does not hold yet, and add it there. `base` is the URL `pkg` was loaded from: its own relative `catalogs` are read from there. A dependency that is open already must fit its range. Returns what was opened.
- `hook(extra: readonly string[] = []): (id: string, range: string) => Promise<FerretPackage | null>` — The code loader's `open` hook: a package required later (by id) is searched in the resolver's catalogs.

### FmdlModel

*class* · `packages/levels/src/fmdl.ts:35`

```ts
class FmdlModel
```

A resolved model with its files loaded: every glTF any level of it needs is read once and shared by every placement. Building a level is then synchronous
(a lazy rung of the perspective backend makes its meshes when first shown).

- `static async load(resolved: ResolvedModel, read: FileReader, scene: BABYLON.Scene, o: FmdlLoadOptions = {}): Promise<FmdlModel>` — The plans of the levels this device draws, loaded: read every file of every level, once.
- `plan(level: number): AssemblyPlan` — the plan of a level (the device tier applied)
- `build(level: number, name = `${this.resolved.id}:${level}`): BABYLON.TransformNode` — The nodes of one level of the model, with every included instance placed on it. The meshes are instances of the loaded glTF's, so a thousand of the same model share their vertex data. The node is not parented: the caller hangs it where it belongs and disposes it.
- `stageModel(): { id: string; resolved: ResolvedModel; read: FileReader; make(level: number, name: string): { root: BABYLON.TransformNode; plan: AssemblyPlan } }` — This model as something a `ModelStage` can place by name (`fmdl-motion.ts`): the nodes of a level and the plan they were made from.
- `ladder(o: { impostor?: string } = {}): ModelRung[]` — The ladder this device draws the model by: its levels, the impostor, the point (`ladderOfModel`); throws, naming them, when thresholds were not measured.
- `async place_entity(entity: Entity, backend: BabylonBackend, o: { impostor?: string; coherence?: { kind?: string; link?: number; gap?: number }; fade?: number; keepFrames?: number; /** the entity does not move once placed: the meshes of a rung keep their world matrices from the moment they are made (the CPU cost of thousands of parts) */ static?: boolean } = {}): Promise<Perspective>` — Give an entity this model, drawn by size on the screen: a lazy rung for each level (made when first shown, dropped when long unused), the impostor rung from the model's baked atlas, the point from the atlas's look. Like models are one coherent group (`coherence.kind` is the model's id, or the one given), so a field of atoms is drawn as one: neighbours never differ by a level. Returns the entity's `Perspective` component.
- `bounds(): { centre: Vec3; radius: number }` — The bounding sphere of the whole in its own frame (its finest level, includes placed), measured once: the lazy rungs have no meshes to measure until shown.

### LevelService

*class* · `packages/levels/src/levels.ts:114`

```ts
class LevelService implements Service
```

The level registry and travel between levels. `travel(id)` shows the loading screen (events), removes the old level with
everything it made, builds or loads the new one, moves the persistent entities (the player) to the spawn point and announces
the new level. Events: `level:loading` { id, progress }, `level:ready` { id, report }, `level:unloaded` { id }, `level:failed` { id, error }.
`state` is the game's data that survives travel and goes to `Platform.state` with `saveData`.

- `readonly name: "levels"`
- `state: Record<string, unknown>` — persistent state across levels: inventory, flags, health ... plain JSON
- `readonly spawns: Map<string, SpawnPoint>`
- `readonly transitions: TransitionRegistry` — the game's transitions: register them by name and choose which one a travel uses
- `current: LevelDef | null`
- `travelling: boolean`
- `report: LevelReport`
- `animGraphs: Record<string, any>` — the animation graphs of the current level package (its manifest's `animGraphs`), by name
- `movement: Record<string, number>` — the player character values of the current level package (its manifest's `movement`), over the engine's defaults
- `libraries?: (manifest: import('./manifest').LevelManifest, levelId: string) => Promise<void>` — plugged in by `installLevelLibraries` (./libraries): require the libraries a level's manifest needs before the level is built
- `packageLoader?: (ctx: LevelContext, level: LevelDef, report: LevelReport) => Promise<void>`
- `readonly persistent: Set<Entity>` — entities that always travel with the player (the player itself): they are placed at the spawn, never removed
- `constructor(readonly opts: LevelOptions = {})`
- `init(world: World)`
- `register(def: LevelDef): this`
- `unregister(id: string): boolean` — Remove a level from the registry (a catalog that no longer lists it). The level being played is not touched.
- `replace(def: LevelDef): this` — Register, or replace a level of the same id that is not the one being travelled to (a catalog update).
- `catalogs?: { register(url: string, o?: unknown): Promise<unknown> }` — Plugged in by `installCatalogs` (./catalog): the remote levels of a catalog.
- `registerCatalog(url: string, o?: unknown): Promise<unknown>` — Fetch a catalog and register its levels; needs `installCatalogs`.
- `has(id: string): boolean`
- `get(id: string): LevelDef`
- `list(): LevelDef[]`
- `exempt(e: Entity): this` — An entity that is not part of any level though it appears while one loads (another player's avatar): it is not removed with the level.
- `keep(e: Entity): this` — Entities that go with the player to every level.
- `async travel(id: string, opts: TravelOptions = {}): Promise<LevelReport>`
- `spawn(id?: string): SpawnPoint | null` — The spawn point with that id, or the level's default one.
- `place(e: Entity, s: SpawnPoint)` — Put an entity at a spawn point (any entity with a CharacterMovement is teleported properly).
- `hold<T>(work: Promise<T>, label = 'artefact'): Promise<T>` — An artefact the level is not ready without. An entity of the level calls this while the level is built (a behaviour's `onAttach`) with the promise of what it still loads (a character's model, its clips). `level:ready` is announced when the last of them has settled, or after `holdMs`; a rejected one is a warning of the report. Outside a travel the hold is ignored. Returns the promise.
- `get holding(): number` — how many holds of the level being built are not taken up yet or still open
- `unload()`
- `onUnload(fn: () => void)` — Run `fn` when the current level is removed (release assets, clear a service).
- `saveData(): { level: string | null; state: Record<string, unknown> }` — What to hand to `Platform.saveState`: the game's state and where the player is.
- `loadData(data: { level?: string | null; state?: Record<string, unknown> } | null | undefined): string | null` — Restore what `saveData` made; returns the level to travel to (or null).
- `dispose()`

### LightBudget

*class* · `packages/levels/src/light-budget.ts:192`

```ts
class LightBudget
```

- `readonly def: LightBudgetDef`
- `onChange?: (entered: number[], left: number[]) => void` — called after a re-ranking when real lights changed hands: indices that entered and left the pool
- `onSounds?: (start: number[], stop: number[]) => void` — called when the nearest lamps with a sound change: indices to start and to stop
- `constructor(readonly scene: BABYLON.Scene, def: LightBudgetDef, readonly opts: LightBudgetOptions = {})`
- `get clustered(): boolean` — is every lamp a real light through clustered lighting
- `get name()`
- `get size()`
- `get real(): number[]` — the lights that are real now (fading ones included)
- `get glowMesh()`
- `glowSize(i: number): number` — the size in metres of lamp `i`'s glow dot now (0: hidden, because it is a real light or out of reach)
- `get lights(): (BABYLON.PointLight | BABYLON.SpotLight)[]`
- `stats(): LightBudgetStats`
- `setBudget(n: number)` — change the budget while running (a quality switch): the pool grows or shrinks, and the next re-ranking fills it
- `update(dt: number)` — one step of the budget: `dt` seconds since the last. It runs by itself every frame; tests call it with a clock of their own
- `dispose()`

### LookPlugin

*class* · `packages/levels/src/material-models.ts:149`

```ts
class LookPlugin extends BABYLON.MaterialPluginBase
```

- `readonly structure: LookStructure`
- `readonly define: string`
- `active: boolean`
- `constructor(material: BABYLON.Material, readonly look: LookDef, readonly masks: Record<string, BABYLON.BaseTexture>)`
- `getClassName()` — Gets the current class name useful for serialization or dynamic coding.
- `deactivate()`
- `prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines)` — a material with no texture of its own draws without UVs unless asked: the masks are read at the first set
- `prepareDefines(defines: BABYLON.MaterialDefines, scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh)` — Sets the defines for the next rendering
- `isReadyForSubMesh()` — Specifies that the submesh is ready to be used.
- `getActiveTextures(t: BABYLON.BaseTexture[])` — Returns an array of the actively used textures.
- `hasTexture(t: BABYLON.BaseTexture)` — Checks to see if a texture is used in the material.
- `getAttributes(attributes: string[], _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh)` — Gets the attributes used by the plugin.
- `getSamplers(samplers: string[])` — Gets the samplers used by the plugin.
- `getUniforms()` — Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos)
- `bindForSubMesh(ubo: BABYLON.UniformBuffer, scene: BABYLON.Scene)` — Binds the material data.
- `dispose(force?: boolean)` — Disposes the resources of the material.
- `getCustomCode(shaderType: string): Record<string, string>` — Returns a list of custom shader code fragments to customize the shader.

### ModelCatalogue

*class* · `packages/levels/src/fmdl-catalogue.ts:25`

```ts
class ModelCatalogue
```

- `add(resolved: ResolvedModel, authorText = ''): this` — a resolved model: the description is made from it (`authorText` is the free part of its `description.md`)
- `has(id: string): boolean`
- `ids(): string[]`
- `list(q: { text?: string; kind?: string; tag?: string; abstract?: boolean } = {}): ModelListing[]` — the models whose words match, best first; the words of a sentence are taken one by one (short and filler words are left out)
- `describe(id: string): ModelDescribed`

### ModelDocks

*class* · `packages/levels/src/fmdl-docks.ts:69`

```ts
class ModelDocks
```

- `constructor(readonly stage: ModelStage, private o: DocksOptions = {})`
- `dispose(): void`
- `parse(ref: string): { actor: Actor; dock: string }` — `<actor>#<dock>` split into the actor and the dock; the dock may be left out when the actor has just one free dock
- `frame(actor: Actor, dock: string): { matrix: BABYLON.Matrix; local: BABYLON.Matrix }` — the dock's frame in the world: the node it sits on and the frame on it, as the loader places them (6.2)
- `describe(name: string): DockInfo[]` — every dock of an actor, and of the models included in it, with the words that say what goes there
- `docked(): DockedPair[]` — the pairs docked now
- `dock(aRef: string, bRef: string, o: DockOptions = {}): DockedPair`
- `undock(ref: string, other?: string): DockedPair[]` — take a pair apart (`undock('h1', 'o')`), or everything an actor or a dock holds (`undock('h1')`, `undock('o#bond-1')`)
- `save(): { fmdlDocks: DockedPair[] }` — the docked pairs as plain JSON: what a level or a game's saved state holds, and what a replica is sent
- `restore(saved: { fmdlDocks: DockedPair[] }): void` — Make the docked pairs of a save (or of the host's replica) true here: pairs that are not in it are undocked, the ones that are missing are docked. A pair is docked where its actors already are (`place: false`: the save was made with them in place, a replica has their poses from the net), so a restored pair does not move anything; a `bond` is rebuilt by its backend, which puts the atoms in the molecule's shape again.

### ModelPrograms

*class* · `packages/levels/src/fmdl-programs.ts:33`

```ts
class ModelPrograms
```

- `constructor(readonly stage: ModelStage, private host: ProgramHost)`
- `find(target: string, ref: string): { actor: Actor; resolved: ResolvedModel; name: string; motion: ModelMotion }` — the motion a name leads to on an actor (the instance's actor, for `<instance>/<name>`)
- `args(resolved: ResolvedModel, name: string, motion: ModelMotion, given: Record<string, unknown> = {}): Record<string, Value>` — the arguments checked against `params` (types, unknown names) and the defaults filled in
- `missingForms(motion: ModelMotion): string[]` — the forms the motion itself uses (`requires.forms` of the motion) that the language does not have: running it needs only those
- `missingModelForms(resolved: ResolvedModel): string[]` — the forms a whole model needs (its `requires.forms`, which holds those of all its motions) that the language does not have: a player refuses the model before running it
- `checkModel(target: string): void` — throws, naming the forms, when this runtime lacks one the actor's model needs
- `async run(target: string, ref: string, args: Record<string, unknown> = {}): Promise<Program>` — Start a motion on an actor. The file is read first (once), so the program is returned when it has started.
- `runNow(target: string, ref: string, args: Record<string, unknown> = {}): Program` — the same for a caller that cannot wait (a command, a form): the files must have been read by `preload`
- `async preload(target: string): Promise<void>` — read every motion file of an actor's model and of the models included in it
- `resolver()` — the `motionResolver` of the actuators' capability: `motion.run { motion, target, args }`

### ModelStage

*class* · `packages/levels/src/fmdl-motion.ts:296`

```ts
class ModelStage
```

The placed models of a world by name. A `Service` of `@ferret/core`: add it to the world and its clock is the fixed step's; in a test call `step`.

- `readonly name: "fmdl-stage"`
- `readonly actors: Map<string, Actor>`
- `constructor(private o: StageOptions = {})`
- `time(): number`
- `fixedUpdate(dt: number): void`
- `update(dt: number): void`
- `step(dt: number): void`
- `addModel(model: StageModel): this`
- `modelIds(): string[]`
- `adopt(name: string, id: string, root: Node, plan: AssemblyPlan, from?: string): Actor` — put an already built model on the stage under a name (a model the game made itself)
- `actor(name: string): Actor` — An actor by name. An included instance is addressed `<actor>/<instance>` (and deeper: `<actor>/<instance>/<instance>`): it is the instance's nodes and parts of the whole it is in, seen as an actor of its own, so a motion of the included model runs on it.
- `appear(id: string, o: { name?: string; at?: Vec3; level?: number; scale?: number; parent?: string } = {}): Actor` — a model appears: built on `level`, placed at `at`, named `name` (default `<id>#<n>`)
- `vanish(name: string): void` — take an actor away, with the actors let go from it staying
- `letGo(name: string, instance?: string): string[]` — Let included instances go: each becomes an actor of its own, `<actor>/<instance>`, where it is (its world matrix kept), no longer a part of the whole's nodes. With no instance named, every one. Returns the new names.
- `attachClips(name: string, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {}): ClipPlayer` — put the skeletal clips of an actor on its own skeleton
- `nodeHost(): NodeHost` — the nodes of the actors as handles of the language (`move-along`, `turn-to`)

### OcclusionCulling

*class* · `packages/levels/src/occlusion-culling.ts:21`

```ts
class OcclusionCulling implements Service
```

- `readonly name: "occlusion-culling"`
- `init(world: World): void`
- `get supported(): boolean`
- `get meshes(): number`
- `apply(o: OcclusionOptions): number` — give queries to the level's big meshes (and to those that load later under the root)
- `unapply(): void`
- `qualityKnobs(): QualityKnob[]`
- `dispose(): void`

### OceanView

*class* · `packages/levels/src/ocean.ts:173`

```ts
class OceanView
```

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `get ready(): boolean` — has every depth texture been baked at least once (for loading screens and tests)
- `constructor(private scene: BABYLON.Scene, private o: OceanOptions = {})`
- `setSea(o: { whitecaps: number; streaks: number; wavelength: number; wind: number })` — the state of the sea for its foam and chop: the share of the surface under whitecaps (`seaCondition(...).whitecaps` of
- `setWind(dirDeg: number)`
- `setWaves(list: OceanWave[])`
- `get waves(): readonly OceanWave[]`
- `setLight(o: { toSun: V3; sunColor: V3; light?: number; skyTop?: V3; skyHorizon?: V3; rain?: number })` — the light: the direction TO the sun, its colour, how bright the day is (0..1), the sky colours for a missing cube, the rain 0..1
- `setColors(o: { deep?: V3; shallow?: V3; foam?: number; clarity?: number })` — the colours of the water: deep and shallow (linear 0..1), and how much the crests foam; `clarity`: metres of water the bed shows through (default 4: a murky sea; a clear bay over sand shows its bed through 10 m and more), the shallow colour fades out over 1.5 times that
- `setFog(color: V3 | BABYLON.Color3, density: number)`
- `setReflection(tex: BABYLON.BaseTexture | null)` — the sky the sea mirrors: a cube texture of the sky and its clouds (`createSkyProbe`); null: the two sky colours
- `prime(cam: V3)` — bake the depth round a point at once (a loading screen)
- `update(time: number, cam: V3, level = 0)` — each frame: the clock, the water level, the camera (the grid follows it; the depth boxes move when the camera has gone a quarter of their size)
- `dispose()`

### PackageMount

*class* · `packages/levels/src/ferret.ts:36`

```ts
class PackageMount
```

Connects packages to a LevelService. `add(pkg)` registers the package's levels (as `<id>` for the first package, `<pkgid>/<id>`
for the others, or with the `prefix` given); `url(pkg, path)` gives a blob URL for any file of a package, for sounds, textures
and video. Nothing is unpacked: a file is read from the package when a level asks for it, and a model's blob URL goes when the
level that held it is gone.

- `readonly packages: PackageSet`
- `readonly assets: MountAssets` — give this to the level loader instead of the asset cache (`installPackages` does)
- `readonly loader: PackageLoaderOptions` — the options the level loader runs with: hand this to `installEditor` as its `loader` so the editor's draft shows in reloads
- `constructor(readonly levels: LevelService, private inner: MountAssets, readonly opts: MountOptions = {})`
- `add(pkg: FerretPackage, o: { prefix?: string } = {}): LevelDef[]` — Open a package into the mount and register its levels. Returns what was registered.
- `startLevel(pkg: FerretPackage): string | null` — The level a package starts in (`entry.level` of a game, else its first), as registered.
- `async url(pkg: FerretPackage, path: string): Promise<string>` — A blob URL for a file of a package (`path` inside `pkg`, or `ferret://other/path`). Stays valid until `dispose`.
- `async fetch(url: string): Promise<FetchResult>` — The loader's `fetch` for package urls; anything else goes to the real one.
- `forget(pkgId: string): void` — Drop everything cached for a package (its blob URLs): it was replaced by another version.
- `dispose(): void`

### PartRig

*class* · `packages/levels/src/fmdl-motion.ts:71`

```ts
class PartRig
```

- `readonly parts: Map<string, Part>`
- `readonly children: Map<string, PartRig>` — the rigs of the included instances by instance name
- `constructor(readonly root: Node, readonly plan: AssemblyPlan, private clock: () => number = () => 0)`
- `names(): string[]` — every moving part's address, the instances' as `<instance>/<part>`
- `has(address: string): boolean`
- `value(address: string): number` — the value of a part now (radians for a hinge or a rotor, metres for a slider), the moves brought up to the clock
- `limits(address: string): [number, number] | null`
- `kind(address: string): 'hinge' | 'slider' | 'rotor'`
- `set(address: string, v: number): number` — jump to a value, held inside the part's limits; the parts linked to it follow
- `to(address: string, v: number, seconds: number, curve = 'smooth'): Waitable` — go to a value over `seconds` by an ease of the language; the waitable is done when it has arrived or another move of the part took over
- `advance(): void` — bring every move up to the clock (also the instances')
- `moving(): boolean`
- `detach(instance: string): PartRig | undefined` — a rig for an instance that is let go: the whole no longer moves it

### PlacementSource

*class* · `packages/levels/src/placements.ts:205`

```ts
class PlacementSource implements CellSource
```

A `CellSource` that also understands placement lists: a cell whose file is `*.placements.json` is read through `get` (the loader's fetch), its models are loaded through the inner
source, and `instantiate` gives the thin-instance root; any other file goes to the inner source untouched. Streaming, memory budgets and `ready()` need no change.

- `constructor(private readonly inner: CellSource, private readonly scene: BABYLON.Scene, private readonly get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>, private readonly o: { resolver?: PlacementResolver; warn?: PlacementWarnings } = {})`
- `async load(url: string): Promise<void>`
- `async read(url: string): Promise<{ file: PlacementFile; urls: Map<string, string> }>` — read and check a list, and load every model it names (once each)
- `async instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>`
- `release(url: string): void`

### PrefetchService

*class* · `packages/levels/src/prefetch.ts:31`

```ts
class PrefetchService implements Service
```

- `readonly name: "prefetch"`
- `constructor(private readonly levels: LevelService, o: PrefetchOptions = {})`
- `init(world: World): void`
- `near(zone: string, levelId: string, o: { inSeconds?: number } = {}): () => void` — Doors and zones: entering `zone` makes `levelId` wanted (the player is probably about to go there).
- `hint(id: string, o: { inSeconds?: number; from?: 'level' | 'game' } = {}): void` — `id` is wanted. With `inSeconds` (the player will need it in about that long) the start is put off as long as the estimate allows it to still finish in time; without it the download starts at once (when no travel is running).
- `focus(ids: string[]): void` — Only these are wanted from now on: every other background download stops at its next file.
- `cancel(id: string): void`
- `get bandwidth(): number` — The smoothed link speed in bytes per second, 0 when nothing was measured.
- `state(id: string): JobState | 'none'`
- `async idle(id: string): Promise<void>` — Resolves when the level's background download has finished (done, cancelled or failed).
- `status(): { rate: number; jobs: Record<string, { state: JobState; wanted: boolean; bytes: number }> }`
- `dispose(): void`

### ProbeVolume

*class* · `packages/levels/src/probe-volume.ts:89`

```ts
class ProbeVolume
```

The baked grid on the GPU and the plugin on every PBR material of the scene (also those added later).

- `readonly textures: BABYLON.RawTexture3D[]`
- `enabled: boolean`
- `constructor(readonly scene: BABYLON.Scene, readonly def: ProbeVolumeDef, data: ArrayBuffer)`
- `setEnabled(on: boolean)` — Switch the baked light on or off (the materials recompile).
- `dispose()`

### PropellerView

*class* · `packages/levels/src/propeller.ts:27`

```ts
class PropellerView
```

- `disc: BABYLON.TransformNode | null` — the disc, once made (the first frame it is wanted)
- `hidden: boolean` — both blades and disc hidden (a view from the cockpit that does not want them)
- `constructor(private scene: BABYLON.Scene, readonly props: BABYLON.TransformNode[], o: PropellerViewOptions = {})`
- `setLayerMask(mask: number)` — the layer mask the disc is drawn on (a cockpit camera's layer; the blades' meshes are the caller's)
- `update(omega: number | readonly number[], dt: number)` — call each frame: `omega` the shaft speed of the engine behind each propeller node (rad/s; one number for all), `dt` the frame's time
- `dispose()`

### RuntimeAssets

*class* · `packages/levels/src/runtime.ts:55`

```ts
class RuntimeAssets implements Service
```

- `readonly name: "runtime-assets"`
- `constructor(private readonly o: RuntimeAssetsOptions)`
- `init(world: World): void`
- `async bytes(ref: string, o: Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'> = {}): Promise<Uint8Array>` — The verified bytes of any reference.
- `async url(ref: string, o: Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'> = {}): Promise<string>` — A URL the engine's loaders (Audio, Texture, video) can read, for any reference.
- `status(ref: string): string`
- `model(ref: string, o: ModelOptions = {}): ModelHandle` — Ask for a model. Returns at once with the placeholder in place.
- `get scene(): BABYLON.Scene`
- `get events()`
- `get models()`
- `forget(h: ModelHandleImpl): void`
- `async modelUrl(ref: string, o: ModelOptions): Promise<string>`
- `dispose(): void`

### SequencePlayer

*class* · `packages/levels/src/sequence.ts:92`

```ts
class SequencePlayer
```

Plays one sequence on the scene. `update(dt)` once per frame.

- `time: number`
- `playing: boolean`
- `finished: number` — how many times it has ended (a looping one counts each wrap)
- `constructor(readonly def: SequenceDef, private scene: BABYLON.Scene, private find: (name: string) => BABYLON.TransformNode | null, private emit: (name: string, data: unknown) => void = () => undefined)`
- `play(from = 0)`
- `stop()`
- `update(dt: number)`
- `apply()`

### ShipWake

*class* · `packages/levels/src/wake.ts:42`

```ts
class ShipWake
```

- `readonly mesh: BABYLON.Mesh`
- `constructor(scene: BABYLON.Scene, name: string, private pose: (t: number) => { x: number; z: number; dx: number; dz: number }, o: ShipWakeOptions)`
- `update(t: number)` — call each frame with the time the ship's pose is read at
- `dispose()`

### SnapshotRendering

*class* · `packages/levels/src/snapshot-rendering.ts:24`

```ts
class SnapshotRendering implements Service
```

- `readonly name: "snapshot-rendering"`
- `stats: { records: number; invalidations: number; }` — how many times the draw list changed under a recording, for the debug view and tests
- `constructor(private o: SnapshotOptions = {})`
- `get supported(): boolean`
- `get active(): boolean` — is a snapshot recorded or being replayed now
- `init(world: World): void`
- `enable(): void` — start snapshotting (a no-op on WebGL2)
- `disable(): void`
- `invalidate(): void` — the draw list changed: draw normally for a few frames, then record again
- `qualityKnobs(): QualityKnob[]`
- `dispose(): void`

### StillCameraFreeze

*class* · `packages/levels/src/still-camera.ts:11`

```ts
class StillCameraFreeze implements Service
```

The CPU knob of the plan-OFFLOAD G1: while the camera has not moved for `stillFrames` frames (a dialogue, a cutscene, a menu over the scene) the list of
active meshes is frozen (`scene.freezeActiveMeshes()`: no frustum test of thousands of meshes a frame) and given back the frame the camera moves or the
scene's mesh list changes. Meshes that move keep drawing at their new places; what a freeze cannot see is a mesh entering the view while the camera is
still, so the knob is the regulator's last resort among the CPU ones (visibility 0.6). Level 0 (the default) is off, level 1 is on.

- `readonly name: "still-camera-freeze"`
- `stillFrames: number`
- `init(world: World): void`
- `attach(scene: BABYLON.Scene): void`
- `qualityKnobs(): QualityKnob[]`
- `dispose(): void`

### StreamingDebugView

*class* · `packages/levels/src/streaming-debug.ts:13`

```ts
class StreamingDebugView
```

- `constructor(private readonly world: World, private readonly sv: StreamingService, private readonly block: () => { cells: Record<string, { bounds: number[] }> } | null)`
- `get visible(): boolean`
- `show(): void`
- `hide(): void`

### StreamingService

*class* · `packages/levels/src/streaming.ts:67`

```ts
class StreamingService implements Service
```

- `readonly name: "streaming"`
- `tuning: { radiusScale: number; budgetScale: number; memoryScale: number; }` — Runtime scales on top of the options
- `init(world: World): void`
- `get active(): boolean`
- `blockDef(): StreamingBlock | null` — the block being streamed (for the debug view and tools)
- `begin(block: StreamingBlock, source: CellSource, o: StreamingOptions): void` — Start streaming a level. The cells within `loadRadius` of the focus are what `ready()` waits for.
- `end(): void` — Stop streaming and release everything this service added. Called when the level is unloaded.
- `cellLevel(id: string): number | undefined` — the variant resident (or being made) now, for tools and tests: 0 is the full file; undefined for an unknown cell
- `memory(): { resident: number; cap: number | null; pinned: number }` — Bytes the resident cells take against the cap (pinned ones are counted and never evicted).
- `gate(): string[]` — The cells that must be in before the level is playable: those within `loadRadius` of the focus.
- `ready(): Promise<void>` — Resolves when every cell of the gate is loaded (or has failed: a missing far cell must not hold the player).
- `update(_dt = 0): void` — Called once per rendered frame.
- `async loadBundle(id: string): Promise<void>` — Load a bundle (the files an interior needs) now; resolves when it is in. Loading it twice is one load.
- `bundleState(id: string): State | undefined`
- `bundleRoots(id: string): BABYLON.TransformNode[]`
- `hasCell(id: string): boolean`
- `cellRoot(id: string): BABYLON.TransformNode | null` — the root of a resident cell's instance (what an entity that `needs` the cell looks its node up in), else null
- `cellState(id: string): State | undefined`
- `snapshot(): { cells: Record<string, State>; bundles: Record<string, State> }`
- `dispose(): void`

### SwarmSim

*class* · `packages/levels/src/swarm.ts:69`

```ts
class SwarmSim
```

- `readonly pos: Float32Array` — x y z of every agent, flat
- `readonly vel: Float32Array`
- `readonly scale: Float32Array`
- `centre: [number, number, number]`
- `constructor(readonly def: SwarmDef)`
- `step(dt: number, wind?: { intensity: number; direction: [number, number] })`

### TransitionRegistry

*class* · `packages/levels/src/transitions.ts:55`

```ts
class TransitionRegistry
```

- `register(name: string, t: Transition | (() => Transition)): this` — Register a transition by name: one object, or a function that makes a fresh one per travel. Registering `default` sets what is used when nothing else is chosen.
- `has(name: string): boolean`
- `names(): string[]`
- `choose(fn: TransitionChooser): this` — `(from, to, plan) => name`: decides per travel (a theme in `to.tags`, a short wait in `plan.cached`).
- `pick(from: LevelDef | null, to: LevelDef, plan: LevelPlan, named?: string): string` — The name to use: the one the call named, else the chooser's, else `default`, else the bar. A name that is not registered falls back to the bar.
- `create(name: string): Transition`

### TransitionRun

*class* · `packages/levels/src/transitions.ts:91`

```ts
class TransitionRun
```

A transition with the guarantees of 5.1 around it: `enter` has 2 s to be on screen; a throw anywhere is logged and the bar takes
over; a broken transition never blocks the travel. After a fallback every further call is a no-op and `name` reads `bar`.

- `name: string`
- `fellBack: string | null` — set when the game's transition failed and the engine's bar replaced it
- `constructor(readonly wanted: string, private readonly t: Transition, private readonly ctx: TransitionContext, private readonly o: RunOptions = {})`
- `async enter(): Promise<void>`
- `update(p: TransitionProgress): void`
- `async ready(): Promise<void>` — Resolves when the game lets the player in. A cancel does not hold the player in a transition that waits for a button.
- `async fail(err: StreamError): Promise<boolean>` — True when the transition showed the failure itself.
- `dispose(): void`

### TravelAborted

*class* · `packages/levels/src/levels.ts:66`

```ts
class TravelAborted extends Error
```

The player (or the menu) cancelled the travel.

- `constructor(readonly id: string)`

### VisibilityService

*class* · `packages/levels/src/visibility.ts:14`

```ts
class VisibilityService implements Service
```

Draws only what the player can see from the grid cell they stand in (VisibilityBlock). A lookup when the cell changes, nothing per frame
otherwise. Cells streamed in later are covered too (the nodes are looked for again when a cell arrives). A cell the table does not know shows everything.

- `readonly name: "visibility"`
- `stats: { changes: number; hiddenGroups: number; hiddenMeshes: number; }` — counts for tests and the debug view
- `init(world: World): void`
- `get active(): boolean`
- `current(): string | null`
- `isShown(group: string): boolean`
- `begin(block: VisibilityBlock, root: BABYLON.Node, o: VisibilityOptions = {}): void`
- `end(): void`
- `dispose(): void`
- `keyAt(x: number, z: number): string` — The grid cell of a point.
- `update(_dt = 0): void` — Called once per rendered frame.

## Functions

### actorMatrix

*function* · `packages/levels/src/placements.ts:102`

```ts
function actorMatrix(a: Placement): BABYLON.Matrix
```

The actor's transform as a matrix (scale, then rotation, then position).

