# @ferret/levels: API (continued)

### ProgramPlugin

*class* · `packages/levels/src/material-program.ts:296`

```ts
class ProgramPlugin extends BABYLON.MaterialPluginBase
```

- `active: boolean`
- `constructor(material: BABYLON.Material, built: BuiltProgram)`
- `get program(): MaterialProgram`
- `getClassName()` — Gets the current class name useful for serialization or dynamic coding.
- `deactivate()`
- `prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines)` — Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called.
- `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, _engine: BABYLON.AbstractEngine, subMesh: BABYLON.SubMesh)` — 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.

### 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`

### ScreenDecals

*class* · `packages/levels/src/screen-decals.ts:43`

```ts
class ScreenDecals
```

- `readonly colour: BABYLON.RenderTargetTexture` — the buffer of colour (rgb premultiplied by the opacity) and opacity
- `readonly surface: BABYLON.RenderTargetTexture` — the buffer of roughness, metallic (premultiplied) and opacity
- `readonly pass: { value: number; }` — which of the two passes is being drawn: the decal materials read it each time they are bound
- `constructor(private readonly scene: BABYLON.Scene)`
- `get count(): number` — the boxes drawn now
- `add(box: BABYLON.AbstractMesh): void` — put a decal's box mesh in: it is taken out of the camera's picture and drawn only into the buffers
- `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:21`

```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), and the list is taken anew every `refreshFrames` frames (a mesh
switched on or shown meanwhile appears then). A freeze the scene carries out later (it waits until it is ready) is taken back if it is no longer wanted.
Level 0 (the default) is off, level 1 is on.

- `readonly name: "still-camera-freeze"`
- `stillFrames: number`
- `refreshFrames: number` — how many frames a frozen list lives before it is taken anew
- `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

### acquireDepthRenderer

*function* · `packages/levels/src/material-models.ts:439`

```ts
function acquireDepthRenderer(scene: BABYLON.Scene, cam: BABYLON.Nullable<BABYLON.Camera>): BABYLON.DepthRenderer | null
```

the scene's depth pass, drawn while a material asks for it (the glow's DepthFade reads it)

### actorMatrix

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

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

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

### addScreenDecals

*function* · `packages/levels/src/screen-decals.ts:119`

```ts
async function addScreenDecals(scene: BABYLON.Scene, mats: LevelMaterials, specs: readonly ScreenDecalSpec[]): Promise<{ count: number; dispose(): void }>
```

The decals of a level in the scene: for each spec a box mesh with the decal's material (a master of the level carried whole, made as a projected decal), placed by its matrix. Returns what disposes them.
The meshes are made one by one (a clone of one cube shares its geometry): each has its own matrix, which its material reads.

### alphaAt

*function* · `packages/levels/src/ambient-particles.ts:59`

```ts
function alphaAt(keys: Array<[number, number]>, t: number): number
```

the alpha at the normalised life t (linear between the keys; clamped at both ends)

### ambientCapacity

*function* · `packages/levels/src/ambient-particles.ts:56`

```ts
function ambientCapacity: (d: Pick<AmbientParticlesDef, "rate" | "lifetime">) => number
```

how many particles are alive at once: rate x the longest life (plus a margin)

### applyEnvironment

*function* · `packages/levels/src/environment.ts:286`

```ts
function applyEnvironment(scene: BABYLON.Scene, def: EnvironmentDef, name = 'env', o: { /** the game's shared clock in seconds (the world's time): waves are drawn from it, so every peer sees the same sea at the same moment */ clock?: () => number; /** a height field of what moves a river (see `WaterResponseMap`) */ waterResponse?: WaterResponseMap; /** parts the game draws itself: left out */ skip?: Array<'sun' | 'ambient' | 'fog' | 'sky' | 'water'>; /** makes an effect of the vfx catalogue for an `effects` entry that names one (`vfx`); without it such an entry is the simple fire */ vfx?: (name: string, at: Vec3, scale: number, params?: Record<string, number>) => EnvironmentVfx } = {}): Environment
```

Build the environment in a scene. Dispose it when the level unloads.

### applyFoliageWind

*function* · `packages/levels/src/foliage-wind.ts:249`

