# @ferret/levels: API (continued)

### MaterialLooksHandle

*interface* · `packages/levels/src/material-look.ts:163`

```ts
interface MaterialLooksHandle
```

- `update(looks: MaterialLooks | undefined): void` — replace the looks: only what changed is touched
- `targets(scope: LookScope, o?: { filter?: string; limit?: number; aliases?: boolean }): Promise<{ entries: LookTarget[]; total: number; truncated: boolean }>` — the scene's addresses of a scope (regex `filter` on the uid; the most used first, `limit` of them). A model is listed by its best uid; `aliases` lists its other names (placement key, library id, glTF mesh name) too: they all work as addresses
- `resolve(scope: LookScope, uid: string): Promise<LookTarget | null>` — one address, or null when nothing of the scene answers to it
- `read(scope: LookScope, uid: string, material: string): MaterialInfo | null` — the values of that material on the first mesh the address covers, now (what the screen shows)
- `ready(): Promise<void>` — resolves when the names the looks need are read and the scene is in step with them
- `dispose(): void` — takes every look off and stops watching

### MaterialLooksOptions

*interface* · `packages/levels/src/material-look.ts:135`

```ts
interface MaterialLooksOptions
```

- `textureUrl?: (ref: string) => Promise<string> | string` — the URL a map reference is read from (a file of the level's folder, a URL, a `ferret://` file); default: absolute URLs as they are
- `warn?: (message: string) => void` — a problem to report (a map that could not be read, an ambiguous address)
- `glbIndex?: () => Promise<GlbIndex | null>` — the names of the scene glb (for the type fallback by glTF mesh name); read only when a look or a listing needs it

### MaterialOptions

*interface* · `packages/levels/src/library.ts:115`

```ts
interface MaterialOptions
```

- `variant?: string`
- `name?: string`
- `scene?: BABYLON.Scene`

### MaterialOverride

*interface* · `packages/levels/src/placements.ts:33`

```ts
interface MaterialOverride
```

A library material standing in for a material of the model.

- `library: string`
- `variant?: string`

### MaterialScaleDef

*interface* · `packages/levels/src/material-scale.ts:18`

```ts
interface MaterialScaleDef
```

Repair of baked materials that came out wrong from the Unreal export.
`match` is a regular expression over the glTF material name; then
 - `flat: [r, g, b]` (0..255, sRGB) replaces the albedo picture by one colour (the picture's average over its painted texels, kept in the build config).
   The exporter bakes some materials over the lightmap UVs, so the picture is an atlas of islands on a black background while the mesh reads it through
   its first UV set: part of the surface lands on black. The surface turns matte (the bake's metal/roughness picture is the same wrong atlas); the normal map stays;
 - `flatLinear: [r, g, b]` (0..1, LINEAR, as a material parameter of the original gives it) does the same with the colour as the shader takes it: `flat` divides
   its sRGB numbers by 255 and hands them to the shader as they are, so it draws lighter than the picture it was read from (kept as it is for the levels built on it);
 - `albedo` is a LINEAR multiplier of the albedo (the light the surface returns): 2 makes it twice as bright;
 - `noVertexColors: true` stops the meshes of the material from tinting it with their vertex colours. Unreal's painted vertex colours are masks the
   material blends with (moss, dirt), already baked into the picture, but glTF viewers multiply the albedo by them: violet and cyan blotches on the walls.
   (An InstancedMesh draws with its source mesh's flag, so the source is the one switched.)
It covers the materials that exist now and every one a streamed cell adds later (they are handled once their picture or mesh is set, at most 300 frames later).

- `match: string`
- `flat?: [number, number, number]`
- `flatLinear?: [number, number, number]`
- `albedo?: number`
- `noVertexColors?: boolean`

### ModelDescribed

*interface* · `packages/levels/src/fmdl-catalogue.ts:21`

```ts
interface ModelDescribed
```

- `id: string`
- `abstract: boolean`
- `lineage: string[]`
- `description: ModelDescription`
- `markdown: string`

### ModelHandle

*interface* · `packages/levels/src/runtime.ts:37`

```ts
interface ModelHandle
```

A model on its way. `node` is the placeholder until the model is in, then the model's root.

- `readonly ref: string`
- `readonly state: ModelState`
- `readonly node: BABYLON.TransformNode | null`
- `readonly ready: Promise<{ root: BABYLON.TransformNode; dispose(): void } | null>` — resolves with the instance, or null when it failed or was disposed (the reason is in `error` and the `asset:failed` event)
- `readonly error?: StreamError`
- `dispose(): void`

### ModelListing

*interface* · `packages/levels/src/fmdl-catalogue.ts:20`

```ts
interface ModelListing
```

- `id: string`
- `summary?: string`
- `kind?: string`
- `category?: string`
- `tags: string[]`
- `abstract: boolean`
- `extends?: string`
- `score: number`

### ModelOptions

*interface* · `packages/levels/src/runtime.ts:25`

```ts
interface ModelOptions extends Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'>
```

- `placeholder?: PlaceholderSpec` — shown at once, replaced by the model (default: a small box); `'none'` shows nothing until the model is in
- `parent?: BABYLON.TransformNode` — the node the model hangs from (an entity's node): the placeholder and then the model are its children
- `position?: [number, number, number]`
- `name?: string`

### ModelPlacement

*interface* · `packages/levels/src/library.ts:83`

```ts
interface ModelPlacement extends Omit<ModelOptions, 'pkg'>
```

- `tier?: LibraryTier`
- `yaw?: number`

### MountAssets

*interface* · `packages/levels/src/ferret.ts:14`

```ts
interface MountAssets extends PackageAssets
```

What the mount needs from the asset cache (an AssetCache fits).

- `load(url: string, ext?: string): Promise<void>`

### MountOptions

*interface* · `packages/levels/src/ferret.ts:21`

```ts
interface MountOptions
```

- `packages?: PackageSet` — the packages that are open together (default: a new set); `ferret://<id>/<path>` is looked up in it
- `loader?: Partial<PackageLoaderOptions>` — passed on to the level loader (collisions, an editor's draft manifests ...)
- `fetch?: (url: string) => Promise<FetchResult>` — replace `fetch` for urls that are not in a package

### OcclusionOptions

*interface* · `packages/levels/src/occlusion-culling.ts:10`

```ts
interface OcclusionOptions
```

Occlusion queries for the big meshes of an interior: the GPU says which large meshes are hidden behind others (a castle's walls hide
most of the level), and the CPU stops recording their draws. Babylon runs the queries on WebGL2 (`mesh.occlusionType`); a query's answer is a frame late,
so only meshes that are large and heavy enough to be worth a query get one (`minRadius` metres of bounding sphere, `minIndices` indices), and the type is
optimistic: a mesh with no answer yet is drawn. Meshes under `root` only; `unapply` gives them back. Where the engine has no occlusion queries nothing happens.

- `root: string` — the level root's name: only meshes named `<root>/...` get queries
- `minRadius?: number` — bounding sphere radius a mesh needs, metres (default 3)
- `minIndices?: number` — indices a mesh needs (default 3000)
- `algorithm?: 'conservative' | 'accurate'` — 'conservative' (default: a query is skipped for a frame after it was seen) or 'accurate' (a query every frame)

### OceanOptions

*interface* · `packages/levels/src/ocean.ts:16`

```ts
interface OceanOptions
```

- `name?: string`
- `radius?: number` — how far the grid reaches, metres (default 150 km: the horizon from 6 km up is 280 km away, but the haze has the rest)
- `rings?: number`
- `sectors?: number`
- `depthAt?: (x: number, z: number) => number` — metres of water under (x, z), negative on land; omitted: deep everywhere
- `far?: number` — the three depth boxes round the camera: edge length in metres (default 400 km, 48 km and 8 km) and texels (default 256); the far one tells the land from the sea to the horizon, so the sea is never drawn under distant land (where the depth buffer could not keep them apart)
- `coarse?: number`
- `fine?: number`
- `texels?: number`
- `rowsPerFrame?: number` — rows of a depth texture baked per frame once it has to move (default 24)
- `fog?: 'exp' | 'exp2'` — the fog: 'exp' (density per metre) or 'exp2'

### OceanWave

*interface* · `packages/levels/src/ocean.ts:15`

```ts
interface OceanWave
```

- `wavelength: number`
- `amplitude: number`
- `steepness?: number`
- `direction?: number`

### OpenedDependency

*interface* · `packages/levels/src/dependencies.ts:24`

```ts
interface OpenedDependency
```

A dependency that was opened: which catalog it came from and the URL of the file that was read.

- `id: string`
- `version: string`
- `range: string`
- `catalog: string`
- `url: string`
- `pkg: FerretPackage`

### PackageAssets

*interface* · `packages/levels/src/package.ts:23`

```ts
interface PackageAssets
```

What the loader needs from `@ferret/assets` (an AssetCache fits).

- `load(url: string): Promise<void>`
- `instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>`
- `release(url: string): void`

### PackageCommandHooks

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

```ts
interface PackageCommandHooks
```

- `resolve?: (url: string) => PackageInput | Promise<PackageInput>` — turn a url or name into something `FerretPackage.open` reads (default: the url itself)
- `opened?: (pkg: FerretPackage, url: string) => void` — told when a package was opened from `url` (so a host can write changes back to where it came from)
- `write?: (pkg: FerretPackage, name: string, bytes: Uint8Array) => Promise<void>` — write a built `.ferret` (a file next to the source, a download); without it `pkg.pack` only reports what it built
- `publish?: (files: Record<string, Uint8Array>) => Promise<void>` — put the files of `pkg.publish` where the server serves them: { path: bytes }, paths relative to the site root (a folder to upload, a CDN)
- `persist?: (pkg: FerretPackage) => Promise<{ files?: number; bytes?: number; appended?: number; dead?: number; compacted?: boolean } | void>` — keep an edited package: a folder package writes its changed files, a zip is packed again. Called by \`pkg.save\`
- `compact?: (pkg: FerretPackage) => Promise<{ before: number; after: number }>` — write a project (`.fprj`) again without the bytes its saves left behind (`compactZip`): where it came from, or a download. Called by `pkg.compact`
- `behaviours?: () => Iterable<string>` — behaviours the game registers itself (for \`pkg.validate\`)
- `trusted?: () => Iterable<string> | undefined` — key ids the reader trusts (for \`pkg.verify\` and the code check)

### PackageLoaderOptions

*interface* · `packages/levels/src/package.ts:29`

```ts
interface PackageLoaderOptions
```

- `assets: PackageAssets`
- `fetch?: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer(): Promise<ArrayBuffer> }>` — replace `fetch` (tests, a Platform file API)
- `collisions?: boolean` — make the level's meshes collide (default true)
- `manifest?: (def: LevelDef) => LevelManifest | undefined` — a manifest to use instead of the one in the package: the editor's draft (return undefined to load the file)
- `streamingRadiusScale?: number` — scale the streaming radii of every streamed level (a tier may ask for less)
- `forceNavBuild?: (def: LevelDef) => boolean` — build the NavMesh from `navBuild` even if navmesh.bin exists (the editor, after a rebuild)
- `placements?: PlacementResolver` — finds library models and materials by id for placement lists (`*.placements.json`; an `AssetLibrary` gives it: `placementResolver()`); lists that name only `ferret://` files need none

### Placement

*interface* · `packages/levels/src/placements.ts:34`

```ts
interface Placement
```

- `actor: string`
- `model: string` — a key of `models`
- `position: Vec3`
- `rotation?: Quat`
- `scale?: number | Vec3`
- `materials?: Record<string, MaterialOverride>`

### PlacementBuildOptions

*interface* · `packages/levels/src/placements.ts:123`

```ts
interface PlacementBuildOptions
```

- `scene: BABYLON.Scene`
- `instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>` — make an instance of a loaded model file (an asset cache's `instantiate`)
- `urls: Map<string, string>` — the file reference of each model name of the placement list (resolved before; see `PlacementSource.load`)
- `resolver?: PlacementResolver`
- `materials?: Map<string, Promise<BABYLON.Material>>` — library materials already made, by `id#variant` (shared by the cells of one level: a material is made once, the library owns it)
- `warn?: PlacementWarnings`
- `name?: string` — the root of the new nodes is named so (default `placements`)

### PlacementFile

*interface* · `packages/levels/src/placements.ts:43`

```ts
interface PlacementFile
```

- `format: typeof PLACEMENTS_FORMAT`
- `models: Record<string, PlacementModel>`
- `actors: Placement[]`

### PlacementGroup

*interface* · `packages/levels/src/placements.ts:88`

```ts
interface PlacementGroup
```

- `key: string`
- `model: string`
- `materials?: Record<string, MaterialOverride>`
- `actors: Placement[]`

### PlacementInstance

*interface* · `packages/levels/src/placements.ts:114`

```ts
interface PlacementInstance
```

- `root: BABYLON.TransformNode`
- `groups: { key: string; model: string; meshes: BABYLON.Mesh[]; actors: string[] }[]` — one entry per drawn group: the meshes that carry its thin instances and the actors in their order
- `count: number` — instances drawn
- `dispose(): void`

### PlacementModel

*interface* · `packages/levels/src/placements.ts:31`

```ts
interface PlacementModel
```

A model by library item id, or by a file reference of a package.

- `library?: string`
- `ref?: string`
- `tier?: LibraryTier`

### PlacementResolver

*interface* · `packages/levels/src/placements.ts:46`

```ts
interface PlacementResolver
```

What the placement needs to find models and materials of the library by id (an `AssetLibrary` gives it: `placementResolver()`).

- `modelRef(m: PlacementModel): Promise<string> | string` — the `ferret://` file of a library model (its tier chosen)
- `material(o: MaterialOverride): Promise<BABYLON.Material>` — a library material to put on the model's meshes

### PlacementWarnings

*interface* · `packages/levels/src/placements.ts:113`

```ts
interface PlacementWarnings
```

- `(message: string): void`

### PrefetchOptions

*interface* · `packages/levels/src/prefetch.ts:16`

```ts
interface PrefetchOptions
```

- `settleMs?: number` — wait this long after a level is ready before the first background download (the level's own first seconds come first)
- `margin?: number` — safety factor on the estimate: start early enough to finish in `eta * margin` (default 1.5)
- `assumedRate?: number` — assumed link speed in bytes/s until something has been measured (default: unknown, so hints start at once)
- `now?: () => number`
- `setTimer?: (fn: () => void, ms: number) => unknown`
- `clearTimer?: (t: unknown) => void`

### PreviewOptions

*interface* · `packages/levels/src/transitions.ts:147`

```ts
interface PreviewOptions
```

- `seconds?: number` — how long the fake download lasts
- `bytes?: number`
- `files?: number`
- `fail?: boolean` — end with a failure instead of readiness (to see the game's failure screen)
- `cached?: boolean` — `cached`: plan says the wait is short
- `signal?: AbortSignal`

### ProbeVolumeDef

*interface* · `packages/levels/src/probe-volume.ts:7`

```ts
interface ProbeVolumeDef
```

Baked global illumination: a regular grid of L1 spherical harmonics (the radiance arriving at each point, RGB), written by
`tools/ue-export/bake-gi`. The shader of every PBR material looks up the grid trilinearly at the surface and adds the diffuse light the
lamps, the sky and the bounces give there. It replaces the flat hemispheric ambient light (which the loader turns off when a volume exists).

- `file: string` — the baked grid, relative to the package: `probes.bin`
- `origin: [number, number, number]` — the position of the first probe, metres
- `spacing: number` — metres between probes
- `dims: [number, number, number]` — probes along x, y, z
- `gain?: number` — scale of the baked light (default 1)
- `fill?: number` — how much of the level's flat `ambient` light stays on beside the baked light, 0..1 (default 0: none). A hemispheric fill that brightens ceilings and darkens floors where the bake's bounce light is short
- `down?: number` — the share of the baked light that faces turned down (ceilings) get, 0..1 (default 1: all of it)

### ProgramBridgeLike

*interface* · `packages/levels/src/fmdl-programs.ts:134`

```ts
interface ProgramBridgeLike
```

- `lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown`

### ProgramHost

*interface* · `packages/levels/src/fmdl-programs.ts:24`

```ts
interface ProgramHost
```

- `run(program: string, o: { target?: string; params: Record<string, Value> }): Program` — start a program text with its parameters on a target (the runtime's: the actuators' `cap.run`)
- `knows(name: string): boolean` — is `name` a word of the language

### PropellerViewOptions

*interface* · `packages/levels/src/propeller.ts:10`

```ts
interface PropellerViewOptions
```

The picture of a spinning propeller. The shaft speed comes from the flight model (`Aeroplane.propOmega`, rad/s): a real propeller turns at 1000..1500 rpm, 3 or 4 blades
pass a point 60..100 times a second, and the screen shows 60 frames: a blade seen at its true angle strobes, and looks slow or runs backwards. So the blades are drawn
at their true angle only while a blade moves a small part of the blade spacing in a frame (taxiing, starting); as the speed rises they fade into the disc the eye sees at
speed (a faint disc, darker where the blades sweep, the tips a ring), which fades in. `propellerBlur` is that blend, pure, for the picture and for tests.

Nodes: the propeller's node (`Prop`, or `Prop_L` and `Prop_R`) has its pivot on the shaft, which is its local X axis.

- `blades?: number` — blades on the propeller (default 3)
- `radius?: number` — the disc's radius, m (default: read off the blades' bounds, else 1.6)
- `blurFrom?: number` — the blur starts when a blade moves this share of the blade spacing in one frame (default 0.25) ...
- `blurTo?: number` — ... and is complete at this share (default 0.7)

### PropulsorBindOptions

*interface* · `packages/levels/src/fmdl-propulsors.ts:10`

```ts
interface PropulsorBindOptions
```

- `field: FlowField`
- `actuator?: (name: string) => { force: V3; on: boolean } | undefined` — the state of a named actuator: its force (N) and whether it is running; undefined when the physics does not run
- `surface?: SurfaceQuery`
- `scale?: number` — the multiplier of every jet (the game's override)
- `onGroundEffect?: (actor: string, id: string, extra: V3, at: V3) => void`

### RelevanceBlock

*interface* · `packages/levels/src/manifest.ts:132`

```ts
interface RelevanceBlock
```

- `modes?: Record<string, { omega?: number; horizon?: number; floorOmega?: number }>`
- `hold?: number` — seconds a thing stays in a finer class before it may go to a coarser one
- `gonePx?: number` — below this many pixels a thing is not drawn at all

### RiverDef

*interface* · `packages/levels/src/water.ts:80`

```ts
interface RiverDef
```

- `points: Vec3[]` — the centre line, close points [x, y, z] in metres (y is the surface there); the spline is sampled by the exporter, a metre or so apart
- `widths: number[]` — the width at each point, metres
- `flow: number` — metres per second the surface moves downstream (the first point to the last)

### RoomReflection

*interface* · `packages/levels/src/room-reflection.ts:42`

```ts
interface RoomReflection
```

- `readonly cube?: BABYLON.RenderTargetTexture`
- `readonly drawn: Promise<void>` — settles when the room has been drawn into the cube (or the capture failed or was disposed): a game keeps its loading screen up until then, the first draw compiles shaders
- `refresh(): void` — draw the room again (after a change of light or furniture)
- `dispose(): void`

### RoomReflectionDef

*interface* · `packages/levels/src/room-reflection.ts:15`

```ts
interface RoomReflectionDef
```

What the glossy and the clear surfaces of an interior reflect: the room itself. The level is drawn once into a cube map from a point of the room (the lit
walls, the windows, the furniture, with the baked light on them) after it has loaded, and that cube becomes the scene's environment texture. Without it an
interior has no sky to reflect, and dark ceramic, glass, metal and polished floors draw as dull flat colour.

With a `box` the lookup is box-projected: a reflection ray is cut against the room's walls instead of read at infinity, so a floor shows the window
where the window is. One capture serves the whole room; a mirror or a very large room wants more than one point (not done).

- `position?: Vec3` — where the cube is drawn from, metres (the package's frame). Default: the box's centre at 1.4 m above its floor.
- `box?: { center: Vec3; size: Vec3 }` — the room: the box the reflection rays are cut against. Default: the baked probe grid's bounds.
- `resolution?: number` — side of a cube face in pixels (default 256: 6 x 256 x 256 half floats, about 3 MB with its mip levels)
- `intensity?: number` — scale of the reflected light (default 1: the picture's own exposure is taken out, see `capture`)

### RunOptions

*interface* · `packages/levels/src/transitions.ts:85`

```ts
interface RunOptions
```

- `enterTimeoutMs?: number`
- `log?: (event: string, detail: Record<string, unknown>) => void`

### RuntimeAssetsOptions

*interface* · `packages/levels/src/runtime.ts:47`

```ts
interface RuntimeAssetsOptions
```

- `store: AssetStore`
- `models: MountAssets` — loads and instantiates glTF (an `AssetCache`, or `mount.assets` when packages are in use)
- `mount?: PackageMount` — needed for `ferret://` references

### SequenceDef

*interface* · `packages/levels/src/sequence.ts:28`

```ts
interface SequenceDef
```

- `name: string`
- `length: number`
- `loop?: boolean`
- `play?: 'begin' | 'trigger' | 'manual'`
- `trigger?: string`
- `rate?: number`
- `tracks: SequenceTrack[]`
- `events?: Array<{ t: number; name: string }>`

### SequenceTrack

*interface* · `packages/levels/src/sequence.ts:17`

```ts
interface SequenceTrack
```

- `target: string | { camera: true }`
- `position?: Key<[number, number, number]>[]`
- `positionAxes?: [boolean, boolean, boolean]` — which of x, y, z the position keys animate (default all); the others keep the node's own value (Unreal: a transform track with only some channels keyed)
- `scaleAxes?: [boolean, boolean, boolean]` — the same for scale
- `rotation?: Key<[number, number, number, number]>[]`
- `scale?: Key<[number, number, number]>[]`
- `fov?: Key<number>[]`

### ShipWakeOptions

*interface* · `packages/levels/src/wake.ts:8`

```ts
interface ShipWakeOptions
```

The long wake of a ship on the sea, drawn. A ship's turbulent track runs for kilometres behind a destroyer and hundreds of metres behind a
submarine and is seen from any height. It is laid along the path the ship took (each row is where the ship was some seconds ago, so it bends in a turn): a narrow
white core that spreads and thins, and the two faint arms of the Kelvin wedge (half angle 19.5 degrees: 0.354 m sideways for every metre astern).
`Wake` of

- `length: number` — how far astern the track runs, m (a destroyer: 2500; a submarine: 450)
- `beam: number` — the hull's beam, m
- `speed: number` — the ship's speed, m/s: the time a row of the track is behind the ship is its distance over this
- `sternBack?: number` — where the track starts behind the ship's reference point (its stern), m
- `rows?: number` — rows along the track (default 72)
- `height?: number` — the height over the water, m (default 1.8: above the waves of a fresh sea)

### ShoreDef

*interface* · `packages/levels/src/water.ts:60`

```ts
interface ShoreDef
```

- `outline: [number, number][]`
- `width?: number` — metres of foam inside the edge (default 1.5)

### SlopeRamp

*interface* · `packages/levels/src/landscape.ts:38`

```ts
interface SlopeRamp
```

Unreal's WorldAlignedBlend parameters (Blend Sharpness, Blend Bias), as the material instance has them: `slopeAlpha(up, ramp)`.

- `sharpness: number`
- `bias: number`

### SnapshotOptions

*interface* · `packages/levels/src/snapshot-rendering.ts:15`

```ts
interface SnapshotOptions
```

Snapshot rendering of a level that does not change its draw list. On a WebGPU engine Babylon can record the commands of a frame once
(render bundles) and replay them: the CPU stops recording thousands of draws. A replay keeps the draw list of the frame it recorded, so the service
watches what changes it: meshes, materials, lights and particle systems added or removed, the number of active meshes, the visibility service's cell, a level
loading or unloading, and anything the game reports with `invalidate()` (a node enabled or hidden, a material swapped). When the list changes, the snapshot is
switched off, the frame is drawn as usual for `settleFrames` frames, and a new snapshot is recorded. Nodes that only MOVE (doors, gates, characters, the
camera) need nothing: in `standard` mode uniforms and world matrices are still updated every frame and only the recorded draws are replayed.

`fast` mode skips the scene's own work while replaying (no uniform updates: only for a scene that does not move at all, a still frame); `standard` is the
default. The mode, and so the whole service, does nothing on the WebGL2 engine. The regulator's knob `levels.snapshot` (CPU): level 0 is off, 1 is on (the cheaper step).

- `settleFrames?: number` — frames drawn normally after a change before a new snapshot is recorded (default 20)
- `mode?: 'standard' | 'fast'` — 'standard' (default) or 'fast'
- `auto?: boolean` — when false (default) the service is idle until `enable()`: a level that declares itself static turns it on

### SoundOptions

*interface* · `packages/levels/src/library.ts:123`

```ts
interface SoundOptions
```

- `audio: SoundSink`
- `name?: string` — the name to play it by (default the item id)
- `format?: 'wav' | 'mp3'` — the file to use; default by tier: the MP3 (smaller) on `mobile` and `low`, the WAV on `desktop`, whichever there is when only one is
- `tier?: LibraryTier`

### SoundSink

*interface* · `packages/levels/src/library.ts:118`

```ts
interface SoundSink
```

What `AssetLibrary.sound` needs of the audio service (`AudioService` of `@ferret/media` is one): take the bytes of a file and define a sound over them.

- `addFile(key: string, data: Uint8Array): unknown`
- `define(name: string, def: Record<string, unknown>): unknown`
- `has(name: string): boolean`

### SpawnPoint

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

```ts
interface SpawnPoint
```

- `id: string`
- `position: BABYLON.Vector3`
- `yaw: number`
- `human?: string`

### StageModel

*interface* · `packages/levels/src/fmdl-motion.ts:265`

```ts
interface StageModel
```

what the stage can place by id: the loader's `FmdlModel` is one (`stage.addModel`), a test gives its own

- `id: string`
- `resolved?: ResolvedModel` — the resolved model and a reader of its files by qualified path: what its motions are found and read from (`ModelPrograms`)
- `read?: (qualified: string) => Promise<Uint8Array>`
- `make(level: number, name: string): { root: Node; plan: AssemblyPlan }` — the nodes of a level, not parented, and the plan they were made from

### StageOptions

*interface* · `packages/levels/src/fmdl-motion.ts:287`

```ts
interface StageOptions
```

- `scene?: BABYLON.Scene`
- `emit?: (name: string, payload: unknown) => void` — the events of the world (`world.events.emit`); none in a plain test

### StreamCellDef

*interface* · `packages/levels/src/manifest.ts:32`

```ts
interface StreamCellDef
```

One grid cell of a streamed level: visual content only; collision is whole-level and resident. `bounds` = [minX, minY, minZ, maxX, maxY, maxZ].

- `bounds: [number, number, number, number, number, number]`
- `file: string`
- `size?: number`
- `priority?: number`
- `pinned?: boolean` — always resident (the play area round the spawn): fetched first, part of the ready gate, never released and never evicted for memory
- `layer?: string` — a key of `layers`: the cell uses that layer's radii instead of the block's (foliage is wanted closer than houses)
- `memory?: number` — bytes the cell takes once resident (geometry plus decoded textures); counted against `memoryBudget`. Default: `size`
- `lod?: string` — a low-poly stand-in shown while the cell is farther than `loadRadius` but within `lodRadius` (a few percent of the cell's triangles, no textures worth the name)
- `details?: StreamDetailDef[]` — Lighter variants of the same cell (fewer triangles, smaller textures), nearest first: the cell is made of its `file` within `fullRadius` of the player and of the first variant whose `radius` reaches it farther out (the last one up to `loadRadius`). A variant has the cell's mesh names for what it keeps but may leave small things out, so an entity that `needs` the cell exists only while the full file is the resident one.

### StreamDetailDef

*interface* · `packages/levels/src/manifest.ts:49`

```ts
interface StreamDetailDef
```

One lighter variant of a streamed cell (`StreamCellDef.details`): `radius` is the distance from the player up to which it is wanted (increasing along the list, at most `loadRadius`); `size` / `memory` are what it takes once resident.

- `file: string`
- `radius: number`
- `size?: number`
- `memory?: number`

### StreamingBlock

*interface* · `packages/levels/src/manifest.ts:52`

```ts
interface StreamingBlock
```

The `streaming` block. A level without it loads whole, as before.

- `cell: number` — the grid size in metres the cells were cut with (informational for tools)
- `cells: Record<string, StreamCellDef>`
- `loadRadius: number` — metres from the player: cells inside are loaded (and are part of the ready gate at the spawn)
- `unloadRadius: number` — cells farther than this are released; must be at least `loadRadius`
- `bundles?: Record<string, { files: string[]; trigger?: string }>` — groups of files loaded together when a zone is entered (or on demand)
- `lodRadius?: number` — metres from the player within which a cell's `lod` stand-in is shown; at least `loadRadius` (default: `unloadRadius`)
- `fullRadius?: number` — metres from the player within which a cell is made of its full file; farther (up to `loadRadius`) it is made of its `details` variants. Default: `loadRadius` (the variants are not used). A change of variant has `detailHysteresis` metres of margin (default 8), so a player standing on a border does not make a cell swap back and forth.
- `detailHysteresis?: number`
- `readyRadius?: number` — metres from the player within which the cells are what `ready()` waits for (the start screen); the rest of `loadRadius` streams in behind the player, nearest first, under the memory budget. Default: `loadRadius`.
- `layers?: Record<string, { loadRadius?: number; unloadRadius?: number; lodRadius?: number; fullRadius?: number }>` — radii per kind of cell, over the block's: a cell names its layer in `layer`. `unloadRadius` must not be below `loadRadius` (that gap is the hysteresis)
- `memoryBudget?: number` — bytes of cells that may be resident at once (this tier's cap: every tier package has its own block). Pinned cells are counted but never evicted; a nearer cell takes the place of farther ones, and when it still does not fit it waits (event `stream:budget`)
- `maxPerFrame?: number` — pacing over the service's defaults (2 cells and 4 ms per update, 3 fetches at once); the host's options win
- `budgetMs?: number`
- `concurrency?: number`
- `texturesProgressive?: boolean` — reserved: low mips first, upgrade later; nothing acts on it yet

### StreamingOptions

*interface* · `packages/levels/src/streaming.ts:28`

```ts
interface StreamingOptions
```

- `at(file: string): string` — where the level's files are (cell and bundle file names are relative to it)
- `focus?: () => Focus[]` — the places that matter, asked every update; when it gives none (or is left out): the persistent entities of the level service, else the active camera
- `radiusScale?: number` — scale both radii (a tier may ask for less)
- `memoryBudget?: number` — bytes of resident cells, over the block's `memoryBudget` (a tier or a device may ask for less)
- `maxPerFrame?: number` — most cells instantiated in one update
- `budgetMs?: number` — milliseconds of instantiation work per update; at least one cell is always added when something waits, so streaming cannot starve
- `concurrency?: number` — most cells fetched at once
- `now?: () => number`

### SwarmDef

*interface* · `packages/levels/src/swarm.ts:10`

```ts
interface SwarmDef
```

A swarm of small flyers (butterflies, a moth round a lamp, fireflies): each agent is pushed by the forces Unreal's Niagara "hanging particulates" stack uses, summed and
integrated with drag and a speed limit: a curl-noise field (a swirling, divergence-free drift), a vortex round a vertical axis through the centre, an attraction to the
centre, the wind, and an optional repulsion near the centre (a moth bumping off the lamp). Plain numbers, deterministic from the seed; metres, seconds.
The Babylon part (`buildSwarm`) draws every agent as an instance of one mesh, turned along its flight.

- `name?: string`
- `position: [number, number, number]` — centre of the swarm
- `count: number`
- `radius: number` — the agents start inside a sphere of this radius about `position` + `offset`
- `offset?: [number, number, number]`
- `scale?: [number, number]` — uniform scale range of the mesh
- `drag?: number` — 1/s
- `speedLimit?: number` — m/s
- `curl?: Array<{ strength: number; frequency: number }>` — curl noise layers: strength is m/s^2, frequency 1/m
- `vortex?: { amount: number; radius: number; pull?: number }`
- `attraction?: { radius: number; strength: number; exponent?: number }` — pulls towards the centre inside `radius` with a strength falling off as (1 - d/radius)^exponent
- `repulsion?: { radius: number; strength: number; exponent?: number }` — pushes away from the centre inside `radius` (negative attraction), `kill` m: an agent closer is put back at the edge
- `windAir?: number` — m/s^2 added along x/z of the level's wind, times this (default 0)
- `seed?: number`
- `distance?: number` — the swarm runs only while the camera is within this many metres (default 40)

### Transition

*interface* · `packages/levels/src/transitions.ts:37`

```ts
interface Transition
```

- `enter(ctx: TransitionContext): Promise<void> | void` — The travel starts. Show something at once. Resolve when it is on screen (after 2 s the engine's bar takes over).
- `update(p: TransitionProgress): void` — The target's progress, many times a second.
- `ready(ctx: TransitionContext): Promise<void> | void` — The target is ready. Resolve when the game wants to leave: a door has opened, a button was pressed, a timer ran out.
- `fail(ctx: TransitionContext, err: StreamError): boolean | void | Promise<boolean | void>` — The target failed or the player cancelled. Return true when the transition shows the failure itself (Retry / Back); otherwise the engine's screen is shown.
- `dispose(): void`

### TransitionContext

*interface* · `packages/levels/src/transitions.ts:16`

```ts
interface TransitionContext
```

- `from: LevelDef | null`
- `to: LevelDef`
- `plan: LevelPlan` — what the travel will download; `cached` means a short wait is expected
- `world: World`
- `events: EventBus`
- `ui?: UIService` — the services a game's splash usually wants, when the game has them
- `audio?: unknown`
- `input?: unknown`
- `xr?: { active: boolean; state: string }` — the VR session service when the game has one: a transition may show its interlude world in the headset; `xr.active` says whether a session runs
- `persistent: Set<Entity>` — the player and what travels with them
- `host?: SceneHost` — the scene host (5.3): make a second world for an interlude with `host.create`, show it with `host.show`. The engine shows the level's world again when the player is let in. Present when the game added a `SceneHost`.
- `signal: AbortSignal` — the player cancelled

### TransitionProgress

*interface* · `packages/levels/src/transitions.ts:14`

```ts
interface TransitionProgress
```

What a transition is told, many times a second, while the target downloads. Numbers are honest bytes of what the target needs.

- `loaded: number`
- `total: number`
- `files: number`
- `rate: number`
- `eta: number`
- `phase: string`

### TravelOptions

*interface* · `packages/levels/src/levels.ts:68`

```ts
interface TravelOptions
```

- `spawn?: string`
- `keep?: Entity[]` — keep these entities: they move to the new level's spawn instead of being removed (the player)
- `keepOld?: boolean` — Keep the old level's way back: if the new one fails after the old was released, build the old one again and put the player where they were (default: LevelOptions.keepOldUntilReady, else the hub).
- `signal?: AbortSignal` — Cancel from a menu: before the old level is released the player simply stays; later they are put back.
- `transition?: string` — The game's transition for this travel, by the name it registered (else its chooser, else `default`, else the engine's bar).

### ValidateOptions

*interface* · `packages/levels/src/ferret.ts:182`

```ts
interface ValidateOptions
```

- `packages?: PackageSet` — the other open packages, for `ferret://` references and dependencies
- `behaviours?: Iterable<string>` — behaviours the game registers itself (besides those packages provide); when given, an unknown behaviour is an issue
- `checksums?: boolean` — check the sha256 of every file (default true)
- `engine?: EngineVersions | false` — the engine that is running; default this build's (`FERRET_VERSION`, `BABYLON_VERSION`); `false` skips the check of the manifest's `engine`
- `tierView?: boolean` — set when `pkg` is already one tier's view of a game (its own call for each tier)

### VirtualTextureDef

*interface* · `packages/levels/src/landscape.ts:47`

```ts
interface VirtualTextureDef
```

- `resolution?: number` — texels along the longer side of the rectangle (default 2048)
- `blendHeight?: number` — metres above the ground over which a prop's albedo fades from the ground colour to its own (default 1.5)
- `strength?: number` — 0..1, how much of the ground colour a prop takes at its foot (default 1)
- `meshes: string` — regex source: the meshes (by name, anywhere in the level) whose materials sample the virtual texture

### VisibilityBlock

*interface* · `packages/levels/src/manifest.ts:146`

```ts
interface VisibilityBlock
```

The `visibility` block: a level of many rooms (a castle) draws only what can be seen from where the player stands. The level's nodes are
split into named groups (a room, a corridor); the floor plan is cut by a grid of `cell` metres in x and z (origin 0, key "ix_iz" with
ix = floor(x / cell)); `see[key]` lists the groups that can be seen from anywhere in that grid cell. A tool computes the lists (rays against
the level's collision, tools/visibility.mjs). The player in a cell that has no entry sees everything: a gap in the table is never a hole.

- `cell: number`
- `groups: Record<string, { nodes: string[] }>` — group id -> the glTF node names that make it up (each node with all it carries)
- `always?: string[]` — groups that are always drawn (a landmark seen from everywhere)
- `see: Record<string, string[]>`
- `mode?: 'visible' | 'enable'` — 'visible' (default): meshes of an unseen group are not drawn but keep their collision; 'enable': the nodes are disabled (cheapest; collision goes too)

### VisibilityOptions

*interface* · `packages/levels/src/visibility.ts:5`

```ts
interface VisibilityOptions
```

- `focus?: () => { x: number; z: number } | null` — where the viewer stands; default the camera

### Waitable

*interface* · `packages/levels/src/fmdl-motion.ts:36`

```ts
interface Waitable
```

- `done(): boolean`
- `result?: unknown`

### WakeRow

*interface* · `packages/levels/src/wake.ts:22`

```ts
interface WakeRow
```

- `dist: number`
- `tau: number`
- `coreHalf: number`
- `coreAlpha: number`
- `armOffset: number`
- `armHalf: number`
- `armAlpha: number`

### WaterDef

*interface* · `packages/levels/src/water.ts:21`

```ts
interface WaterDef
```

- `level: number` — y of the surface at rest
- `centre?: [number, number]` — centre (x, z) and size (x, z) of the surface, metres
- `size?: [number, number]`
- `absorption?: Vec3` — the colour of the water seen from above when deep: Unreal's single-layer water `Absorption` is the distance per colour channel (cm) light goes before it is gone, `Scattering` how much the water sends back; the colour is the scattering tinted by those distances
- `scattering?: Vec3`
- `deepBrightness?: number` — a factor on that deep colour (default 1): a scattering of 1 asks for the full colour, which the original shows dimmed by the light that reaches the water in the shade of its banks
- `sky?: { top?: Vec3; horizon?: Vec3 }` — the colour of the sky it reflects (default the sky's horizon / top)
- `roughness?: number` — 0..1 (default 0.02)
- `specular?: number` — 0..1, the part of the sky a calm surface reflects head-on (default 0.02, about water's Fresnel at normal incidence)
- `waves?: WaterWave[]`
- `opacity?: number` — 0..1, how opaque the surface draws (default 0.92)
- `foam?: number` — 0..1, how strongly breaking crests turn to white water (default 0.8; a gentle sea has none whatever this is)
- `meso?: number` — 0..1: patches, wind streaks and whitecaps that show from high above, where real waves are smaller than a pixel (default 0: off)
- `river?: RiverDef` — a river instead of a rectangle (Unreal's WaterBodyRiver: a spline with a width): the surface is a ribbon along the centre line, its ripples run downstream at `flow`, the banks get a rim of foam. With a river `level` is the height of the first point, `centre`, `size` and `waves` are not used.
- `shore?: ShoreDef` — a lake with a shore (Unreal's WaterBodyLake: a closed spline): the surface is cut to this outline ([x, z] points in metres, 3..64, either winding) and a band of `width` metres inside the edge turns to foam (a lapping shore). The surface's extent is the outline's bounding box; `centre` and `size` are not used.

### WaterResponseMap

*interface* · `packages/levels/src/water.ts:279`

```ts
interface WaterResponseMap
```

a height field of what moves the surface (a jet's dent, rings, a wash) laid over a river: size x size cells of 4 floats (surface height above rest m, slope x, slope z, foam 0..1); `@ferret/physics-response` fills it from a `WaterSurface`. Without one a river is drawn as before.

- `readonly size: number`
- `readonly cell: number`
- `readonly originX: number`
- `readonly originZ: number`
- `readonly data: Float32Array`
- `readonly active: boolean`
- `readonly version: number`
- `readonly rings?: { readonly packed: Float32Array; readonly max: number }` — the ring sources (RingField of

### WaterSurfaceView

*interface* · `packages/levels/src/water.ts:283`

```ts
interface WaterSurfaceView
```

- `mesh: BABYLON.Mesh`
- `material: BABYLON.ShaderMaterial`
- `setWaves(waves: WaterWave[]): void`
- `setReflection(tex: BABYLON.BaseTexture | null): void`
- `dispose(): void`

### WaterWave

*interface* · `packages/levels/src/water.ts:10`

```ts
interface WaterWave
```

- `wavelength: number` — metres crest to crest
- `amplitude: number` — metres, crest above the rest level
- `steepness?: number` — 0..1: how sharp the crests are (Gerstner Q)
- `direction?: number` — degrees about the vertical, the way the wave travels (0 = +x)

## Types

### EnvironmentPart

*type* · `packages/levels/src/levels.ts:49`

```ts
type EnvironmentPart = 'sun' | 'ambient' | 'fog' | 'sky' | 'water'
```

a part of a level's environment a game may leave out (`LevelDef.environment.skip`)

### FileReader

*type* · `packages/levels/src/fmdl.ts:16`

```ts
type FileReader = (qualified: string) => Promise<Uint8Array>
```

