# @ferret/levels: API (continued)

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

```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'> } = {}): Environment
```

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

### applyFoliageWind

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

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

### applyLandscape

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

```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:246`

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

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

### applyMaterialLooks

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

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

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

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

```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:37`

```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:126`

```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:127`

```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:138`

```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).

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

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

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

### 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).

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

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

### ensureObjectHeight

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

```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:119`

```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:22`

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

extinction per metre at height `h`

### fogOpticalDepth

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

```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).

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

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

### groundSourceOf

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

```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:33`

```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).

### groupKey

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

```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:90`

```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).

### heightRaster

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

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

### indexGlb

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

```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:167`

```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:156`

```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:172`

```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:440`

```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:50`

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

### instanceMatrix

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

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

### isPlacementsFile

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

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

### layerBlendGlsl

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

```ts
function layerBlendGlsl(layers: LandscapeLayerDef[], pos: string, tex = 'texture', linear = 'toLinearSpace', up = '1.0'): 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>. Leaves `vec3 lsColour` (linear) and, with normal maps, `vec3 lsNormal` (tangent space) 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`.

### levelCost

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

```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).

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

### loadLandscapeTexture

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

```ts
function loadLandscapeTexture(url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }): Promise<BABYLON.BaseTexture>
```

the default landscape texture: a Babylon Texture from a URL the browser can load (http, blob, data), resolved once loaded

### lookDefine

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

```ts
function lookDefine: (s: LookStructure) => string
```

### lookGlsl

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

```ts
function lookGlsl(s: LookStructure): string
```

The model as GLSL statements for the fragment shader's "before lights" point: needs `surfaceAlbedo`, `vPositionW`, `vNormalW`, the varying `vFerretLkUv` (first UV set)
and, with a ground blend, `vFerretLkH` (the object's height, metres). Leaves the colour in `surfaceAlbedo`.

### lookMasks

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

```ts
function lookMasks(s: LookStructure): string[]
```

the mask pictures of a structure in the order samplers are numbered

### lookStructure

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

```ts
function lookStructure(look: { colourLayers?: ColourLayersDef; macro?: MacroVariationDef[]; groundBlend?: GroundBlendDef }): LookStructure
```

### lutElevation

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

```ts
function lutElevation(i: number, n = LUT_SIZE): number
```

the view elevation (radians above the horizon) of table entry `i`: dense near the horizon, where the sky changes fastest

### maskSample

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

```ts
function maskSample(texel: [number, number, number, number], channel: MaskChannel = 'rgb'): Vec3
```

The mask sample of a channel choice: one channel repeated, or the three colour channels.

### miePhase

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

```ts
function miePhase(c: number, g: number): number
```

### mixLayer

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

```ts
function mixLayer(colour: Vec3, color: Vec3, mask: Vec3, power = 1): Vec3
```

`mix(colour, layer.color, pow(mask, power))` per colour channel (`mask` is the picture's sample: one value repeated, or its three channels for `rgb`).

### movingNodes

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

```ts
function movingNodes(world: World, scene: BABYLON.Scene, o: FreezeOptions): Set<BABYLON.Node>
```

the nodes that move: entity nodes, sequence targets, the listed ones

### pickTier

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

```ts
function pickTier<T>(have: Partial<Record<LibraryTier, T>>, want: LibraryTier = 'desktop'): { tier: LibraryTier; value: T } | null
```

The first tier at or below `want` that the item has (a low-end device asks for `low` and gets `low`, never `desktop`).

### planCollisionChunks

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

```ts
function planCollisionChunks(def: CollisionChunksDef, at: [number, number, number][], resident: ReadonlySet<number>): { load: number[]; drop: number[] }
```

Which chunks to load and which to drop for the places in `at` (metres), given the ones resident. A chunk stays while it is within `unloadRadius` of any place; it comes when within `loadRadius`.

### previewTransition

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

```ts
async function previewTransition(world: World, registry: TransitionRegistry, name: string, o: PreviewOptions = {}): Promise<{ name: string; fellBack: string | null; updates: number; ended: 'ready' | 'failed' }>
```

Run a registered transition against a fake travel, without travelling: the author sees it in the viewer and tests it in
Playwright. Returns what the transition was told.

### projectionUvs

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

```ts
function projectionUvs(p: Vec3, scale: number): [[number, number], [number, number], [number, number]]
```

Where a macro picture is read for a world position (metres): the UVs of the XY, YZ and XZ projections of Unreal, `scale` in Unreal units.

### projectionWeights

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

```ts
function projectionWeights(n: Vec3, sharpness = MACRO_DEFAULT_SHARPNESS): Vec3
```

The weights of the three projections (XY, YZ, XZ planes of Unreal) from the world normal given in this world's axes.

### propellerBlur

*function* · `packages/levels/src/propeller.ts:22`

```ts
function propellerBlur(omega: number, dt: number, blades = 3, from = 0.25, to = 0.7): number
```

how much of the propeller is blur: 0 blades only, 1 the disc only; `omega` rad/s, `dt` the frame's time, s

### propulsorsOf

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

```ts
function propulsorsOf: (a: Actor) => [string, ModelPropulsor][]
```

the declared propulsors of an actor's model (empty for a model that declares none)

### rankNearest

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

```ts
function rankNearest(items: readonly { position: Vec3; priority?: number; range?: number }[], at: Vec3, n: number, opts: { held?: ReadonlySet<number>; hysteresis?: number; maxDistance?: number; filter?: (i: number) => boolean; byView?: (position: Vec3, radius: number) => boolean } = {}): number[]
```

The indices of the `n` lights that matter most to a viewer at `at`: the smallest distance / priority, within `maxDistance`. Lights in `held`
(the ones that are real now) count as nearer by `hysteresis`, so a newcomer has to be clearly nearer to take over.

### rayleighPhase

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

```ts
function rayleighPhase(c: number): number
```

### refKind

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

```ts
function refKind(ref: string): RefKind
```

Which scheme a reference uses.

### registerCatalogueCommands

*function* · `packages/levels/src/fmdl-catalogue.ts:70`

```ts
function registerCatalogueCommands(register: RegisterFn, catalogue: ModelCatalogue, stage: ModelStage, o: { ready?: (actor: string) => Promise<void> | void } = {}): void
```

`ready` is awaited when a model has appeared (the programs read the model's motion files then, so a motion can run at once)

### registerDockCommands

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

```ts
function registerDockCommands(register: RegisterFn, docks: ModelDocks): void
```

`fmdl.docks`, `fmdl.dock`, `fmdl.undock`, `fmdl.docked`, `fmdl.docks.restore`: what an agent calls

### registerGroundSource

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

```ts
function registerGroundSource(scene: BABYLON.Scene, name: string, src: GroundSource): () => void
```

Make a landscape's baked ground findable by materials of the scene; returns the function that takes it away again.

### resolveAtmosphere

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

```ts
function resolveAtmosphere(a: AtmosphereDef = {}): ResolvedAtmosphere
```

### riverRibbon

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

```ts
function riverRibbon(points: Vec3[], widths: number[])
```

The ribbon of a river: two vertices per point, at half the width to either side of the centre line (sideways = the horizontal tangent turned a quarter).
uv = (metres along the river, metres across from the centre); `side` is -1 / +1 (the bank), `tangent` the horizontal direction downstream (x, z).

### rotateAboutAxis

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

```ts
function rotateAboutAxis(axis: V3, turns: number, pivot: V3, pos: V3): V3
```

Unreal's RotateAboutAxis: the offset (new minus old position) of `pos` turned by `turns` about the axis through `pivot`

### sampleKeys

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

```ts
function sampleKeys(keys: Key<number | number[]>[], t: number, quat = false): number | number[]
```

the value of a key track at time t: held before the first and after the last key

### scopeKey

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

```ts
function scopeKey: (s: LookScope) => "types" | "instances"
```

### shoreDistance

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

```ts
function shoreDistance(outline: [number, number][], x: number, z: number): number
```

signed distance from (x, z) to the outline's edge, metres: positive inside, negative outside (even-odd rule, nearest edge)

### simpleGrassWind

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

```ts
function simpleGrassWind(p: V3, time: number, intensity: number, weight: number, speed: number, additional: V3 = [0, 0, 0]): V3
```

SimpleGrassWind (Unreal cm, seconds): the offset of a vertex at `p` (the world position, cm)

### skyRadiance

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

```ts
function skyRadiance(t: AtmosphereTable, elevation: number, cosSun: number, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): Vec3
```

Radiance of the sky in a direction, in the picture's units for a sun of unit colour and strength: `elevation` of the view above the horizon,
`cosSun` the cosine of the angle between the view and the sun. The dome's shader does the same on the GPU.

### slopeAlpha

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

```ts
function slopeAlpha(up: number, r: SlopeRamp): number
```

Unreal's WorldAlignedBlend ("w/Vertex Normals") over the ground normal's up component (1 = flat, 0 = vertical): the dot with the world up is remapped to
0..1, times Blend Sharpness, plus Blend Bias minus half the sharpness, saturated = saturate(0.5 * sharpness * up + bias).
(The reference the GLSL of `layerBlendGlsl` repeats.)

### slopeShares

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

```ts
function slopeShares(up: number, s: LandscapeSlope): [number, number, number]
```

Weights of the three pictures of a slope layer (steep[0], steep[1], own) at a ground whose normal has up component `up`; they sum to 1.

### smoothTri

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

```ts
function smoothTri: (x: number) => number
```

Unreal's three-component (3 - 2a) a^2 of a = |frac(x + 0.5) * 2 - 1|

### spawnFromManifest

*function* · `packages/levels/src/levels.ts:435`

```ts
function spawnFromManifest(s: ManifestSpawn): { id: string; position: [number, number, number]; yaw?: number }
```

### sunLightColour

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

```ts
function sunLightColour(color: Vec3, transmittance: Vec3, amount: number): Vec3
```

The sun light's colour after the atmosphere: the transmittance along the sun ray (scaled to a strongest channel of 1) mixed in by `amount`.

### treeSway

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

```ts
function treeSway(p: V3, pivot: V3, time: number, intensity: number, windIntensity: number, dir: [number, number], heightInBox: number): V3
```

MF_TreesWind's "wind offset" (Unreal cm): the tree turns about its pivot

### unfreezeStatic

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

```ts
function unfreezeStatic(scene: BABYLON.Scene, root?: string): number
```

give the frozen meshes back (all of the scene's, or those under `root`)

### unrealFalloff

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

```ts
function unrealFalloff(d: number, range: number): number
```

Unreal's legacy point light: (1 - (d/R)^2)^8, no 1/d^2 (its default falloff exponent)

### useHairFibre

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

```ts
function useHairFibre(root: BABYLON.Node, o: HairFibreOptions = {}): number
```

Swap every strand material under `root` for the fibre material. Returns how many meshes were changed.

### useUnrealFalloff

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

```ts
function useUnrealFalloff(): boolean
```

Babylon's standard (linear) light falloff becomes Unreal's legacy curve in the PBR shader (GLSL and WGSL), for every material compiled after
this call. Done once per page, before the pool's lights are made, so no material was compiled with the old one.

### validateAmbientParticles

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

```ts
function validateAmbientParticles(v: unknown, at = 'motes'): ManifestIssue[]
```

### validateAtmosphere

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

```ts
function validateAtmosphere(a: unknown, at = 'environment.skyAtmosphere'): { path: string; message: string }[]
```

### validateEnvironment

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

```ts
function validateEnvironment(e: unknown, at = 'environment'): ManifestIssue[]
```

### validateFoliageWind

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

```ts
function validateFoliageWind(v: unknown, at = 'foliageWind'): ManifestIssue[]
```

### validateLandscapes

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

```ts
function validateLandscapes(l: unknown, at: string): { path: string; message: string }[]
```

### validateLightBudget

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

```ts
function validateLightBudget(d: unknown, at = 'environment.lights'): ManifestIssue[]
```

### validateLookDef

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

```ts
function validateLookDef(d: unknown, p: string, bad: (path: string, message: string) => void): void
```

the problems of one look (`d` is the object at path `p`)

### validateManifest

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

```ts
function validateManifest(m: unknown): ManifestIssue[]
```

Check a manifest against the schema. Returns the problems; an empty list means the manifest is usable.

### validateMaterialLooks

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

```ts
function validateMaterialLooks(v: unknown, at = 'materialLooks'): ManifestIssue[]
```

### validateMaterialScale

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

```ts
function validateMaterialScale(v: unknown, at = 'materialScale'): ManifestIssue[]
```

### validatePackage

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

```ts
async function validatePackage(pkg: FerretPackage, o: ValidateOptions = {}): Promise<PackageIssue[]>
```

`pkg.validate`: the package's own checks (manifest, files, sha256, no code in kinds without code) and then every level: its
manifest against the schema, and that the scene, collision mesh and navmesh it names exist — in the package or, through
`ferret://`, in a declared dependency.