```ts
function applyFoliageWind(scene: BABYLON.Scene, def: FoliageWindDef, o: { clock?: () => number; flowMap?: FoliageFlowMap } = {}): FoliageWindHandle
```

### applyLandscape

*function* · `packages/levels/src/landscape.ts:754`

```ts
async function applyLandscape(scene: BABYLON.Scene, def: LandscapeDef, o: ApplyLandscapeOptions): Promise<LandscapeView>
```

Put a landscape's layer blend on its mesh's material, mark a far plane, and bake the virtual texture and hand it to the props.
A problem (a texture that does not load, a mesh that is not there) is a warning in the view, never a thrown error: the level still loads with the baked look.

### applyMaterialLook

*function* · `packages/levels/src/material-models.ts:610`

```ts
function applyMaterialLook(material: BABYLON.Material, look: LookDef, o: ApplyLookOptions): () => void
```

Put the model on a PBR material; returns the function that takes it off again. A material with none of its fields is left as it is.

### applyMaterialLooks

*function* · `packages/levels/src/material-look.ts:200`

```ts
function applyMaterialLooks(scene: BABYLON.Scene, initial: MaterialLooks | undefined, o: MaterialLooksOptions = {}): MaterialLooksHandle
```

### applyMaterialProgram

*function* · `packages/levels/src/material-program.ts:471`

```ts
function applyMaterialProgram(material: BABYLON.Material, program: MaterialProgram, o: ApplyProgramOptions): () => void
```

Put a program on a PBR material; returns the function that takes it off again.

### applyMaterialScale

*function* · `packages/levels/src/material-scale.ts:42`

```ts
function applyMaterialScale(scene: BABYLON.Scene, defs: MaterialScaleDef[]): { dispose(): void; flush(force?: boolean): void; scaled: number; meshesCleared: number }
```

### applySunShadows

*function* · `packages/levels/src/sun-shadows.ts:57`

```ts
function applySunShadows(sun: BABYLON.DirectionalLight, def: SunShadowsDef = {}): SunShadows
```

Shadows from the sun on the meshes handed to `add`. A mesh of a material with an opacity mask or alpha test casts by its mask.

### assignShadowRoles

*function* · `packages/levels/src/sun-shadows.ts:116`

```ts
function assignShadowRoles(generator: Pick<BABYLON.ShadowGenerator, 'addShadowCaster'>, meshes: Iterable<BABYLON.AbstractMesh>, o: ShadowRoleOptions = {}): ShadowRoleResult
```

One function that chooses the roles of the meshes of a scene for a shadow generator: every mesh whose material is of a type that takes shadows (`takesShadows`) receives
them, and those `casts` picks (default all of them) cast. Meshes with no vertices or a material of another type (the ground's and the sea's own shaders) are skipped.

### atmosphereColours

*function* · `packages/levels/src/atmosphere.ts:190`

```ts
function atmosphereColours(t: AtmosphereTable, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): { top: Vec3; horizon: Vec3; ground: Vec3 }
```

colours of the sky that the rest of the environment uses (water, reflection, fog): the zenith, the horizon away from the sun, the ground

### bendOffset

*function* · `packages/levels/src/foliage-wind.ts:93`

```ts
function bendOffset(p: V3, player: V3, distance: number, strength: number, v: number, radius = 0): V3
```

MF_Collusion (Unreal cm): grass pushed away from `player`

### bindPropulsors

*function* · `packages/levels/src/fmdl-propulsors.ts:38`

```ts
function bindPropulsors(actor: Actor, o: PropulsorBindOptions): PropulsorSet | undefined
```

Bind the propulsors of `actor`. Returns the set (call `update()` once a step after the actuators) or undefined when the model declares none.

### blendWeights

*function* · `packages/levels/src/landscape.ts:210`

```ts
function blendWeights(weights: number[], heights: number[] = [], heightBlend: number[] = []): number[]
```

Weights of the layers at a point -> the weights the material uses: normalised to sum 1 (no paint at all = the first layer), then height blended.

### bloomWeight

*function* · `packages/levels/src/environment.ts:147`

```ts
function bloomWeight(intensity: number): number
```

### buildAmbientParticles

*function* · `packages/levels/src/ambient-particles.ts:66`