### validatePlacements

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

```ts
function validatePlacements(x: unknown, at = 'placements'): ManifestIssue[]
```

### validateProbes

*function* · `packages/levels/src/probe-volume.ts:24`

```ts
function validateProbes(p: unknown, at = 'environment.probes'): { path: string; message: string }[]
```

### validateRelevance

*function* · `packages/levels/src/manifest.ts:331`

```ts
function validateRelevance(r: unknown): ManifestIssue[]
```

the `relevance` block: numbers that are positive and finite, modes keyed by name

### validateRoomReflection

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

```ts
function validateRoomReflection(r: unknown, at = 'environment.roomReflection'): ManifestIssue[]
```

### validateSequences

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

```ts
function validateSequences(v: unknown, at = 'sequences'): ManifestIssue[]
```

### validateSwarm

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

```ts
function validateSwarm(v: unknown, at = 'swarms'): ManifestIssue[]
```

### validateVisibility

*function* · `packages/levels/src/visibility.ts:117`

```ts
function validateVisibility(v: any): ManifestIssue[]
```

### validateWater

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

```ts
function validateWater(w: unknown, at: string): { path: string; message: string }[]
```

### virtualTextureShare

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

```ts
function virtualTextureShare(above: number, blendHeight: number, strength = 1): number
```

The colour a prop takes at height `above` metres over the ground: the share of the ground colour (virtual texture) it keeps.

### wakeFade

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

```ts
function wakeFade(age: number): { core: number; arm: number }
```

how much of its first strength a row of the track keeps `age` seconds after the ship passed: the foam core slowly, the wave arms several times faster (they disperse)

### wakeProfile

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

```ts
function wakeProfile(o: ShipWakeOptions): WakeRow[]
```

the shape of the track: pure, for the picture and for tests

### waveHeight

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

```ts
function waveHeight(waves: WaterWave[], x: number, z: number, t: number): number
```

Height of the waves at (x, z) and time t: the sum of Gerstner waves' vertical part, metres above the level.

## Interfaces

### Actor

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

```ts
interface Actor
```

- `name: string`
- `id: string` — the id of the model, or of the included model an instance was let go from
- `root: Node`
- `rig: PartRig`
- `clips?: ClipPlayer`
- `from?: string` — the actor this one was let go from
- `resolved?: ResolvedModel` — the model it is of (its resolved form, its reader)
- `read?: (qualified: string) => Promise<Uint8Array>`

### AmbientParticlesDef

*interface* · `packages/levels/src/ambient-particles.ts:10`

```ts
interface AmbientParticlesDef
```

Motes in a box of air (dust in a sunbeam, pollen, falling leaves): a particle emitter that spawns at random places of a box, lives a few seconds, drifts with a small random
velocity and fades in and out. Unreal's Cascade dust (P_Ambient_Dust: ParticleModuleLocation box, Lifetime uniform, Velocity uniform, Size, ColorOverLife with an alpha
curve, spawn rate) maps one to one; the numbers come from the particle asset (see vschool_ferret tools/ambient-particles.mjs). Lengths are metres.
It runs only while the camera is within `radius` (default 40 m) of the box centre, as the fires do.