```ts
function buildAmbientParticles(scene: BABYLON.Scene, d: AmbientParticlesDef, texture: BABYLON.Texture, name: string): { ps: BABYLON.ParticleSystem; at: BABYLON.Vector3; radius: number }
```

the Babylon side; `texture` is any soft sprite

### buildAtmosphereTable

*function* · `packages/levels/src/atmosphere.ts:118`

```ts
function buildAtmosphereTable(def: AtmosphereDef | undefined, sunElevation: number, n = LUT_SIZE): AtmosphereTable
```

Fill the table for the sun at `sunElevation` radians above the observer's horizon.

### buildPlacements

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

```ts
async function buildPlacements(file: PlacementFile, o: PlacementBuildOptions): Promise<PlacementInstance>
```

Make the instances of a placement list: one clone of each mesh of a model per group, carrying the group's actors as thin instances.

### buildSwarm

*function* · `packages/levels/src/swarm.ts:114`

```ts
function buildSwarm(scene: BABYLON.Scene, d: SwarmDef, source: BABYLON.Mesh, name: string, wind?: () => { intensity: number; direction: [number, number] }, follow?: BABYLON.TransformNode)
```

one mesh drawn once per agent (instances), turned along its flight; returns what to update and dispose

### buildWater

*function* · `packages/levels/src/water.ts:395`

```ts
function buildWater(scene: BABYLON.Scene, def: WaterDef, o: { response?: WaterResponseMap; name: string; skyTop: Vec3; skyHorizon: Vec3; sunDir: Vec3; sunColor: Vec3; /** the game's shared clock in seconds: with it every peer draws the same waves at the same moment (default: this surface's own time since it was built) */ clock?: () => number }): WaterSurfaceView
```

Build one water surface in a scene. `sky` and `sun` come from the rest of the environment.

### captureRoomReflection

*function* · `packages/levels/src/room-reflection.ts:56`

```ts
function captureRoomReflection(scene: BABYLON.Scene, def: RoomReflectionDef, o: { name?: string; fallbackBox?: { center: Vec3; size: Vec3 }; onError?: (m: string) => void } = {}): RoomReflection
```

Draws the level into a cube map once the scene is ready and installs it as `scene.environmentTexture`. The probe draws the meshes as they are, with the
image processing of the scene's materials (exposure, curve), so the reflected light is divided by the exposure to land at the picture's own brightness.
`fallbackBox` is the probe grid's bounds, used when the definition has no box of its own.

### catalogUrls

*function* · `packages/levels/src/dependencies.ts:30`

```ts
function catalogUrls(list: readonly string[] | undefined, base: string): string[]
```

The catalog URLs a manifest names, made absolute against the URL the package was loaded from. Bad entries are skipped (validation reports them).

### cellDistance

*function* · `packages/levels/src/streaming.ts:62`

```ts
function cellDistance(b: StreamCellDef['bounds'], x: number, z: number): number
```

Distance on the ground plane from a point to a cell's box (0 inside it).

### checkDistanceField

*function* · `packages/levels/src/distance-field.ts:43`

```ts
function checkDistanceField(h: unknown, bytes?: Uint8Array): string | undefined
```

what is wrong with a distance field, or undefined

### compileProgram

*function* · `packages/levels/src/material-program.ts:60`

```ts
function compileProgram(p: MaterialProgram, o: { srgb?: readonly number[]; unlit?: boolean; arrays?: readonly (readonly number[])[]; screenDecal?: boolean } = {}): CompiledProgram
```

The GLSL of a program. `srgb` lists the indices of its textures that are colour and are decoded in the shader; `unlit` the material has no lighting.

### createKtx2Array

*function* · `packages/levels/src/texture-array.ts:38`

```ts
function createKtx2Array(scene: BABYLON.Scene, layers: readonly DecodedKtx2[], o: { name?: string; anisotropy?: number } = {}): BABYLON.BaseTexture
```

One array texture of `layers` (all with the same layout; layer k = layers[k]). Trilinear, repeat, the given anisotropy. The texture owns its GL object: `dispose()` frees it.

### createSkyProbe

*function* · `packages/levels/src/water.ts:266`

```ts
function createSkyProbe(scene: BABYLON.Scene, meshes: BABYLON.AbstractMesh[], o: { size?: number; every?: number; at?: [number, number, number] } = {}): BABYLON.RenderTargetTexture
```