- `name?: string`
- `position: [number, number, number]` — the centre of the box
- `size: [number, number, number]` — the box's full size
- `rate: number` — particles per second
- `lifetime: [number, number]` — seconds, [min, max]
- `sprite: [number, number]` — the sprite's size in metres, [min, max]
- `color: [number, number, number]` — linear colour 0..1
- `alpha?: Array<[number, number]>` — alpha over the normalised life: [[t, alpha], ...] with t rising from 0 to 1
- `velocity?: { min: [number, number, number]; max: [number, number, number] }` — m/s: each axis is drawn between the two
- `radius?: number` — metres: the emitter runs only within this distance of the camera (default 40)

### ApplyLandscapeOptions

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

```ts
interface ApplyLandscapeOptions
```

- `at: (file: string) => string` — turn a file name of the def into a URL
- `texture?: (url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture>` — create a texture from a URL (default: a Babylon Texture, resolved once loaded); tests pass their own
- `scope?: BABYLON.AbstractMesh[]` — the name pattern of the meshes of the virtual texture's props is searched among these (default: all meshes of the scene)

### ApplyLookOptions

*interface* · `packages/levels/src/material-models.ts:240`

```ts
interface ApplyLookOptions
```

- `masks: Record<string, BABYLON.BaseTexture>` — the picture of each name of the material's `masks`, loaded as data (not sRGB), repeating

### AssetLibraryOptions

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

```ts
interface AssetLibraryOptions
```

- `store: AssetStore`
- `mount: PackageMount`
- `assets?: RuntimeAssets` — needed for characters
- `tier?: LibraryTier` — the package tier to open (default `desktop`); a tier a package does not have falls back to its plain file
- `policy?: CatalogPolicy` — the catalog policy (trusted keys, `allowUnsigned`)
- `session?: () => string | null | undefined` — the SW session of the person, for the calls that change the library (`library.add`, `library.accept`, `library.reject`, `library.incoming`); default: the world's `account` service
- `onModelReady?: (root: BABYLON.TransformNode, id: string) => void` — called with the root of every static model of the library when its file is in (its yaw set): a game's hook for what it does to each model, such as the culling of parts too small to see (`PartCuller.add`)
- `code?: { origin?: boolean | ((pkg: FerretPackage) => boolean); trusted?: () => Iterable<string> | undefined; engine?: Record<string, unknown>; loader?: CodeLoader; importModule?: CodeLoaderOptions['importModule'] }` — How the code of `module` items may run (`module(id)`). `origin`: the library is the game's own, so its code is the game's (default: the catalog is on the page's own origin); otherwise a package must carry a valid signature, from `trusted` keys when given. `engine`: the engine's API the code reads its `@ferret/*` imports from (default `globalThis.Ferret`, the shared engine of `lib/ferret/ferret.js`); a game that bundles the engine passes the packages the modules need (`{ ...terrain, ...waves }`), and they are set as `globalThis.Ferret` when the page has none. `loader`: a code loader of the game's own.

### AtmosphereDef

*interface* · `packages/levels/src/atmosphere.ts:18`

```ts
interface AtmosphereDef
```

Unreal's `SkyAtmosphere` component. Every field is optional and defaults to the component's own default. Lengths km, coefficients per km.

- `groundRadius?: number` — planet radius, km (6360)
- `atmosphereHeight?: number` — thickness of the air, km (60)
- `rayleighScattering?: Vec3` — Rayleigh scattering per km (0.005802, 0.013558, 0.0331)
- `rayleighScaleHeight?: number` — Rayleigh scale height, km (8)
- `mieScattering?: Vec3` — Mie scattering per km (0.003996 each)
- `mieAbsorption?: Vec3` — Mie absorption per km (0.00444 each)
- `mieScaleHeight?: number` — Mie scale height, km (1.2)
- `mieAnisotropy?: number` — Mie anisotropy g, -1..1 (0.8)
- `absorption?: Vec3` — ozone absorption per km at the middle of its layer (0.00065, 0.001881, 0.000085)
- `groundAlbedo?: Vec3` — colour of the ground the air sits on (0.402 each)
- `multiScatteringFactor?: number` — how much of the single scattering comes back as multiple scattering (1)
- `skyLuminanceFactor?: Vec3` — colour factor on the sky's luminance (1 each)
- `observerAltitude?: number` — how far the observer is above the ground, km (0)

### AtmosphereTable

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

```ts
interface AtmosphereTable
```

- `n: number`
- `rayleigh: Vec3[]` — Rayleigh in-scatter per view elevation, phase left out, per channel, in units of the sun's irradiance
- `mie: Vec3[]` — the same for Mie
- `sunTransmittance: Vec3` — share of the sun's light that reaches the observer: the sun disc's and the lit ground's colour (zero with the sun under the horizon)
- `ground: Vec3` — colour of the ground below the horizon, in the same units (albedo x sun and sky light)
- `g: number`
- `skyLuminanceFactor: Vec3`
- `multiScatter: number`
- `sunElevation: number`