A cube map of the sky for water to mirror: renders `meshes` (the sky dome, cloud layers, anything far away) into a cube from `at` (default: the camera, so a dome that follows the camera is seen from inside) and refreshes it every `every` frames (default 30: clouds drift slowly; 0 renders once). Give the result to `WaterSurfaceView.setReflection`.

### curl

*function* · `packages/levels/src/swarm.ts:60`

```ts
function curl(x: number, y: number, z: number, seed = 0): [number, number, number]
```

a smooth divergence-free vector field (the curl of a vector potential made of sines), in [-~1.7, ~1.7]; the same point gives the same vector

### decalBoxMatrix

*function* · `packages/levels/src/screen-decals.ts:33`

```ts
function decalBoxMatrix(d: Pick<ScreenDecalSpec, 'position' | 'axes' | 'half'>): BABYLON.Matrix
```

the world matrix of a unit cube [-1, 1]^3 that is the decal's box (columns: the axes scaled by the half extents, then the position)

### decalBufferOf

*function* · `packages/levels/src/decal-buffer.ts:62`

```ts
function decalBufferOf(scene: BABYLON.Scene, create = false): DecalBuffer | undefined
```

The scene's decal buffer; with `create`, made if there is none (the `rendertarget` part of Babylon must be loaded), and every material is told to look for it.

### decodeKtx2

*function* · `packages/levels/src/texture-array.ts:14`

```ts
async function decodeKtx2(engine: BABYLON.AbstractEngine, bytes: Uint8Array): Promise<DecodedKtx2>
```

Decode a KTX2 file the way Babylon's own texture loader does (same decoder, same worker pool, the formats this GPU takes).

### deepColour

*function* · `packages/levels/src/water.ts:141`

```ts
function deepColour(absorption: Vec3 = [110, 158, 350], scattering: Vec3 = [0.05, 0.05, 0.05]): Vec3
```

The deep colour of the water from Unreal's absorption distances and scattering (linear RGB).

### defaultLibraryUrl

*function* · `packages/levels/src/library.ts:159`

```ts
function defaultLibraryUrl(): string
```

### distanceFieldSizes

*function* · `packages/levels/src/distance-field.ts:37`

```ts
function distanceFieldSizes(h: DistanceFieldHeader): { table: number; atlas: number; texels: [number, number, number] }
```

the bytes the data of a header holds: the table, then the atlas

### distanceFieldUniforms

*function* · `packages/levels/src/distance-field.ts:93`

```ts
function distanceFieldUniforms(h: DistanceFieldHeader): [string, number, number, number, number][]
```

the uniforms of the lookup, in this order (material-program.ts declares and fills them)

### distanceToBounds

*function* · `packages/levels/src/collision-chunks.ts:14`

```ts
function distanceToBounds(b: CollisionChunkDef['bounds'], x: number, y: number, z: number): number
```

Distance from a point to a box (0 inside).

### ditherValue

*function* · `packages/levels/src/material-models.ts:90`

```ts
function ditherValue(x: number, y: number, noise: number, threshold = PIXEL_DEPTH_THRESHOLD): number
```

DitherTemporalAA's value for a pixel (Unreal's graph with no temporal sample; `noise` is the noise texture's red channel, 0..1): `threshold + (mod(x + 2y, 5) + noise) * 0.16665`.

### dockPhysicsOf

*function* · `packages/levels/src/fmdl-docks.ts:250`

```ts
function dockPhysicsOf(host: { bodies: Iterable<{ node: Node; body: unknown }>; kernel: { addConstraint(d: any): any; removeConstraint(c: any): void; setPosition(b: any, p: Vec3): void; onConstraintBreak(cb: (c: any) => void): () => void } }): DockPhysics
```

the kernel of a physics host as the docks' physics

### effectiveFogDensity

*function* · `packages/levels/src/height-fog.ts:44`

```ts
function effectiveFogDensity(f: HeightFogDef, h: number): number
```

the flat density Babylon's exponential fog takes for a view at height `h`: the density of the air there (a ray along the ground is what a walker sees most)

### engineImports

*function* · `packages/levels/src/dock-engine.ts:17`

```ts
function engineImports(text: string): string[]
```

The package names the code of a module imports from the shared engine (`@ferret/<name>`), in order of appearance.

### ensureLocalBounds

*function* · `packages/levels/src/material-program.ts:253`

```ts
function ensureLocalBounds(mesh: BABYLON.AbstractMesh): boolean
```

The bounds of a mesh's own vertices (Unreal's ObjectLocalBounds), as two constant vertex attributes of the source mesh so every instance reads them.

### ensureObjectHeight

*function* · `packages/levels/src/material-models.ts:412`

```ts
function ensureObjectHeight(mesh: BABYLON.AbstractMesh): boolean
```

The height of a mesh's own local bounds along y, metres: Unreal's ObjectBounds (its z). Written once as a constant vertex attribute of the source mesh so the shader can read it per object, thin instances included.

### environmentBabylonParts

*function* · `packages/levels/src/environment.ts:138`

```ts
function environmentBabylonParts(env?: EnvironmentDef): string[]
```

The Babylon parts a level's environment needs beyond the core: the post-processing pipeline for bloom, particles for fire.

### flickerFactor

*function* · `packages/levels/src/light-budget.ts:142`

```ts
function flickerFactor(l: Pick<BudgetLight, 'flicker'>, phase: number, t: number): number
```

the multiplier of a light's intensity at time `t` seconds

### flickerValue

*function* · `packages/levels/src/light-budget.ts:137`

```ts
function flickerValue(phase: number, t: number): number
```

a smooth repeatable noise in 0..1: two sines of unrelated rate, per light phase (no random state, so tests and replays agree)

### fogDensityAt

*function* · `packages/levels/src/height-fog.ts:26`

```ts
function fogDensityAt(f: HeightFogDef, h: number): number
```

extinction per metre at height `h`

### fogOpticalDepth

*function* · `packages/levels/src/height-fog.ts:34`

```ts
function fogOpticalDepth(f: HeightFogDef, h0: number, dirY: number, dist: number): number
```

Optical depth of a straight ray from a point at height `h0` going `dist` metres along a direction with vertical component `dirY` (-1..1):
the integral of the density, exact for each layer. The transmittance is exp(-depth).

### fogVeilOf

*function* · `packages/levels/src/fog-veil.ts:86`

```ts
function fogVeilOf(scene: BABYLON.Scene): FogVeil | undefined
```

the veil of the scene's environment, if its fog has one (for shaders of their own: the sky, the sea)

### freezeStatic

*function* · `packages/levels/src/static-freeze.ts:35`

```ts
function freezeStatic(world: World, scene: BABYLON.Scene, o: FreezeOptions): number
```

freeze every static mesh of the level; returns how many were frozen

### gammaOfLinear

*function* · `packages/levels/src/material-scale.ts:38`

```ts
function gammaOfLinear: (k: number) => number
```

the albedo colour is a gamma colour for the shader: a linear multiplier k is k^(1/2.2) of it

### gradientFaces

*function* · `packages/levels/src/environment.ts:203`

```ts
function gradientFaces(top: Vec3, horizon: Vec3, ground: Vec3, n = 8): Uint8Array[]
```

A cube map of the sky's gradient (ground below the horizon, top above): every face a few texels, smooth at every mip level, so any roughness reads it.

### graphGlsl

*function* · `packages/levels/src/material-models.ts:224`

```ts
function graphGlsl(e: GraphExpr, smp: (name: string, uv: string) => string, depthCm = 'ferretLkDepthCm'): Typed
```

one node as a GLSL expression, float (t 1) or vec3 (t 3); `smp` reads a named picture at a uv; `depthCm` is the pixel's distance along the view axis in centimetres

### graphMeanColour

*function* · `packages/levels/src/level-materials.ts:190`

```ts
function graphMeanColour(n: any): [number, number, number] | undefined
```

The colour a master's colour graph gives where its pictures read a middle value (0.5): constants, lerp, power, add, mul. Undefined for anything else.

### groundBlendAttributes

*function* · `packages/levels/src/material-models.ts:57`

```ts
function groundBlendAttributes(w: number, own: { metallic: number; roughness: number; occlusion: number }, ground: { roughness: number }): { metallic: number; roughness: number; occlusion: number }
```

What BlendMaterialAttributes leaves of an object's own attributes where the ground weighs `w`: the ground's roughness, the metallic of a MakeMaterialAttributes default (0), occlusion 1.

### groundSourceOf

*function* · `packages/levels/src/landscape.ts:599`

```ts
function groundSourceOf(scene: BABYLON.Scene, name?: string): GroundSource | undefined
```

The ground of the landscape called `name`, or of the first landscape that has one; undefined while none is baked (a material then draws without the blend).

### groundWeight

*function* · `packages/levels/src/material-models.ts:50`

```ts
function groundWeight(h: number, objectHeight: number, up: number, g: GroundBlendDef): number
```

The share of the ground colour at a pixel `h` metres over the ground, on an object `objectHeight` metres high, whose vertex normal points up by `up` (-1..1).

### groupByLayout

*function* · `packages/levels/src/texture-array.ts:29`

```ts
function groupByLayout(files: readonly DecodedKtx2[]): number[][]
```

Indices of `files` grouped by layout, in the order the layouts first occur.

### groupKey

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

```ts
function groupKey(a: Placement): string
```

The group an actor draws in: its model and its material overrides, so actors of one group are one thin-instance draw.

### groupPlacements

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

```ts
function groupPlacements(file: PlacementFile): PlacementGroup[]
```

### hairFibreMaterial

*function* · `packages/levels/src/hair-fibre.ts:67`

```ts
function hairFibreMaterial(scene: BABYLON.Scene, o: HairFibreOptions = {}): BABYLON.ShaderMaterial
```

The fibre material for a scene (one per scene and option set).

### hasLook

*function* · `packages/levels/src/material-models.ts:212`

```ts
function hasLook(look: LookDef): boolean
```

Does a definition carry anything of this model?

### hasPackedNormals

*function* · `packages/levels/src/landscape.ts:431`

```ts
function hasPackedNormals: (layers: LandscapeLayerDef[]) => boolean
```

does a packed landscape carry normals or occlusion

### heightFogOf

*function* · `packages/levels/src/height-fog-material.ts:99`

```ts
function heightFogOf(scene: BABYLON.Scene): HeightFogMaterials | undefined
```

the scene's height fog along the rays, if its environment asks for one (`fog.alongRay`): shaders of their own (the sea) take its `values`

### heightFogShaderValues

*function* · `packages/levels/src/height-fog-material.ts:87`

```ts
function heightFogShaderValues(f: HeightFogDef, h: number): [number, number, number, number]
```

Per-layer numbers of the shader at the camera's height `h`: [density of the first layer at the eye (per metre), its falloff k (per metre, natural log),
the same for the second layer (0, 0 without one)]. The density along a ray is d0 x exp(-k x (y - h)).

### heightRaster

*function* · `packages/levels/src/landscape.ts:243`

```ts
function heightRaster(positions: ArrayLike<number>, rect: [number, number, number, number], w: number, h: number): Float32Array
```

Spread vertices (x, y, z; z is the plane's second axis) over a w x h raster of the rectangle: the height of the nearest vertex per texel, holes filled.

### importFromBytes

*function* · `packages/levels/src/code.ts:223`

```ts
async function importFromBytes(bytes: Uint8Array): Promise<LibraryModule>
```

The default import: the checked bytes as a module behind a blob URL (so what runs is exactly what was checked).

### indexGlb

*function* · `packages/levels/src/material-look.ts:114`

```ts
function indexGlb(bytes: ArrayBuffer | Uint8Array): GlbIndex
```

read the JSON chunk of a .glb (or the bytes of a .gltf)

### installCatalogCommands

*function* · `packages/levels/src/catalog.ts:176`

```ts
function installCatalogCommands(world: import('@ferret/core').World, levels: LevelService, client: CatalogClient): void
```

The catalog commands: the viewer and an agent open a catalog, list its levels with their state on the device,
refresh it and travel into a level. `catalog.levels {check: true}` opens each level's package (a few ranged reads) to say whether
its core set is `cached` or `missing` and how many bytes a visit would download; without `check` the state is `unknown`.

### installCatalogs

*function* · `packages/levels/src/catalog.ts:165`

```ts
function installCatalogs(levels: LevelService, mount: PackageMount, store: AssetStore, defaults: CatalogOptions = {}): CatalogClient
```

Plug catalog support into a LevelService: afterwards `levels.registerCatalog(url)` works.

### installCode

*function* · `packages/levels/src/code.ts:230`

```ts
function installCode(world: World, mount: PackageMount, o: CodeLoaderOptions = {}): CodeLoader
```

Let a mount run the code of its packages.

### installCodeCommands

*function* · `packages/levels/src/commands.ts:121`

```ts
function installCodeCommands(world: World, code: CodeLoader): void
```

`pkg.require` and `pkg.loaded`: run the code of an open package (and of its dependencies) through a CodeLoader, and list what runs.

### installDockForms

*function* · `packages/levels/src/fmdl-docks.ts:283`

```ts
function installDockForms(bridge: DockBridgeLike, docks: ModelDocks): void
```

`(dock a b [:joint fixed|hinge|ball|bond] [:axis (vec x y z)] [:limits (list lo hi)] [:break N] [:place #f])` and `(undock a [b])`. `a` and `b` are refs
(`actor#dock`, or an actor alone when it has one free dock). The value of `dock` is the second ref.

### installLevelLibraries

*function* · `packages/levels/src/libraries.ts:63`

```ts
function installLevelLibraries(levels: LevelService, code: CodeLoader): void
```

Make `travel` require the libraries of every package level before it is built. The ones the manifest names are found through the
loader's `open` hook (the catalog) when they are not open yet; the ones only the open libraries' `provides` imply are already open.
Emits `level:libraries` { level, libraries } with what was required.

### installModelForms

*function* · `packages/levels/src/fmdl-motion.ts:492`

```ts
function installModelForms(bridge: FormBridgeLike, stage: ModelStage): void
```

### installPackageCommands

*function* · `packages/levels/src/commands.ts:33`

```ts
function installPackageCommands(world: World, mount: PackageMount, hooks: PackageCommandHooks = {}): void
```

The `pkg.*` commands (PLAN.md 4.9), by hand and through MCP alike, over a PackageMount:
pkg.open, pkg.unlock, pkg.level, pkg.list, pkg.info, pkg.validate, pkg.deps, pkg.verify, pkg.code, pkg.pack, pkg.save, pkg.keys,
pkg.catalog and pkg.publish.
`installCodeCommands` adds pkg.require and pkg.loaded (running a package's code).

### installPackageLoader

*function* · `packages/levels/src/package.ts:54`

```ts
function installPackageLoader(levels: LevelService, o: PackageLoaderOptions): void
```

Teach a LevelService to load level packages: a folder with `manifest.json`, `scene.glb` and optionally `navmesh.bin`.
Problems with the wiring (a node the manifest names is missing, a behaviour is not registered) do not stop the level:
they are collected in the report so the game still runs and the artist sees what to fix.

### installPackages

*function* · `packages/levels/src/ferret.ts:169`

```ts
function installPackages(levels: LevelService, assets: MountAssets, o: MountOptions = {}): PackageMount
```

Set a LevelService up to play packages.

### installProgramForms

*function* · `packages/levels/src/fmdl-programs.ts:140`

```ts
function installProgramForms(bridge: ProgramBridgeLike, programs: ModelPrograms): void
```

`(run-motion "name" [:on actor] :param value ...)`: lasts until the motion's program has ended

### installSequences

*function* · `packages/levels/src/sequence.ts:144`

```ts
function installSequences(world: { events: { on(n: string, f: (e: any) => void): () => void; emit(n: string, d?: unknown): void } }, scene: BABYLON.Scene, defs: SequenceDef[], find: (name: string) => BABYLON.TransformNode | null)
```

Plays a level's sequences: `begin` ones at once, `trigger` ones when the trigger volume with that id is entered (the world's `trigger:enter`), `manual` ones when
the game calls `play(name)`. Returns the players by name; `dispose()` removes the listeners.

### installStreamCommands

*function* · `packages/levels/src/runtime.ts:205`

```ts
function installStreamCommands(world: World, store: AssetStore): void
```

`stream.status` and `stream.cache`: what the store is doing and what it holds on the device.

### installStreamingDebug

*function* · `packages/levels/src/streaming-debug.ts:57`

```ts
function installStreamingDebug(world: World, sv: StreamingService): StreamingDebugView
```

`stream.debug {on?}`: show or hide the cell boxes of the streamed level; returns whether they are shown.

### installTravelCommands

*function* · `packages/levels/src/transitions.ts:196`

```ts
function installTravelCommands(world: World, registry: TransitionRegistry): void
```

The `travel.*` commands: `travel.preview {name, seconds?, bytes?, fail?, cached?}` and `travel.transitions`.

### installUnrealFilm

*function* · `packages/levels/src/unreal-film.ts:85`

```ts
function installUnrealFilm(): void
```

Make Babylon's PBR and standard materials able to tone map with Unreal's film curve (`toneMappingType = UNREAL_FILM_TONEMAPPING`). Safe to call again.

### instanceMatrix

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

```ts
function instanceMatrix(w: BABYLON.Matrix, t: BABYLON.Matrix): BABYLON.Matrix
```

The instance matrix for a mesh whose world matrix inside the model is `w` and an actor transform `t`: `w * t * w^-1`.

### isHairFibreMaterial

*function* · `packages/levels/src/hair-fibre.ts:51`

```ts
function isHairFibreMaterial(m: BABYLON.Material | null | undefined): boolean
```

Is this glTF material a strand material?

### isMirrored

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

```ts
function isMirrored(a: Placement): boolean
```

an actor whose scale turns space over (an odd number of negative axes): its faces wind the other way, so it is drawn by a mesh of its own with the culling turned round

### isPlacementsFile

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

```ts
function isPlacementsFile: (name: string) => boolean
```

a file name that holds a placement list (a streaming cell's `file` ending so is placed, not loaded as a glb)

### isReliefDecal

*function* · `packages/levels/src/decal-buffer.ts:15`

```ts
function isReliefDecal: (m: AbstractMesh) => boolean
```

### ktx2Layout

*function* · `packages/levels/src/texture-array.ts:26`

```ts
function ktx2Layout: (d: DecodedKtx2) => string
```

The key two decoded files must share to be layers of one array: size, GL format, number of levels.

### layerBlendGlsl

*function* · `packages/levels/src/landscape.ts:312`

```ts
function layerBlendGlsl(layers: LandscapeLayerDef[], pos: string, tex = 'texture', linear = 'toLinearSpace', up = '1.0', o: BlendGlslOptions = {}): string
```

The layer blend as GLSL statements. Needs in scope: `vec2 <pos>` (metres in the landscape's coordinates), uniform `vec4 ferretLsRect` (minX, minZ, 1/sizeX, 1/sizeZ),
samplers ferretLsW<i>, ferretLsA<k>, ferretLsN<k>, ferretLsR<k>, ferretLsX<k>. Leaves `vec3 lsColour` (linear), with normal maps `vec3 lsNormal` (tangent space) and, when a layer says anything of its
roughness (image, scale or alpha), `float lsRoughness` set.
`tex` is the sampling function (texture in GLSL ES 3, texture2D in the procedural texture's shader), `linear` converts sRGB to linear.
`up` is a GLSL float expression: the up component of the ground normal, for the layers with a `slope` or a `world`.

### levelCost

*function* · `packages/levels/src/fmdl.ts:384`

```ts
function levelCost(model: FmdlModel, level: number): { files: number; instances: number }
```

How much a level of a placed model costs, from its plan: the files, and the instances drawn (a whole with its includes).

### levelFilesFromFetch

*function* · `packages/levels/src/level-materials.ts:153`

```ts
function levelFilesFromFetch(get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer?(): Promise<ArrayBuffer> }>, at: (path: string) => string): LevelFiles & { revoke(): void }
```

`LevelFiles` over a fetch like the package loader's: `at` turns a level-relative path into the URL the fetch takes.

### levelLibraries

*function* · `packages/levels/src/libraries.ts:42`

```ts
function levelLibraries(manifest: LevelManifest, providers: Iterable<Provider>): Record<string, string>
```

Which libraries a level needs: those its manifest names, and every one of `providers` whose `provides` the level uses (a level key
with content, a capability it switches on, an actuator or rotor kind, a flow source). Id -> version range, sorted by id.

### levelMaterialRefs

*function* · `packages/levels/src/level-materials.ts:88`

```ts
function levelMaterialRefs(def: MaterialDef): { ref: string; slot: string; colour: boolean }[]
```

every texture reference of a definition: the maps and the pictures (`masks`), with the slot they are read for

